Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Admin – Inline. Add a default value
There is a structure class StatPersonalForm(forms.ModelForm): class Meta: model = StatPersonal fields = "__all__" pass class StatPersonalInline(admin.TabularInline): model = StatPersonal form = StatPersonalForm extra = 0 class StatistDaysAdmin(admin.ModelAdmin): list_display = ('date_seconds','section') inlines = [StatPersonalInline, ] class StatPersonal(models.Model): personal = models.ForeignKey(Personal, on_delete=models.SET_NULL,help_text="",verbose_name="", blank=True, null=True) plan = models.PositiveSmallIntegerField(blank=True, null=True, help_text="", verbose_name="") fact = models.PositiveSmallIntegerField(blank=True, null=True, help_text="", verbose_name="") statistDays = models.ForeignKey(StatistDays, on_delete=models.SET_NULL,help_text="", verbose_name="Дневной отчёт", blank=True, null=True) class Personal(models.Model): name = models.CharField(max_length=100, blank=True, help_text="", verbose_name="") count = models.PositiveSmallIntegerField(blank=True, null=True, help_text="", verbose_name="") section = models.ForeignKey(Section, on_delete=models.SET_NULL, blank=True, null=True) I already have a bundle of user and section. How do I add rows to StatPersonal when adding StatistDays. it is necessary that when creating StatistDays, StatPersonal immediately displays lines depending on users. if not(request.user.is_superuser): sectionUser = SectorToUser.objects.get(user=request.user) for pers in Personal.objects.filter(section=sectionUser.section): obj.attendance_set.create(personal=pers, plan=pers.count,fact=pers.count) -
Spotify API - I am getting 403 (Forbidden) when pausing a track
I am working on Spotify API integration using Django + React stack. When pausing a track, I am getting this error: "PUT /spotify/pause-song HTTP/1.1" 403 2 Fetching track information is working, it's just not the same thing with the pause. views.py class PlaySong(APIView): def put(self, response): room_code = self.request.session.get('room_code') room = Room.objects.filter(code=room_code)[0] if self.request.session.session_key == room.host or room.guest_can_pause: res = play_song(room.host) if res.status_code == 204: return Response({}, status=status.HTTP_204_NO_CONTENT) else: return Response({}, status=res.status_code) return Response({}, status=status.HTTP_403_FORBIDDEN) utils.py BASE_URL = "https://api.spotify.com/v1/me/" def get_user_tokens(session_id): user_tokens = SpotifyToken.objects.filter(user=session_id) if user_tokens.exists(): return user_tokens[0] else: return None def pause_song(session_id): access_token = get_user_tokens(session_id).access_token url = f"{BASE_URL}player/pause" response = requests.put(url, {}, headers={ 'Authorization': f'Bearer {access_token}' }) return response -
How to sync smtp mailbox to local inbox
I am creating an email campaign system in which I have several connected accounts. I am fetching emails from SMTP periodically through IMAP. How can I sync with the SMTP server, like webmail I am using? Or how can I determine from where to start fetching because I am not finding any unique identifier? Here is my code def fetch_emails(connected_account, count=10): try: imap_server = connected_account.server username = connected_account.server password = connected_account.password # Connect to the IMAP server mail = imaplib.IMAP4_SSL(imap_server) mail.login(username, password) # Select the mailbox (inbox) mail.select('inbox') # Search for the most recent emails in the inbox status, data = mail.search(None, 'ALL') if status != 'OK': print("No messages found!") return [] emails = [] # Decode the byte string data to a regular string and split it into individual IDs email_ids = data[0].decode().split() # Limit the number of emails to fetch to 'count' (default is 10) email_ids = email_ids[-count:] if len(email_ids) > count else email_ids # Iterate through each email id for num in email_ids: print(num) # Fetch the email data status, msg_data = mail.fetch(num, '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): # Parse a bytes email into a message object msg = email.message_from_bytes(response_part[1]) # Decode the email … -
AWS Gunicorn configuration Amazon Linux Work not properly
enter image description here This image is show problem. When i run gunicorn service with this configuration. GNU nano 5.8 pair.service [Unit] Description=Gunicorn instance to serve Pair After=network.target [Service] PermissionsStartOnly=true User=ec2-user Group=ec2-user WorkingDirectory=/usr/share/nginx/html/pair Environment="PATH=/usr/share/nginx/html/pair/venv/bin" ExecStart=/usr/share/nginx/html/pair/venv/bin/gunicorn --workers 3 --bind 127.0.0.1:8001 ft_pair.wsgi:application [Install] WantedBy=multi-user.target i faced this problem but when i run the project on AWS Amazone linux with this command python manage.py runserver my project working fine also with this command working fine on server. /usr/share/nginx/html/pair/venv/bin/gunicorn --bind 127.0.0.1:8001 ft_pair.wsgi:application I want this with gunicorn service. enter image description here This image is working fine when i run project with command. I'm very thankfull. -
Django ORM model 'save' method and race condition / ACID Isolation
if we examine the following code: class SomeModel(models.Model): ... def save(self, *args, **kwargs): self.validate_unique() super().save() def validate_unique(self, *args, **kwargs): super().validate_unique(*args, **kwargs) # Doing an ORM query on the model with *filter* on the model attributes & an associated model, # and if exist - dont create a new instance, if not - create a new instance. is_duplicated = SomeModel.objects.filter(name=given_name_from_user, attribute_from_associated_model=some_attr) if is_duplicated: raise Exception("go wrong") # Else - continue to save Now, it will work with the development server, but not with a production one like gunicorn or uvicorn, because the save method gurantee us atomicity, but not isolation, right? for us to gurantee isolation, we should use ‘get_or_create’ on the view level? I’m mistake somewhere? Any comment will help, Thanks! -
Should I put Django venv directory in .gitignore?
In my book Python Crash Course 2nd edition it is recommended to put ll_env (venv directory) in .gitignore. It says, "We tell Git to ignore the entire ll_env directory, because we can re-create it automatically at any time" But in my opinion this is a very bad move because I won't be able to roll back the installation of packages. Do I need to do it? Why? -
An appointment system [closed]
So basically I am trying to make a project for medical purposes in django. The projects is like there are some services like appointing for having a cold, having a daze, having a headache and... and also user can choose multiple services, like they can have a daze and catch a cold at the same time. There are 3 types of users, admin, patient and doctor. There are many Doctors and each doctor can do his own services. Also doctors can do several services that are chosen by patients and not only one, and in the end, I want the chosen services for the chosen doctor in the chosen appointment time to be shown after a payment in the homepage of the doctor And I have no Idea how to build such a system Would be thankful if you guys give me some idea about how can I do it and some examples I also tried to implement something like a system of buying a product which shows up after the payment for the admin, but I don't know how to show it for the doctor, and not only admin -
How do i enable user to login with new password after reseting it
I am trying to create a password reset system in django. So the issue is that I'm trying to login my user after resetting the password but the system throws an Invalid credentials error. I used a custom user model that takes in username as the unique identifier. Here is the login code in views.py def ilogin(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, f'Welcome {username}!') return redirect('index') else: if myUser.objects.filter(username=username).exists(): messages.error(request, 'Invalid credentials provided.') else: print('eeeeeee') messages.error(request, f'Account with username "{username}" does not exist. Please create an account.') return redirect('login') # Redirect back to login page else: return render(request, 'user/login.html') here the code for reseting the password: def password_reset_confirm(request, token): try: reset_token = PasswordResetToken.objects.get(token=token) if not reset_token.is_valid: messages.error(request, 'This reset link is expired or invalid.') return redirect('login') if request.method == 'POST': new_password = request.POST.get('new_password') confirm_password = request.POST.get('cofirm_password') if new_password == confirm_password: user = reset_token.user print(user) user.set_password(new_password) user.save() reset_token.is_used = True reset_token.save() messages.success(request, 'Your password has been reset successfully.') return redirect('login') else: messages.error(request, 'Password do not match') return render(request, 'emails/password_reset_confirm.html') except PasswordResetToken.DoesNotExist: messages.error(request, 'Invalid password reset link') return redirect('login') I am tryin to create … -
DLL load failed while importing cv2: The specified module could not be found. Import error
I have seen similar problems on stackoverflow, they work on a local system, but I am dockerizing a project and using windows containers. Those solutions don't work in docker. I think I am missing some system files, I just don't know which. This error is related to opencv-python. I tried installing opencv-contrib-python But it did not work for me -
HTML coun'd locate my image when I put the folder into my django app
Before I put the html file inside the template folder follow along with my dijango project, it work perfectly. However, when I build a template folder, and put my CSS and HTML file in, the images are not able to upload why? I try to put all the image into the template folder or add /images/.jpg, but it doesn't work Company_Folder--> storefront --> main--> template--> images --> img enter image description here enter image description here -
How to protect a top secret python script?
I'm developing a project in a client-server architecture. The client is a python 3.12 script that will run on customers desktops and the server is a Django 5.0.x application. I will distribute the client script after running pyinstaller -F script.py, so the package has approximately 40MB because of the virtual enviroment with python libs. So, I need to protect the client script to avoid people can read my code and copy my idea. I was thinking in to create an auxiliary script so this auxiliary script and server will do these basic steps: Auxiliary script generates an RSA assymetric keypair Auxiliary script sends the public key to django application. Django application encrypts the main script with this public key and return a response with encrypted main script as response Auxiliary script downloads the encrypted main script and decrypt with private key Auxiliary script loads the unencrypted main script into the memory Finally, auxiliary script execute the main script. The problem is, even I convert the auxiliary script to a binary by using pyinstaller, if someone do something and can read the auxiliary script code, so this person can edit the code and make the step 5) writes the main script … -
How do I set up a domain name stator page for a Django web server?
Right now my server runs the Django page like this: dato138it.ru:8000/contents. And I need to run it from the browser like this in the browser: dato138it.ru It all works on a cloud server timeweb.clouds. How do I set up a domain name stator page specifically for a Django web server? The problem is that a separate page from the Lamp web server is currently running. So the domain now sees this page from Lamp by default: dato138it.ru -
Interact with inbuilt django DB in python files
I have a form that needs to interact with the DB inbuilt into django. How would I do that in my forms.py file. Do I just use the default sqlite3 built into python or does django have a different way of doing it? I have written a basic post/get request on the frontend. On the backend, I just need to interact with the database. I do not want to use the inbuilt django auth system as I will need to access the database for other use cases also. Any help is appreciated! -
How to add CSS class to a ReCaptchaField v2 in Django forms
I am trying to add Bootstrap class to align the reCAPTCHA in the center. How do I add a class for this in the form? Without doing a custom CSS file or changing template file. from Django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, PasswordResetForm, SetPasswordForm, PasswordChangeForm from django.core.exceptions import ValidationError from django.forms.widgets import PasswordInput, TextInput from django_recaptcha.fields import ReCaptchaField from django_recaptcha.widgets import ReCaptchaV2Invisible class CustomAuthForm(AuthenticationForm): username = forms.CharField(required=True, max_length = 50, widget=forms.TextInput(attrs={"placeholder": "Email", "class":"form-control"})) password = forms.CharField(required=True, max_length = 50, widget=forms.PasswordInput(attrs={"placeholder":"Password", "class":"form-control"})) captcha = ReCaptchaField(required=True) -
Playing an audio file on server from django
I have a raspberry pi that I have hooked up to a door chime sensor so it plays different sounds as people enter the building. Right now, I just made a short script to play those sounds from whatever is in a directory, and it works fine. I decided that it might be easier to upload sounds, and organize their play order if I setup a web server, and since I tend to use django for all web servers, I thought I could get it to work. I know it's a pretty big hammer for such a small nail, but I use it regularly, so it's easy for me to use. This code, when I put it in the django InteractiveConsole, plays just fine. When I try to call it from a PUT request in a view, it won't play the sound, but it also doesn't throw any errors. This is the case both on my computer and the pi. >>> import vlc >>> media_player = vlc.MediaPlayer() >>> media = vlc.Media("/home/pi/chime/media/clips/clip1.mp3") >>> media_player.set_media(media) >>> media_player.play() Is there something that would prevent these kinds of calls from running in a django view? Is there a way to work around it? -
dj-rest-auth and django allauth email addresses
When I try to delete a user already registered from the db i get this : update or delete on table "users_user" violates foreign key constraint "account_emailaddress_user_id_2c513194_fk_users_user_id" on table "account_emailaddress" also when I register a user, only the email, username and password gets registered in the db. Serializers: class RegisterSerializer(serializers.Serializer): password = serializers.CharField( write_only=True, required=True, validators=[validate_password], ) password2 = serializers.CharField( write_only=True, required=True, ) class Meta: model = User fields = [ "first_name", "last_name", "location", "username", "email", "password", "password2", ] extra_kwargs = { "first_name": {"required": True}, "last_name": {"required": True}, "location": {"required": False}, } def validate_username(self, username): username = get_adapter().clean_username(username) return username def validate_email(self, email): email = get_adapter().clean_email(email) return email def validate_password1(self, password): password = get_adapter().clean_password(password) return password def validate(self, data): if data["password"] != data["password2"]: raise serializers.ValidationError( {"password": "Password fields didn't match."} ) return data def get_cleaned_data(self): return User( username=self.validated_data.get("username", ""), email=self.validated_data.get("email", ""), password=self.validated_data.get("password", ""), first_name=self.validated_data.get("first_name", ""), last_name=self.validated_data.get("last_name", ""), location=self.validated_data.get("location", ""), ) def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self, commit=False) if "password1" in self.cleaned_data: try: adapter.clean_password(self.cleaned_data["password1"], user=user) except DjangoValidationError as e: raise serializers.ValidationError( {"password": list(e.messages)} ) # user.is_active = False user.save() return user View: class RegisterView(CreateAPIView): serializer_class = api_settings.REGISTER_SERIALIZER permission_classes = api_settings.REGISTER_PERMISSION_CLASSES token_model = … -
My django form keeps giving me the error message even though i still get the data i'm trying to send in the database, what could be wrong? th
I'm trying to add a staff with django everything seems to be working fine i even see the entry in the database but once i click the submit button instead message.success i get message.error i cant seem to figure out the issue. This is what my form for add_staff template looks like <form role="form" method="post" action="/add_staff_save"> {% csrf_token %} <div class="card-body"> <div class="form-group"> <label>Email address</label> <input type="email" class="form-control" name="email" placeholder="Enter email"> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control" name="password" placeholder="Password"> </div> <div class="form-group"> <label>Firstname</label> <input type="text" class="form-control" name="first_name" placeholder="First Name"> </div> <div class="form-group"> <label>Lastname</label> <input type="text" class="form-control" name="last_name" placeholder="Last Name"> </div> <div class="form-group"> <label>Username</label> <input type="text" class="form-control" name="username" placeholder=" User Name"> </div> <div class="form-group"> <label>Address</label> <input type="text" class="form-control" name="address" placeholder="Address"> </div> </div> <div class="form-group"> {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="alert alert-success" style="margin-top:10px"> {{ message }} </div> {% endif %} {% if message.tags == 'error' %} <div class="alert alert-danger" style="margin-top:10px"> {{ message }} </div> {% endif %} {% endfor %} {% endif %} </div> <!-- /.card-body --> <div class="card-footer"> <button type="submit" class="btn btn-primary btn-block">Add Staff</button> </div> </form> This is my views.py and the function that handles adding staff from … -
Django FOREIGN KEY constraint failed when registering new users
I'm encountering a "FOREIGN KEY constraint failed" error while trying to register new users in my Django application. Here's the relevant code from my models.py, serializers.py, and views.py files: Serializers.py: User = get_user_model() class UserSerializer(serializers.ModelSerializer): friends = serializers.SerializerMethodField() class Meta: model = User fields = ['id', 'name', 'email', 'date', 'password', 'profile_picture', 'friends'] extra_kwargs = {'password': {'write_only': True, 'required': True}} def get_friends(self, obj): friends = obj.get_friends() # Assuming get_friends returns a list of friend objects return friends if friends else [] # Return empty list if friends is empty @transaction.atomic def create(self, validated_data): print("User Serializer create()") print("Validated data: ", validated_data) user = User.objects.create_user(**validated_data) print("User before tokenization ", user.__dict__) print("User created, about to tokenize") # Check if user is saved in the database try: user_check = User.objects.get(email=user.email) print("User saved in database: ", user_check.__dict__) except User.DoesNotExist: print("User not found in database") raise serializers.ValidationError({"error": "User not saved in database"}) try: token, created = Token.objects.get_or_create(user=user) if created: print("Token created: ", token.key) else: print("Token already exists for user: ", token.key) print("User and Token creation successful") # Ensuring transaction is committed transaction.on_commit(lambda: print("Transaction committed successfully")) return user except Exception as e: print("Error during token creation: ", str(e)) raise serializers.ValidationError({"error": "Token creation failed"}) views.py class UserView(APIView): def post(self, … -
Hired at a new job - I can do 85% of responsibilities except some things related to the website. How do I get a sitemap?
I am in charge of adding content to a website - it uses Wagtail. I know nothing about programming. My superior has asked me to do a website audit and wants to know if the sitemap file is set up correctly. My problem is that I do not know how to get a sitemap. On a broader level I have no idea who created the website or how to access the more complex areas (Django contrib sitemap app?) I apologize for being so ignorant but could anyone describe to me the first steps I should take? That might include questions I could ask the people around me to gain access to what I need to get to. -
Docker-compose is able to compile program but is unable to open link to Local host
I have a basic Django project that I have put into a docker container. Currently I have it running on https locally just for the development phase because it is a requirement. When I run my program without docker it opens successfully on https://127.0.0.1:8000. Which is the address the message says its currently running on. But when I use the same logic on my docker container after running docker-compose up the container compiles but I am unable to load the web page. When I try to run the address from the docker container I just get the generic site cannot be reached error. Link I used to get https during development: Docker-compose.yml version: "3.8" services: django: build: . container_name: frontend command: python manage.py runserver_plus --cert-file cert.pem --key-file key.pem volumes: - .:/usr/src/app ports: - "8000:8000" depends_on: - pgdb pgdb: image: postgres container_name: backend environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres Dockerfile FROM python:3.12.3 ENV PYTHONUNBUFFERED=1 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install django RUN pip install -r requirements.txt settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'location', 'rest_framework', 'django_extensions', ] I tried to change the port number but it still didn't work. -
Django query for a select item return '---------'
I'm trying to populate a select item with a django queryset. It's working fine but at the begining of the list of the dropdown menu on the select item I always have a '---------' as first option. forms.py class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ModelChoiceField(queryset=models_products.objects.values_list('product_denomination', flat=True),required=False, widget=forms.Select(attrs={'id': 'editable-select-2'})) The "product_denomination" on the database only contains 2 lines but I always have this '---------' on first option. What am I missing ? -
NOT NULL constraint failed on PUT request in Django
I'm new to Django and I'm having trouble handling form-data and raw data in PUT requests. I need to update records of a Person model via a PUT request. The Person model has several fields including fname, sname, age, and gender, all of which are required. I have a view to handle the PUT request, and I’m trying to handle both JSON and form-data formats in the request body. However, when I send a PUT request via Postman, I encounter the following error: Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: api_person.fname To handle different request formats, I first attempt to parse the request body as JSON. If JSON parsing fails, I fall back to handling form-data. Here’s the relevant part of my view: ` try: # Attempt to parse request body as JSON data = json.loads(request.body) fname = data.get('fname') sname = data.get('sname') age = data.get('age') gender = data.get('gender') except json.JSONDecodeError: # Handle form-data if JSON parsing fails fname = request.POST.get('fname') sname = request.POST.get('sname') age = request.POST.get('age') gender = request.POST.get('gender') # Update person object with received data person.fname = fname person.sname = sname person.age = age person.gender = gender person.save() ` I expected this approach to handle both request … -
using nginx host multiple django apps/docker in one server. return to root path not the apps' path
I have a django app. The code snippet for the function load_form(request) in views.py. ''' def load_form(request): if request.method == 'POST': newQAForm = QAForm(request.POST) if newQAForm.is_valid(): instance = newQAForm.save(commit=False) instance.save(using='RadDataWarehouse') return redirect('confirmation') ''' and another function ''' def confirmation(request): return render(request, 'confirmation.html') ''' It runs well in local. It will direct it to http://127.0.0.1:8000/confirmation/ after save the form to database. After I deployed it to linux server. I had a issue after save it to database. It will direct to https://abcdomain.com/confirmation/; But I suppose it will go to https://abcdomain.com/protocolqa/confirmation/ The nginx.conf for the Reverse Proxy is below: ''' location /protocolqa/ { proxy_pass http://localhost:8511/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Script-Name /protocolqa; proxy_set_header X-Original-URI $request_uri; } ''' how to fix it and let it got to https://abcdomain.com/protocolqa/confirmation/ -
Best approach to object creation in the background without using a task queue system?
I have been thinking of the best approach to a record creation in the background without using django signals, or celery, etc. I do not want to use signals due to the fact that the sender Model would be called a very high number of times, as that table gets created/updated quite often. So I am looking to avoid this approach. My goal is to run a function that goes through some complex logic, ultimately ending in an EmailRecordTracker object creation in which I am doing some tracking to determine whether an email needs to be sent out or not at a later point in time. The function I need to create needs to get hit after a user submits a form and the form is fully saved. I was looking into asynchronous support possibly. https://docs.djangoproject.com/en/5.0/topics/async/ Workflow is pretty simple: User submits form, updates a form, etc. User is able to continue to navigate through app while my function to create an EmailTrackerRecord gets ran in the background. Any advice would be appreciated! -
Is there a way to create a run configuration for a manage.py command in Pycharm
I want to be able to run a manage.py management command via a Pycharm run configuration. Is there a way to do this?