Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websockets not working with Django channels after deploying
I'm trying to deploy my Django project, but I faced some difficulties. Everything is working perfectly on local machine. I'm using Django + nginx + uvicorn (runned by supervisor). Also, I got my SSL certificate in use. When I try to connect to websocket (/ws) via loading the page and making my js files work, I get a message in console: WebSocket connection to 'wss://example.com/ws/' failed Here is my nginx config map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 80; server_name example.com; return 301 https://example.com$request_uri; } server { listen 443 ssl; ssl on; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; server_name example.com; client_max_body_size 100M; gzip on; gzip_vary on; gzip_proxied any; gzip_http_version 1.1; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript; location /ws/ { proxy_pass https://uvicorn/ws; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_http_version 1.1; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_intercept_errors on; proxy_redirect off; proxy_cache_bypass $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-NginX-Proxy true; proxy_ssl_session_reuse off; } location /static/ { root /root/server/social; expires 1d; } location /media/ { root /root/server/social; expires 1d; } location / { proxy_pass https://uvicorn; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } upstream uvicorn { server unix:/tmp/uvicorn.sock; } And the supervisor config [program:django] … -
Django Pycharm debbuger - can't find '__main__' module in ''
I'm trying to solve a problem where django isn't redirecting the way it should, so I'm trying to debug it with Pycharm Community Edition. I've tried setting a Run/Debug configuration as such: But whenever I try to debug it, it gives me this error: C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\Scripts\python.exe: can't find '__main__' module in '' But when I try to just run it, without debugging, it works fine, as seen bellow: I've checked out the following questions but I still can't find an solution: Django 4 Pycharm debugger error: can't find 'main' module in '' - Tried updating Pycharm but nothing changed Pycharm gets error "can't find 'main' module" - Proper script path is already selected What else can I do? Thank you. -
how to override user.check_password(password)
I need to override user.check_password(password) method because I am using a legacy database which is using passwords hashed with .net framework I created a Function that can hash a password and compare it with the hash password which is already saved in the database. my question is how can I override check_password function and when I use it with my function, it will return True -
'CustomUser' object has no attribute 'get'
I'm trying to auto-assign a ModelForm field to be a ForeignKey from the Model that the ModelForm is based off of. The Model includes a ForeignKey that references a CustomUser. What I'd like to do is auto-assign the ModelForm field so that a logged-in user can submit the form as save the data to the database. I keep getting this error: 'CustomUser' object has no attribute 'get'. I don't understand what is throwing this error. I have pointed the settings to my CustomUser and registered the models in the admin files for each app. Additionally, both Models show up in the admin section of my project, but when I save the form for a logged in user I get that error and it doesn't save to the database. Code Below for Reference: class CustomUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Account must have an email address') user = self.model( email = self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email = self.normalize_email(email), password = password,) user.is_admin = True user.is_staff = True user.is_active = True user.is_superuser = True user.save(using = self._db) return user class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length = 100, unique = True) … -
Django: related_name issue
I am trying to make a query with related_name. I need to list tenants and its domain. But I am getting this error: 'TenantManager' object has no attribute 'domains' What am I doing wrong? models.py class Tenant(TenantMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) created_on = models.DateField(auto_now_add=True) objects = TenantManager() auto_create_schema = True auto_drop_schema = True class Domain(DomainMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) domain = models.CharField(max_length=253, unique=True, db_index=True) tenant = models.ForeignKey(settings.TENANT_MODEL, db_index=True, related_name='domains', on_delete=models.CASCADE) managers.py class TenantManager(models.Manager): def list_all(self): return self.domains.all() viewsets.py class TenantViewSets(viewsets.GenericViewSet): authentication_classes = (JWTAuthentication,) permission_classes = [IsAuthenticated, IsAdminUser, IsSuperUser] def list(self, request): queryset = Tenant.objects.list_all() serializer = Tenant.Serializer(queryset, many=True) return Response(serializer.data) serializers.py class DomainSerializer(serializers.ModelSerializer): tenant = serializers.RelatedField(read_only=True) class Meta: model = Domain fields = ( "id", "domain", "tenant", ) class TenantSerializer(serializers.ModelSerializer): domain = DomainSerializer(read_only=True) class Meta: model = Tenant fields = ( "id", "name", "schema_name", "created_on", "domain", ) -
Django admin site form auto-filled with values in many-to-many relationship
class Student(models.Model): id = models.IntegerField(primary_key=True, unique=True, null=False) name = models.CharField(max_length=100, null=False) password = models.CharField(max_length=100, null=False) course = models.ManyToManyField('Course', related_name='students', blank=True) class Meta: verbose_name_plural = 'Students' def __str__(self): return self.name class Course(models.Model): id = models.IntegerField(primary_key=True, null=False) name = models.CharField(max_length=255, null=False, unique=True) class Meta: unique_together = ('id','name') verbose_name_plural = "Courses" def __str__(self): return self.name I have two models, student and courses and the relationship is many to many. From the django admin site, after adding a new course if I want to add new student the courses field in the student form is already filled with all the added courses and when I save I can't remove those courses. I want to create student without assigning courses initially. How do I do that? -
Problem with different schema relationship in Django Migrations
I have a multiple schema database with relationships between them and I have a problem migrating the database in Django. Firstly I created a BaseModel to override the meta class parameters: base_models.py: import django.db.models.options as options from django.db import models options.DEFAULT_NAMES = options.DEFAULT_NAMES + ("database",) class BaseErpModel(models.Model): class Meta: abstract = True database = "erp" models.py from django.db import models from config.base_models import BaseErpModel from teste_migrate.users.models import User class TrendUpload(BaseErpModel): trend_name = models.CharField("Tendência", max_length=255) created_at = models.DateTimeField("Data de criação", auto_now_add=True) user = models.ForeignKey(User, verbose_name="Usuário", on_delete=models.DO_NOTHING) class Meta(BaseErpModel.Meta): database = "erp" def __str__(self): return f"{self.trend_name} - {self.created_at}" dbrouter.py from django.apps import apps class BaseRouter(object): """A router to control all database operations on models in the erp schema""" def db_for_read(self, model, **hints): "Point all operations on model to 'database' meta db" if hasattr(model._meta, "database"): return model._meta.database return "default" def db_for_write(self, model, **hints): "Point all operations on model to 'database' meta db" if hasattr(model._meta, "database"): return model._meta.database return "default" def allow_relation(self, obj1, obj2, **hints): "Allow any relation in the same Database" return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Don't allow migrate to 'not_alowed_relation_models' """ try: model = apps.get_model(app_label, model_name) except: return None try: database = model._meta.database allow_migration = model._meta.allow_migration except: database … -
How to regroup blog posts with multiple categories by category in Django template
I have Blog with posts that have multiple categories class BlogDetailPage(Page): heading = models.CharField(max_length=150, blank=False, null=False) categories = ParentalManyToManyField("blog.BlogCategory", blank=False) ... class BlogCategory(models.Model): title = models.CharField(max_length=30,unique=True) slug = AutoSlugField(populate_from='title') ... My posts are as follows: Post 1: Category A Post 2: Category A, Category B Post 3: Category B I want regroup posts by category as below: Category A Post 1 Post 2 Category B Post 2 Post 3 My current solution is not giving me correct results. {% regroup posts by categories.all as posts_by_categories %} <ul> {% for category in posts_by_categories %} <li>{{ category.grouper.0 }} # first category name <ul> {% for post in category.list %} <li>{{ post.id }}, {{post.categories.all}}</li> {% endfor %} </ul> </li> {% endfor %} Amy ideas? -
How to save a bunch of many to many fileds using model to dict
I have a group of many to many fields that i am trying to save together with the other fields that are not many to many in django. def save_model(self, model_obj, model_cls): """ Get and save fields of a specific model """ kwargs = model_to_dict(model_obj, fields=[field.name for field in model_obj._meta.fields], exclude=['id', 'maternal_visit_id', 'maternal_visit']) for key in self.get_many_to_many_fields(model_obj): kwargs[key] = (self.get_many_to_many_fields(model_obj).get(key)) temp_obj = model_cls.objects.create(**kwargs, maternal_visit_id=self.id, maternal_visit=self.instance) temp_obj.save() am getting the many to many fields like def get_many_to_many_fields(self, model_obj): """ Return a dictionary of many-to-many fields in a model """ return model_to_dict(model_obj, fields=[field.name for field in model_obj._meta.get_fields() if isinstance(field, models.ManyToManyField)]) and when the script runs, it is giving me an error Internal Server Error: /admin/flourish_caregiver/maternalvisit/6128fcdc-8d39-41eb-a94d-fe839dd69a6e/change/ Traceback (most recent call last): File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/edc_model_admin/model_admin_next_url_redirect_mixin.py", line 68, in change_view return super().change_view(request, object_id, form_url=form_url, extra_context=extra_context) File "/Users/mcturner/.venvs/flourish/lib/python3.9/site-packages/django_revision/modeladmin_mixin.py", line 24, in change_view return super(ModelAdminRevisionMixin, self).change_view( File … -
How can I use newspaper3k with Django-rest-framework? I want to scrap news articles through newspaper3k then save in sqlite3
I want to scrap news articles through newspaper3k then save in sqlite3. I couldn't find any code where django and newspaper3k coded together. Please help me by writing proper code. Thanks -
How i can implement Calender Schedule Event in Django?
I want to implement this calender event with django. How i can do it .....?? enter image description here -
Why am I getting `NOT NULL constraint failed` error with Django?
I am new to Django. I am to create some sort of todo app. I am having trouble setting IntegerField as optional field. As far as I can see the problem is when I try to save to save the object to the database. I get error: NOT NULL constraint failed: lista_row.quantity. I have made (and migrated) migrations. Here is my models.py: from django.db import models from django.contrib import admin class Row(models.Model): name = models.CharField(max_length=200) quantity = models.IntegerField(null=False, blank=True) -
vuejs 401 unauthorized with axios from django backend with token
im trying to fetch data from django rest backend with axios in vuejs frontend but each time i get this error. the tokens match but it is still not authorizing. {"message":"Request failed with status code 401","name":"AxiosError","config":{"transitional":{"silentJSONParsing":true,"forcedJSONParsing":true,"clarifyTimeoutError":false},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1,"maxBodyLength":-1,"env":{"FormData":null},"headers":{"Accept":"application/json, text/plain, */*","Authorization":"Token838881311c52b89dd937815066e7eb3a3221604c"},"baseURL":"http://127.0.0.1:8000","method":"get","url":"/api/v1/clients/"},"code":"ERR_BAD_REQUEST","status":401} the axios looks like this axios .get('/api/v1/clients/') .then(response => { for(let i = 0; i< response.data.length; i++){ this.clients.push(response.data[i]) } }) .catch(error => { console.log(JSON.stringify(error)) }) } the settings in my django are ALLOWED_HOSTS = ['*'] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8000", ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES":( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ) } -
I can't using dynmaic loop in my django project
The problem is: The joined path (S:\cdnjs.cloudflare.com\ajax\libs\Swiper\6.4.8\swiper-bundle.min.js) is located outside of the base path component (C:\My projects - python\My_django_application\Myproject\static), i have many like this error. enter image description here I can return 4 pictures, I can also more.for example if i would return in my views, 'movies1': Movies_obj[:5], it's will show a 5 movies in home page. I uploaded 12 movies through the admin. As you can see in the link to the image, after I log in, the images appear to me, I have added Next and Previous buttons, but I can not use the loop. I worked with Boostrap Studio in the first part, to import photos and design. I tried to change things in settings, I tried almost everything, I could not use it. This is my first big project. My home HTML: </div> <div class="article-clean"></div> <script src="{% static 'MainHome/HeaderFooter/assets/bootstrap/js/bootstrap.min.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/bs-init.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/https://cdnjs.cloudflare.com/ajax/libs/baguettebox.js/1.11.1/baguetteBox.min.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/Simple-Slider.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/https://cdnjs.cloudflare.com/ajax/libs/Swiper/6.4.8/swiper-bundle.min.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/Lightbox-Gallery.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/Simple-Slider-1.js' %}"></script> <script src="{% static 'MainHome/HeaderFooter/assets/js/Swipe-Slider-7.js' %}"></script> </div> <div id ="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <div class="row"> {% for mv1 in movies1 %} <div … -
NGINX: Block all external IPs except the server IP where ReactJS is hosted?
Can anyone help how to configure nginx so it only accepts the server IP where ReactJS is hosted? Ive tried many options to no avail. I always see ReactJS is using the client IP where the user is currently browsing (because of I guess of its client-based nature). Unfortunately, I need to block all other request to protect my Django rest api from external requests. My Django app is having this nginx reverse proxy by the way. How do you guys do this? -
Creating MySQL views with id to work with Django
I have a mysql view that I wish to define as a self-managed Django model managed = False I don't have an id column because I am doing multiple joins and the resulting view has more rows than any of the joined tables. I get a 1054 error When I try to access the model myview.objects.all() OperationalError: (1054, "Unknown column 'myview.id' in 'field list'") [Q] How do I either add an auto-incremented id column to the view and/or tell Django not to look for the 'id' field? -
Login Button is not appearing in mobile view, working fine in PC. Using Django/python and html
I'm trying to see the login button on the upper right hand screen, its working fine on PC, but in my mobile I do not see the signup button, maybe its being overlapped by something else, not sure, please help: Im using django with bulma stylesheets. HTML Code: <!DOCTYPE html> <html> <head> <!-- Meta --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Title--> <title>F.C. Rayados Playa del Carmen</title> <!-- Styles --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css"> </head> <body> <!-- Navbar --> <nav class="navbar is-light"> <div class="navbar-brand"> <a href="{% url 'frontpage' %}" class="navbar-item"><strong>Inicio</strong></a> </div> <div class="navbar-menu"> <div class="navbar-end"> <div class="navbar-item"> <div class="buttons"> {% if request.user.is_authenticated %} <a href="{% url 'logout' %}" class="button is-danger">Log out</a> {% else %} <a href="{% url 'signup' %}" class="button is-success"><strong>Registrate</strong></a> <a href="{% url 'login' %}" class="button is-light">Log in</a> {% endif %} </div> </div> </div> </div> </nav> <!-- End Navbar --> <!-- Main content --> <section class="section"> {% block content %} {% endblock %} </section> <!-- End Main content --> </body> </html> -
How to efficiently build product model with subcomponent list in django application
I am developing a product catalog web application that consists about 100 of main products build from 15-25 subproducts. Subproduct catalog is much larger, as there are almost 500 different components to build the main products. Subproducts are also multi-layer builds. Components should be stored to sqlite database and data should be reachable by the product id to create some packaging documentation, boms and other lists. I haven't really found any good examples that I could apply to this problem as making lists like this doesn't seem to be as easy as I thought it would. Does anyone know any examples that would be helpful to case like this? -
Django debugger does not start by VS Code launch.json
Until recently my Django projects would debug fine using launch.json file. But it stopped working today and I have no idea about it. Changes made by me in system were: Clean-Installing Windows Installing python in default path just for current user and not all users Problem Description: As soon as I click F5 key the debugger starts for some milliseconds and stops automatically without any prompt. As it does not shows any error I tried to log errors by nothing in it. It does not even load terminal to run commands. The added configuration in launch.json file is as below: { "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true, "logToFile": true, "console": "integratedTerminal", "cwd": "${workspaceFolder}", "host": "localhost" } ] } Can someone help to troubleshoot this, I have already tried: Creating new projects Reinstalling Python Creating new environment Resetting VS Code Sync Settings Run other dubug configurations {they are working fine) Changing django debug configuration My current options are: Research more (Already spent a hours would take more) Wait for solution by someone Clean Install Windows and all software's (Would be like BhramaAstra) -
Django: Reverse accessor clashed with reverse accessor
In the code below, I have a post, likes, comment models. When I try to migrate the models to activate it, I am getting a reverse accessor error. For likes, user_that_liked only like once, while user_liked_to can have many likes. For comments, both user_that_commented and user_commented_to can have many comments. How should I set up my models so I can do what I want with the models, while also getting this issue fixed. If you need more information, let me know. from django.db import models from django.contrib.auth.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_question = models.CharField(max_length=200) pub_date = models.DateTimeField() class Likes(models.Model): user_that_liked = models.ForeignKey(User, on_delete=models.CASCADE) user_liked_to = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField() like_or_dislike = models.IntegerField(default=0) class Comment(models.Model): user_that_commented = models.ForeignKey(User, on_delete=models.CASCADE) user_commented_to = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField() comment = models.CharField(max_length=300) -
Skip Django Allauth " You are about to sign in using a third party account from Google" page
How can I skip the page and automatically logged in users, when they clicked on Login in With Google. -
best message broker for Django?
I'm learning Django with a book and it shows the use of rabbitmq to deal with the messaging for an online shop, but some of the commands don't work and some of the code is deprecated. Do you have any recommendation for a message broker that works well for Django? Thanks and have a nice day! -
How to filter multiple nested serializer in django rest framwork
I've Tripserializer class contain nested serializer PackageSerializer, inside it there is nested serializer PriceSerializer . class Trip_apiView(generics.ListCreateAPIView): queryset= Trip.objects.all() serializer_class=TripSerializer class PackageSerializer(serializers.ModelSerializer): price=PriceSerializer(source='trip_price', many=True, read_only=True) class Meta: model = Package exclude = ('is_active', 'create_date', 'modify_date') class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price exclude = ('is_active', 'create_date', 'modify_date') this my views: class Trip_apiView(generics.ListCreateAPIView): queryset= Trip.objects.all().order_by('title') serializer_class=TripSerializer I receive list of all trips from GET method like this: [ { "id": 137, "title": "dqw", "package": { "id": 139, "price": { "id": 78, "price": 2.2, "sale_price": 2.2, "trip_package": 139 }, "package_name": "wfe", "description": "fwe", "trip": 137 }, }, {....}, {....} ] How Can I Filter this List of trips by price and by title -
How to make relation between rows in the same table in Django
Let me show an example first: Table1: id | sub_is | name ---|--------|----- 1 |null | group 1 2 |1 | group 2 3 |1 | group 3 4 |2 | group 4 5 |2 | group 5 6 |3 | group 6 7 |1 | group 7 8 |4 | group 8 It will be look like a small structure: group 1 |- group 2 | |-group 4 | | |-hroup 8 | |-group 5 |- group 3 | |-group 6 |- group 7 My question is: How can I do this in Django? How, if it is possible, I can make relation between two rows in the same table? Thanks for any suggestions and any help. -
I don’t understand how to write correct query to database by Django orm
I have two models: Class Page(models.Model): Id Class LinkedPage(models.Model): page = models.ForeignKey(Page) created_year = models.IntegerField(…) I want to get queryset of linkedPage that are group by page and have the highest created_year in the his group. For example: There is page with 3 linked page created year that are 2011, 2005, 2019. There is the second page with 3 linked page created year that are 1960, 2017, 2005. I want to get 2 records(instance with all fields) year that are 2019(from the first page) and 2017(from the second page). Thanks a lot