编辑具有ForeignKey的表单到其他模型

时间:2017-12-04 20:08:00

标签: django python-3.x

我有一个用户需要填写的表单,该表单的模型为ForeignKey到另一个模型(问题)

当我创建一个新表单时,它按预期工作。 当我尝试编辑现有记录时,我能够在模板中获取相关数据,但是当我点击提交时它失败并没有错误 - 当我调试它时,表单上的故障无效且问题是无。

# form
class AnswerForm(forms.ModelForm):
    question = forms.ModelChoiceField(
        label=_(u'question'),
        widget=forms.HiddenInput(),
        queryset=Question.objects.all())
    description = forms.CharField(
        label=_(u'description'),
        widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '4'}),
    max_length=2000,
    required = False)
link = forms.URLField(
    label=_(u'link'),
    max_length=1000,
    required = False)
price = forms.DecimalField(
    label=_(u'price'),
    widget=forms.TextInput(attrs={'class': 'form-control'}),
    #max_length=100,
    required = False)
currency = forms.ModelChoiceField(
    label=_(u'currency'),
    required=False,
    queryset=Currency_converter.objects.all())

class Meta:
    model = Answer
    exclude = ('user','link_domain_name',)
    fields = ['link','price', 'currency','description']

def clean(self):
    cleaned_data = super(AnswerForm, self).clean()
    if cleaned_data.get('link')==''  and cleaned_data.get('price')==None and 
cleaned_data.get('description')=='' :
        raise forms.ValidationError(_("You must fill at least one field!"))
    if cleaned_data.get('link')=='' and cleaned_data.get('price')!=None :
        raise forms.ValidationError(_("Add link to the price you found!"))
    if cleaned_data.get('price')!=None and 
cleaned_data.get('currency')==None :
        raise forms.ValidationError(_("set currency for the price you 
set!"))
    return cleaned_data 

        #view
    def answer(request,question_id ,answer_id):
        path_to_pic = filepath_link_as_pictures()
        question = get_object_or_404(Question, pk=question_id)
        if answer_id != '0':
            instance = get_object_or_404(Answer, pk=answer_id)
            if instance.user != request.user:
                return HttpResponseForbidden()
        else:
            instance = Answer()
            instance.question = question
        form = AnswerForm(request.POST or None, instance=instance)
        if request.POST :
           if form.is_valid():
               ....
#HTML
{% for field in form.visible_fields %}
 <div class="form-group">
{{ field.label_tag }}

{% if form.is_bound %}
  {% if field.errors %}
    {% render_field field class="form-control is-invalid" %}
    {% for error in field.errors %}
      <div class="invalid-feedback">
        {{ error }}
      </div>
    {% endfor %}
  {% else %}
    {% render_field field class="form-control is-valid" %}
  {% endif %}
{% else %}
  {% render_field field class="form-control" %}
{% endif %}

{% if field.help_text %}
  <small class="form-text text-muted">{{ field.help_text }}</small>
{% endif %}
 </div>
{% endfor %}

看起来我错过了一些东西,因为我得到了模板中的所有数据,为什么我不将问题字段作为模板中的隐藏字段?

由于

1 个答案:

答案 0 :(得分:0)

我发现了问题 ModelChoiceField需要是初始的

initial = { 'question':question})

你需要传递answer.id的东西,它被错误删除,所以它创建了一个新的记录,而不是更新现有的记录

{% url 'answer' question.id  form.instance.id|default_if_none:0 %}