如何在ModelForm中预填充字段

时间:2017-02-05 22:46:30

标签: python django django-forms django-views

这是我的<div class="parent" id="1"> Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum </div>模型,它构成了用户帖子的内容:

Post

这是我的表格:

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',
        ]

当用户提交def post(request): allauth_login = LoginForm(request.POST or None) allauth_signup = SignupForm(request.POST or None) form_post = PostForm(request.POST, 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) 提交帖子时,如何自动将PostForm字段设置为发帖人?

编辑:以下代码仍然提供user

TypeError at /post/ __init__() got an unexpected keyword argument 'user'

1 个答案:

答案 0 :(得分:1)

请求user。所以你可以写:

user=request.user

多数人

所以你的观点应该是这样的

def post(request):

    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)

    form_post = PostForm(request.POST, request.FILES, user=request.user)
    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)

UPD

仅在用户通过身份验证时才有效。要查看用户是否已通过身份验证,您可以在视图中添加@login_required装饰器,例如:

from django.contrib.auth.decorators import login_required
@login_required
def post(request):
  ...

此外,我认为你必须发表if声明,为经过身份验证的用户呈现页面,而不是。例如

if request.user.is_authenticated():
  form_post = PostForm(request.POST, request.FILES, user=request.user)
  if form_post.is_valid():
    ...
else:
  ..