How i can add like on product page - python

I can like my products from admin panel,and i want to add posibility to like them by url products/item/like,i have view of like but i dont know what i should add to there.This is my views.py
class LikeToggleView(AjaxResponseMixin, JSONResponseMixin, FormView):
http_method_names = ('post',)
form_class = LikeForm
product = None
#csrf_exempt
def dispatch(self, request, *args, **kwargs):
product_id = kwargs['product_pk']
try:
self.product = Product.objects.get(id=product_id)
except Product.DoesNotExist:
raise Http404()
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
pass
this is forms.py
class LikeForm(forms.ModelForm):
user = forms.ModelChoiceField(User.objects.all(), required=False)
product = forms.ModelChoiceField(Product.objects.all())
ip = forms.GenericIPAddressField(required=True)
this is models.py
class Like(TimeStampedModel):
product = models.ForeignKey(Product, related_name='likes')
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='likes')
ip = models.GenericIPAddressField(blank=True, null=True)
class Meta:
unique_together = (('product', 'user'), ('product', 'ip'))
def __str__(self):
return '{} from {}'.format(self.product, self.user or self.ip)

Related

I want to restrict a particular user from creating a saved class object if the current user id is different from the id in the live class object

My models.py
from django.db import models
from django.contrib.auth.models import User
import datetime
from django.utils import timezone
# Create your models here.
class LiveClass(models.Model):
standard = models.IntegerField()
no_of_students_registered = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'Class'
def __str__(self):
return str(self.standard) + ' class'
class User_details(models.Model):
name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30)
standard = models.IntegerField(default=0)
email = models.EmailField()
mobile_number = models.IntegerField()
class Meta:
verbose_name_plural = 'User_details'
def __str__(self):
return str(self.name)
class Mentor(models.Model):
name = models.CharField(max_length=30)
details = models.TextField()
ratings = models.FloatField(default=2.5)
class Meta:
verbose_name_plural = 'Mentors'
def __str__(self):
return self.name
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_name = models.CharField(max_length=30)
chapter_details = models.TextField()
mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
class_time = models.DateTimeField()
end_time = models.DateTimeField(default=timezone.now())
isDoubtClass = models.BooleanField(default=False)
doubtsAddressed = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
def __str__(self):
return self.chapter_name
class SavedClass(models.Model):
class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
is_registered = models.BooleanField(default=False)
is_attended = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'SavedClasses'
def __str__(self):
return 'SavedClass : ' + str(self.class_details)
my views.py
from django.shortcuts import render
from rest_framework import mixins
from rest_framework import generics
from django.contrib.auth.mixins import LoginRequiredMixin
from rest_framework import status
from django.contrib.auth.models import User
from rest_framework.response import Response
from django.contrib.auth import authenticate
from . import serializers
from . import models
# Create your views here.
class ListLiveClass(mixins.ListModelMixin, LoginRequiredMixin, generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class LiveClassView(mixins.ListModelMixin,
mixins.CreateModelMixin,
LoginRequiredMixin,
generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
if request.user.is_superuser:
return self.create(request, *args, **kwargs)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
class LiveClassViewId(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
LoginRequiredMixin,
generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
lookup_field = 'id'
def get(self, request, id=None, format=None):
if id:
return self.retrieve(request)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
def put(self, request, id, format=None):
if request.user.is_superuser:
return self.update(request, id)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
def delete(self, request, id, format=None):
if request.user.is_superuser:
return self.destroy(request, id)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
class ListMentors(mixins.ListModelMixin, LoginRequiredMixin, generics.GenericAPIView):
queryset = models.Mentor.objects.all()
serializer_class = serializers.Mentor_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class ListUserDetails(mixins.ListModelMixin, LoginRequiredMixin, generics.GenericAPIView):
queryset = models.User_details.objects.all()
serializer_class = serializers.User_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
#api endpoints to save and register live classes
class SavedClassView(LoginRequiredMixin, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
serializer_class = serializers.SavedClass_serializer
def get_queryset(self):
user = self.request.user
return models.SavedClass.objects.filter(user=self.request.user.id)
def get(self, request):
return self.list(request)
def post(self, request):
cur_user = self.get_object()
#return self.create(request)
return Response(status=status.HTTP_403_FORBIDDEN)
my serializers.py
from rest_framework import serializers
from . import models
class LiveClass_serializer(serializers.ModelSerializer):
class Meta:
model = models.LiveClass
fields = '__all__'
class SavedClass_serializer(serializers.ModelSerializer):
class Meta:
model = models.SavedClass
fields = '__all__'
class User_details_serializer(serializers.ModelSerializer):
saved_class = SavedClass_serializer()
class Meta:
model = models.User_details
fields = '__all__'
class LiveClass_details_serializer(serializers.ModelSerializer):
class Meta:
model = models.LiveClass_details
fields = '__all__'
class Mentor_serializer(serializers.ModelSerializer):
class Meta:
model = models.Mentor
fields = '__all__'
In savedClass view in GET request i am rendering all the savedClass Model wherever user in the model matches with the current user , now in POST request i want to create the savedclass row only for the current user and forbids the user from creating a view with different user id
I also needs help in my SavedClass model where whether a user is registered or not can only be decided by the admin
I tries different possible things but not able to do it, i am new to Django so needs help
You can get the logged in user from request.user so something like this should work
def post(self, request):
cur_user = request.user
if cur_user.id == request.data.user:
return self.create(request)
return Response(status=status.HTTP_403_FORBIDDEN)
assuming that only logged in users can call this api

UNIQUE constraint failed: groups_groupmember.group_id, groups_groupmember.user_id

I am working on small django project and for that i have created one functionality that allows user to create and then join the group.
Now , here is the problem :
whenever i leave the group and try to rejoin it , it shows error that i mentioned in the the question
"UNIQUE constraint failed: groups_groupmember.group_id, groups_groupmember.user_id"
here is my join class :
class JoinGroup(LoginRequiredMixin, generic.RedirectView):
def get_redirect_url(self, *args, **kwargs):
return reverse('groups:single', kwargs={'slug': self.kwargs.get('slug')})
def get(self, request, *args, **kwargs):
group = get_object_or_404(Group, slug=self.kwargs.get('slug'))
from sqlite3 import IntegrityError
try:
# GroupMember.objects.create(group=group)
GroupMember.objects.create(user=self.request.user, group=group)
except IntegrityError:
messages.warning(self.request, 'already a member!')
else:
messages.success(self.request, 'You are now a member!')
return super().get(request, *args, **kwargs)
Here is my models.py
from django.db import models
from django.utils.text import slugify
from django.urls import reverse
# Create your models here.
# GROUPS MODELS.PY
import markdown
from django.contrib.auth import get_user_model # returns user model that currently active in this project
User = get_user_model()
from django import template
register = template.Library()
class Group(models.Model):
name = models.CharField(max_length=256, unique=True)
slug = models.SlugField(allow_unicode=True, unique=True)
description = models.TextField(blank=True, default='')
description_html = models.TextField(editable=False, default='', blank=True)
members = models.ManyToManyField(User, through='GroupMember')
def __str__(self):
return self.name
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
self.description_html = markdown.markdown(self.description)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse('groups:single', kwargs={'slug': self.slug})
class Meta:
ordering = ['name']
class GroupMember(models.Model):
group = models.ForeignKey(Group, related_name='memberships', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Meta:
unique_together = ('group', 'user')
Can you please help me to solve this problem ? Thank you ! :)
How about use get_or_create
class JoinGroup(LoginRequiredMixin, generic.RedirectView):
def get_redirect_url(self, *args, **kwargs):
return reverse('groups:single', kwargs={'slug': self.kwargs.get('slug')})
def get(self, request, *args, **kwargs):
group = get_object_or_404(Group, slug=self.kwargs.get('slug'))
_, created = GroupMember.objects.create(user=request.user, group=group)
if not created:
messages.warning(request, 'already a member!')
else:
messages.success(request, 'You are now a member!')
return super().get(request, *args, **kwargs)

How can I make only superusers to edit model

I have 2 models: Recipe and Ingridient and I want that only superusers will be able to edit model Ingridient, normal users can only view ingridients and are not able to edit them. Right now is set that way that if you are logged in you have all permissions, but I want that only superusers have ability to edit Ingridients and normal logged in users are able to add recipes (not able to edit ingridients).
#views.py
class ReceptViewRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
queryset = Recipe.objects.all()
lookup_field = 'id'
serializer_class = RecipeSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def delete(self, request, *args, **kwargs):
try:
id = request.data.get('id', None)
response= super().delete(request, *args, **kwargs)
if response.status_code == 204:
from django.core.cache import cache
cache.delete("{}".format(id))
return response
except Exception as e:
return response({
"Message":"Failed"
})
def update(self, request, *args, **kwargs):
response = super().update(request, *args, **kwargs)
if response.status_code == 200:
mydata = response.data
from django.core.cache import cache
cache.set("ID :{}".format(mydata.get('id', None)),{
'title':mydata["title"],
'description':mydata["description"],
'image':mydata["image"],
'galery':mydata["galery"],
'kitchen_type':mydata["kitchen_type"],
'num_persons':mydata["num_persons"],
'preparation_steps':mydata["preparation_steps"]
})
return response
class SestavinaViewRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView):
queryset = Ingridient.objects.all()
lookup_field = 'id'
serializer_class = IngridientSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def delete(self, request, *args, **kwargs):
try:
id = request.data.get('id', None)
response= super().delete(request, *args, **kwargs)
if response.status_code == 204:
from django.core.cache import cache
cache.delete("{}".format(id))
return response
except Exception as e:
return response({
"Message":"Failed"
})
def update(self, request, *args, **kwargs):
response = super().update(request, *args, **kwargs)
if response.status_code == 200:
mydata = response.data
from django.core.cache import cache
cache.set("ID :{}".format(mydata.get('id', None)),{
'name':mydata["name"],
'quantity':mydata["quantity"],
'calories':mydata["calories"],
'protein':mydata["protein"],
'carbon':mydata["carbon"],
'fiber':mydata["fiber"],
'fat':mydata["fat"],
'saturated_fat':mydata["saturated_fat"]
})
return response
class RecipeListView(generics.ListCreateAPIView):
model = Recipe
serializer_class = RecipeSerializer
queryset = Recipe.objects.all()
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
class IngridientsListView(generics.ListCreateAPIView):
model = Ingridient
serializer_class = IngridientSerializer
queryset = Ingridient.objects.all()
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
#models.py
class Ingridient(models.Model):
name = models.CharField(default='', max_length=20)
quantity = models.IntegerField(default=0)
calories = models.IntegerField(default=0)
protein = models.IntegerField(default=0)
carbon = models.IntegerField(default=0)
fiber = models.IntegerField(default=0)
fat = models.IntegerField(default=0)
saturated_fat = models.IntegerField(default=0)
def __str__(self):
return self.name
class Recipe(models.Model):
title = models.CharField(default='', max_length=60)
description = models.TextField(default='',max_length=1000)
image = models.ImageField(default='',upload_to='pics', blank=True)
galery = models.ImageField(default='', blank=True)
kitchen_type = models.CharField(default='',max_length=35)
num_persons = models.IntegerField(default=0)
preparation_steps = models.TextField(default='')
Ingridients = models.ManyToManyField(Ingridient)
def __str__(self):
return self.title
#serializers.py
class IngridientSerializer(serializers.ModelSerializer):
class Meta:
model = Ingridient
fields = ('name', 'quantity', 'calories', 'protein', 'carbon', 'fiber', 'fat',
'saturated_fat')
class RecipeSerializer(serializers.ModelSerializer):
Ingridients = IngridientSerializer(many=True)
class Meta:
model = Recipe
fields = ('title', 'description', 'image', 'galery', 'kitchen_type', 'num_persons',
'preparation_steps', 'Ingridients')
If you're willing to set up Django model permissions for your Ingredient model instead (i.e. add an "Ingredient Editors" group, and add all superusers to that group, then allow those users to edit Ingredients), you can use the DjangoModelPermissions permissions class instead of IsAuthenticatedOrReadOnly.
If you really do simply want to give all superusers write permissions, you can adapt DRF's IsAuthenticatedOrReadOnly permission class
to something like
class IsAdminOrReadOnly(BasePermission):
def has_permission(self, request, view):
return bool(
request.method in SAFE_METHODS or
request.user and
request.user.is_superuser
)
and then use that permission class instead.

How to display a current user only in django user form

class Book(models.Model):
description = models.CharField(max_length=10)
pdf = models.FileField(upload_to='books/pdfs/')
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.description
def delete(self, *args, **kwargs):
self.pdf.delete()
super().delete(*args, **kwargs)
#forms.py
class BookForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(BookForm, self).__init__(*args, **kwargs)
class Meta:
model = Book
fields = ('description', 'pdf', 'user')
When i run an application it shows all the users, I want to restrict to only current user who is logged in.

How to get ChoiceField data based on current user

I have a model StaffProfile.while creating a form for Visiti want to get staff_user data(Based on current user) to that ChoiceField (to_meet).
models.py
class StaffProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
related_name="user_profile")
staff_user = models.ManyToManyField(User, null=True, blank=True,
related_name="staff_user")
class Visit(models.Model):
name = models.CharField(max_length=200, name="name")
gender = models.CharField(choices=GENDER_CHOICE, max_length=1, name="gender")
mobile = models.CharField(max_length=18, default="", name="mobile")
to_meet = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py
class VisitForm(forms.ModelForm):
to_meet = forms.ChoiceField(choices=[], required=False, label="Select Staff")
class Meta:
model = Visit
fields = ("__all__")
def __init__(self, *args, **kwargs):
super(VisitForm, self).__init__(*args, **kwargs)
self.fields['to_meet'].choices = StaffProfile.objects.filter(user=request.user).values_list("staff_user")
Initially override the __init__() method of your view
class VisitForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(VisitForm, self).__init__(*args, **kwargs)
self.fields['to_meet'].choices = [self.request.user]
to_meet = forms.ChoiceField(choices=[], required=False, label="Select Staff")
class Meta:
model = Visit
fields = "__all__" # small typo here
Then, in your view,
def foo_view(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = VisitForm(request.POST,request=request)
# check whether it's valid:
if form.is_valid():
# do somrthing
.....
You need to pass the request from view to form. For example:
def some_view(request):
form = VisitForm(request=request)
# rest of the code
and use it in the form:
def __init__(self, *args, **kwargs):
request = kwargs.pop('request')
super(VisitForm, self).__init__(*args, **kwargs)
self.fields['to_meet'].choices = StaffProfile.objects.filter(user=request.user).values_list("staff_user")

Categories