Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-filter using filter class in another filter class
I use django-filter I have two models named Person and Member. Person has been defined as foreign key in Member. As an example here, I added less fields, normally the PersonModel model has a lot more fields. What I want to do here is to use all the filter fields I created for person in the filter class I created for Member. models.py class PersonModel(models.Model): name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class MemberModel(models.Model) register_no = models.CharField(max_length=20, unique=True) person = filters.ForeignKey(PersonModel, on_delete=models.PROTECT, related_name='members') filters.py class PersonFilter(filters.FilterSet): name= filters.CharFilter(field_name='name') last_name= filters.CharFilter(field_name='last_name') class MemberFilter(filters.FilterSet): register_no = filters.CharFilter(field_name='register_no') # # I want to use PersonFilter here # for example: person = PersonFilter(lookup_expr="person") or how? # # I don't want to do it this way: # person_name = filters.CharFilter(field_name='person__name') # person_last_name = filters.CharFilter(field_name='person__last_name') -
How to convert Figma design to Django?
I am making an app using Django and Python and I want to integrate some Figma designs with my web application. Does anyone know how to do this? -
Deploying Django on Heroku smart-open Causing Failure
Trying to deploy Django project to Heroku I get the following error: python setup.py egg_info did not run successfully. exit code: 1 error in smart_open setup command: 'python_requires' must be a string containing valid version specifiers; Invalid specifier: '>=3.6.*' note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed Tried multiple versions of smart-open and tried removing it from requirements.txt, the invalid specifier is NOT in my requirements.txt (this is: smart-open==4.1.0) or I have tried multiple other versions, all break the build. I’ve tried changing setup tools on Heroku to eg setuptools==40.3.0, no dice (same errors). -
Django app not loading with DisallowedHost error even after adding IP to ALLOWED_HOSTS
I'm facing an issue with my Django web application deployment on an Amazon EC2 instance. The app is running using Gunicorn and Nginx as a reverse proxy. However, when I try to access the app using the public IP address (ipaddress:8000), it's not loading, and I keep getting a "DisallowedHost" error. Here are the steps I've taken so far: In my Django settings.py, I've added the public IP address to the ALLOWED_HOSTS setting: python Copy code ALLOWED_HOSTS = ['ipaddress:8000'] I've confirmed that Gunicorn is running and bound to ipaddress:8000 . Nginx is configured as a reverse proxy with the following settings: nginx Copy code server { listen 80; server_name ipaddress:8000 location / { proxy_pass http://ipaddress:8000 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } Despite these configurations, the app still does not load, and I receive the following error in my Django logs: css Copy code [2023-08-02 17:28:00 +0000] [#] [INFO] Starting gunicorn 21.2.0 [2023-08-02 17:28:00 +0000] [#] [INFO] Listening at: http://ipaddress:8000 (#) ... DisallowedHost at / Invalid HTTP_HOST header: 'ip address'. You may need to add 'ipaddress' to ALLOWED_HOSTS. It seems like Django is still considering the request host as 'ipaddress', even though I've explicitly added it to ALLOWED_HOSTS. Any … -
Prevent custom django admin url from redirecting to change view
I have defined a custom django admin url that I am using as a custom action link in the changelist view and will also be used by the form posted in that custom view. # used in the overridden changelist.html <a href="{% url 'admin:get_monthly_report' %}">Get Monthly Report</a> # in the model admin def get_urls(self): urls = super().get_urls() urls += [ path( 'get_monthly_report/', self.admin_site.admin_view(self.get_monthly_report), name='get_monthly_report' ), ] return urls Problem is clicking on the link keeps trying to redirect the change view (doesn't make sense why Django is trying to guess instead of using the actual view defined for the URL). Given that what am doing is close enough to what is suggested in the documentation, either the documentation left this problem out or am doing something wrong -
Error when changing project server from Django to Azure
When I converted the website I have from Django storage to Azure, I got some errors I cant seem to fix. This was setup by a coworker of mine, and everything worked fine there, but on my computer, both at work and at my other computer home the same error occurs. django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I have tried the following commands pip install req.txt pip install django pip install mssql django-mssql pip install django-mssql-backend pip install pyodbc python manage.py makemigrations python manage.py migrate python manage.py runserver Below is the ouput from my pip freeze command. Perhaps there are some missmatched versions that is causing some conflicts. aiohttp==3.7.4.post0 anyio==3.7.1 api-display-purposes==0.0.3 appdirs==1.4.4 APScheduler==3.10.1 arabic-reshaper==3.0.0 asgiref==3.6.0 asn1crypto==1.5.1 astroid==2.15.6 async-timeout==3.0.1 attrs==21.2.0 autobahn==23.6.2 Automat==22.10.0 autopep8==2.0.2 bcrypt==4.0.0 beautifulsoup4==4.12.2 blinker==1.6.2 cachetools==5.3.1 capstone==5.0.0rc2 certifi==2022.9.24 cffi==1.15.1 chardet==3.0.4 charset-normalizer==2.1.1 clarifai==9.6.3 clarifai-grpc==9.6.1 click==8.1.3 colorama==0.4.6 colored-traceback==0.3.0 configparser==3.8.1 constantly==15.1.0 cryptography==38.0.1 cssselect2==0.7.0 defusedxml==0.7.1 dill==0.3.7 discord==1.0.1 discord.py==1.6.0 distlib==0.3.7 Django==2.1.15 django-allauth==0.54.0 django-colorfield==0.9.0 django-countries==7.5.1 django-crispy-forms==2.0 django-jsonview==2.0.0 django-mssql==1.8 django-mssql-backend==2.8.1 django-multiselectfield==0.1.12 django-tinymce4-lite==1.8.0 djangorestframework==3.14.0 EasyProcess==1.1 emoji==2.7.0 exceptiongroup==1.1.2 filelock==3.12.2 Flask==2.3.1 future==0.18.3 googleapis-common-protos==1.60.0 greenlet==2.0.2 grpcio==1.56.2 h11==0.14.0 html5lib==1.1 httpcore==0.17.3 httpx==0.24.1 hyperlink==21.0.0 idna==2.10 importlib-metadata==6.6.0 instapy==0.6.16 … -
Problem with picture tags in Django templates
I'm getting some issues with a picture tag in a Django template. The goal is easy, I'm just trying to add to my website an image which may be in Avif, Webp or JPG/PNG format. I've written my HTML as I've done several times before, but somehow it's not working as expected. So the problem is as follows: in a first try, the AVIF version (which corresponds to the first source tag) is well loaded 👌🏻, but if I delete it from the server (or change its name), I was expecting WebP version to be loaded, though the alt message is shown. This is my code: <picture> <source srcset="{% static 'my_app/img/' %}{{ topic.image|avif_image }}" type="image/avif"> <source srcset="{% static 'my_app/img/' %}{{ topic.image|webp_image }}" type="image/webp"> <img src="{% static 'my_app/img/' %}{{ topic.image|original_image }}" alt="{{ topic.name }} image" loading="lazy"> </picture> Note: avif_image, webp_image and original_image are just some custom filters I've created to return each image's name, while topic is the field sent from the view to the template. I realized that the browser is always trying to load the first source tag, I mean, if I reorder the code and set WebP as the first one, I get the same problem but the … -
How to sort by letter in Django
On my website, there are different listings arranged as (a-e), (e-j), (j-o), (o-t), and all. When a user clicks on any of these listings, I want the website to retrieve data from the database starting with titles that fall within the selected letter range. However, I'm not very familiar with how to implement this functionality. Can anyone help me with this? index.html <div class="widget-content"> <h4>Sort by letter</h4> <ul class="widget-links"> {% for letter_range in letter_ranges %} {% if selected_range == letter_range %} <li><strong>{{ letter_range }}</strong></li> {% else %} <li><a href="?range={{ letter_range }}">{{letter_range}}</a></li> {% endif %} {% endfor %} </ul> views.py def index(request): letter_ranges = ['All', 'a-e', 'e-j', 'j-o', 'o-t', 't-z'] selected_range = request.GET.get('range', 'All') if selected_range == 'All': queryset = tabir.objects.filter(is_active=True) else: start_letter, end_letter = selected_range.split('-') queryset = tabir.objects.filter(title__istartswith__range=(start_letter, end_letter), is_active=True) context = { "tabirs": queryset, "current_date": datetime.now(), "selected_range": selected_range, "letter_ranges": letter_ranges, } return render(request, "ruya/index.html", context) models.py class tabir(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=200) description = RichTextField() is_active = models.BooleanField(default=False) is_home = models.BooleanField(default=False) release_date = models.DateTimeField(null=False,blank=True) #default=datetime.date.today create_date = models.DateTimeField(editable = False, auto_now_add=True)#default=datetime.date.today slug = models.SlugField(null= False, blank=True,unique=True, db_index=True, editable=False) -
HTML Django conditional statement dependent on radio button choices
I am working on an attendance system where teachers can mark a student as Present, Absent, or Late, but they can only enter a comment if a student is marked Absent or Late. I would like to make the Comment text input disabled when Present is selected. I tried different if statements with <input type="text" name='{{student.ssystudentid}}_comment' id="comment" maxlength="100">, but none seemed to work. Below is my code and a screenshot of the page. <form action="{% url 'attendance:submitAttendance' %}" method="post" name="fullForm"> {% csrf_token %} <table> <tr> <th>Student Name</th> <th>P/A/L</th> <th>Comment</th> </tr> {% for student in list_of_students %} <tr> <td>{{student}}</td> <td> <div class="radio-button"> {% for attendanceType in list_of_attendanceTypes %} {% if attendanceType.attendancetype == "Present" %} <input type="radio" name='{{student.ssystudentid}}_attendancetype' id='{{student.ssystudentid}}{{attendanceType}}' value={{attendanceType.attendancetypeid}} checked="checked"> <label for='{{student.ssystudentid}}{{attendanceType}}'> {{attendanceType}}</label> {% else %} <input type="radio" name='{{student.ssystudentid}}_attendancetype' id='{{student.ssystudentid}}{{attendanceType}}' value={{attendanceType.attendancetypeid}}> <label for='{{student.ssystudentid}}{{attendanceType}}'> {{attendanceType}}</label> {% endif %} {% endfor %} </div> </td> <td> <input type="text" name='{{student.ssystudentid}}_comment' id="comment" maxlength="100"> </td> </tr> {% endfor %} </table> <input type = "submit" value = "Save Attendance"/> </form>[![enter image description here][1]][1] Please note that I am not using Django forms. Any help will be appreciated. -
how do I access a previously created from a page on a different page
I am trying to open a modal i created that shows a team member's info. I want this same modal to be linked to the team members' names on a differnt page so that the same info pops up when the name is clicked. the modal works fine in the team page, but I just can't seem to figure out how to have the same modal pop up on the other page. I asked ChatGPT, and it gave me a bunch of code which did not work and I think I messed up even my previously written code. PLS HELP (sidenote: this is my first time building a website so I am very new at this). I am using django to build the website. team.html (original modal) {% extends 'base.html' %} {% block title %}Green Team - Our Team{% endblock %} {% block heading %}Our Team{% endblock %} {% block content %} <div class="container"> <div class="row justify-content-center"> {% for team_member in team_members %} <div class="col-md-4"> <div class="team-member-card team-card-center" data-toggle="modal" data-target="#teamMemberModal{{ team_member.id }}"> <div class="profile-picture profile-picture center"> <img src="{{ team_member.image.url }}" alt="{{ team_member.name }}"> </div> <div class="team-member-info"> <h3 class="name"> {% if team_member.id in team_member_pks %} <a href="#" class="author-link" data-toggle="modal" data-target="#teamMemberModal{{ team_member.id … -
how can i customize google signup template in django
before i finish signup this template apper and i want to customize it urls.py path('accounts/', include('allauth.urls')), path('users/', include('users.urls', namespace='users')), setting.py INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'grappelli', 'captcha', 'users', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google',] SOCIALACCOUNT_LOGIN_ON_GET=True SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS':{'access_type':'online'} } } LOGIN_REDIRECT_URL = 'home:home' LOGIN_URL = 'users:login' AUTHENTICATION_BACKEND=( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) i make templates>account>sinup.html but it did not work -
Handle UploadedFile in csv.reader
I am trying to read an uploaded file without saving it: def import_file(request): if request.method != 'POST': form = UploadForm() else: form = UploadForm(request.POST, request.FILES) if form.is_valid(): rdr = csv.reader(request.FILES["file"], delimiter=',') for row in rdr: print(row) ... But I get iterator should return strings, not bytes (the file should be opened in text mode) If i was reading a file with open function, I could have opened it with 'rt'. But in this case I am dealing with InMemoryUploadedFile class if I'm not mistaken. So I can't re-open it. What is the correct aproach here? Based on simpilar topics I've tried using read() and decode("UTF-8") and decode("ISO-8859-1") on the InMemoryUploadedFile, but so far nothing worked. -
Django run raw sql on existing queryset
I'm using Django 3.2 and Django Rest Framework 3.12.2. We have some custom OrderingFilters that override OrderingFilter and manipulate the received queryset. We override the get_ordering() function of the OrderingFilter: def get_ordering(self, request, queryset, view): So far we used some of the django queryset abilities. Now, I want to run a raw sql as part of the ordering process. As far as I know, we can do something like - MyModel.objects.raw("select * from my_model.....") The problem is that as I see, we can only select from the whole table (my_model in that case) and not from the already prepared queryset. What I would like to be able to do is something like - query_set = MyModel.objects.filter(created_at='2023.03.07') raw_query_set = query_set.raw("select * from query_set ...") Is it possible in some way? -
Unresolved reference 'showaddress' in pycharm
in pycharm this happen when i create class show this in admin .py this error pops up immediately how to solve this error everytime it shows this error in the console that it is reflecting this error give me step by step solution for this error -
Comments On How JoeFlow Package Works
I've just started working with JoeFlow package and need some help on it. I've installed it successfully and created an application based on joeflow tutorial. But why workflows stop in second node i.e. 'has_user' with status 'scheduled' How can I make workflows to proceed? Any advice is appreciated. Thank you -
Django why function can't be stopped with redirect to a specific URL
In a function (create_mapping) I call another function (GetCsvHeadersAndSamples) that calls another function (get_csv) that tries to get a CSV file. I want to check in this last function if the file is present before displaying a form or return a request message saying the file was not found. I also use the get_csv function in a bunch of other places create_mapping() def create_mapping(request, pk): flow = Flow.objects.get(pk=pk) if flow.fl_file_name == "": messages.error( request, 'Aucun fichier n\'a été enregistré pour ce flux. Veuillez le télécharger et mettre à jour le flux.') return redirect('flows:flow-update', pk=pk) fl_fiche_header_flow = fetch_fiche_headers(pk) headers_samples = GetCsvHeadersAndSamples(request, pk) # <------ call #2 func. HERE headers_json = make_headers_json(headers_samples['headers']) form = MappingForm(request.POST or None, headers_samples=headers_samples, fl_fiche_header_flow=fl_fiche_header_flow) context = { 'form': form, 'flow': flow, # 'mappings': mappings, 'headers_json': headers_json, 'title': 'Création Mapping Field', } if request.method == 'POST': [...] GetCsvHeadersAndSamples() def GetCsvHeadersAndSamples(request, flow_id): # returns tuple (file, separator, encoding) get_file_and_attribs = get_csv(request, flow_id). # <------ call #3 func. HERE file = get_file_and_attribs[0] separator = get_file_and_attribs[1] encoding = get_file_and_attribs[2] with open(file, newline='', encoding=encoding) as f: reader = csv.reader(f, delimiter=separator) headers = next(reader) samples = next(itertools.islice(csv.reader(f), 1, None)) headersAndSamples = {'headers': headers, 'samples': samples} return headersAndSamples get_csv() def get_csv(request, flow_id): flow = … -
Iframe responsive
I have a website where I cant make the iframe responsive. The map looks properly in computer however the map is invisible in mobile phone. I am currently using bootstrap <div class="container d-none d-sm-block mb-5 pb-4"> <div class="wrapper" id="map" style="height: 480px; position: relative; overflow: hidden;"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d5994.821337674272!2d69.25345364107476!3d41.29992894681807!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x38ae8ae3e16117eb%3A0xe38bf57767a5d5a9!2z0KjQutC-0LvQsCDihJY5MQ!5e0!3m2!1sru!2s!4v1689872593583!5m2!1sru!2s" width="1100" height="450" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe> </div> Maybe the problem is with bootstrap style so below are links and scripts: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <link rel="shortcut icon" type="image/x-icon" href="img/favicon.png"> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link rel="stylesheet" href="{% static 'blog/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/owl.carousel.min.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/magnific-popup.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/font-awesome.min.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/themify-icons.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/nice-select.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/flaticon.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/gijgo.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/animate.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/slicknav.css' %}"> <link rel="stylesheet" href="{% static 'blog/css/style.css' %}"> <script src="{% static 'blog/js/vendor/modernizr-3.5.0.min.js' %}"></script> <script src="{% static 'blog/js/vendor/jquery-1.12.4.min.js' %}"></script> <script src="{% static 'blog/js/popper.min.js' %}"></script> <script src="{% static 'blog/js/bootstrap.min.js' %}"></script> <script src="{% static 'blog/js/owl.carousel.min.js' %}"></script> <script src="{% static 'blog/js/isotope.pkgd.min.js' %}"></script> <script src="{% static 'blog/js/ajax-form.js' %}"></script> <script src="{% static 'blog/js/waypoints.min.js' %}"></script> <script src="{% static 'blog/js/jquery.counterup.min.js' %}"></script> … -
Django Multiple User type and extra fields
I have a project. My project has multiple user types and every type has different fields. For example user types are admin, teacher,student, admin area does not need any changes, teacher fields-> branch (mathematics, physics teacher), mentor, mentor student(relationship) student fields->school name, score, school number .... I want use admin panel and for example i want to create student in one page How should i design my model? if its impossible , what could be the alternatives Thank you for your assistance i tried abstractuser and proxy -
WebSocket connection to 'ws://localhost:8000/ws/Python/' failed: in django
I'm trying to get a WebSocket running for a Django project I'm working on, but I can't get the WebSocket to connect, which is strange since I copied the example chat application. HTML part {% block scripts %} {{ room.slug|json_script:"json-roomname" }} <script> const roomName = JSON.parse(document.getElementById('json-roomname').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/' + roomName + '/' ); chatSocket.onmessage = function(e){ console.log('onmessage') } chatSocket.onclose = function(e){ console.log('onclose') } </script> {% endblock %} routing.py from django.urls import path from .import consumers websoscket_urlpatterns =[ path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi()), ] asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter,URLRouter import room.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WeChat.settings') application = ProtocolTypeRouter({ "http" : get_asgi_application(), "websocket" : AuthMiddlewareStack( URLRouter( room.routing.websoscket_urlpatterns ) ) }) consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) First time I'm using the WebSocket. I run the Python file and inspect the browser but I got an unexpected error like Python:64 WebSocket connection to 'ws://localhost:8000/ws/Python/' failed: (anonymous) @ Python:64 it shows the redline under the ( new WebSocket) const … -
My django server does not save my model object but if I use python shell it does
I'm still learning django, I tried to save an object from my app models on the django server but it does not work, and it shows OperationalError at/admin but if I try to use python shell to save it, it saves I need help please. -
I want to add multiple foreign key at single field in Django Model? Is it possible?
I am building an Online Attendance Application in Django. In which the teacher initiates attendance and students give their responses. Everything is great, but the problem occurs when one practical class is taken by more than one teacher at a time. I don't know how to reference multiple teacher full_name from Teacher model on a single teacher field in Attendance model. The models are: class Teacher(models.Model): full_name = models.CharField(max_length=100, unique=True) class Attendance(models.Model): std_session = models.CharField(max_length=10, default="2023-24") att_date = models.DateField(default=date.today) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) subject_name = models.CharField(max_length=50) std_class = models.CharField(max_length=50) unique_code = models.IntegerField(default=0) total_students = models.IntegerField(default=0) is_active = models.BooleanField(default=True) The view to save attendance data has a simple form.save() method. -
Getting error: from django.core.urlresolvers import reverse
I am working on django app. I am getting error when calling module. from django.core.urlresolvers import reverse "urlresolvers" here is underlined red. Which package am I missing? -
how to create user using admin token
i was trying to create user using admin token but the console show me unauthorized when i try to create the user the back-end is Django the front-end is react.js .... only admin can create the user const handleSubmit = async (values) => { try { console.log("here",values) // Make a POST request to the backend API endpoint // Get the admin token from localStorage const adminToken = localStorage.getItem('token'); console.log(adminToken) // Check if the admin token exists if (!adminToken) { console.log("Admin token not found."); // Optionally, you can show an error message or handle the absence of the token return; } // Include the admin token in the request headers const config = { headers: { Authorization: `Bearer ${adminToken}`, }, }; const response = await axios.post("http://128.140.431.171:21000/users/", values,config); // Check if the request was successful if (response.status === 200) { console.log("Driver registration successful!"); // Optionally, you can show a success message or redirect the user to another page } else { console.log("Driver registration failed."); // Optionally, you can show an error message or handle the error in another way } } catch (error) { console.log("An error occurred while registering the driver:", error); // Optionally, you can show an error message or handle … -
Django authenticate function return None although the User isn't None
I am try to make login with custom User which using email instead of username, but authenticate(email=email, password=password) returns None although the user is exist class CustomUserManager(UserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class User(AbstractUser): email = models.EmailField(max_length=254, unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() # use the custom manager def __str__(self): return self.email Views.py: class LoginView(FormView): template_name = 'login.html' form_class = LoginForm def form_valid(self, form): email = form.cleaned_data['email'] password = make_password(form.cleaned_data['password']) print(email, password) # for debugging purposes user = authenticate(email=email, password=password) print(user) # for debugging purposes if user is not None: login(self.request, user) return redirect('home') else: messages.info(self.request, 'invalid username or password') return redirect('login') backends.py: from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class EmailBackend(ModelBackend): def authenticate(self, request, password=None, email=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None settings.py AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = [ 'accounts.backends.EmailBackend', ] I want to know why the value of user is None. I am sure the email and … -
Django, sorted fields type many-to-many in admins pages
Good day! It is necessary to display when editing the structure of the field (belonging to the parent) and sort by belonging to the parent object, which is displayed in the admin panel. I am creating a page for publishing documents in 3 categories, each category has a model (also the page itself). The following content models.py class Pages(models.Model): slug = models.CharField(default="", max_length=64, verbose_name="Slug", help_text="Фигурирует в URL, как id для ссылки на страницу") title = models.CharField(default="", max_length=255, verbose_name="Краткий заголовок", help_text="Заголовок, отображаемый в меню, блоках и прочее") description = models.CharField(default="", max_length=255, verbose_name="Описание", help_text="Описание подробное страницы, обычно используется в поисковых системах, как параметр description") public_name = models.CharField(default="", max_length=255, verbose_name="Отображаемый заголовок", help_text="Заголовок в шапке страницы") date_pub = models.DateField(default=datetime.date.today, editable=False, verbose_name="Отображаемый заголовок", help_text="Заголовок в шапке страницы") fullmenu = models.BooleanField(default=False, verbose_name="Раскрытое меню на странице", help_text="Отображать на десктопах постоянно открытое меню сайта") class Meta: ordering = ['-date_pub'] verbose_name = 'Страницы сайта' verbose_name_plural = 'Страницы сайта' def __str__(self): return self.title def get_containers(self): return Containers.objects.filter(page_member=self) #Files module #Tags menu class TagsMenu(models.Model): titlemenu = models.CharField(default="", blank=True, max_length=80, verbose_name="Название критерия файла", help_text="Название критерия файла по которому идёт выборка") order = models.IntegerField(default=0, verbose_name="Приоритет", help_text="Чем меньше число, тем выше приоритет, как порядковый номер") class Meta: ordering = ['order'] verbose_name = 'Меню тегов' …