Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple annotation for one Case-When
I'm currently trying to annotate multiple value with the same When in a Case for a Django QuerySet. Currently I have something like this: my_qs.annotate( dynamic_status_deadfish=Case( when_inactive, when_only_recently_published, when_no_published_ad, when_not_enough_booking, when_low_booking_cnt, default=default, output_field=HStoreField(), ) ) with one of those when looking like this: when_inactive = When( is_active=False, then={"status": stats_cts.INACTIVE, "reason": None}, ) when_only_recently_published = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then={ "status": stats_cts.PENDING, "reason": OwnerStatsStatusReason.RECENTLY_SUSPENDED, }, ) when_no_published_ad = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=False), then={ "status": stats_cts.PENDING, "reason": OwnerStatsStatusReason.NO_BOOKABLE_TO_MODERATE, }, ) As you can see my output is a dict, or more exactly an Hstore. Ideally, I'd like one distinct annotation for status and for reason so that I don't have to deal with serialization and have an easier access to the annotation than with this HSTore One way would be to duplicate the when for status and reason as the condition are the same, but I don't like it. Something like this: when_only_recently_published = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then=Value(stats_cts.PENDING), ) when_only_recently_published_reason = When( Q(is_old_published_ad_exists=False) & Q(is_recently_published_ads_exists=True), then=Value(OwnerStatsStatusReason.RECENTLY_SUSPENDED), ) ... my_qs.annotate( dynamic_status_deadfish=Case( when_inactive, when_only_recently_published, when_no_published_ad, when_not_enough_booking, when_low_booking_cnt, default=default, ), dynamic_status_deadfish_reason=Case( when_inactive_reason, when_only_recently_published_reason, when_no_published_ad_reason, when_not_enough_booking_reason, when_low_booking_cnt_reason, default=default_reason, ) ) Any way to somehow set two annotations in a Case or something similar ? -
django search a value in multiple fields
There is a way to search a determinated value inside of N fields? (Without have to get all the db to filter it with for in) Something like this: db = id name age 1 Juan 10 2 Pedro 31 3 Laura 55 4 3_Manuel 11 search(3) => OUTPUT [[2 Pedro 31] , [4 3_Manuel 11]] search("au") => OUTPUT [[1 Juan 10]] -
How to manage azure blob storage with django in production?
I have a django app and I am using the library django-storages[azure]. When I run the django app local I can upload images via django admin to my storage container on azure. But I also have an web app with url: https://example.azurewebsites.net and I try to upload images from the mentioned url. But that doesn't work - the images are not uloaded to the storage container. So this are my azure settings in the settings.py file: DEFAULT_FILE_STORAGE = 'dierenwelzijn.custom_azure.AzureMediaStorage' STATICFILES_STORAGE = 'DierenWelzijn.custom_azure.AzureStaticStorage' STATIC_LOCATION = "static" MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = "dier" AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' STATIC_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' Question: what I have to change so that I can upload images from the hostmachine with url: https://example.azurewebsites.net ? -
How to store the data of two different django models which share one to many relationship via a single HTML form?
I have a single HTML form to fill up the details of both patient and his/her doctor. I have created a One to many relationship between Doctor and Patient models using ForeignKey. The form(docpatient.html) goes like this: <form action="{% url 'requestlanding' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <h2> Patient Details </h2> <label for="patientName"> Patient's Name: </label> <input type="text" id="patientName" name="patientName" required> <label for="age"> Age: </label> <input type="number" id="age" name="age" required> <label for="gender"> Gender: </label> <select id="gender" name="gender" required> <option value="male"> Male </option> <option value="female"> Female </option> <option value="other"> Other </option> </select> <label for="contactNumber"> Contact Number: </label> <input type="tel" id="contactNumber" name="contactPatient" required> <label for="email"> Email: </label> <input type="email" id="email" name="emailPatient" required> <label for="media"> Upload patient's picture: </label> <input type="file" id="media" name="wrecommend" accept="image/*,video/*,pdf/*"> <h2> Doctor Details </h2> <label for="doctorName"> Doctor's Name: </label> <input type="text" id="doctorName" name="doctorName" required> <label for="specialization"> Specialization: </label> <input type="text" name="specialization" id="specialization" required> <label for="contactNumber"> Contact Number: </label> <input type="tel" id="contactNumber" name="contactDoctor" required> <p> (All the information must be correct and proper) </p> <button type="submit"> Submit </button> </form> I have created Patient and Doctor models as following: from django.db import models from django.core.validators import MinValueValidator, MaxValueValidator class Doctor(models.Model): name = models.CharField(max_length=50, blank=False) phone = models.IntegerField( validators=[MinValueValidator(1000000000), MaxValueValidator(9999999999)], blank=False, ) … -
Are multiple Django indices necessary?
I've a Django model that, among other fields, has time, station and variable. Nearly always, queries will be done providing the three fields - occasionally and very rarely, I might want to query using only one of them. In this case, does it matter if the index is set to models.Index(fields=["station", "time", "variable"]) or models.Index(fields=["time", "station", "variable"]) or other permutation of the three? Would it be useful to add all possible permutation or is it irrelevant? If there any performance penalty or benefit in adding all permutations? Many thanks! -
How to show the results of a many-to-many relationship backward direction via Django admin?
I have two models defined, groups and group_members, with the latter defining a many-to-many relationship to the former: class Group(models.Model): group_name = models.CharField(max_length=100, default="New Group") group_created_date = models.DateField(default=date.today) class GroupMember(models.Model): groups_joined = models.ManyToManyField(Group) email = models.EmailField(max_length=100) name = models.CharField(max_length=100) And then for my admin.py I simply have: admin.site.register(Group) admin.site.register(GroupMember) This works rather well from one side, when viewing GroupMember objects I can see and edit all the groups they belong to. However when viewing Group objects, I can not see the relationship from that side - I cannot see any members who belong to that group. What would I need to add to my admin.py to make this happen? I've been searching on how to do this but the answers either seem to convoluted and/or out of date. -
how to fix the following error? Error connecting Django to MSSQL
File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\backends\base\base.py", line 292, in _cursor self.ensure_connection() File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\backends\base\base.py", line 274, in ensure_connection with self.wrap_database_errors: File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\utils.py", line 91, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\ProgramData\Anaconda3\envs\Lib\site-packages\django\db\backends\base\base.py", line 275, in ensure_connection self.connect() File "C:\ProgramData\Anaconda3\envstest\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\django\db\backends\base\base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\ProgramData\Anaconda3\envs\test\Lib\site-packages\mssql\base.py", line 366, in get_new_connection conn = Database.connect(connstr, **args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'user'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'user'. (18456); [28000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)") DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': 'Test', 'USER': 'user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } mssql and pyodbc were installed -
Weird bug when looking at a user profile in django
So I have 2 user types: a company and a job seeker. The problem is when I go to the seeker's profile from a job application, or directly go to a seekers profile, it returns the data of the current logged in company. Like this: Here's the view for the JobApplication: class JobApplicationsView(CompanyRequiredMixin, LoginRequiredMixin, DetailView): model = Job template_name = "applications/job_applications.html" context_object_name = "job" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) job = self.get_object() # Get all job applications for the current job job_applications = JobApplication.objects.filter(job=job) context["job_applications"] = job_applications return context Here's the template job_applications.html {% extends "base.html" %} {% block content %} <div class="container mt-5"> <h1 class="mb-4">{{ job.title }} - Job Applications</h1> {% if job_applications %} <ul class="list-group"> {% for application in job_applications %} <li class="list-group-item"> <strong>Applicant:</strong> {{ application.applicant.username }}<br> <strong>Cover Letter:</strong> {{ application.cover_letter }}<br> {% if application.resume %} <a href="{{ application.resume.url }}" download class="btn btn-primary">Download Resume</a> {% else %} <span class="text-muted">No resume attached</span> {% endif %} </li> {% endfor %} </ul> {% else %} <p>No applications for this job yet.</p> {% endif %} </div> {% endblock %} To get it right, the localhost:8000/job-seeker/seeker1 should show the data of the job seeker. This happens to all profiles, when I use … -
Apple Store Server Notification: Python OpenSSL certificate loading fails in "header too long"
On my django server, I'm trying to decode the JWT content sent by the Apple Store Server Notification using Apple's package app-store-server-library-python. Under the official documentation, when starting to do the verification and decoding, we find this line: root_certificates = load_root_certificates() The implementation is not provided unfortunately. By looking here and there, I've tried several implementations that always fail in : OpenSSL.crypto.Error: [('asn1 encoding routines', '', 'header too long')] Here is my implementation: def load_root_certificates(): in_file = open("AppleRootCA-G3.cer", "rb") data = in_file.read() in_file.close() return load_certificate(FILETYPE_ASN1, data) Thanks for the help! -
Why do we return only a limited amount of information from a websocket event?
I'm working on implementing a real-time chat application that uses web sockets and a 3rd party application. This 3rd party application has various events that does not transmit the full message object, but rather a limited set of data. Wouldn't it be better to return the full message object, because it would greatly simplify the process of updating the client? What's happening right now is that I have to engage in complex search and update operations. I guess I am having trouble understanding this design choice because, at least in my eyes, returning the full message object shouldn't take up that much additional bandwidth. Here are some examples. API Responses Dialog (Represents chat between two people) [ { "id": 2, "created": 1704771541, "modified": 1704771541, "other_user_id": "1", "unread_count": 12, "username": "admin", "last_message": { "id": 36, "text": "f", "sent": 1704847056, "edited": 1704847056, "read": false, "sender": "1", "recipient": "2", "out": false, "sender_username": "admin" } } ] Message { "id": 36, "text": "f", "sent": 1704847056, "edited": 1704847056, "read": false, "sender": "1", "recipient": "2", "out": true, "sender_username": "admin" } Web Socket Events New Message {"msg_type": 3, "random_id": -999999, "text": "Hi …", "receiver": "2", "sender_username": "johntaylor"} Message Added {"msg_type": 8, "random_id": -999999, "db_id": 46} Unread count … -
Update OneToOneField Relationship in Django
I want to update to exera field of User models in Django programmatically in my program. how can i update the extra field of User model in Django? def user_profile(request): query_set = str(Group.objects.filter(user=request.user)[0]) if query_set == 'user': user = request.user name = user.first_name family = user.last_name extrainfo = ExtraInfo.objects.get(User=user) extrainfo.title = 'business' extrainfo.save() return render(request, 'user-profile.html', {'name': name, 'family': family, 'title': user.extrainfo.title}) else: messages.warning(request, 'Unauthorized Access!') return render(request, 'warnings.html') from django.db import models from django.contrib.auth.models import User class ExtraInfo(models.Model): User = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) title = models.CharField(max_length=25, blank=True) -
Integrate sslcommerz payment gateway in my Django project
I have alreadt integrated Paypal payment gateway in my django project fllowing this tutorial. Now, I want to integrate sslcommerz for users to give more option to pay. Here are some codes of my project. config/settings.py """ Django settings for config project. Generated by 'django-admin startproject' using Django 5.0. For more information on this file, see https://docs.djangoproject.com/en/5.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.0/ref/settings/ """ from pathlib import Path # 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/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-f=f@1a*+svrxj#j8_4ik%c@gd16_s6@c$(n%4p$(66*6g7we6)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product', 'user_account', 'cart', 'order', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'product.context_processors.categories', 'cart.context_processors.cart' ], }, }, ] WSGI_APPLICATION = 'config.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', … -
Wrong credentials cause sign in alert box
I have react frontend and django backend. I am seeing an alert box when I enter incorrect credentials on my login screen. On Google Chrome I see the network call in pending state When I click on 'Cancel' button on the dialog, I see 401 error (as expected since invalid credentials were entered). Am I missing anything? Why am I seeing this dialog? -
Creating a PDF with PDFkit and Wkhtmltopdf, but encountering an issue where the entire table is being pushed to the next page. How can I resolve this
I'm facing an issue while generating PDFs in Python Django using PdKit and Wkhtmltopdf. Specifically, when the table has more than 10 items, it gets pushed to the next page. I've attempted the following solutions: Added the following CSS styles: page-break-inside: avoid !important; } table { page-break-inside:auto } tr { page-break-inside:avoid !important; page-break-after:auto !important } thead { display:table-header-group !important} tfoot { display:table-footer-group !important} ``` 2. Tried using the JavaScript solution provided - https://github.com/AAverin/JSUtils/blob/master/wkhtmltopdfTableSplitHack/wkhtmltopdf_tableSplitHack.js [![Image 1 ][1]][1] [![Image 2][2]][2] [1]: https://i.stack.imgur.com/TO2Hb.png [2]: https://i.stack.imgur.com/Dt3Wl.png -
Content-Security-Policy: The page’s settings blocked the loading of a resource at inline (“script-src”)
This is the code I copied from some blogs for google authentication OAUTH 2.0. The code was based on django backend and react.js frontend. In my project I am using django as backend but next.js 14 using typescript as frontend. When openGoogleLoginPage function is called after clicking a button google login page gets opened but in console Content-Security-Policy: The page’s settings blocked the loading of a resource at inline (“script-src”) error is shown. And After clicking on any account it sends get request to server but in django server "GET /api/v1/auth/login/google/?code=4%2F0AfJohXm69xHTNpnP3QX8CbhwTO18s4XZIFERfUDq_pfhaOgCYPm6jpf3XRyxTg_ziIB8Lw&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=2&prompt=consent HTTP/1.1" 500 103892 is shown const Home = () => { const [username, setUsername] = useState(localStorage.getItem('goggleFirstName')) useEffect(() => { const storedUsername = localStorage.getItem("user_goggle"); if (storedUsername) { setUsername(storedUsername); } }, []); const openGoogleLoginPage = useCallback(() => { const googleAuthUrl = "https://accounts.google.com/o/oauth2/v2/auth"; const scope = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", ].join(" "); const params = new URLSearchParams({ response_type: "code", client_id: REACT_APP_GOOGLE_CLIENT_ID, redirect_uri: `${REACT_APP_GOGGLE_REDIRECT_URL_ENDPOINT}/google`, prompt: "select_account", access_type: "offline", scope, }); const url = `${googleAuthUrl}?${params}`; window.location.href = url; }, []); const handleLogout = () => { localStorage.clear(); // Clear localStorage when the button is clicked setUsername("") }; The tutorial which I was following is this. I have been stuck with this problem for a couple … -
ORA-02019 Error When Executing Queries on Remote Oracle DB in Django Application
I'm currently working on a Django application that interacts with an Oracle database. My application needs to execute SQL queries on a remote Oracle database, which is configured in the settings.py file. The SQL queries I'm trying to execute have a syntax similar to: SELECT * FROM table@source Here, source is a different database than the one currently executing the query. Both the source and target databases are Oracle databases. Despite the remote database being configured in settings.py, I encounter the following error when executing the first query: ORA-02019: connection description for remote database not found I'm looking for guidance on how to resolve this error. Here's some additional information that might be helpful: I've confirmed that the remote database is accessible outside of the Django environment. The user credentials used in settings.py have the necessary privileges. The application works fine with local database queries. Has anyone encountered a similar issue or can provide insights into what might be going wrong? Any advice on configuring Django to work seamlessly with remote Oracle databases using database links would be greatly appreciated. Thank you in advance for your help! -
In Django how to compare two texts and print a message about correctness?
I'm new to Django. In Django i would like to compare two texts and receive a message if they are the same or different. In reality these two texts are two short HTML codes. The page can reload easily, I'm only interested in the logic behind comparing the two texts (and not the use of Ajax, jQuery, JS). A text will be inserted in the front-end by the user, who will write in a div (no textarea) with contenteditable="true" which is already present in my code. I have already prepared an example text in the black panel, so I would like to compare the entire block of text (from up to ). While the other text will be contained in the backend (in a variable or something similar). Then I will click on the button and in the gray rectangle i would like to print CORRECT: the two texts are the same or ERROR: the two texts are different. Important is that i don't want to use textarea, but as already said I want to use the div with contenteditable="true" that I already have in my code. HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta … -
DoesNotExist at /.../pk/
So I created a simple CRUD simple, like a tweet, where you have Username, Title and Message/Description It was working well and I was following a tutorial, then it happened I don't know what going on because my models seems to be ok class Topic(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Room(models.Model): host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) #participants = updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name class Message(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Room, on_delete=models.CASCADE) body = models.TextField() updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.body[0:50] It also doesn't seem to be an error in my views def room(requests,pk): room = Room.objects.get(id=pk) message = Message.objects.get(id=pk) context = {'room':room, 'message':message} return render(requests,'base/buy.html',context) def createRoom(request): form = RoomForm() if request.method == 'POST': form = RoomForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form':form} return render(request, 'base/room_form.html', context) But then I noticed this error in my shell Traceback (most recent call last): File "c:\Users\adrya\thegreatsite\base\views.py", line 2, in <module> from .models import Room, Message ImportError: attempted relative import with no known parent package these are the models I imported from django.shortcuts import render, … -
How to hide Graphql Apis from everyone on internet
I have a website built using Python Django framework and backend APIs are designed using GraphQL api. The graphql url is like below, http://0.0.0.0:8000/graphql/ All my apis are currently accessible by everyone on the internet. I need to hide those behind some authentication (login / password). Please suggest some ways to fix this. -
Django is very slow in the browser when I'm coding my Django app
I want some helps. I'm working on a ecommerce website. I code my side in localhost side. However, when I launch my site on the browser like chrome, it takes a long Time to reload and it's slow. Some éléments don't appear and I can easily work. I want your help plaise. Sorry for my Bad english, I'm from french speaker country. I don't know how to résolve this issue.. -
Differences when running HTML script with "python manage.py" or Visual Studio Code's Live Server
I'm building a website and I've been experiencing some issues when debugging. I'm using Visual Studio Code and the framework Django. I'm really new to this so I could be making some silly mistake. The problem I have is this: I'm trying to insert a date-time picker to an HTML (particularly, a flatpickr date-time picker). I want it to be included in a particular div section, and I've followed the corresponding instructions to do this. Nevertheless, when I run the code using the "python manage.py runserver", the calendar appears in a top-left position instead of at the bottom, where the div is. This is how it looks running the "python manage.py runserver" command: (https://i.stack.imgur.com/t96x2.png). And this is how it looks when I use the "Open with Live Server" option in Visual Studio Code: (https://i.stack.imgur.com/HH1Pv.png) When using the "Open with Live Server" option, of course, the css isn't applied, so it just shows the HTML. But there the calendar appears where it should. I send also the HTML code of the page. I paste the code of the webpage here {% load static %} <html> <head> <title>Atención dental Dalla Vecchia</title> <link rel="stylesheet" href="{% static 'C:/Users/CgLenovo/Documents/Programas/Sitio_web_dental_3/Dental_website/static/home/css/style.css' %}"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" … -
How to display the value instead of the ID in the form in Django
I need to display the time, but the form outputs the ID models.py class Ticket(models.Model): concert = models.ForeignKey('Concert', related_name='concert_name', on_delete=models.PROTECT) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) place = models.ForeignKey('Place', on_delete=models.PROTECT) date_time = models.ForeignKey('Time', on_delete=models.PROTECT) price = models.IntegerField(blank=True, null=True) def __str__(self): return f"{self.first_name}, {self.last_name}, {self.date_time}" class Concert(models.Model): name_concert = models.CharField(max_length=50) description = models.TextField(max_length=500) length = models.TimeField() type = models.ForeignKey('Type', on_delete=models.PROTECT) janr = models.ForeignKey('Janr', blank=True, null=True, on_delete=models.PROTECT) regisser = models.ForeignKey('Regisser', blank=True, null=True, on_delete=models.PROTECT) date_time = models.ForeignKey('Time', on_delete=models.PROTECT) img = models.ImageField(upload_to='photo/', blank=True, null=True) price = models.IntegerField(blank=True, null=True) def __str__(self): return self.name_concert class Time(models.Model): date_time = models.DateTimeField() def __str__(self): return format(self.date_time, "%d.%m.%y %H:%M") forms.py class ticketForm(forms.ModelForm): class Meta: model = Ticket fields = ['first_name', 'last_name', 'concert', 'date_time', 'price', 'place'] widgets = { "first_name": TextInput(attrs={ 'class': 'input-style', 'placeholder': 'Имя' }), "last_name": TextInput(attrs={ 'class': 'input-style', 'placeholder': 'Фамилия' }), "concert": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': 'ticket.concert_name', 'readonly': 'readonly' }), "date_time": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': 'ticket.date_time', 'readonly': 'readonly' }), "price": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': 'ticket.price', 'readonly': 'readonly' }), "place": TextInput(attrs={ 'class': 'input-style', 'placeholder': '', 'value': '', 'readonly': 'readonly' }) } views.py def ticketsSite(request, concert_id): ticket = get_object_or_404(Concert, id=concert_id) form = ticketForm(initial={'concert': ticket.name_concert, 'price': ticket.price, 'date_time': ticket.date_time}) context = { 'ticket': ticket, 'form': form … -
Authenticate method in django returns None
It is the first time I do a project in Django. As a first step, I am creating methods to sign-up and sign-in users. The sign-up works well. However, after registering an user, I try to sign-in without success. My models.py file is: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, username, email, password=None, **extra_fields): user = self.model(username=username, email=email, **extra_fields) # set_password will handle the password before saving it in the database # It hash the password before saving it user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(username, email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=20, unique=True) email = models.EmailField(unique=True) password = models.CharField(max_length=256) fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] def __str__(self): return self.username class Meta: managed = True db_table = "users" and the sign-in method in views.py is the following one: def signin(request): if request.method == "POST": username = request.POST.get("username") password = request.POST.get("password") # Authenticate the user user = authenticate(request, username=username, password=password) # If it is not None - user exists and right credentials if user: login(request, user) fname = … -
Implementing Autocomplete for M2M Fields in Wagtail CustomUser Model
I have added two additional fields to my CustomUser model in my Wagtail project. These two fields are many-to-many (m2m) fields, and in the form, I want these fields to be represented as an Autocomplete feature. How can I achieve this? models.py class User(AbstractUser): journal = models.ManyToManyField("journal.Journal", verbose_name=_("Journal"), blank=True) collection = models.ManyToManyField("collection.Collection", verbose_name=_("Collection"), blank=True) forms.py class CustomUserEditForm(UserEditForm): journal = forms.ModelMultipleChoiceField(queryset=Journal.objects.all(), required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) class CustomUserCreationForm(UserCreationForm): journal = forms.ModelMultipleChoiceField(queryset=Journal.objects.all(), required=False, label=_("Journal")) collection = forms.ModelMultipleChoiceField(queryset=Collection.objects.filter(is_active=True), required=True, label=_("Collection")) -
Python - remove commas and leave decimal points from string as number
As of title, I need to remove commas from string number and leave decimal point, but the problem is input can be with . or ,. This input will be saved for Django model's DecimalField For example: Input: 250,000,50 250,000 250000.00 25,000 Output: 250000.50 250000.00 250000.00 25000.00 What I have tried: def _normalize_amount(self, value -> str): normalized_amount = value[:-3].replace(",", "") + value[-3:] return Decimal(normalized_amount) Problem is that this function can not handle the cases where user enters , as decimal point. How to solve this case ?