在Django视图中创建嵌入式表单

时间:2019-01-15 12:00:01

标签: django django-forms django-templates django-views

我有一个规则类,一条规则是一个问题和一个答案的组合:

Route::group(['namespace' => 'W3public\ContactForm\Http\Controllers'], function () {
    Route::get('contact-us', 'ContactFormController@index');
    Route::post('contact-us', 'ContactFormController@store')->name('contact-us');
});

我想为该规则创建一个表单,其中有两个输入:一个输入问题,另一个输入答案。单击提交时,应将规则保存在规则表中,将问题保存在问题表中,将答案保存在答案表中。这是我得到的最大成果:我为每个模型创建了一个表单,然后在一个view方法中调用了这些表单:

class Rule(models.Model):
    name = models.CharField(max_length=32)

class Question(models.Model):
    name = models.CharField(max_length=32)
    rule_id = models.ForeignKey(Rule, on_delete=models.CASCADE, null=True, blank=True)

class Answer(models.Model):
    name = models.CharField(max_length=32)
    rule_id = models.ForeignKey(Rule, on_delete=models.CASCADE, null=True, blank=True)

但这不是我想要的视图,并且每个模型都独立保存。谁能为我找到解决方案?谢谢。

1 个答案:

答案 0 :(得分:0)

我认为您可以像这样将这些字段添加到RuleForm中,并覆盖save方法以保存它们:

class RuleForm(forms.ModelForm):
    question = forms.CharField(required=True)
    answer = forms.CharField(required=True)

    class Meta:
       model = Rule
       fields=['name', 'question', 'answer']

    def save(self, commit=False):
       question = self.cleaned_data.pop('question')
       answer = self.cleaned_data.pop('answer') 
       rule = super(RuleForm, self).save(commit=True)
       Question.objects.create(rule=rule, name=question)
       Answer.objects.create(rule=rule, name=answer)
       return rule

现在,您只需要在视图中传递规则表:

def create_rule_view(request,id, sc_id):
    rule = RuleForm(request.POST or None)
    if rule.is_valid():
        rule.save()
        return redirect('../')
    context = {
        'rule': rule,
    }
    return render(request, "rule/create_rule.html", context)