Foreignkey get avatar - python

I am learning how to build a Learning management system and I am having trouble trying to attach a users avatar to any posted comments they make.
Any direction/help would be really appreciated.
So I have a Profile model and a Comment model and I have added a Foreignkey to the Profile model in my Comment model. How can I get the users avatar from the Profile model and render this in the comments box in HTML?
Here are my models:
class Comment(models.Model):
course = models.ForeignKey(Course, related_name='comments', on_delete=models.CASCADE)
user_avatar = models.ForeignKey(Profile, null=True, related_name="comments", on_delete=models.CASCADE)
lesson = models.ForeignKey(Lesson, related_name='comments', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE)
class Profile(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
name = models.CharField(max_length=100, blank=True, null=True)
occupation = models.CharField(max_length=100, blank=True, null=True)
residence = models.CharField(max_length=100, blank=True, null=True)
active_id = models.BooleanField(default=True)
avatar = models.ImageField(null=True, blank=True, upload_to ='uploads/profile_pics/',default='uploads/default.jpg')
and my views.py:
#api_view(['POST'])
def add_comment(request, course_slug, lesson_slug, pk):
data = request.data
name = data.get('name')
content = data.get('content')
course = Course.objects.get(slug=course_slug)
lesson = Lesson.objects.get(slug=lesson_slug)
profile = Profile.objects.get(id=pk)
comment = Comment.objects.create(course=course, lesson=lesson, name=name, content=content, user_avatar=request.profile, created_by=request.user)
serializer = CommentsSerializer(comment)
return Response(serializer.data)
serializers.py:
class CommentsSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('id', 'name', 'content', 'created_at', 'user_avatar', 'created_by')

Related

How to get username field automatically in Django

I am working on a Django project which is something similar to Fiverr in its working. I have used abstractuser where there is a buyer and seller. The seller creates a gig then the buyer will go through the gig before placing an order. My issue is how to get the seller and place him in the order that the buyer will create from reading the gig. Currently I am using the system whereby the buyer will have to manually choose a gig from a list, which I think is not effective.
Here is my Models.py
`class User(AbstractUser):
is_buyer=models.BooleanField(default=False)
is_seller=models.BooleanField(default=False)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(default='avatar.jpg', null=True, blank=True)
about = models.CharField(max_length=100)
def __str__(self):
return self.user.username
class Gig(models.Model):
seller = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False)
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500, null=True, blank=True)
gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Order(models.Model):
buyer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False)
seller = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='+', null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500)
amount = models.IntegerField(max_length=50, blank=False)
is_ordered = models.BooleanField(default=False)
order_id = models.UUIDField(default=uuid.uuid4, unique=True, db_index=True, editable=False)
slug = models.SlugField(null=True)
def __str__(self):
return self.title`
And views.py where I am getting the submissions;
def createOrder(request):
profile = request.user.profile
form = CreateOrderForm()
if request.method == 'POST':
form = CreateOrderForm(request.POST, request.FILES)
if form.is_valid:
order = form.save(commit=False)
order.buyer = profile
order.save()
# form.save()
messages.info(request, 'Order Succesfully Created')
return redirect('create_order')
else:
messages.error(request, 'Order Not Created! Try Again Later')
context = {'form':form}
return render(request, 'users/create_order.html', context)
Any help will he highly appreciated.

Cannot assign "'1'": "Groups.profile" must be a "Profile" instance

I have Profile Model that have instance model user.. I am trying to create group using form. that group model have Profile model as instance, so how do I select authenticated user automatic to create group, I getting confused...
This is my Group Model
class Groups(models.Model):
profile = models.ForeignKey(Profile, related_name='my_groups', on_delete=models.CASCADE)
groups_name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150, unique=True)
cover_pic = models.ImageField(upload_to='images/groups/', null=True, blank=True)
type_group = models.CharField(max_length=150)
created_date = models.DateTimeField(auto_now_add=True)
about_group = models.TextField(max_length=600)
members = models.ManyToManyField(Profile,through="GroupMember")
def __str__(self):
return self.groups_name
This is my profile Model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
slug = models.SlugField(max_length=100, unique=True)
profile_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True)
cover_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True)
user_bio = models.TextField(null=True,blank=True, max_length=255)
designation = models.CharField(blank=True,null=True, max_length=255)
education = models.CharField(blank=True, null=True, max_length=255)
marital_status = models.CharField(blank=True, null=True, max_length=60)
hobbies = models.CharField(blank=True, null=True, max_length=500)
location = models.CharField(blank=True, null=True, max_length=500)
mobile = models.IntegerField(blank=True, null=True)
def __str__(self):
return str(self.user)
This is form for create group
class GroupCreateForm(forms.ModelForm):
class Meta:
model = Groups
fields = ('cover_pic', 'profile', 'groups_name', 'type_group', 'about_group')
profile = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control input-group-text',
'value':'',
'id':'somesh',
'type': 'hidden',
}))
This is create group html file
this is html page
this is error..
You have set a CharField for profile in your form. When you send data to this form, it tries to make a Group record with a FK to a CharField for example "1" and this gives you error because you should pass Profile object to Group.
Depends on what exactly you want, there are some options.
You can use ModelChoiceField. Read about it in https://docs.djangoproject.com/en/3.2/ref/forms/fields/#django.forms.ModelChoiceField
Or you can use Inline FormSet and read about it in https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets
And an example for Inline FormSet in Creating a model and related models with Inline formsets

