简体   繁体   English

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

[英]Can't save form data to Django database

I'm creating forms for my Django project, and I have a problem: I can't save form data to Django database for one of my forms. 我正在为我的Django项目创建表单,但有一个问题:我无法将其中一个表单的表单数据保存到Django数据库中。 I can add data for Wish_list model, but can't add a comment. 我可以为Wish_list模型添加数据,但不能添加评论。 There are no any error messages, just no changes after submitting the form. 提交表单后,没有任何错误消息,也没有任何更改。 Can you please tell me where I have a mistake? 您能告诉我哪里有错误吗?

This is my models (from moders.py): 这是我的模型(来自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)

This is forms.py: 这是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')

This is urls.py: 这是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'),
]

This is from views.py: 这是来自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})

This is the template for Comment 这是评论模板

{% 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 %}

And this is a template to add comment (the one I have a problem with): 这是一个添加评论的模板(我有一个问题):

{% 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 %}

The instance must match the form's model, Comment_to_wish_list . instance必须与表单的模型Comment_to_wish_list It doesn't make sense to pass instance=wish_list to the form, because the model doesn't match. instance=wish_list传递给表单没有意义,因为模型不匹配。

You can set the comment_to field after saving the form with commit=False , in the same way that you set the person field: 您可以在使用commit=False保存表单后,以与设置person字段相同的方式设置comment_to字段:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM