Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sign Up view test not passing [Django REST]
I'm trying to test the sign up view in Django using REST Framework but I'm getting an assertio error AssertionError: 201 != 400 when defining self.assertEqual(status.HTTP_201_CREATED, response.status_code). I'm not really sure where this error comes from so I'm asking for some help. Here is what I have: accounts/models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ class CustomUser(AbstractUser): username = models.CharField(max_length=20, unique=True) email = models.EmailField(_('email address'), unique=True) def __str__(self): return self.email accounts/serializers.py from django.contrib.auth import get_user_model from django.core.validators import EmailValidator from rest_framework import serializers from rest_framework_simplejwt.serializers import TokenObtainPairSerializer import re def company_email_validation(email): pattern = r'(@gmail|@hotmail|@googlemail|@yahoo|@gmx|@ymail|@outlook|@bluewin|@protonmail|@online|@web|@online|@aol|@live)' return bool(re.search(pattern, email)) class UserSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) def validate(self, data): email_validator = EmailValidator() email_validator(data['email']) if (company_email_validation(data['email'])): raise serializers.ValidationError('You must use a company email') if data['password1'] != data['password2']: raise serializers.ValidationError('Passwords must match.') return data def create(self, validated_data): data = { key: value for key, value in validated_data.items() if key not in ('password1', 'password2') } data['password'] = validated_data['password1'] data['email'] = validated_data['email'] return self.Meta.model.objects.create_user(**data) class Meta: model = get_user_model() fields = ( 'id', 'username', 'email', 'password1', 'password2', ) read_only_fields = ('id',) accounts/views.py from django.contrib.auth import get_user_model from rest_framework import generics from rest_framework_simplejwt.views import TokenObtainPairView from .serializers import UserSerializer, … -
How to create the foreign key relationship between Account and Post models on the model level, not on a database level?
I want to create the foreign key relationship between Account and Post models on the model level, not on a database level. I have created a custom account user, https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#custom-users-and-proxy-models The models are: Account : first_name, last_name, email, password, username Post : user, text, created_at, updated_at class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return self.is_admin # Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY) def has_module_perms(self, app_label): return True class Post(models.Model): user = models.CharField(max_length=30) text = models.TextField(max_length=500) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user -
Django rest framework POST nested serializer using action
I am new to django. I am having trouble with nested serializers. The nested serialization doesn't work as expected. when I am trying to create and post a new student, it does not create and post every thing and I got the following typeError: django.db.models.manager.BaseManager._get_queryset_methods..create_method..manager_method() argument after ** must be a mapping, not str and I see the rest as following: { "is_existing_student": "yes", "name" :"SN school" "street": "Main Road", "city" : "London" "student": {} } But the name of the student should be created too. it should be like this: { "is_existing_student": "yes", "name" :"SN school" "street": "Main Road", "city" : "London" "student": { "first_name": "John" } } Can someone help me? In my serializers.py class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True) class Meta: model = School fields = ['is_existing_student', 'name', 'city', 'street', 'student'] def create(self, validated_data): student_data = validated_data.pop('student') school_instance = School.objects.create(**validated_data) for student_data in student_data: Student.objects.create(school_instance=school_instance, **student_data) return school_instance in my views.py class SchoolViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() @action(detail=True, methods=['POST']) def school(self, request, *args, **kwargs): school_serializer = self.get_serializer(data=request.data) if school_serializer.is_valid(): school_serializer.save() else: return Response(status=status.HTTP_204_NO_CONTENT) -
Why we use JWT if we can use Redux for routes
Sorry for this question, I'm working in a project with React/Django/PostgreSQL, I realised a basic routes managing using Redux. I didn't understand what is the utility of Web Tokens, I want to use them in my project but for now I can see that I can do plenty premission things using Redux states. I really need to know some use cases for using Web Tokens for the whole projects. Thank you -
(421, b'Cannot connect to SMTP server, connect error 10061')
I'm trying to send an actual email to myself from my website using send_mail. I had used localhost and the following cmd command, python -m smtpd -n -c DebuggingServer localhost:1025 in order to test it. It intercepts with no problem, but I don't see anything in my inbox. Here is the settings.py file: EMAIL_HOST = '178.67.220.242' # My current ip address EMAIL_PORT = '587' # Port of the email host EMAIL_HOST_USER = 'b....a1@gmail.com' # Here is my actual email EMAIL_HOST_PASSWORD = '.....' # Here is my actual password from my email login EMAIL_USE_TLS = True EMAIL_USE_SSL = False Here is the views.py file: from django.shortcuts import render from django.core.mail import send_mail from .forms import ContactForm def contact(request): form = ContactForm if request.method == 'POST': message_name = request.POST.get('name') message_email = request.POST.get('email') message = request.POST.get('message') send_mail(message_name, message, message_email, ['b....a1@gmail.com']) return render(request, 'contact.html', {'form': form}) Here is the error: Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\1\PycharmProjects\StasProject\sales_project\contact\views.py", line 15, in contact send_mail(message_name, message, message_email, ['badabuska1@gmail.com']) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\1\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\mail\backends\smtp.py", line … -
Django Rest Framework - How can I serialize a complex many-to-many object model with a custom table join?
I'm new to Django and Django REST Framework. I have a fairly complex relationship model, the intent is to have a shopping cart with many orders: class Product(models.Model): name = models.CharField(max_length=200) class Order(models.Model): title = models.CharField(max_length=200) items = models.ManyToManyField(Product, through='TableJoin') class TableJoin(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) quantity = models.IntegerField() I'm having trouble both using the ORM to pull a complete Order model (with relations), and to then serialize that. -
Heroku 500 internal error (due to postgres field errors?)
Im running an app on heroku that has a postgres db. I encountered a strange situation that whenever I pass in more than 50 characters inside the first field (title) of a ModelForm I get an Server Error (500) message and the app crashes. If the length of the input is 50 or less characters then the app works fine. I double checked that in models.py the CharField's max_lenght is more than 50 class Ad(models.Model): title = models.CharField(max_length=240) I also checked that the max character length is 240 in postgres /dt+ table desription Column | Type | Collation | Nullable | Default | Storage | Stats target | Description -----------------------+------------------------+-----------+----------+------------------------------------+----------+--------------+------------- id | integer | | not null | nextval('ads_ad_id_seq'::regclass) | plain | | category | text | | not null | | extended | | title | character varying(240) | | not null | | extended | | I haven't inputed any constraints on character lengths in the forms.py also. And what else is strange that in my local development env (also running on postgres) the app does not crash if I enter more that 50 characters in the title field. Both versions are tracked by git vc. Unfortunately the … -
django Error: Tried everything suggested by every website existing on google but still getting "The given username must be set"
I am working on user registration for an E-commerce Website I am not using any forms.py and there is no Indentation issue. I am passing simple JSON on postman on POST method to check if it is working or not, but I am getting errors. Below is my code and my error. I will be grateful for your help. My model.py from django.db import models from django.contrib.auth.models import AbstractUser import datetime class User(AbstractUser): created_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username My View.py class Register(APIView): def post(self, request): username = request.POST.get('username') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') email = request.POST.get('email') if password == confirm_password: if Client.objects.filter(username = username).exists(): return Response({"message": "this username already exist"}) elif Client.objects.filter(email = email).exists(): return Response({"message": "This emaila address is already taken"}) else: user= Client.objects.create_user(username = username, password =confirm_password, email=email) user.save() else: return Response({"message": "Try it again"}, 404) My urls.py from django.urls import path from user_authentication.views import Login, Logout, Register urlpatterns = [ path('login/', Login.as_view()), path('logout/', Logout.as_view()), path('register/', Register.as_view()), ] Error--- Exception Value: The given username must be set Internal Server Error: /register/ Traceback (most recent call last): File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Lenovo\Documents\GitHub\E-commerce\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response … -
List liked post in django
Suppose class Post(models.Model): content = models.CharField(...) image = models.ImageField(...) class PostLike(models.Model): user = models.ForiegnKey(User,...) post = models.ForeignKey(Post,...) class PostSave(models.Model): user = models.ForiegnKey(User,...) post = models.ForeignKey(Post,...) How do i list all the liked post in serializers with fields ["content","image","liked","saved"] ? Here liked will be true for all as the list is coming from liked posts. And saved will be true if request.user and post_id in PostSave. view def getLikedPost(request): obj = # Get all the liked post serializer = CustomSerializer(obj.,many=True) result = JsonResponse(serializer.data, safe=False) Help me in completing view and serializer Thanks in Advance! -
Internal Server Error (500) showing on sub-routes when running Django on server
I'm hosting my Django application on a VPS and I'm using Django Rest Framework and the Django Admin Site. Everything seemed working running fine (check the below image), but when I try to click on my API's I'm redirected to a Server Error (500) page. One thing to notice is that when I'm running the app locally on my machine everything is working fine. Below is my settings.py if it can help in anyway: Django settings for thepatron project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os import django_heroku import datetime from dotenv import load_dotenv # Initialize environment variables load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! try: SECRET_KEY = str(os.getenv('SECRET_KEY')) except KeyError as e: raise RuntimeError("Could not find a SECRET_KEY in environment") from e # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ # VPS '194.5.159.80', # … -
Schedule emails on a specific time using Django and celery
This is the use case I am looking for : User will register on my application It is a note making and remainder application While creating remainder users will enter the time my application wants to send user an email at that time I have to use celery for the same I read several posts and stack overflow answers but didn't get proper answer for the same. My application is written in Django. -
Django + ElasticSearch + Docker - Connection Timeout no matter what hostname I use
I'm having issues connecting with my Elasticsearch container since day 1. First I was using elasticsearch as the hostname, then I've tried the container name web_elasticsearch_1, and finally I'd set a Static IP address to the container and passed it in my configuration file. PYPI packages: django==3.2.9 elasticsearch==7.15.1 elasticsearch-dsl==7.4.0 docker-compose.yml version: "3.3" services: web: build: context: . dockerfile: local/Dockerfile image: project32439/python command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" env_file: - local/python.env depends_on: - elasticsearch elasticsearch: image: elasticsearch:7.10.1 environment: - xpack.security.enabled=false - discovery.type=single-node networks: default: ipv4_address: 172.18.0.10 settings.py # Elasticsearch ELASTICSEARCH_HOST = "172.18.0.10" ELASTICSEARCH_PORT = 9200 service.py from django.conf import settings from elasticsearch import Elasticsearch, RequestsHttpConnection es = Elasticsearch( hosts=[{"host": settings.ELASTICSEARCH_HOST, "port": settings.ELASTICSEARCH_PORT}], use_ssl=False, verify_certs=False, connection_class=RequestsHttpConnection, ) traceback HTTPConnectionPool(host='172.18.0.10', port=9200): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x7f1973ebd6d0>, 'Connection to 172.18.0.10 timed out. (connect timeout=5)')) -
Django asgi Single thread executor already being used, would deadlock deployment error
my run command for django asgi application using gunicorn looks like this: gunicorn -b '0.0.0.0:8000' myproject.asgi:application -w 4 -k uvicorn.workers.UvicornWorker --access-logfile /logs/access.log --access-logformat "%(h)s %(l)s %(u)s %(t)s %(r)s %(s)s %(b)s %(f)s" >> /logs/error.log When I try to access any endpoint of the application, I get Single thread executor already being used, would deadlock error. I am using following package versions: Django=3.2.4 asgiref==3.4.0 uvicorn==0.15.0 gunicorn==20.1.0 -
Django star rating system AJAX and JavaScript
I am trying to implement a star rating system on a Django site. I have found the following, and like the style of the stars here: https://www.w3schools.com/howto/howto_css_star_rating.asp Currently have a limited understanding of JavaScript, AJAX and Django. Does anyone know how to use the stars in the above example combined with AJAX and Django, so you are able to update the database (models) without a page refresh when a user selects a rating? It is also important that users are only able to vote once, i.e. they are not allowed to rate a page twice. For this, there must be an IP check. I am confused about the code and I need help. models.py: class Rating(models.Model): ip = models.CharField(max_length=15) post = models.ForeignKey(Post, related_name='ratings', on_delete=models.CASCADE) score = models.IntegerField(default=0, validators=[ MaxValueValidator(5), MinValueValidator(0), ] ) def __str__(self): return str(self.pk) views.py: def RatingView(request): obj = Rating.objects.filter(score=0).order_by("?").first() context ={ 'object': obj } return render(request, 'blog/post_detail.html', context) # def get_client_ip(self, request): # x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') # if x_forwarded_for: # ip = x_forwarded_for.split(',')[0] # else: # ip = request.META.get('REMOTE_ADDR') # return ip def RateView(request): if request.method == 'POST': element_id = int(request.POST.get('element_id')) val = request.POST.get('val') print(val) obj = Rating.objects.get(id=element_id) obj.score = val obj.save() return JsonResponse({'success':'true', 'score': val}, safe=False) … -
Pass video uploaded via django to cv2
I am uploading video via django and want to process it using cv2. This is how video uploaded via django is accessed. video_obj = request.FILES['file_name'] Next i want to pass it to opencv. I dont want to save video in disk first and then acess it via cv2 using following code cap = cv2.VideoCapture(vid_path) I tried passing this video_obj to VideoCapture this way video_obj = request.FILES['file_name'] cap = cv2.VideoCapture(video_obj) But i got following error Can't convert object of type 'TemporaryUploadedFile' to 'str' for 'filename' VideoCapture() missing required argument 'apiPreference' (pos 2) -
Django: Foreign Key to User -> Form is not validating because field is required
I'm currently creating a Registration-Page with two parts One part is about the Username and a Passwort. The second part is about choosing the own PC-Configuration After defining everything, the User can register to get to the Main-Page. Therefore I got a Model called "PC_Configuration" with a bunch of Foreign-Keys to the different Database-Models of the Processors/Graphicscards etc.: class PC_Configuration(models.Model): user = models.ForeignKey(User, related_name='user_id', on_delete=models.DO_NOTHING) processor = models.ForeignKey(Processors, related_name='processor_id', on_delete=models.DO_NOTHING) graphicscard = models.ForeignKey(Graphicscard, related_name='graphicscard_id', on_delete=models.DO_NOTHING) os = models.ForeignKey(OS, related_name='os_id', on_delete=models.DO_NOTHING) ram = models.ForeignKey(RAM, related_name='ram_id', on_delete=models.DO_NOTHING) harddrive = models.ForeignKey(Harddrive, related_name='harddrive_id', on_delete=models.DO_NOTHING) Also, there is one ForeignKey to the User to connect the Configuration to the respective User-ID. Inside views.py, I've been creating a DropdownForm for all the Dropdown-Fields which the User shall choose on his own: class DropdownForm(forms.ModelForm): class Meta: model = models.PC_Configuration exclude = [] def __init__(self, *args, **kwargs): super(DropdownForm, self).__init__(*args, **kwargs) self.fields['processors'].queryset = DropdownForm.objects.all() self.fields['processors'].label_from_instance = lambda obj: "%s" % obj.name self.fields['graphicscard'].queryset = DropdownForm.objects.all() self.fields['graphicscard'].label_from_instance = lambda obj: "%s" % obj.name self.fields['os'].queryset = DropdownForm.objects.all() self.fields['os'].label_from_instance = lambda obj: "%s" % obj.name self.fields['ram'].queryset = DropdownForm.objects.all() self.fields['ram'].label_from_instance = lambda obj: "%s" % obj.name self.fields['harddrive'].queryset = DropdownForm.objects.all() self.fields['harddrive'].label_from_instance = lambda obj: "%s" % obj.name But regarding the fact, that the User-ID shall … -
Blank page showing in django server after adding python in index.html file
please help i'm following a tutorial and not showing desierd output in the server page. Every thing was going smoothly until the index.html page content not shown This is my index.html file <!DOCTYPE html> <html lang="eng"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script> <title>document</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> </head> <body> <div class="container"> <div class="row"> **{% for Product in product_objetcs %}** <div class="col-md-3"> <div class="card"> <img src="{{ product.image }}" class="card-img-top"> <div class="card-body"> <div class="card-title"> **{{ product.tittle }}** </div> <div class="card-text"> **{{ product.price }}** </div> </div> </div> **{% endfor %}** </div> </div> </div> </body> </html> this is my views page from django.shortcuts import render from.models import Product # Create your views here. def index(request): product_objects = Product.objects.all() return render(request, models "my models page looks like this" from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=200) price = models.FloatField() discount_price = models.FloatField() category = models.CharField(max_length=200) description = models.TextField() image = models.CharField(max_length=300) -
How to setup Openwisp-radius with Django
Hello kindly help with is error, i am trying to get started with openwisp-radius with django project. after setting up my django project with openwisp radius when i run py manage.py migrate i run into this error Applying openwisp_radius.0013_remove_null_uuid_field...Traceback (most recent call last): django.db.utils.OperationalError: (1280, "Incorrect index name 'nas_uuid_694a814a_uniq'") -
django (errno: 150 "Foreign key constraint is incorrectly formed")')
recently when in want to migrate my model I encountered this error in django: "(errno: 150 "Foreign key constraint is incorrectly formed")')" class PartCategory(models.Model): name=models.CharField("نام",max_length = 50) code=models.CharField("کد",max_length = 50,unique=True) description=models.CharField("توضیحات",max_length = 50) priority=models.IntegerField("اولویت", null=True) isPartOf = models.ForeignKey('self',on_delete=models.CASCADE,verbose_name="زیر مجموعه",null=True,blank=True) def __str__(self): return self.name class Meta: db_table = "partcategory" -
Cloudinary Image Upload errpr in django python while hosted in pythonanywhere
So i use pythonanywhere to host a django website where pictures are uploaded and shown the uploaded pictures are stored in cloudinary showing the pictures is working fine but when i upload a post i get this error: Error at /post/ Unexpected error - MaxRetryError("HTTPSConnectionPool(host='api.cloudinary.com', port=443): Max retries exceeded with url: /v1_1/meme-topia/image/upload (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f8d77f41370>: Failed to establish a new connection: [Errno 111] Connection refused'))") Models file: from django.db import models from cloudinary.models import CloudinaryField # Create your models here. class MemeImg(models.Model): Title = models.CharField(max_length=500) Post_Img = CloudinaryField('image') def __str__(self): return self.Title Forms file: from django import forms from .models import MemeImg class PostImg(forms.ModelForm): class Meta: model = MemeImg fields = '__all__' And then the source code link:https://github.com/Shadow-Knight503/memoster503.git Please help -
Django/Vue session data for login in development mode
I have a Django/Vue app. I want to login my user to my app but I don't know how it works in the development mode. For production, I build my vue files and access them via Django views so in production, sessions are simply managed by Django. This is OK. But in development mode, I access the FE via a different port. In this case, when I login my user, how Django know that this user is logged in? What should I do to make this happen as in Production without extra configurations? If extra configurations are needed, what are they? -
Django comments xtd giving me error 404 when posting a comment
I have implemented Comments XTD package to allow users to comment in my Article model. Everything works great except the fact that when I am clicking Send I get Error 404. Comment and I need to manually come back to the article to see my newly added comment. I also receive email notification so the only problem is with url that is being generated once I click Send. Could you please tell me how to fix it? article_detail.html <div id="comments" class="pb-4 mb-4"> {% get_comment_count for article as comment_count %} {% if comment_count %} <h5> {% blocktrans count comment_count=comment_count %} There is {{ comment_count }} comment below. {% plural %} There are {{ comment_count }} comments below. {% endblocktrans %} </h5> <hr /> {% endif %} {% if article.allow_comments %} <div class="comment"> <H4 class="">Post your comment</H4> <div class="well"> {% render_comment_form for article %} </div> </div> {% else %} <h5 class="">Only moderators can add comments in this article</h5> {% endif %} {% if comment_count %} <hr /> <ul class="media-list" id="comment-list" style="text-align: left;"> {% render_xtdcomment_tree for article allow_feedback show_feedback allow_flagging %} </ul> {% endif %} </div> urls.py in my articles app urlpatterns = [ path('articles/', views.articles_view, name='articles'), path('article/<slug:slug>', views.ArticleDetailView.as_view(), name='article'), ] urls.py in … -
Django REST Framework - how to start functions on backend after event on frontend
I'm creating webapp and using DRF on the server. I want to start function on server, after event on frontend (for example - button clicked) Example: User is typing '2021' in input field on frontend and click the button ,,generate" The '2021' is transfering to function ,generate_list_of_sundays(year)' on server The function return list of all sundays in typed year List is displayed to user on frontend Of course this is simple example. I want to know how to get this type of communications between frontend and backend. -
Complex annotation to get all statuses for each user counted
In my leads table I need to count the number of leads for each status for each user. Is there a way to do that by arm annotate ? Right now I have something like this: leads.objects.values("created_by","status").annotate(total=Count("status")).order_by("created_by") and output is like: [{'created_by':"Andrew Ray', "status":'ACTIVE", 'total':4}, {'created_by':Andrew Ray', "status":'LOST", 'total':2}, {'created_by':Andrew Ray', "status":'WON", 'total':1}] is there a way to get it like this: [{'created_by':"Andrew Ray', "ACTIVE" : 4, "LOST": 2, "WON":1}] Active Won Lost are a values of STATUS field in leads model there is also another there and I would like to make key and value pai for each of them for each user (CharField) -
django 4.0rc1 and django-taggit "TypeError: get_extra_restriction() missing 1 required positional argument: 'related_alias'" on filtering by Tag
After upgrading Django to 4.0rc1, wherever I try to filter Objects by it's Tag (django-taggit) entrys = Entry.objects.filter(tags__name__in=["Tag1", "Tag2"]) or entrys = Entry.objects.filter(tags__id=tag.id) I get the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 1354, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1189, in execute_sql sql, params = self.as_sql() File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 545, in as_sql from_, f_params = self.get_from_clause() File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 833, in get_from_clause clause_sql, clause_params = self.compile(from_clause) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 463, in compile sql, params = node.as_sql(self, self.connection) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/sql/datastructures.py", line 81, in as_sql extra_cond = self.join_field.get_extra_restriction(self.table_alias, self.parent_alias) File "/dirkb/.venv/lib/python3.8/site-packages/django/db/models/fields/reverse_related.py", line 168, in get_extra_restriction return self.field.get_extra_restriction(related_alias, alias) TypeError: get_extra_restriction() missing 1 required positional argument: 'related_alias' Does anyone have a solution or a workaround?