0

I am new to django and am stuck at a very basic level. I want to create a model that stores the article posted by the the user. In the model I am able to save my article but how can I save the user id in that model. On submitting this form only the title and body are saved.

My models.py file is as follows:

class Article(models.Model):
    Title = models.CharField(max_length=169)
    Body = models.TextField()
    Author_id = models.CharField(max_length=3)

    def __unicode__(self):
        return self.Title

My forms.py is as follows:

class AddArticle(forms.ModelForm):

    class Meta:
        model = Article
        fields = ('Title', 'Body')

and my views.py is:

def UploadArticle(request):
    if request.POST:
        form = AddArticle(request.POST)
        if form.is_valid():
            Article.Author_id = request.user.id #I guess my mistake lies here, but how to avoid it
            form.save()
            return HttpResponseRedirect('/articles/all')
        else:
            form = AddArticle()

    args = {}
    args.update(csrf(request))
    args['form']=AddArticle()
    return render_to_response('add.html', args)

Any help please

2 Answers 2

1

Change Author_id = models.CharField(max_length=3) to Author = models.ForeignKey(User)

Then do what dm03514 is suggesting

Sign up to request clarification or add additional context in comments.

Comments

0

get the article instance first, commit explained in docs

article = form.save(commit=False)

then assign the author

article.Author = request.user 

creating an Author field will automatically create an Author_id field in your table. I think if you create your field named Author_id it could create an Author_Id_id field? It's safer in some ways to work with objects ie 'User' instance then it is to work with integers ie user.id

article.save()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.