Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why the path of static files change when I add slash (/) at the end of the url's path in django
Why when I use slash in url's path the path of static files get changed: Below is main project urls.py file: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('app_home.urls')), path('blog', include('app_blog.urls')), ] if settings.DEBUG == True: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and forexample if I add slash at the end of blog the path of static files get changed: path('blog/', include('app_blog.urls')), therefore the path if I add a slash will be: http://127.0.0.1:8000/**blog**/static/vendor/bootstrap/js/bootstrap.bundle.min.js (and none of static files are functional because the path is changed) instead of the correct path which is: http://127.0.0.1:8000/static/vendor/bootstrap/js/bootstrap.bundle.min.js -
Docker django project problem with mysqlclient for using mysql
I have problem with docker container build process with docker compose, the django project that i want to build, has problem in mysqlclient library installation and usage, I use pip cache for faster build process and lower internet download traffic, but in this way the mysqlclient library seems that did not completely installed : If i run a db related command this error shown : Or inside container : If i uninstall it and install it again without using cache, the problem goes away : I use python:3.11-slim image and install all dependencies before going for this : RUN apt install apt-utils python3-dev \ default-libmysqlclient-dev pkg-config gcc -y --no-install-recommends The process of building this specific library is different when i not use cache and after that everything is works fine . why !? mysqlclient==2.2.1 host : ubuntu 23.10 django 4-5 -
When i click back on django root url it gives error page not found
Hello everyone i face problem in djnago ,When i click back on root url,in urls.py it give error page not found.plz answer my question quickly. I only add html template in djnago, all pages works properly but when we click back on root url it give error of page not found -
I m not able to send Json data to Django views.py , im trying Ajax for this but its not working , also its show CSRF error
I'm facing an issue with CSRF verification in a Django project when making an AJAX POST request. Here's a simplified version of my code: **registration.html *** <form method="POST" onsubmit="return validateForm()"> (----this revieves the data------) {% csrf_token %} <label for="name">Name:</label> <input type="text" id="name" name="name" required /> <label for="email">Email:</label> <input type="email" id="email" name="email" required /> <label for="password">Password:</label> <input type="password" id="password" name="password" required /> <input type="submit" value="Register" name="createuser"/> </form> </div> </div> <script> let URLd ="{% url 'defaultpg' %}" let nameInput = document.getElementById("name"); let emailInput = document.getElementById("email"); let passwordInput = document.getElementById("password"); (------below funtion validates it -----) function validateForm() { var csrfToken = $("input[name='csrfmiddlewaretoken']"); let nameValue = nameInput.value; let emailValue = emailInput.value; let passwordValue = passwordInput.value; let isNameValid = /^[a-zA-Z]+$/.test(nameValue); let isEmailValid = /^\S+@\S+\.\S+$/.test(emailValue); let isPasswordValid = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(passwordValue); if (isNameValid) { if (isEmailValid) { if (isPasswordValid) { alert("Successful"); $.ajax({ type: "POST", url: '/defaultpg', headers: {"X-CSRFToken":'{{ csrf_token }}'}, data: { "name": nameValue, "email": emailValue, "password": passwordValue, 'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]") }, dataType: "json", success: function (data) { // any process in data alert("successful"); }, error: function () { alert("failure"); } }); } else { alert("Password must contain letters, capital letter, small letter, special character, and numbers with a length above 8"); } } else { alert("Please enter a … -
How to Constraint Date Range From Intersection
I have a model defined like below class Event(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) start = models.DateField() end = models.DateField() I would like to setup constraints such that time span of each room's event is not intersect with each other. For example: Event 1: Room A, date: [2024-01-01, 2024-01-05]; Event 2: Room A, date: [2024-01-08, 2024-01-12]; <- Fine Event 3: Room A, date: [2024-01-04, 2024-01-07]. <- NOT fine Event 3 is not fine because Room A is already occupied by Event 1 on Jan 4th and Jan 5th. How can I achieve this with model constraints? -
OperationalError at / no such column: app_post.category_id
I'm working on a Django project (like a blog), and I'm bit struggling with when I edit models in live project (meaning that I cannot lose my db). In this case originally I didn't have category to my posts, now I have added but there is an issue. When I apply makemigrations and migrate, I get this: OperationalError at / no such column: learning_app_post.category_id Tried also this by some internet sources: python manage.py migrate --fake learning_app zero ... and when I migrate again, I get django.db.utils.OperationalError: table "learning_app_post" already exists. So I end up in the loop, any ideas here? This is my models.py class Category(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") category_name = models.CharField(max_length=255, verbose_name="Category name") parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True) def clean(self): if self.parent: if self.parent.parent: raise ValidationError("A category that already has a parent cannot be set as the parent of another category.") def save(self, *args, **kwargs): self.clean() super(Category, self).save(*args, **kwargs) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.category_name class Post(models.Model): category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, blank=True, null=True, default=None) ... #rest of the post model Thanks in advance! -
Django rest framework is providing the wrong parameters to custom permission class
I'm having an issue where Django Rest Framework's custom permission system is treating my custom permissions' methods like they are classmethods or staticmethods. When hitting a breakpoint in the permission method: def has_permission(self, request, view=None): self is an instance of request instead of an instance of the permission class request is an instance of view and I had to put view=None because it was crashing with missing parameter errors Have I configured it wrong somehow? My IsEmailVerified permission used as a default permission has been working as expected for a month, but when adding custom permissions more programmatically I get errors. File "/app/api/permissions.py", line 50, in has_permission user = request.user ^^^^^^^^^^^^ AttributeError: 'ExampleViewSet' object has no attribute 'user' settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'api.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'api.permissions.IsEmailVerifiedPermission', ), . . . } permissions.py class IsEmailVerifiedPermission(BasePermission): def has_permission(self, request, view=None): return request.user.email_verified def has_object_permission(self, request, view=None, obj=None): return request.user.email_verified class UserCreated(BasePermission): def has_permission(self, request, view=None): # While debugging the parameters don't line up: # self is an instance of request # request is an instance of view # and I had to put view=None because it was crashing with missing parameter errors def has_object_permission(self, request, view=None, obj=None): # … -
nginx configuration for vps server react and django app
I really new with deploy, but finnally I've got some results: I run my react app in <my_ip>:3000 I run my django project in <my_ip>:8000 What I need is: run <my_domain_name> react app run <my_domain_name>/admin django app I faced with the problem with nginx configuration. I try at list start one app, but got 502 error. sudo nano /etc/nginx/sites-available/default/ server { listen 80; server_name my_domain.com; access_log /var/log/nginx/example.log; location /media/ { root /home/ubuntu/server; expires 30d; } location /static/ { root /home/ubuntu/server; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; 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; } } I checked /etc/hostname is test I add this hostname to /etc/hosts 127.0.0.1 localhost 127.0.1.1 test 127.0.1.1 unassigned-hostname.unassigned-domain unassigned-hostname # The following lines are desirable for IPv6 capable hosts ::1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters Restart nginx successfully done, but I still see my projects only on 3000 and 8000 posts. How can I fix it? sudo service nginx restart Also how correctly add the react app into nginx settings? One more: I run my react app with command npm start. But when I close the terminal, 3000 port also stop working. How can I fix this issue? For django … -
Backend not working after pulling a commit from history that worked
I have my Authentication System backend on Django and Frontend on React. I was trying to implement a new API endpoint and suddenly my authentication system is not working (Auth system made with Djoser). I can assure you that before moving on to the new API I tested the Authentication System API's with POSTMAN and everything worked fine. I am using postgres db. I pulled a git commit from history that worked for sure, and still not working. One of my friends is a collaborator and for him is working, he force pushed and overwritten everything but for me for some reason it doesn't work anymore. When trying to Sign Up (or Login) I get this error POST /auth/users/ HTTP/1.1" 400 29 POST /auth/users/activation/ HTTP/1.1" 400 50 POST /auth/jwt/create/ HTTP/1.1" 401 63 Here is my 2 models from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.dispatch import receiver # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = … -
Heroku - Django - Translation not working in production
I am trying to translate some static text with a Django app. It works on my local, but not on production. I use Heroku. What I did: After doing some research it seems to be partly because .mo is in my .gitignore.py. However, I read a few times that this should remain as such and instead automate compile messages in an app.json file. Which is what I did below: app.json { "scripts": { "release": "python manage.py compilemessages" }, } With the 'gettext' buildpack added to Heroku, I did manage to see a large push of lines contained in my local .mo file on the production logs. However, I cannot seem to be able to render them. I can clearly see the .mo files when running: heroku run bash -a appname find . -name "*.mo" Questions: Should I simply remove the .mo from .gitignore to fix the issue? Am I right to continue on the current path and find a solution without removing .mo from .gitignore? -
Issue with API pagination in django
the problem I'm having is that when I try to click next in the pagination that I did, the link param name "dataType" dosen't stays and it resets to none value, please help. I'm Using django I did some debug and appears like this: [13/Jan/2024 13:33:57] "GET /search/?query=Spaghetti&dataType=&page=27 HTTP/1.1" 200 9901 query: Spaghetti, dataType: Branded, page: 1 [13/Jan/2024 13:34:06] "GET /search/?query=Spaghetti&dataType=Branded HTTP/1.1" 200 7304 query: Spaghetti, dataType: , page: 2 And this is my html: <!-- PAGINATION LINKS --> <div class="pagination"> <span class="step-links"> {% if pagination.current_page > 1 %} <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page=1">&laquo; first</a> <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page={{ pagination.current_page|add:'-1' }}">previous</a> {% endif %} <span class="current"> Page {{pagination.current_page}} of {{pagination.total_pages}}. </span> {% if pagination.current_page < pagination.total_pages %} <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page={{ pagination.current_page|add:'1' }}">next</a> <a href="{% url 'search_aliment' %}?query={{query}}&dataType={{dataType}}&page={{pagination.total_pages}}">last &raquo;</a> {% endif %} </span> </div> I don't know if the issue is from the views.py or the html or the forms.py, apreciate your responses!!! I have tried changing the links in the html and nothind I did worked. -
Django ecommerce modeling- how to model product/service options?
I am currently facing a dilemma where we are creating a service which can be used for billing or ecommerce-type applications where products and services are modeled and can be sold. I am working on Services, which have ServiceOptions. The Services are assigned to Businesses, which will each contain a unique combination of Services and ServiceOptions. Because of this, I have represented a Service which all possible ServiceOptions point to as a foreign key relation, creating a BusinessService to assign the unique variants to a Business. However, I am currently unable to understand how to model the relationship between ServiceOptions and the BusinessService. My current service models are as follows: class Service(models.Model): name = models.CharField(max_length=150) description = models.CharField(null=True, max_length=450) price = models.IntegerField(null=True) class ServiceOption(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) name = models.CharField(max_length=150) description = models.CharField(null=True, max_length=450) price = models.IntegerField(null=True) class BusinessService(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) price_override = models.IntegerField(null=True) is_active = models.BooleanField(default=False) activation_date = models.DateTimeField(default=timezone.now) Here we create a unique entity tying the Service to the Business, but this is not sufficient to represent the ServiceOptions, as the BusinessService.service.serviceoption relation contains ALL possible options, not those specific to the business. I have considered structuring the models as follows: … -
Django/Stripe No Reverse Match
I've been following this tutorial (https://www.saaspegasus.com/guides/django-stripe-integrate/) on integrating a subscription service to my application. Everything seems fine, when i checkout it updates my stripe database with the new subscription, but i get a NoReverseMatch error after clicking the checkout button. Specifically, the error says "NoReverseMatch at /subscription-confirm/ Reverse for 'subscription_details' not found. 'subscription_details' is not a valid view function or pattern name." Nowhere in my code do i define a "subscription_details", i was assuming that maybe this was something that came included in the djstripe package? Also the tutorial does nothing to define it either. I'm kind of lost here. The one thing that i see is a little odd is on my views file, when trying to import 'from djstripe.settings import djstripe_settings' and 'from djstripe.models import Subscription', that Pylance isnt recognizing djstripe.settings or djstripe.models. Here is some of the code i think is relevant, if you guys want to see more just ask. Thanks in advance! views.py: from typing import Any from django.db.models.query import QuerySet from django.urls import reverse_lazy, reverse from django.views.generic.edit import CreateView from django.views.generic import TemplateView, ListView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from .models import Picks from django.shortcuts import render from django.core.mail import send_mail, … -
The Connection between two models inside model.py Django
I have database for my Music's and I wanna add a new one for my Artists. What I need is that when I'm adding a new music application check the artist name if artist name was in the Artist Model then pass ,and if not artist name add to Artist Model. class Artist(models.Model): name = models.CharField(max_length=100) followers = models.IntegerField(default=0) class Music(models.Model): name = models.CharField(max_length=150) artist = models.CharField(max_length=150) length = models.CharField(max_length=20) genre = models.CharField(max_length=100) release_date = models.IntegerField() likes = models.IntegerField(default=0) imageLink = models.CharField(max_length=200) mp3Link = models.CharField(max_length=200) def get_artist(self): return self.artist # Set Artist in Artist Model try: # To check Artist exists or not Artist.objects.get(name = get_artist) except: # if Artist not exist then add it Artist(name = get_artist).save() -
Wraning in Django Model
I don't Understand What this exactly means! RuntimeWarning: Accessing the database during app initialization is discouraged. To fix this warning, avoid executing queries in AppConfig.ready() or when your app modules are imported. warnings.warn(self.APPS_NOT_READY_WARNING_MSG, category=RuntimeWarning) Watching for file changes with StatReloader Performing system checks... -
Static files not loading properly
Things I have done: 1.base template i have provide {% load static %} <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="apple-touch-icon" sizes="76x76" href="/static/assets/img/apple-icon.png" > <link rel="icon" type="image/png" href="{% static 'assets/img/favicon.png' %}" > <title> Al Amal Jewellery - {% block title %}{% endblock %} </title> <!-- Fonts and icons --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700" rel="stylesheet" /> <!-- Nucleo Icons --> <link href="{% static "assets/css/nucleo-icons.css" %}" rel="stylesheet" /> <!-- Font Awesome Icons --> <script src="https://kit.fontawesome.com/42d5adcbca.js" crossorigin="anonymous"></script> <!-- CSS Files --> <link id="pagestyle" href="{% static "assets/css/soft-ui-dashboard.css?v=1.0.5" %}" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha256-eTyxS0rkjpLEo16uXTS0uVCS4815lc40K2iVpWDvdSY=" crossorigin="anonymous"></script> <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} </head> <body class="{% block body_class %}{% endblock %}"> {% include "includes/sidebar.html" %} <main class="main-content max-height-vh-full h-100"> {% include "includes/navigation.html" %} {% block content %}{% endblock content %} </main> {% include "includes/fixed-plugin.html" %} {% include "includes/scripts.html" %} <!-- Specific JS goes HERE --> {% block javascripts %}{% endblock javascripts %} <script> var win = navigator.platform.indexOf('Win') > -1; if (win && document.querySelector('#sidenav-scrollbar')) { var options = { damping: '0.5' } Scrollbar.init(document.querySelector('#sidenav-scrollbar'), options); } </script> </body> </html> statics in setting.py based on Managing Static Files """ Django settings for … -
build docker container with postgresql on rpi2
I built django project with cookie-cutter-django. Everything works fine on my local, I could build and running stacks. Now, I am trying to deploy it to my raspberry pi 2. But having issue with psycopg. First, here is the basic config of the project. cookie-cutter-django django 4.2.8 python 3.11.7 Secondly, here is my rpi os info. Operating System: Raspbian GNU/Linux 11 (bullseye) Kernel: Linux 6.1.21-v7+ Architecture: arm postgresql is not installed Thirdly, my local device for development. ubuntu 22.04 I cloned the repo and tried to build production.yml. And got this error. 417.5 Collecting prompt-toolkit==3.0.43 (from -r production.txt (line 50)) 417.6 Downloading prompt_toolkit-3.0.43-py3-none-any.whl.metadata (6.5 kB) 420.4 ERROR: Could not find a version that satisfies the requirement psycopg-binary==3.1.17 (from versions: none) 420.4 ERROR: No matching distribution found for psycopg-binary==3.1.17 I researched a lot, but couldn't find the right answer. The possible solution I could think of was installing the pure python installation on psycopg official documentation. so I tried to add libpq5 to Dockerfile, but having different error like this screenshot. Here is my production Dockerfile. FROM node:20-bullseye-slim as client-builder ARG APP_HOME=/app WORKDIR ${APP_HOME} COPY ./package.json ${APP_HOME} RUN npm install && npm cache clean --force COPY . ${APP_HOME} RUN npm run … -
Django no app_label in model
I have a django rest app called hotels, my structure directory is the following: app/ ├── config │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── hotels │ ├── admin.py │ ├── apps.py │ ├── filters.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── serializers.py │ ├── tests │ └── views.py ├── __init__.py └── __pycache__ └── __init__.cpython-38.pyc In the models.py file I have defined a class called HotelChain as follows: class HotelChain(TimestampedModel): PRICE_CHOICES = [ (1, "$"), (2, "$$"), (3, "$$$"), (4, "$$$$"), ] title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) description = models.TextField(blank=True) email = models.EmailField(max_length=50, blank=True) phone = models.CharField(max_length=50, blank=True) website = models.URLField(max_length=250, blank=True) sales_contact = models.CharField(max_length=250, blank=True) price_range = models.PositiveSmallIntegerField(null=True, blank=True, choices=PRICE_CHOICES) def __str__(self): return f"{self.title}" But I am getting this error: RuntimeError: Model class app.hotels.models.HotelChain doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I tried adding class Meta: app_label = 'hotels' To the class definition but it doesn't fix the issue. My app config is this one: INSTALLED_APPS = ( 'hotels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_filters', 'import_export', ) -
How to grant permissions to a so that server allows the creation of directories on the fly
When a user uploads a picture, my django code creates a directory (or folder if you want) with his name (picked up from the session user). This works in my local development environment but production does not grant that permission just like that. So, for savy system administrators out there here it goes: This code is fine MODEL def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user, filename) images = ResizedImageField(size=[500, 300], upload_to=user_directory_path, blank=True, null=True) VIEWS.py for image in images: Photos.objects.create(images=image, builtproperties_id=last_built_id, user=username) So, this creates me a directory in this path: media/user_peter media/user_mary etc I thought that by doing this: sudo chmod 775 media It would allow the creation of subdirectories (user_peter, user_mary etc) but, apparently it does not as I got a "permission denied" wrist slap. What command would do that? Thank you -
Is it possible to use requests-cache functionalities on vercel?
Since vercel doesn't support SQLite, I am wondering if python applications like Django deployed on vercel will be able to leverage the functionalities of python's popular requests-cache library. Reason for this is because this library generate SQLite files for caching purpose. Also, is there any workaround using SQLite on vercel. What I tried: using requests-cache library for serverless environment. What is expected: Django app running without any problem on vercel -
Using Model Field Values inside Model.py
I have Model in django and I wanna use username value inside this Account Model to Address ImageField How can I do that? class Account(models.Model): nickname = models.CharField(max_length=150) username = models.CharField(max_length=70) password = models.CharField(max_length=70) email = models.EmailField(max_length=70) avatar = models.ImageField(upload_to = f'userdata/{username}/avatar/' ,default= MEDIA_ROOT + 'default/img/avatar.png') -
Dealing with Tokens in django and react
I'm currently working on a social network app for my Backend, I'm using Django and for the Frontend React-TS. After doing a bit of research, I've decided to use a JWT Token (Generated with help of rest_framework_simplejwt), and use it in requests as a BearerToken. Currently, I'm saving the AccessToken and the RefreshToken in the local storage, but having read a bit about how storing tokens in local storage can pose security risks, such as exposure to Cross-Site Scripting (XSS) attacks, I grew a bit worried. I thought I'd ask here since I came across too many suggestions online (HTTP-Only Cookies, Database Storage with Encryption and Password-Based Encryption). Since I lack the experience to decide which to use when, I would appreciate any and every advice. How do you store your Tokens and why? -
Contact Form, with sending emails but no email is received, DJANGO REST FRAMEWORK
My problem is the terminal says that it is sending email, but there is no email received. Here is my views ` from rest_framework.views import APIView from GoGet import settings from .models import * from rest_framework.response import Response from .serializer import * from django.core.mail import send_mail from django.conf import settings Create your views here. class ContactView(APIView): serializer_class = ContactSerializer def post(self, request): serializer = ContactSerializer(data=request.data) # subject = models.Contact.subject if serializer.is_valid(raise_exception=True): serializer.save() self.send_contact_email(serializer.validated_data) return Response(serializer.data) def send_contact_email(self, data): subject = 'New Contact Form Submission' message = f''' Name: {data['name']} Email: {data['email']} Subject: {data['subject']} Message: {data['message']} ''' send_mail( subject, message, settings.EMAIL_HOST_USER, # Sender's email address [settings.CONTACT_EMAIL], # Receiver's email address (can be a list of multiple emails) fail_silently=True, )` Im expecting an email, but i dont receive any, checked the spams, sent, there is nothing -
Django Auth Login
I have a django project, when I create a user from empty migration files, I can logged in perfectly. But when I create a user from POST method, I can't logged in and it throwing invalid credentials. This is my user model class User(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField("Username", max_length=50, unique=True) password = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_password_reset = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) deleted_at = models.DateTimeField(null=True, blank=True) roles = models.ManyToManyField(Role, related_name='users') def delete(self, *args, **kwargs): self.deleted_at = timezone.now() self.save() def save(self, *args, **kwargs): # Hash the password before saving self.password = make_password(self.password) super(User, self).save(*args, **kwargs) def __str__(self): roles_str = "\n".join([str(role) for role in self.roles.all()]) return f"(username: {self.username}, id: {self.id}, is_active: {self.is_active}, is_password_reset: {self.is_password_reset}, roles:\n{roles_str})" this is my login API view @api_view(['POST']) @authentication_classes([]) @permission_classes([AllowAny]) def login(request): username = request.data.get('username') password = request.data.get('password') user = authenticate(request, username=username, password=password) if user: serializer = UserSerializer(user, context={'request': request}) refresh = RefreshToken.for_user(user) data = { 'user': serializer.data, 'refresh': str(refresh), 'access': str(refresh.access_token), } return Response(data) else: return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) I already tried to debug using raw password without hashing and print out the request from login. It prints out exactly the same as in the database. But it keeps … -
Herokuga django loyihamni joylashtirdim
Men loyihamni migrate va createsuperuser qilishim lozim. Lekin buni amalga oshirib bulmayapti. Qanday qilib loyihamni migrate qilsam buladi. Qanday tavsiya beraszlar Run consoledan migrate va boshqa buyruqlarni berdim ammo buyruqlarimni loyiha papkasiga saqlamayapti