Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display multiple views in a Django project's template?
I have a Django project with multiple apps and I would like to manage the template from the project root folder. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', "DIRS": [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': {...} }] In the homepage index.html of the project I'm trying to display num_exchanges and num_accounts generated in the views.py of app1 and app2. The problem is that only num_exchanges is printed not the second variable. If I switch the include in urlpatterns then the second variable is generated not the first one. How can I print both variables ? urls.py (project) urlpatterns = [ path('admin/', admin.site.urls), url(r"^", include("app1.urls"), name='app1'), url(r"^", include("app2.urls"), name='app2'), ] index.html (project) {% load static %} {% block content %} <h2>App1</h2> <p>Records in database:</p> <ul> <li><strong>Exchanges:</strong> {{ num_exchanges }}</li> </ul> <h2>App2</h2> <p>Records in database:</p> <ul> <li><strong>Account:</strong> {{ num_accounts }}</li> </ul> {% endblock %} views.py (app1) from django.shortcuts import render from app1.models import Exchange def app1_stats(request): num_exchanges = Exchange.objects.count() context = { 'num_exchanges': num_exchanges } return render(request, 'index.html', context=context) urls.py (app1) from django.urls import path from app1.views import app1_stats urlpatterns = [ path('', app1_stats, name='index'), ] views.py (app2) from django.shortcuts import render from app2.models import Account def app2_stats(request): num_accounts = Account.objects.count() context = { … -
own authenticate backend django
i want to do an authenticate backend to authenticate users that i've in a web services but i don't have a class user, so how can i do this backend to authenticate the users that i try to login ? i have this function to consumed the web services: def web_service (): user = request.POST['username'] passwd = request.POST['password'] result = cliente.service.execute('{\ "user":"portalServicios",\ "password":"pechuga",\ "object":"user",\ "command":"authenticate",\ "login":"'+ user +'",\ "pass":"'+ passwd +'"\ }') result_dict = json.loads(result) -
How to get POST and create message using DetailView on Django
I have Post model and Message model. I want to create message on one post and preview it message. I can't think of how I can do this using DetailView Class. How can I do this? All my code models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) body = models.TextField() date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] views.py class PostDetailView(DetailView): model = Post def post(self, request, *args, **kwargs): message = Message( user = request.user, post = self.post, body = request.POST.get('body') ) message.save() return super(PostDetailView,self).post(request, *args, **kwargs) -
Create a model object when creating a user in Django, UNIQUE constraint failed
I have this model: class Family(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, unique=False) def __str__(self): return self.name class Meta: ordering = ['name'] And I am also using this function to create a family object when a user is created: @receiver(models.signals.post_save, sender=User) def user_created(sender, instance, created, **kwargs): if created: Family.objects.create(user=instance) I have a couple questions: I am getting an django.db.utils.IntegrityError: UNIQUE constraint failed: family_tree_family.name error, how to resolve it? How to use the **kwargs in user_created function. I create users using curl. -
Debugging an elusive edge case where browser reloads randomly
I've spent weeks trying to figure out this bug. My app has a client where a specific page will reload after she's spent some time filling in new information in a form. I can't figure out any reason for the page to reload. There are no error messages. Nothing is being captured in Sentry. So I can't reproduce locally. How do I even start going about this... could I do some sort of context capture when listening to the page reloading event? As I'm not aware of any captured necessary information I'm not even sure what do send to sentry. I'll try and save the unsaved data to local storage. But... any ideas on how to go about this is much appreciated. -
NameError: name 'mark_safe' is not defined (Django)
I have this code below in "admin.py": # "admin.py" class AdminImageWidget(AdminFileWidget): def render(self, name, value, attrs=None, renderer=None): output = [] if value and getattr(value, "url", None): image_url = value.url file_name = str(value) output.append( f'<a href="{image_url}" target="_blank">' f'<img src="{image_url}" alt="{file_name}" width="150" height="150" ' f'style="object-fit: cover;"/> </a>') output.append(super(AdminFileWidget, self).render(name, value, attrs, renderer)) return mark_safe(u''.join(output)) Then, I got this error below: NameError: name 'mark_safe' is not defined So, I want to import "mark_safe" but I don't know where I can get the "mark_safe" from: from <I don't know> import mark_safe Where can I get "mark_safe" from? -
Getting ERROR:500 while adding multiple objects in modelviewset
I need to add multiple users using modelviewset but i got status code 500 i did some research but it seems not working, i did overwrite the create method with many=True, and also in serializer i did overwrite init function Here is my view.py; class StudentView(viewsets.ModelViewSet): serializer_class = StudentSerializer permission_classes = (UserAccessPermissions,) def create(self, request, *args, **kwargs): serializer = self.get_serializer( data=request.data, many=True) serializer.is_valid(raise_exception=True) # problem is here with perform_create i think self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def get_queryset(self): username = self.request.user user = User.objects.get(username=username) if user.is_teacher: teacher = Teacher.objects.get(username=username) students = Student.objects.filter( department_name__in=teacher.department_name.all(), college_name=user.college_name) elif user.is_collegeAdmin: students = Student.objects.filter(college_name=user.college_name) return students and serializers.py class StudentSerializer(UserSerializer): department = serializers.ReadOnlyField(source='get_department_name') batch = serializers.ReadOnlyField(source='get_batch_name') college = serializers.ReadOnlyField(source='get_college_name') def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(StudentSerializer, self).__init__(many=many, *args, **kwargs) class Meta: model = Student fields = "__all__" postman body; [{ "college_name": "3d1f82fb-c2db-41f1-9dea-8d875009355f", "enrollment_no": "8520258585852", "username": "student", "full_name": "studentbhai", "mobile_no": "+918520852001", "Date_of_Birth": "2000-10-05", "password": "Stu@1234", "email": "student@gmail.com", "department_name": "1", "batch_name": "1" }, { "college_name": "3d1f82fb-c2db-41f1-9dea-8d875009355f", "enrollment_no": "8520258585852", "username": "student2", "full_name": "studentbhai", "mobile_no": "+918520852001", "Date_of_Birth": "2000-10-05", "password": "Stu@1234", "email": "student2@gmail.com", "department_name": "1", "batch_name": "1" }] -
Using Django all-auth in a standalone app: paths that do not start with 'accounts/' are NOT FOUND 404
I am using Django 3.2, and am creating a standalone user registration and management app, that uses django-allauth to handle all of the registration functionality. My stand alone app directory structure is like this: core /core settings.py urls.py # ... /django-myown-userprofile /userprofile models.py urls.py # ... myapp.tox setup.py setup.cfg # ... core/core/urls.py from django.urls import path, include urlpatterns = [ # ... path(user, include('userprofile.urls')), path(admin, admin.site.urls) ] core/django-myown-userprofile/userprofile/urls.py from django.urls import path, include urlpatterns = [ path('accounts', include('allauth.urls')), path('accounts/profile', ProfileView.as_view(), 'user-profile'), # ... ] When I attempt to access any of the allauth endpoints (e.g.): http://localhost:8000/user/accounts/login I get the error 404 Not found. It seems that django-allauth is expecting the path to be of the form: http://localhost:8000/accounts/... How do I change this behaviour of django-allauth ? -
How to integrate python script in a django project
So I am extremely new to programming, and am stuck at this issue, I am using python with Django and Mongodb for database. I need to write a service that assigns an ID (not the one assigned by mongodb) upon each user form submission. for example entry 1's ID will be [Prefix entered by user] 2101, entry 2's ID will be [Prefix entered by user] 2102, so its basically adding in the number 2100. I have no idea how and where to integrate this logic in my code. I have tried a few solutions on the internet but nothing seems to work. my code: Model.py class Writeups(Document): blog_id = 2100 title = fields.StringField(max_length=120) date_created = fields.DateField(blank=True, null=True) date_modified = fields.DateField(blank=True, null=True) version_number = fields.DecimalField(null= True , max_digits=1000, decimal_places=2) storage_path = fields.StringField(max_length=120) STRIKE_READY_BRIEF = 'SRB' STRIKE_READY_THREAT_REPORT = 'SRTR' PREFIX_CHOICES = [ (STRIKE_READY_BRIEF, 'SRB'), (STRIKE_READY_THREAT_REPORT, 'SRTR'), ] prefix = fields.StringField( max_length=4, choices=PREFIX_CHOICES, null=False, blank=False, ) views.py: @csrf_exempt def writeups_request(request): """ Writeup Request """ if request.method == 'GET': try: data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', } writeups = WriteupsFormset(data) # print(writeup) return render(request, "writeups/writeups.html", {'writeups_forms': writeups}) except Exception as e: print(e) response = {"error": "Error occurred"} return JsonResponse(response, safe=False) if request.method == … -
Problem with QuerySet filter and data display
I need to display a list of filtered participants who previously registered using the form for the event. and i don't want to use 'if' {% for participant in participants %} {% if participant.event.id == event.id %} {{ participant.first_name }} {{ participant.last_name }}, {%endif%} {% endfor %} before displaying, I have to approve the participants' applications in the ModelMultipleChoiceField (or something else) class EventForm(ModelForm): name = forms.TextInput(attrs={'class':'form-control'}), venue = forms.Select(attrs={'class':'form-select'}), event_date = forms.TextInput(attrs={'class':'form-control'}), participants = forms.ModelMultipleChoiceField( to_field_name="participants", queryset=Participant.objects.all(),#filter for participants who applied for a specific event widget=forms.CheckboxSelectMultiple ), description = forms.Textarea(attrs={'class':'form-control'}), class Meta: model = Event fields = ('name', 'venue', 'event_date', 'participants', 'description') how do I filter the list by events from the Participant model in the form above, I'm trying to display a list of participants filtering by the event for which they registered. In the form below (ParticipantForm) participants send their applications for approval to the EventForm class ParticipantForm(forms.ModelForm): first_name = forms.CharField(widget=forms.Textarea(attrs={ 'rows': '1', })) last_name = forms.CharField(widget=forms.Textarea(attrs={ 'rows': '1', })) event = forms.ModelChoiceField(queryset=Event.objects.all(), widget=forms.HiddenInput()) class Meta: model = Participant fields = ['event', 'first_name', 'last_name'] This is my first time writing on stack over flow. Sorry for mistakes -
Django ORM query works on shell but time outs in Api View
I have large list of ids and wanted to filter objects using those ids: list_of_ids = [1, 2, 3, 4, ...] MyModel.objects.filter(id__in=list_of_ids)[:20] That query works just fine from shell, but when I try to do the same thing in API View it time outs: from rest_framework.response import Response from rest_framework.views import APIView class MyModelAPIView(APIView): def get(self, request): ids = [1, 2, 3, 4, 5, ...] print(MyModel.objects.filter(id__in=ids)[:20]) return Response({}) After I got the response with a 504 status code, I see in terminal logs what the print function did: django_1 | <QuerySet [<MyModel: 231>, <MyModel: 268>, <MyModel: 269>, <MyModel: 271>, <MyModel: 272>, <MyModel: 274>, <MyModel: 275>, <MyModel: 277>, <MyModel: 280>, <MyModel: 281>, <MyModel: 282>, <MyModel: 284>, <MyModel: 285>, <MyModel: 288>, <MyModel: 289>, <MyModel: 290>, <MyModel: 291>, <MyModel: 292>, <MyModel: 294>, <MyModel: 298>]> But I can't find out why do request time outs? I could not find similar problems there -
Django OTP login using phone number
I want to authenticate user with Phone number and login with Phone number OTP, I have MSG91 api I know we need to user Custom User model but I don't Know about clear Idea For custom User model and OTP login With Phone number anyone Have answers For My Question. ** (And also forgot password using Phone number otp)** -
How to show messages using DetailView on Django
I have Message model and Post model. I want to show all messages which posted to one post. I can't think of how to get all messages at certain post using DetailView Class. How can I do this? or should I create another ListView Class for messages? All my code models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) topic = models.ForeignKey(Topic,on_delete=models.SET_NULL,null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) class Message(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) body = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.body[0:50] views.py class PostDetailView(DetailView): model = Post -
Mypy with django: Define foreign key to be overridden in child class
I have an abstract base class and 2 child classes. I want to define the create_product method on the base class, but mypy errors, rightly saying that I haven't defined product on the base class. How should I do this correctly? I imagine i should declare a sort of empty field on the Base class, but I can't find any docs on this. Error: error: Unexpected attribute "product" for model "Base" [misc] Code: class Base(Model): identifier = CharField() class Meta: abstract = True @classmethod def create_product( cls, *, identifier=identifier, product=product ): return cls.objects.create( identifier=identifier, product=product # Error here ) class ChildA(Base): product = models.OneToOneField(...) class ChildB(Base): product = models.OneToOneField(...) Note I'm using the django-stubs and django-stubs-ext libraries -
Django : Why is string condition False if select_related field not coated in STR()?
In my function, my query is : mappings = MappingField.objects.filter( fl_fiche_header_flow_id=fhf.pk).order_by('fl_fiche_inside_field_position') .select_related('fl_fiche_header_flow') Why when I print (label is models.Charfield): mapping.fl_fiche_header_flow.label I got well : appli1 And when I check the condition : if mapping.fl_fiche_header_flow.label == 'appli1': I obtain False? Why do I need to str(mapping.fl_fiche_header_flow.label) in my condition for getting true? Is it only due to select_related or is it a general principle ? -
can any one tell how can i get an appropriate output only using a foreign key in models
this is my models.py file models.py from django.db import models from django.utils import timezone class Movielist(models.Model) : Title = models.CharField(max_length=1000) Description = models.TextField(blank=True) ReleaseDate = models.DateTimeField(verbose_name='Release Date', blank=True) Upvote = models.IntegerField(default=0) Downvote = models.IntegerField(default=0) def __str__(self): return self.Title class Actorlist(models.Model): Name = models.CharField(max_length=1000) DateofBirth = models.DateTimeField(verbose_name='Date of Birth',blank=True) def __str__(self): return self.Name class ActorInMovie(models.Model): Movie = models.ForeignKey(Movielist, default=1, on_delete=models.CASCADE, blank=True, related_name='ActorInMovie') Actor = models.ForeignKey(Actorlist, default=1, on_delete=models.CASCADE, blank=True,related_name='ActorsMovie') def __str__(self): return self.Movie.Title this is my views.py file views.py @api_view(['GET']) def apiOverview(request): api_urls = { 'List':'/task-list/', 'Detail View':'/task-detail/<str:pk>/', 'Create':'/task-create/', 'Update':'/task-update/<str:pk>/', 'Delete':'/task-delete/<str:pk>/', } return Response(api_urls) @api_view(['GET']) def MovieName(request): MovieName = Movielist.objects.prefetch_related('ActorInMovie') serializer = MovieListSerializer(MovieName, many=True) return Response(serializer.data) this is my serializers.py file serializers.py from rest_framework import serializers from .models import * class MovieListSerializer(serializers.ModelSerializer): class Meta: model = Movielist fields = "__all__" As output i am getting this as below [ { "id": 1, "Title": "KGF Chapter 1", "Description": "This is very thrilling and suspenseful movie", "ReleaseDate": "2022-04-18T16:22:03Z", "Upvote": 5, "Downvote": 2 }, { "id": 2, "Title": "RRR", "Description": "This is a south Indian movie", "ReleaseDate": "2022-04-19T06:46:54Z", "Upvote": 2, "Downvote": 3 }, { "id": 3, "Title": "Doctor Strange", "Description": "this movie is a part of marvel cinematic universe.", "ReleaseDate": "2022-04-22T07:19:07Z", "Upvote": 12, "Downvote": 7 … -
Writable nested serializer method getting an Error while posting a request
models.py class Client(models.Model): client_id = models.AutoField(unique=True, primary_key=True) org = models.ForeignKey(Organisation, on_delete=models.CASCADE, related_name='org',null=True) product = models.ManyToManyField(Product,related_name='product') client_name = models.CharField(max_length=100) client_code = models.CharField(max_length=20) client_logo = models.ImageField(upload_to=upload_to,storage=DownloadableS3Boto3Storage, null=True, blank=True) currency = MoneyField(max_digits=10, decimal_places=2, default_currency='INR', null=True) billing_method = models.CharField(max_length=40) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) email_id = models.EmailField(max_length=100) contact_no = models.CharField(max_length=20) mobile_no = models.CharField(max_length=20) description = models.TextField(max_length=500) street_address = models.CharField(max_length=250) city = models.CharField(max_length=50) state = models.CharField(max_length=50) country = models.CharField(max_length=50) pincode = models.CharField(max_length=10) industry = models.CharField(max_length=100) company_size = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.IntegerField(default=0, choices=STATUS_CHOICES) class Meta: db_table = "client_master" def __str__(self): return self.client_name serializers.py class Client_Serializers(serializers.ModelSerializer): #product_name = Product_Serializers(many=True) product = Product_Serializers(many=True) class Meta: model = Client fields = ('client_id','currency','billing_method','first_name','last_name','description','street_address','city','state','country','pincode','industry','company_size','client_name', 'contact_no','mobile_no', 'email_id','client_logo','client_code','product',) def create(self, validated_data): products_data = validated_data.pop('product') product = Product.objects.create(**validated_data) for product_data in products_data: Product.objects.create(product=product, **product_data) return product Data receiving on GET method { "client_id": 3, "currency": "0.05", "billing_method": "credit card", "first_name": "career", "last_name": "lab", "description": "NA", "street_address": "tiliconveli", "city": "tirunelveli", "state": "tamilnadu", "country": "India", "pincode": "600200", "industry": "software", "company_size": 100, "client_name": "techfetch", "contact_no": "1234567890", "mobile_no": "1234567890", "email_id": "icanio@gamil.com", "client_logo": "https://icanio-project-management.s3.amazonaws.com/client_logo/sup_bat_fDauRxK.jpg", "client_code": "TFH", "product": [ { "product_id": 5, "product_name": "time" } ] } But while posting it in the same format it is not getting posted, showing like { … -
Django REST Framework - Custom serializer overrides model constraints
My goal is to capitalize all letters coming in a specific field from the user payload in Django Rest Framework. Here the model: class Order(models.Model): class Item(models.TextChoices): FIRST= 'FIRST', _('FIRST') SECOND= 'SECOND', _('SECOND') ... order_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) the_item = models.CharField(max_length=8, choices=Item.choices) The only values admited are "FIRST" and "SECOND" in uppercase. I used this approach to capitalize the letters: In Django Rest Framework: from rest_framework import serializers class UpperCaseSerializerField(serializers.CharField): def __init__(self, *args, **kwargs): super(UpperCaseSerializerField, self).__init__(*args, **kwargs) def to_representation(self, value): value = super(UpperCaseSerializerField, self).to_representation(value) if value: return value.upper() and used in serializers.py like: class OrderCreateSerializer(serializers.ModelSerializer): #Force uppercase item = UpperCaseSerializerField() class Meta: model = Order fields = ['order_id', 'item' ] This actually works, because the input is converted in uppercase, BUT, the model constraints are not taken anymore into account. Payload Example 1: { "the_item": "first" } - LEGIT, converted in FIRST Payload Example 2: { "the_item": "FIRST" } - LEGIT, it's already uppercase Payload Example 3: { "the_item": "1234567" } - COMPLETELY WRONG INPUT, but it is accepted! It should be not! It's clear that it only cares about capitalizing and completely ignoring the model structure, which does not admit strings different from 'FIRST' and 'SECOND'. So, … -
'str' object has no attribute 'days'
when I add products to the vendor it shows this error 'str' object has no attribute 'days' class AddBaseproductToStore(AdminOnlyMixin, generic.TemplateView): template_name = 'manager-admin/add-product-to-store.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['prod_id'] = self.kwargs['pk'] context['vendor'] = self.kwargs['vendor'] return context def get(self, request, *args, **kwargs): product = BaseProduct.objects.get(id=self.kwargs['pk']) vendor_id = self.kwargs['vendor'] base_cat = BaseCategory.objects.all() return render(request, self.template_name, {"product": product, "base_cat": base_cat, 'vendor': vendor_id}) def post(self, request, *args, **kwargs): base_product = BaseProduct.objects.get(id=self.kwargs['pk']) vendor_id = self.kwargs['vendor'] base_category = BaseCategory.objects.get(id=request.POST.get('category')) try: p = Product.objects.get(base_product=base_product, category=Category.objects.get(vendor_id=vendor_id, base_category=base_category)) except: product = Product() product.category = Category.objects.get(vendor_id=vendor_id, base_category=base_category) product.base_product = base_product product.name = request.POST.get('name') product.ar_name = request.POST.get('ar_name') product.sort_order = request.POST.get('sort-order') product.dryclean = request.POST.get('dryclean', '') == 'on' product.normal_dryclean_price = request.POST.get('dryclean_price') product.normal_dryclean_buffer_time = request.POST.get('dryclean_buffer') product.wash_and_pressing = request.POST.get('wash-press', '') == 'on' product.normal_wash_and_pressing_price = request.POST.get('wash-press-price') product.normal_wash_and_pressing_buffer_time = request.POST.get('wash-press-buffer') product.pressing = request.POST.get('press', '') == 'on' product.normal_pressing_price = request.POST.get('press-price') product.normal_pressing_buffer_time = request.POST.get('press-buffer') product.express_dryclean = request.POST.get('exp-dryclean', '') == 'on' product.express_dryclean_price = request.POST.get('exp-dryclean-price') product.express_dryclean_buffer_time = request.POST.get('exp-dryclean-buffer') product.express_wash_and_pressing = request.POST.get('exp-wash-press', '') == 'on' product.express_wash_and_pressing_price = request.POST.get('exp-wash-press-price') product.express_wash_and_pressing_buffer_time = request.POST.get('exp-wash-press-buffer') product.express_pressing = request.POST.get('exp-press', '') == 'on' product.express_pressing_price = request.POST.get('exp-press-price') product.express_pressing_buffer_time = request.POST.get('exp-press-buffer') product.save() if product.express_pressing == True or product.express_dryclean == True or product.express_wash_and_pressing_price == True: product.express = True else: product.express … -
Django returns 500 instead of 401 / 403 when no token passed
I have a Django view that requires a user to be authenticated (The app uses jwt), When the request is being passed without any Authorization header the response is 500, I want it to be 401 / 403 because it should not return an internal server error but an unauthorized error. I searched a lot and could not find a way to customize this behavior Here is the code: views.py: class GetProfileAPIView(APIView): permissions_classes = [permissions.IsAuthenticated] def get(self, request): user = self.request.user user_profile = Profile.objects.get(user=user) serializer = ProfileSerializer(user_profile, context={"request": request}) return Response(serializer.data, status=status.HTTP_200_OK) settings: DJOSER = { "LOGIN_FIELD": "email", "USER_CREATE_PASSWORD_RETYPE": True, "USERNAME_CHANGED_EMAIL_CONFIRMATION": True, "PASSWORD_CHANGED_EMAIL_CONFIRMATION": True, "SEND_CONFIRMATION_EMAIL": True, "PASSWORD_RESET_CONFIRM_URL": "password/reset/confirm/{uid}/{token}", "SET_PASSWORD_RETYPE": True, "PASSWORD_RESET_CONFIRM_RETYPE": True, "USERNAME_RESET_CONFIRM_URL": "email/reset/confirm/{uid}/{token}", "ACTIVATION_URL": "activate/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, "SERIALIZERS": { "user_create": "apps.users.serializers.CreateUserSerializer,", "user": "apps.users.serializers.UserSerializer", "current_user": "apps.users.serializers.UserSerializer", "user_delete": "djoser.serializers.UserDeleteSerializer", }, } REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ) } SIMPLE_JWT = { "AUTH_HEADER_TYPES": ( "Bearer", "JWT", ), "ACCESS_TOKEN_LIFETIME": timedelta(minutes=120), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "SIGNING_KEY": "supersecretkey~!", "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), } enter code here -
whitespace data when deleting in django
I'm planning to delete comments just like in any other social media apps. The problem is when I do .delete() function. it only removes the strings but not the row itself, making it only whitespaces. delete function def delete_comment(request): formType = request.POST.get('formType','') postID = request.POST.get('postID','') commentID = request.POST.get('commentID','') deleteComment = Comment.objects.get(id = commentID).cleanData() result = { 'code': 0, } return JsonResponse({'result':result}) EventListener in $('.delete-button').on('click', function(e){ e.preventDefault(); var commentID = $(this).attr('comment-id'); var form_type = $(this).attr('form-type'); var postID = $(this).attr('post-id'); $.ajax({ type: "POST", url: '/api/comment/edit_comment', data: { "formType":form_type, "postID":postID, "commentID":commentID, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: function(data) { $('.commentCard-'+ commentID).remove(); }, cache: false }); }); html <form action ="" form-type="deletebtn"> <button type="button" class="delete-button post-options btn text-nowrap" post-id = {{ post.id }} comment-id = {{Post_comment.id}} on-click="remove_comment({{post.id}}, {{Post_comment.id}})" > <i class='bx bx-message-square-x'></i> </button> </form> result when deleting result -
Filtering Base Django User by multiple groups
In my Django project I'm using base Django User and Group models. My goal is to get User queryset containing all User object who are assigned to multiple groups at the same time. For example I two groups and three users: from django.contrib.auth.models import User, Group a = Group.objects.create(name='a') b = Group.objects.create(name='b') user_a = User.objects.create_user('a', 'a@a.com', 'a') user_a.groups.add(a) user_b = User.objects.create_user('b', 'b@b.com', 'b') user_b.groups.add(b) user_ab = User.objects.create_user('ab', 'ab@ab.com', 'ab') user_ab.groups.add(a) user_ab.groups.add(b) I have tried filtering using __in on groups nad Q, but with no effect from django.db.models import Q User.objects.filter(groups__in=[a,b]).distinct() <QuerySet [<User: a>, <User: ab>, <User: b>]> User.objects.filter(Q(groups=a) & Q(groups=b)) <QuerySet []> My expected result would be: User.objects.filter(???) <QuerySet [<User: ab>]> -
Django & Ajax chat application
in this chat application i made a room page and i am trying to get messages to this room as jsonResponse but i keep getting this error 'method' object is not iterable... the view: def room(request,room): username = request.GET.get('username') room_details = Room.objects.get(name=room) messages = Message.objects.filter(room=room_details.id) return render(request,'room.html',{ 'username': username, 'room': room, 'room_details': room_details, }),JsonResponse({'messages':list(messages.values)}) Scripts: * $(document).ready(function(){ setInterval(function(){ $.ajax({ method: 'GET', url : "", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.messages) { var temp="<div class='container darker'><b>"+response.messages[key].user+"</b><p>"+response.messages[key].value+"</p><span class='time-left'>"+response.messages[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occured') }, complete: function(xhr,status){ console.log(status); console.log(xhr); } }); },1000); }) </script>* -
Get value from many to many relation django
I would like to get value of the field 'name' of the model User but facing some issues. accounts = list(Account.objects.all()) To receive some value from foreign key models I use: accounts.currency.code (where Account my main model, Currency foreign key model and Code is required field) But for model with manytomany relation this way doesn't work. accounts.user.name 'ManyRelatedManager' object has no attribute 'name' But there name is a charfield of the model User. -
Prevent need for the same select_related clause on multiple views in DRF
Given the following models... class Player(models.Model): user = models.ForeignKey(User) class Activity(models.Model): player = models.ForeignKey(Player) and these serializers... class PlayerSerializer(serializers.ModelSerializer): class Meta: model = Player fields = ['user'] class ActivitySerializer(serializers.ModelSerializer): player = PlayerSerializer() class Meta: model = Activity fields = ['player'] if I want to use django-rest-framework to list all the activities, I need to do something like this... class ActivityViewSet(viewsets.ReadOnlyModelViewSet): queryset = Activity.objects.select_related("player__user") <--- this is needed because the activity serializer is going to serialize the player which has a user serializer_class = ActivitySerializer That's all fine. But then, every time I write a new view which, at some level, uses PlayerSerializer, I'm going to have to remember to do the proper select_related clause in order to keep the number of DB lookups low. I'm going to end up writing a lot of views which have the same select_related clauses (mine are actually a LOT more complicated than this example) and, if the PlayerSerializer ever changes, I'm going to need to remember to change all the view lookups. This doesn't seem very DRY to me and I feel like there must be a better way to do it. Have I missed something obvious?