Here's my Post model which makes up the contents of a user's 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')
Here's my form:
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',
]
And here's my view:
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)
When the user submits the PostForm to submit a post, how do I automatically set the user field to whoever is posting?
Edit: The following code still gives a TypeError at /post/ __init__() got an unexpected keyword argument 'user'
def post(request):
allauth_login = LoginForm(request.POST or None)
allauth_signup = SignupForm(request.POST or None)
if request.user.is_authenticated():
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)
else:
return HttpResponseRedirect("/accounts/signup/")