无法将表单数据保存到Django数据库

时间:2016-05-03 12:43:11

标签: python django database forms save

我正在为我的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 %}

1 个答案:

答案 0 :(得分:1)

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

使用comment_to保存表单后,您可以设置commit=False字段,方法与设置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()