How to nest these Serializes without facing AttributeError: 'BlogPost' object has no attribute 'review_set'

I followed Dennis Ivy proshop Tutorial He used the same approach as the code is
class ReviewSerializer(serializers.ModelSerializer):
class Meta:
model = Review
fields = '__all__'
class ProductSerializer(serializers.ModelSerializer):
reviews = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Product
fields = '__all__'
def get_reviews(self, obj):
reviews = obj.review_set.all()
serializer = ReviewSerializer(reviews, many=True)
return serializer.data
Now I need a Blog for the eCommerce Project and I created another app named blog and Created the models as
class BlogPost(models.Model):
_id = models.AutoField(primary_key=True, editable=False)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
title = models.CharField(max_length=200, null=True, blank=True, help_text="Like How To Treat Hypertension etc")
image = models.ImageField(null=True, blank=True,
default='/placeholder.png')
rating = models.DecimalField(
max_digits=7, decimal_places=2, null=True, blank=True)
numReviews = models.IntegerField(null=True, blank=True, default=0)
createdAt = models.DateTimeField(auto_now_add=True)
youtubeVideoLink = models.CharField(max_length=1000, null=True , blank=True)
def __str__(self):
return str(self.createdAt)
class BlogPostReview(models.Model):
blogpost = models.ForeignKey(BlogPost, on_delete=models.SET_NULL, null=True)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=200, null=True, blank=True)
rating = models.IntegerField(null=True, blank=True, default=0)
comment = models.TextField(null=True, blank=True)
createdAt = models.DateTimeField(auto_now_add=True)
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return str(self.rating)
But when I serialize them via same approach as mentioned above....
class BlogPostReviewSerializer(serializers.ModelSerializer):
class Meta:
model = BlogPostReview
fields = '__all__'
class BlogPostSerializer(serializers.ModelSerializer):
blog_post_reviews = serializers.SerializerMethodField(read_only=True)
class Meta:
model = BlogPost
fields = '__all__'
def get_blog_post_reviews(self, obj):
blog_post_reviews = obj.review_set.all()
serializer = BlogPostReviewSerializer(blog_post_reviews, many=True)
return serializer.data
This error comes
in get_blog_post_reviews
blog_post_reviews = obj.review_set.all()
AttributeError: 'BlogPost' object has no attribute 'review_set'
How to solve this problem or what I'm doing wrong and what need to be fixed. What would be another apporach obv there would be.... And I don't know why Dennis Ivy used review_set in his code. If someone know why we use _set and what are the circumstances please let me know.
The simplest solution is to update your get_blog_post_reviews method:
def get_blog_post_reviews(self, obj):
blog_post_reviews = obj.blogpostreview_set.all() # <- this line has changed
serializer = BlogPostReviewSerializer(blog_post_reviews, many=True)
return serializer.data
The original worked because there was a model named Review, so the automatically created reverse name was review_set. Your model is named BlogPostReview, so the reverse is blogpostreview_set.
More information about reverse relationships in the docs.

NameError: name 'Profile' is not defined

