How to display InLine objects in Django Admin Inte

2019-09-14 20:15发布

This is my current Admin Interface:Admin Interface

A user inputs text through a form & model called "UserText". I have written a function using NLP to extract only the questions from the UserText. I would like each of these individual questions to be displayed in each "User question" section of the Admin Interface. As of now, I cannot get that to work.

Here is my current code:

Models.py

class UserText(models.Model):
    user_input = models.TextField()

class Question(models.Model):
    user_text = models.ForeignKey(
        UserText,
        on_delete=models.CASCADE,
        blank=True,
        null=True,
    )
    user_questions = models.CharField(max_length=2000)

Views.py

def user_text_view(request):
    form = forms.UserTextForm()
    if request.method == 'POST':
        form = forms.UserTextForm(request.POST)
        if form.is_valid():
            UserText = models.UserText
            Question = models.Question
            user_input = request.POST.get('user_input', '')
            user_input_obj = UserText(user_input = user_input)
            user_questions_obj = Question(user_text = user_input_obj,
                user_questions = Question_Init(user_input_obj))
            user_input_obj.save()
            user_questions_obj.save()
            print("Thanks for the questions!")

    else:
        form = forms.UserTextForm()

    return render(request, 'text_input_form.html', {'form': form})

Admin.py

class QuestionInLine(admin.StackedInline):
    model = Question
    display = ('user_questions_obj')


@admin.register(UserText)
class UserTextAdmin(admin.ModelAdmin):
    model = UserText
    display = ('user_input')
    inlines = [
        QuestionInLine,

    ]

And finally my function:

def Question_Init(user_input_obj):

    Beginning_Question_Prompts = ("Who","Whom","What","Where","When","Why","Which",
    "Whose","How","Was","Were","Did","Do","Does","Is")
    Ending_Question_Prompts = ("?",":","...")
    questions = []

    text1 = user_input_obj.user_input

    textList = sent_tokenize(text1)

    for sentence in textList:
        if sentence.startswith(Beginning_Question_Prompts):
           questions.append(sentence)

        if sentence.endswith(Ending_Question_Prompts):
            questions.append(sentence)

    return questions

I know this is a lot, sorry, but I do not know how to get each question to populate the question fields in my Admin Interface. Thanks

1条回答
Animai°情兽
2楼-- · 2019-09-14 20:34

The problem is not your admin interface, but how you create the Question objects. You need to iterate through the result of your function and create linked items for each one:

for question_text in Question_Init(user_input_obj):
     user_questions_obj = Question(user_text=user_input_obj,
                                   user_questions=question_text)
     user_questions_obj.save()
查看更多
登录 后发表回答