0

构建一个表单以让用户提交帖子和图像。我的模型有一个文本字段、图像、发布日期和作者字段。发布日期和作者自动保存,无需任何用户输入。它使用 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 %}
4

1 回答 1

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))
于 2012-10-31T21:03:15.430 回答