ModelForm字段的初始值不起作用

时间:2017-02-06 05:18:57

标签: python django django-models django-forms

我要将None字段设置为登录用户,但它会返回class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=76) date = models.DateTimeField(auto_now=True) content = models.TextField(null=False, default='') image = models.FileField(null=True, blank=True) category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='1') 。这是我的模特:

class PostForm(forms.ModelForm):
    content = forms.CharField(widget=PagedownWidget)
    title = forms.TextInput(attrs={'placeholder': 'title'})

    class Meta:
        model = Post
        fields = [
            'title',
            'content',
            'category',
            'image',
            'id',
            'user'
        ]

我的表格:

def post(request):
    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)
    if request.user.is_authenticated():
        data = {'user': request.user}
        form_post = PostForm(request.POST, request.FILES, initial=data)
        if form_post.is_valid():
            category = form_post.cleaned_data['category']
            for a, b in CATEGORY_CHOICES:
                if a == category:
                    category = b
                    form_post.save()
            return HttpResponseRedirect('/%s' % category)
        else:
            form_post = PostForm()

        context = {
            'allauth_login': allauth_login,
            'allauth_signup': allauth_signup,
            'form_post': form_post
        }

        return render(request, 'post.html', context)
    else:
        return HttpResponseRedirect("/accounts/signup/")

以及用户使用表单发布帖子的视图:

{{ obj.user }}

当我在模板中实际呈现表单时,None会返回{% for obj in Post.objects.all() %} {{ obj.title }} #works {{ obj.content }} #works ... {{ obj.user }} #does not work {% endfor %} 。知道为什么吗?

    <div class="wrap">
    <div class="wrap">
    <div class="wrap">

2 个答案:

答案 0 :(得分:1)

您正在错误地初始化表单。如果请求方法不是POST表单将包含错误。

试试这个:

form_post = PostForm(request.POST or None, request.FILES or None, initial=data) 

<强>更新

您也可以尝试这样做。从表单中删除用户字段,然后在视图中执行以下操作:

if form_post.is_valid():
    instance = form_post.save(commit=False)
    instance.user = request.user
    instance.save()   

答案 1 :(得分:0)

我认为你混淆了initialbound form with data。在您的情况下,我猜测您是先尝试使用有效用户保存帖子,然后重定向到该页面以向用户显示新帖子。

所以它应该是:

def post(request):
    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)
    if request.user.is_authenticated():
        data = request.POST.copy()
        data['user'] = request.user
        form_post = PostForm(data, request.FILES)
        if form_post.is_valid():
            category = form_post.cleaned_data['category']
            for a, b in CATEGORY_CHOICES:
                if a == category:
                    category = b
                    form_post.save()
            return HttpResponseRedirect('/%s' % category)
        else:
            form_post = PostForm()

        context = {
            'allauth_login': allauth_login,
            'allauth_signup': allauth_signup,
            'form_post': form_post
        }

        return render(request, 'post.html', context)
    else:
        return HttpResponseRedirect("/accounts/signup/")

initial - These values are only displayed for unbound formshttps://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.initial