开发者

Django model automatically set fields

开发者 https://www.devze.com 2023-03-01 15:57 出处:网络
I have a form allowing users to post an article. The article table is ch开发者_开发问答ained with the users table so, I need to set the user_id field based on who\'s writing. Normally, django form wil

I have a form allowing users to post an article. The article table is ch开发者_开发问答ained with the users table so, I need to set the user_id field based on who's writing. Normally, django form will display a drop down to allow me to select the author but that's not the case for the user.

I have the following code:

if request.method == 'POST':
    ArticleForm = ArticleForm( request.POST )
    if ArticleForm.is_valid():
        article = ArticleForm.save ()
        return render( request, 'success.html' )
else:
    ArticleForm = ArticleForm()

return render( request, 'post.html', {'ArticleForm': ArticleForm} )

How do I set a field before validating the request which will fail in case not since certain fields are supposed to be set by the code and not based on request data?


Assuming that you are making sure the user is signed in.

models.py:

Article(models.Model):
    text = modesl.TextField()
    user = models.ForeignKey(User)

forms.py:

ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        exclude = ('user',)

views.py:

article = Article(user=request.user)   

if request.method == 'POST':
    form = ArticleForm(request.POST, instance=article)
    if form.is_valid():
        form.save()
        return HttpResponse('success')
else:
    form = ArticleForm(instance=article)

Another way to set data before saving is to use:

if form.is_valid():
    art = form.save(commit=False)
    art.user = request.user
    art.save()
    return HttpResponse('Success')
0

精彩评论

暂无评论...
验证码 换一张
取 消