Reputation: 77
I am writing the create method for a post, which belongs to a group and a user. I keep getting this error, although this is how it's done in the documentation and every other source i've looked at. here are the relevant files:
models.py
from django.db import models
from django.contrib.auth.models import User, Group
class Post(models.Model):
title = models.CharField(max_length=255, unique=True)
body = models.TextField()
likes_total = models.IntegerField(default=0)
pub_date = models.DateTimeField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
def __str__(self):
return self.name
def summary(self):
# return the 1st 100 chars
return self.body[:100]
def pub_date_pretty(self):
# strftime is how to break down time
return self.pub_date.strftime('%b %e %Y')
posts.urls.py
from . import views
from django.urls import path
app_name = 'posts'
urlpatterns = [
path('create/<int:group_id>/', views.create, name='create'),
]
posts.views.py
def create(request, group_id):
group = get_object_or_404(Group, pk= group_id)
if request.method == 'POST':
if request.POST['body']:
post = Post()
post.title = request.POST['title']
post.body = request.POST['body']
post.pub_date = timezone.datetime.now()
post.author = request.user
post.group = group
post.save()
return redirect('/groups/' + str(group_id))
else:
return render(request, 'groups/detail.html', {'group':group})
else:
return render(request, 'groups/detail.html', {'group':group})
the error is thrown when I am saving the group to the post (post.group = group), although this the method that ive learned. Hope someone can figure this out. thanks!!
Upvotes: 1
Views: 693
Reputation: 31474
You seem to have mixed up two different Group
models. In your model you have:
from django.contrib.auth.models import User, Group
and in your view you have:
from groups.models import Group
These are completely different classes, which is why you get an error telling you that you can't assign groups.models.Group
to what should be a auth.models.Group
.
I'm not sure which you intend it to be, but you need to use the same class in both places.
Upvotes: 4