0

我在这里阅读了有关表单数据未保存的其他帖子,但似乎无法确定我自己的问题。有一种感觉,我错过了一些非常基本的东西。非常感谢帮助谢谢。

#model

class AboutMe(models.Model):
    title = models.CharField(max_length=30)
    user = models.ForeignKey(User)
    post = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.title

#form

class AboutMeForm(forms.ModelForm):

    class Meta:
        model = AboutMe
        fields = ['title', 'post']

#view


def post_line(request):
    if request.method == 'POST':
        form = AboutMeForm(request.POST)
        if form.is_valid():
            new_about = form.save(commit=False)
            new_about.user = request.user       
            new_about.save()
            return HttpResponseRedirect('index.html')
    else:
        form = AboutMeForm()
    return render_to_response('post_line.html', locals(), context_instance=RequestContext(request))

#template:

<div class="post_line">
<form enctype="multipart/form-data" action='.' method="post">{% csrf_token %}
    {{ form.as_table }}
    <input type="submit" name="submit" value="post" />
</form>
</div>
4

2 回答 2

0

尝试这样做:

表格.py

class AboutMeForm(ModelForm):
    class Meta:
        model=AboutMe
        fields = YOUR FIELDS

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(AboutMeForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        instance = super(AboutMeForm, self).save(commit=False)
        if self.user:
            instance.user = self.user
        return instance.save()

在views.py上:

def post_line(request):
    if request.method == 'POST':
        form = AboutMeForm(request.POST)
        if form.is_valid():
            new_about = form.save() 
            return HttpResponseRedirect('index.html')
    else:
        form = AboutMeForm()
    return render_to_response('post_line.html', locals(), context_instance=RequestContext(request))
于 2013-10-26T13:29:30.837 回答
0

I am not able to comment here so i am writing here

1) HttpResponseRedirect('index.html') this is wrong here you have to pass some url like

/login/ or /profile/

2) please print your form like

print form and check what you are getting is all fields are valid or anything missing

and then tell the form error

于 2012-08-28T17:56:31.603 回答