使用ModelForm编辑模型数据:ModelForm验证错误

时间:2016-04-16 00:57:49

标签: django forms django-forms django-views

我正在开发我的第一个django应用程序。我正在构建一个允许用户评价啤酒的应用程序。我希望我的用户能够编辑他们已经创建的条目。我把他们带到了ModelForm,并要求他们进入。调用POST方法时,我的数据无效。这是我的model.py:

from django.db import models


 class Rating(models.Model):
    beer_name = models.TextField()
    score = models.DecimalField(max_digits=2, decimal_places=1)
    notes = models.TextField(blank=True)
    brewer = models.TextField(blank=True)

和forms.py:

from django import forms
from ratings.models import Rating


class RatingForm(forms.ModelForm):
    class Meta:
        model = Rating
        fields = ['beer_name', 'score', 'notes', 'brewer']

以下是我的编辑功能的views.py:

def edit(request, row_id):
    rating = get_object_or_404(Rating, pk=row_id)
    if request.method == "POST":
        form = RatingForm(request.POST, instance=rating)
        if form.is_valid():
            form.save()
            return redirect(home)
        else:
            return HttpResponse("Invalid entry.")
    else:
        context = {'form': rating}
        form = RatingForm(instance=rating)
        return render(
            request,
            'ratings/entry_def.html',
            context
        )

但是,每次调用POST时,我都会收到“无效条目”。 HttpResponse,意味着我的form.is_valid()返回False。这是我的模板:

{% extends "base.html" %}

{% block content %}
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-10 col-sm-offset-1">
        <h2>Edit Rating</h2>
        <form role="form" method="post">
          {% csrf_token %}
          <p>Beer Name: <textarea>{{ form.beer_name }}</textarea></p>
          <p>Score: <input type="text" name="BeerScore" value="{{ form.score }}"></p>
          <p>Notes: <textarea>{{ form.notes }}</textarea></p>
          <p>Brewer: <textarea>{{ form.brewer }}</textarea></p>
          <p><button type="submit" class="save btn btn-primary">Save</button></p>
          <p><button type="reset" class="btn btn-primary">Cancel</button></p>
        </form>
      </div>
    </div>
  </div>
{% endblock %}

所以,当我按下“保存”按钮时,我收到了回复。这是我在urls.py中的编辑网址:

urlpatterns = [
    ...
    url(r'rating/edit/(?P<row_id>[0-9]+)/$', edit , name='rating-edit'),
]

1 个答案:

答案 0 :(得分:0)

您在其他没有name属性的字段中包装字段。这很可能导致值从request.POST数据中排除。

此外,Django表单字段都有相应的HTML小部件。因此,除非您需要,否则无需手动呈现HTML。

将模板代码更改为:

<p>
    {{ form.beer_name.label }}: {{ form.beer_name }}
    {% if form.beer_name.errors %}
    <br />{{ form.beer_name.errors }}
    {% endif %}{# repeat for other fields as needed #}
</p>
<p>{{ form.score.label }}: {{ form.score }}</p>

<p>{{ form.notes.label }}: {{ form.notes }}</p>
<p>{{ form.brewer.label }}: {{ form.brewer }}</p>
<p><button type="submit" class="save btn btn-primary">Save</button></p>
<p><button type="reset" class="btn btn-primary">Cancel</button></p>

如果您需要更改窗口小部件,请在表单级别执行此操作:

class RatingForm(forms.ModelForm):
    class Meta:
        model = Rating

    def __init__(self, *args, **kwargs):
        super(RatingForm, self).__init__(*args, **kwargs)

        self.fields['notes'].widget = forms.Textarea()

这样,Django为您管理属性和绑定。

您的视图也可以使用一些清理:

def edit(request, row_id):
    rating = get_object_or_404(Rating, pk=row_id)
    form = RatingForm(request.POST or None, instance=rating)

    if request.method == "POST" and form.is_valid():
        form.save()
        return redirect(home)

    context = {'form': rating}
    return render(request, 'ratings/entry_def.html', context)