【问题标题】:Can't save form data to Django database无法将表单数据保存到 Django 数据库
【发布时间】:2016-05-03 12:43:11
【问题描述】:

我正在为我的 Django 项目创建表单,但我遇到了一个问题:我无法将表单数据保存到 Django 数据库中以用于我的一个表单。我可以为 Wish_list 模型添加数据,但不能添加评论。没有任何错误消息,只是提交表单后没有更改。 你能告诉我哪里出错了吗?

这是我的模型(来自 moders.py):

class Person (AbstractUser):
    phone_number = models.CharField(max_length=30)
    place_of_work_or_study = models.CharField(max_length=100)
    img = models.ImageField(upload_to='Person/', null=True, blank=True)
    class Meta:
        verbose_name = 'Person'
        verbose_name_plural = 'Users'
    def __unicode__(self):
        return self.username

class Wish_list(models.Model):
    person = models.ForeignKey(Person, null=True)
    types = (
        ('Educational', 'Educational'),
        ('Cultural', 'Cultural'),
        ('Sports', 'Sports'),
        ('Fun', 'Fun'),
        ('Other', 'Other')
    )
    type = models.CharField(max_length=50, choices=types, default='Other')
    periods = (
        ('Up to 1 hour', 'Up to 1 hour'),
        ('From 1 to 2 hours', 'From 1 to 2 hours'),
        ('From 2 to 3 hours', 'From 2 to 3 hours'),
        ('More then 3 hours', 'More then 3 hours')
    )
    time_need = models.CharField(max_length=50, choices=periods)
    place_name = models.CharField(max_length=50, blank=False, null=False)
    description = models.CharField(max_length=1000)

    def __unicode__(self):
        return unicode(self.place_name)

class Comment_to_wish_list(models.Model):
    person = models.ForeignKey(Person, null=True)
    comment_to = models.ForeignKey(Wish_list, null=True)
    text = models.CharField(max_length=500)
    def published (self):
        self.published_date = timezone.now()
        self.save()
    class Meta:
        verbose_name_plural = 'comments_to_wish_lists'
    def __unicode__(self):
        return unicode(self.comment_to)

这是forms.py:

class Wish_listForm(forms.ModelForm):
    place_name = forms.CharField(max_length=50, help_text='enter the         place_name')
    types = (
        ('Educational', 'Educational'),
        ('Cultural', 'Cultural'),
        ('Sports', 'Sports'),
        ('Fun', 'Fun'),
        ('Other', 'Other')
    )
    type = forms.ChoiceField(choices=types, help_text='choose the type')
    periods = (
        ('Up to 1 hour', 'Up to 1 hour'),
        ('From 1 to 2 hours', 'From 1 to 2 hours'),
        ('From 2 to 3 hours', 'From 2 to 3 hours'),
        ('More then 3 hours', 'More then 3 hours')
    )
    time_need = forms.ChoiceField(choices=periods, help_text='period')
    description = forms.CharField(max_length=1000, help_text='description')
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    class Meta:
        model = Wish_list
        fields = ('place_name', 'type', 'time_need', 'description','likes')

class Comment_to_wish_listForm(forms.ModelForm):
    text = forms.CharField(max_length=500, help_text='enter the text')
    views = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
    class Meta:
        model = Comment_to_wish_list
        fields = ('text', 'views', 'likes')

这是 urls.py:

app_name = 'friends_plans'
urlpatterns = [
url(r'^$', views.index, name='index'), # start page
url(r'^users/$', views.listing, name='listing'),
url(r'^(?P<person_id>[0-9]+)/wish_list/$',views.wish_list,      name='wish_list'),
url(r'^(?P<person_id>[0-9]+)/$', views.user, name='user'),
url(r'^(?P<person_id>[0-9]+)/(?P<day_id>[0-9]+)/$', views.day, name='day'),
url(r'^add_wish_list/$', views.add_wish_list, name='add_wish_list'),
url(r'^(?P<wish_list_id>[0-9]+)/comment/$', views.comment, name='comment'),
url(r'^(?P<wish_list_id>[0-9]+)/add_comment/$', views.add_comment,   name='add_comment'),
]

这是来自views.py:

def add_comment(request, wish_list_id):
    wish_list = get_object_or_404(Wish_list, pk=wish_list_id)
    if request.method == 'POST':
        form = Comment_to_wish_listForm(request.POST, instance=wish_list)
        if form.is_valid():
            newform=form.save(commit=False)
            newform.person = request.user
            newform.save()
        else:
            print form.errors
    else:
        form = Comment_to_wish_listForm()
    return render(request, 'friends_plans/add_comment.html', {'form': form})

这是评论的模板

{% extends 'friends_plans/base.html' %}
{% block title %} Comments {% endblock %}
{% block content %}
    {% for comment_to_wish_list in wish_list.comment_to_wish_list_set.all %}
        <div>{{comment_to_wish_list.text}}</div>
    {% endfor %}

<div><a href="{% url 'friends_plans:add_comment' wish_list.pk %}">Add  comment</a> </div>
</div>
{% endblock %}

这是一个添加评论的模板(我有问题的那个):

{% extends 'friends_plans/base.html' %}
{% block content %}

<h1>Add a wish_list</h1>
<form method="post"  action="">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="Add comment" />
</form>
{% endblock %}

【问题讨论】:

  • 您似乎没有做任何事情来将 Comment_to_wish_listForm 的结果与实际的 Wish_list 相关联。 (请使用正确的 PEP8 命名:WishList、CommentToWishListForm。)
  • 谢谢你的回答,丹尼尔。但我不知道该怎么做才能纠正这个问题。我认为'instance=wish_list'意味着'wish_list'和所有相关对象将在提交表单后更新。
  • 除了解决问题,还可以阅读这个文档,可以帮助改进源码。 django-best-practices.readthedocs.io/en/latest/code.html

标签: python django database forms save


【解决方案1】:

instance 必须与表单的模型 Comment_to_wish_list 匹配。将instance=wish_list 传递给表单没有意义,因为模型不匹配。

您可以在使用commit=False 保存表单后设置comment_to 字段,方法与设置person 字段相同:

wish_list = get_object_or_404(Wish_list, pk=wish_list_id)
if request.method == 'POST':
    form = Comment_to_wish_listForm(request.POST)
    if form.is_valid():
        instance=form.save(commit=False)
        instance.person = request.user
        instance.comment_to = wish_list
        instance.save()

【讨论】:

  • 您希望将表单发布到add_comment url,因此您应该使用{% url 'friends_plans:add_comment' wish_list.pk %}。请注意,您需要在模板上下文中包含 wish_list 才能使其正常工作。
  • 这就是我正在做的,但又出现了同样的错误!我有(在模板中):{% url 'friends_plans:add_comment' wish_list.pk %} 和:context_dict = {'form': form, 'wish_list': wish_list} 然后:return render(request, 'friends_plans/add_comment.html', {'context_dict': context_dict})(在 views.py 中)
  • 应该是return render(request, 'friends_plans/add_comment.html', context_dict),不要把context_dict放在另一个字典里。
  • 好的,我的“评论”模板中还有一个错误!即使没有使用 context_dict,表单中的数据也被保存到数据库中,因为那个错误,它没有显示在屏幕上!非常感谢您的帮助!!!
猜你喜欢
  • 1970-01-01
  • 2017-03-06
  • 2018-03-16
  • 2016-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-25
  • 1970-01-01
相关资源
最近更新 更多