here is my models.py code. im trying to run the python3.8 manage.py migrate command to create the tables for the database but i keep getting this error, what could be the issue here. Profile is a class in the models.py code. if you need another part of my code please ask
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Image(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null='True', blank=True)
image = models.ImageField(upload_to = 'pics/')
name = models.CharField(max_length=50,blank=True)
caption = models.CharField(max_length=250, blank=True)
likes = models.ManyToManyField(User, related_name='likes', blank=True, )
date_posted = models.DateTimeField(default=timezone.now)
class Comment(models.Model):
comment = models.TextField()
image = models.ForeignKey('Image', on_delete=models.CASCADE,related_name='comments',null='True', blank=True )
name = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments',null='True', blank=True )
created = models.DateTimeField(auto_now_add=True, null=True)
class Profile(models.Model):
name = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='images/', default='default.png')
bio = models.TextField(max_length=500, default="My Bio", blank=True)
followers = models.ManyToManyField(User, related_name="followers", blank=True)
following = models.ManyToManyField(User, related_name="following", blank=True)
You are using the Profile class before defining it. Switch the order of the Comment class and Profile class. Like so:
class Profile(models.Model):
name = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='images/', default='default.png')
bio = models.TextField(max_length=500, default="My Bio", blank=True)
followers = models.ManyToManyField(User, related_name="followers", blank=True)
following = models.ManyToManyField(User, related_name="following", blank=True)
class Comment(models.Model):
comment = models.TextField()
image = models.ForeignKey('Image', on_delete=models.CASCADE,related_name='comments',null='True', blank=True )
name = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments',null='True', blank=True )
created = models.DateTimeField(auto_now_add=True, null=True)
You are referencing the Profile class before this is constructed. You can make use of a string literal instead:
class Comment(models.Model):
# …
user = models.ForeignKey(
'Profile', # &leftarrow; a string literal
on_delete=models.CASCADE,
related_name='comments',
null='True',
blank=True
)
# …
It might also be better to rename the field to profile, to make it clear the ForeignKey is referencing a Profile object, not a User object:
class Comment(models.Model):
# …
profile = models.ForeignKey( # &leftarrow; rename to profile
'Profile',
on_delete=models.CASCADE,
related_name='comments',
null='True',
blank=True
)
# …
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

integerity error in django(i think its about that new foregn key)

im have post model and a profile model on profile model i have a OneToOneField this is my profile model:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
GENDER_CHOICES = [('boy', 'پسر'), ('girl', 'دختر'), ('i prefer not to say', 'ترجیح میدهم نگویم')]
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='profile_pictures', blank=True, default='default.jpg')
name = models.CharField(max_length=30)
age = models.IntegerField(default="0")
birth_day = models.CharField(max_length=30)#DateField(blank=True)
gender = models.CharField(max_length=20, choices=GENDER_CHOICES)
address = models.CharField(max_length=30, blank=True, default="---")
bio = models.TextField(max_length=300, blank=True, default="---")
phone = models.IntegerField(blank=True, null=True)
skills = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorites = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorite_books = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorite_movies = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorite_musics = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorite_sports = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
and this is my post model:
from django.db import models
# from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse
from taggit.managers import TaggableManager
from user.models import Profile
class Post(models.Model):
STATUS_CHOICES = [('published', 'published'), ('draft', 'draft')]
title = models.CharField(max_length=60)
slug = models.CharField(max_length=120, unique=True)
image = models.ImageField(blank=True, upload_to="posts_images", null=True)
image_alt = models.CharField(max_length=35, blank=True, null=True)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
publish_date = models.DateTimeField(default=timezone.now)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published')
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
tags = TaggableManager()
published_manager = PublishedManager()
def __str__(self):
return self.title
class Meat:
ordering = ('-publish_date',)
def get_absolute_url(self):
return reverse('post:post_details', args=[self.slug,])
and i can change the previuos posts and save them but i can't add a new post get this error
IntegrityError at /admin/post/post/add/
NOT NULL constraint failed: post_post.owner_id
you can see that owner_id before i add the profile model i connect djangouser with a foregnkey with post model and its variable was 'owner' but now i deleted but i still get it's error and also when i migrated the new profile i get somethings like error but they was'nt error they was some things like warnings or something like that thanks for helping

Categories

Resources