用户不会在View中自动保存,但会在Admin中保存

时间:2012-10-31 20:39:25

标签: python html django django-forms views

构建表单以允许用户提交帖子和图片。我的模型有文本字段,图像,发布日期和作者字段。发布日期和作者自动保存,无需任何用户输入。它在管理员端使用admin.py。但是,通过视图显示时,它不起作用。为什么呢?

#models.py
    class Question(models.Model):
    text            = models.CharField(max_length = 500)
    image           = models.ImageField(upload_to = 'movie_poster')
    pub_date        = models.DateTimeField(auto_now_add = True)
    author          = models.ForeignKey(User)

    def __unicode__(self):
        return self.title

    class QuestionForm(ModelForm):
        class Meta:
             model = Question
             exclude = ('author', 'pub_date')
#views.py
def add_question(request):
     def save_model(self, request, obj, form, change):
        obj.author = request.user
        obj.save()
     if request.method == "POST":
        form = QuestionForm(request.POST, request.FILES)   
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/home/")
    else:
        form = QuestionForm
        return render_to_response("qanda/add_question.html", {'form': form}, context_instance = RequestContext(request))

#add_question.html
{% block content %}

<div class="loginform">
    <h1> Add Movie:</h1>
    <form enctype = "multipart/form-data" action = "" method = "post">{% csrf_token %}
        {{ form.as_p }}
        <input type = "submit" value = "Add" />
        <input type = "hidden" name = "next" value = "{{ next|escape }}" />
    </form>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

save_model并不是因为在那里无处不在的魔法。我们需要自定义表单:

class QuestionForm(ModelForm):
    def save(self, user=None, force_insert=False, force_update=False, commit=True):
        q = super(QuestionForm, self).save(commit=False)
        q.author = user
        if commit:
            q.save()
        return q

    class Meta:
        model = Question
        exclude = ('author', 'pub_date')

def add_question(request):
    if request.method == "POST":
        form = QuestionForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(user=request.user)
            return HttpResponseRedirect("/home/")
    else:
        form = QuestionForm()
        return render_to_response("qanda/add_question.html", {'form': form}, context_instance=RequestContext(request))