Answer the question
In order to leave comments, you need to log in
Cannot assign "": "Blog.author" must be a "BlogAuthor" instance?
Hello! I want to add an article, I get the error Cannot assign ">": "Blog.author" must be a "BlogAuthor" instance?.
If you do not refer to the BlogAuthor model in Blog.author, but directly to the User everything works, you can add articles, but another error is displayed Cannot query "sk": Must be "User" instance.
How to link models so that there are no errors and everything works? models.py
code
class BlogAuthor(models.Model):
"""
Model representing a blogger.
"""
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
bio = models.TextField(max_length=400, help_text="Enter your bio details here.")
class Meta:
ordering = ["user", "bio"]
def get_absolute_url(self):
"""
Returns the url to access a particular blog-author instance.
"""
return reverse('blogs-by-author', args=[str(self.id)])
def __str__(self):
"""
String for representing the Model object.
"""
return self.user.username
class Blog(models.Model):
"""
Model representing a blog post.
"""
name = models.CharField(max_length=200)
author = models.ForeignKey(BlogAuthor, on_delete=models.SET_NULL, null=True)
# Foreign Key used because Blog can only have one author/User, but bloggsers can have multiple blog posts.
description = models.TextField(max_length=2000, help_text="Enter you blog text here.")
post_date = models.DateField(default=date.today)
class Meta:
ordering = ["-post_date"]
def get_absolute_url(self):
"""
Returns the url to access a particular blog instance.
"""
return reverse('blog-detail', args=[str(self.id)])
def __str__(self):
"""
String for representing the Model object.
"""
return self.name
class BlogListbyAuthorView(generic.ListView):
"""
Generic class-based view for a list of blogs posted by a particular BlogAuthor.
"""
model = Blog
paginate_by = 5
template_name = 'blog/blog_list_by_author.html'
def get_queryset(self):
"""
Return list of Blog objects created by BlogAuthor (author id specified in URL)
"""
id = self.kwargs['pk']
target_author = get_object_or_404(BlogAuthor, pk=id)
return Blog.objects.filter(author=target_author)
def get_context_data(self, **kwargs):
"""
Add BlogAuthor to context so they can be displayed in the template
"""
# Call the base implementation first to get a context
context = super(BlogListbyAuthorView, self).get_context_data(**kwargs)
# Get the blogger object from the "pk" URL parameter and add it to the context
context['blogger'] = get_object_or_404(BlogAuthor, pk=self.kwargs['pk'])
return context
class BlogCreate(LoginRequiredMixin, CreateView):
model = Blog
fields = ['name', 'description']
template_name = 'blog/blog_edit.html'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question