简体   繁体   English

Django 访问 InlineFormset_Factory 中的外键表数据

[英]Django Access Foreign Key Table's Data in InlineFormset_Factory

I am using formsets to create a feedback page but I am not able to access foreign key table values in django template.我正在使用表单集创建反馈页面,但无法访问 django 模板中的外键表值。

I have this models below that are for a feedback system.我在下面有这个模型,用于反馈系统。

Models.py模型.py

class FeedbackForm(amdl.AagamBaseModel):
    feedback_form_id = models.AutoField(primary_key=True)
    subject_teacher = models.ForeignKey(MapMySchoolUserSubject, models.DO_NOTHING)
    feedback_form_date = models.DateField()
    feedback_form_status = models.BooleanField()

    class Meta:
        db_table = 'feedback_form'

class FeedbackFormQuestion(amdl.AagamBaseModel):
    feedback_form_question_id = models.AutoField(primary_key=True)
    feedback_form = models.ForeignKey('FeedbackForm', models.DO_NOTHING)
    feedback_question = models.ForeignKey('FeedbackQuestion', models.DO_NOTHING)

    class Meta:
        db_table = 'feedback_form_question'

class Feedback(amdl.AagamBaseModel):
    feedback_id = models.AutoField(primary_key=True)
    feedback_form_question = models.ForeignKey('FeedbackFormQuestion', models.DO_NOTHING)
    map_myschool_user_standard_section = models.ForeignKey(MapMySchoolUserStandardSection, models.DO_NOTHING)
    feedback_rating = models.IntegerField()
    feedback_comments = models.TextField(blank=True, null=True)
    feedback_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'feedback'

class FeedbackQuestion(amdl.AagamBaseModel):
    feedback_question_id = models.AutoField(primary_key=True)
    question_text = models.TextField()
    feedback_question_credit = models.IntegerField()
    question_group = models.ForeignKey('FeedbackQuestionGroup', models.DO_NOTHING)

    class Meta:
        db_table = 'feedback_question'

class FeedbackQuestionGroup(amdl.AagamBaseModel):
    feedback_question_group_id = models.AutoField(primary_key=True)
    question_group = models.TextField()
    description = models.TextField()

    class Meta:
        db_table = 'feedback_question_group'

The Feedback model is the main model where the rating of feedback is given by students. Feedback model 是主要的 model,其中反馈的评级由学生给出。 As the rating is per question there is one row per question that is in foreign key with the FeedbackFormQuestion which is the relationship (many-to-many) between FeedbackForm and FeedbackQuestion that make up a feedback form.由于评分是针对每个问题的,因此每个问题有一行是外键, FeedbackFormQuestion是构成反馈表单的FeedbackFormFeedbackQuestion之间的关系(多对多)。 Other models are just for analysis and graphs.其他模型仅用于分析和图表。

This is the view where there is a formset for the Model and it is based on a FORM (shown bafter view.py) that manages the looks in html.这是 Model 的表单集的视图,它基于管理 html 中的外观的FORM (显示在 view.py 之后)。 Need formset for handling multiple forms with MySchoolUSer data to be same for all.需要使用 MySchoolUSer 数据处理多个 forms 的表单集对所有人都是相同的。 View.py视图.py

def aagam_feedback(request):
    model_formset = inlineformset_factory(MapMySchoolUserStandardSection, Feedback, fields=('feedback_form_question','feedback_rating','feedback_comments'), form=FormFeedback, can_delete=False)                                  
    stud_nav = views.student_navbar(request)
    stud = MapMySchoolUserStandardSection.objects.get(pk=stud_nav['standard_section_current']['pk'])
    formset = model_formset(queryset=Feedback.objects.none(), instance=stud, initial=[{'feedback_form_question': 4}, {'feedback_form_question': 4}])

    if request.method == "POST":
        formset = model_formset(request.POST, instance=stud)
        if formset.is_valid():
            formset.save()
            return redirect("/")

    return render(request, 'StudentFeedback/aagam_feedback.html', {'formset': formset})

form.py表格.py

from django import forms
from django.forms import ModelForm
from StudentFeedback import models


class FormFeedback(ModelForm):
    CHOICES = [(1, ''),
               (2, ''),
               (3, ''),
               (4, ''),
               (5, '')]
    feedback_rating = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(), label=False, label_suffix=False)

    class Meta:
        model = models.Feedback
        fields = ['feedback_form_question', 'feedback_rating', 'feedback_comments']

This is the html but i am not able to access this data form foreign key table.html这是 html 但我无法从外键表中访问此数据。html

<form method="POST">
  {% csrf_token %}
    {{ formset.management_form }}
    {% for form in formset %}
        // Want to access the question_text below but it is blank.
        {{ form.feedback_form_question.feedback_question.question_text }}
        {% for rating in form.feedback_rating %}
            {{ rating }}
        {% endfor %}
        {{ form.feedback_comments }}
    {% endfor %}
    <input type="submit" class="btn btn-primary col-sm-12" data-toggle="button" aria-pressed="false">
</form>

output output

输出

Expected output预期 output

预期产出

I have used accessed foreign key data like this many times but not sure why it is not coming here.我已经多次使用过这样的访问外键数据,但不知道为什么它不来这里。

Since you don't want to allow the user to select the question just make the field disabled on your form:由于您不想让用户 select 问题只是在您的表单上禁用该字段:

class FormFeedback(ModelForm):
    CHOICES = [(1, ''),
               (2, ''),
               (3, ''),
               (4, ''),
               (5, '')]
    feedback_rating = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(), label=False, label_suffix=False)
    feedback_form_question = forms.ModelChoiceField(
        queryset=FeedbackFormQuestion.objects.all(),
        disabled=True,
    )

    class Meta:
        model = models.Feedback
        fields = ['feedback_form_question', 'feedback_rating', 'feedback_comments']

Now in your form instead of writing {{ form.feedback_form_question.feedback_question.question_text }} which really doesn't make sense as form.feedback_form_question is a form field not the value stored for that field.现在在你的表单中,而不是写{{ form.feedback_form_question.feedback_question.question_text }}这真的没有意义,因为form.feedback_form_question是一个表单字段,而不是为该字段存储的值。 Instead since now we simply have our field as disabled go ahead and render the field (Even if the user tampers with the html it won't be taken by the form).相反,因为现在我们只是将我们的字段设置为禁用 go 并渲染该字段(即使用户篡改 html 它也不会被表单占用)。 Also whenever dealing with forms one should always remember to render the hidden fields, more so in the case of formsets which add several important hidden fields:此外,每当处理 forms 时,应始终记住渲染隐藏字段,在添加几个重要隐藏字段的表单集的情况下更是如此:

<form method="POST">
  {% csrf_token %}
    {{ formset.management_form }}
    {% for form in formset %}
        <!-- Render the hidden fields -->
        {% for field in form.hidden_fields %}
            {{ field }}
        {% endfor %}
        <!-- Render the field -->
        {{ form.feedback_form_question }}
        {% for rating in form.feedback_rating %}
            {{ rating }}
        {% endfor %}
        {{ form.feedback_comments }}
    {% endfor %}
    <input type="submit" class="btn btn-primary col-sm-12" data-toggle="button" aria-pressed="false">
</form>

You can override the __str__ of your model to modify what is displayed:您可以覆盖__str__的 __str__ 来修改显示的内容:

class FeedbackFormQuestion(amdl.AagamBaseModel):
    # Your implementation
    
    def __str__(self):
        return self.feedback_question.question_text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM