Issue
Something is wrong with my method, assign_article_creator. It's supposed to populate the field, custom_user, with the username (email address) of the logged-in user/author, so that the author is associated with any article that they create. But it's not working. In Django Admin, the field custom_user is populated with '----' when an author creates an article. Please help me. Thank you.
models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
class Articles(models.Model):
custom_user = models.ForeignKey(CustomUser, default=None, null=True,
on_delete=models.SET_NULL)
views.py
class CreateArticle(LoginRequiredMixin, CreateView):
model = Articles
form_class = ArticleForm
template_name = "users/add_article.html"
def assign_article_creator(self, request):
if request.method == 'POST':
form = self.form_class(request, data=request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.custom_user = request.user
instance.save()
return render(request=request,
template_name ="users/add_article.html", context={"form":
form})
Solution
When you extend CreateView
, you can't add just any method name you want to the class and expect it to work automatically. Instead, you need to override post()
with the custom logic to assign custom_user
. (You may want to name this author
instead.) You can also leverage super().post()
to do most of the work for you. Note that when you override post()
, you don't need if request.method == 'POST':
because CreateView
already does that for you.
Answered By - Code-Apprentice
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.