Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use the ‘problems’ field in pycharm?
pycharm keeps finding ‘problems’ in the project. it's all completely useless and unfounded. don't know how it works. does anyone use it ? for example, here he found an ‘indent expected’ problem and here's the code: class ProductForm(forms.ModelForm): or here, there's a mistake in the middle of nowhere. code: And so on throughout the project. found 18 errors, looked through each one - all to no avail. is it me who doesn't know how to use it, or it doesn't work? does anyone use it? -
How check if user is logged in on server side React, Django, JWT
I have set up authorization using the JWT token. Now I want to give the user access to the protected view, which requires authorization. class GetUser(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def post(self, request): return Response({'username': request.user.username}) How do I check if the user is logged in on the server side? I wrote an asynchronous function that accesses the django rest framework api. But this function always returns a promise no matter what I do. function saveToken(data) { localStorage.setItem('access_token', data.access) localStorage.setItem('refresh_token', data.refresh) return true } async function isLoggedIn() { return await axios.post('api/getuser/', {}, {headers: {Authorization: 'Bearer ' + localStorage.getItem('access_token')}}) .then(async function (response) { return true }) .catch(async function (error) { return await axios.post('api/token/refresh/', {refresh: localStorage.getItem('refresh_token')}) .then(async function (response) { return saveToken(response.data) }) .catch(async function (error) { return false }) }) } As I understand it, I can't get the value from promise in any way. That's why I decided to write the component this way, but React throws an error. const ComponentMainArea = () => { const location = useLocation() const element = useOutlet() return isLoggedIn().then((value) => { if (!value) { return (<Navigate to="/proxy/8000/login"/>) } else { return ( <div className='mainarea'> <AnimatePresence mode='wait' initial={true}> {element && React.cloneElement(element, { key: … -
https to http nginx works partially
I can use http and https connection to my router(to which connected server) through KeenDNS. I have nginx with following config on the server server { listen 80; server_name example.com; location /static/ { alias /app/staticfiles/; } location / { proxy_pass http://web:8000; 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; } } so when I go to /static/ urls over https everything works, but / urls doesn't and I'm getting 400 bad request. Btw I'm having Django in docker with gunicorn behind proxy_pass's web url. Over http everything works fine. What could be the problem? -
Supporting Apple sign-in for mobile and web using dj_rest_auth, allauth
We are looking to implement Apple sign-in from both the web and mobile using this stack. React SPA using Django 4.2 / DRF 3.15.2 / dj_rest_auth 6.0.0 / allauth 0.61.1 backend Due to the different Client ID for web and mobile, we had to configure two separate apps in SOCIALACCOUNT_PROVIDERS[”apple”] as recommended by allauth. To make this work for the version we are using, we had to manually apply the following patch to 0.61.1 and set the “hidden” property on the mobile app. My impression was that this property is needed to make it work with some admin interface, but maybe not. The explanation is not clear - “For the app specifying the bundle ID, add the following to the settings so that this app does not show up on the web”. We use the same settings for both APPS - secret, key, settings, except for client_id. When we set this property, the “hidden” app (mobile) never gets used and we get a client_id mismatch error when logging in from mobile. So I guess I am not sure I understand the purpose of having that property. Or maybe we are missing some other patch(es) that make this work. In short, … -
Memory Leak When Using Django Bulk Create
I have the following code that constantly checks an API endpoint and then if needed, adds the data to my Postgres database. Every iteration of this loop is leaking memory in the postgresql\operations.py file. Im not sure what data is still being referenced and isnt clearing, so realistically what could be causing this issue? class DataObject(models.Model): raw_data = models.TextField() name = models.TextField(null=True) def post_process(self): data = json.loads(self.raw_data) self.name = data['name'] def do_from_schedule(): api = API() loads = api.grab_all_data() del api datas_to_create = [] for load in loads: data = DataObject() data.raw_data = json.dumps(load) data.post_process() datas_to_create.append(data) DataObject.objects.bulk_create(datas_to_create, ignore_conflicts=True, batch_size=200) del datas_to_create gc.collect() while True: do_from_schedule() time.sleep(5) Here are the results of tracemalloc. Theres a consistent, and unending memory leak. #1: postgresql\operations.py:322: 156.9 KiB return cursor.query.decode() #1: postgresql\operations.py:322: 235.3 KiB return cursor.query.decode() #1: postgresql\operations.py:322: 313.7 KiB return cursor.query.decode() #1: postgresql\operations.py:322: 392.0 KiB return cursor.query.decode() #1: postgresql\operations.py:322: 470.4 KiB return cursor.query.decode() I found this for someone using MySql https://stackoverflow.com/a/65098227/8521346 But im not sure how to even test/ fix this if it was the issue with the postgres client. -
How to use Bootstrap Theme of dashboard in Django admin?
i am new in django , i want to create my own custom admin panel for django project ,i have a bootstrap theme of dashoard and i want to make this as admin panel for my project ,how to do this ,can i do this by overriding the existing admin files like 'admin/base.html' ,'admin/base_site.html', or is there any other method to do this...Please Guide i am trying to over ride the existing file ,is there any other method, also need some guidance about the urls, if i have to use another method then over riding the existing file -
ModuleNotFoundError: No module named, how come no model was named since it is written in the main code and in the model?
I created this model code but the django makemigrations command doesn't work and show an error. The first code is where the database should be and where I put the name of the model I want, the second code is how the model is made so far and the last is the error that appears when I try to use makemigrations. I have no idea what to do to make it work. ``INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'livros'` `from django.db import models class Livros(models.Model): nome = models.CharField(max_length = 100) autor = models.CharField(max_length = 30) co_autor = models.CharField(max_length = 30) data_cadastro = models.DateField() emprestado = models.BooleanField(default=False) nome_emprestado = models.CharField(max_length = 30) data_emprestimo = models.DateTimeField() data_devolução = models.DateTimeField() tempo_duração = models.DateField()` File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'livros' -
Importing login of users/tests module to another application/tests not working in Django
I'm trying to avoid code duplication so I want to import login from users/test to the ordering/test where I need to test different views that have @login_required. users/test.py User = get_user_model() class UserBaseTest(TestCase): def setUp(self): self.user = User.objects.create_user( username='testuser', password='testpass', email='test@gmail.com', phone_number='3401234567' ) def test_login(self): logged_in = self.client.login(username='testuser', password='testpass') self.assertTrue(logged_in, "Login failed in UserBaseTest") ordering/test.py class OrderTest(UserBaseTest): def test_view(self): self.test_login() response = self.client.get(reverse('homepage'), follow=True) self.assertRedirects(response, self.order_url) self.assertTemplateUsed(response, 'ordering/ordering.html') If I ran py manage.py test users no errors and no failures were elevated, but with py manage.py test ordering it gave me: self.assertTrue(logged_in, "Login failed in UserBaseTest") AssertionError: False is not true : Login failed in UserBaseTest -
Inline Images Displayed as Attachments in iOS Mail App
I'm using Django to send HTML emails that include an inline logo image using the cid (Content-ID) method. The email is sent and rendered correctly in most email clients, but in the iOS Mail app, the logo appears also as an attachment at the bottom of the email and than inline within the HTML content. Additionally, the attachment icon is visible in the email list view. Here is the code I’m using (Written in Python/Django): from django.core.mail import EmailMultiAlternatives from email.mime.image import MIMEImage # Sending the email email = EmailMultiAlternatives( subject=subject, body=html_content, from_email=from_address, to=to_email ) email.attach_alternative(html_content, "text/html") # Adding logo as inline attachment with open(self._get_logo(domain), 'rb') as logo_file: logo = MIMEImage(logo_file.read()) logo.add_header('Content-Disposition', 'inline') logo.add_header('Content-ID', '<logo>') # Important: Set CID here email.attach(logo) In the HTML content, I reference the image like this: <img src="cid:logo" alt="Logo"> Is there a known workaround or a specific way to ensure that inline images are displayed correctly in the iOS Mail app without showing them as attachments? Any advice on handling this issue within Django or HTML emails in general would be greatly appreciated. -
Django Development Server Success Message on my EC2 Instance's public ipv4 address and django' default port
I have launched and EC2 Instance with Windows AMI and a security group that has 4 inbound rules. 1. Allow http traffic from all IP addresses 2. Allow https traffic from all IP addresses 3. Custom TCP with port 8000 and RDP to connect to the instance using RDP client. I have connected to the ec2 instance using RDP client and have added an inbound rule for port 8000 on windows firewall. I downloaded python and Django and created a project on the ec2 desktop When I run the development server on the localhost in this case the ec2 instance it is showing the success message. When I want now to run the development server using my ec2 instance's public ipv4 address and port 8000 it is saying this site cannot be reached. Can you help me guys so that when I open my public ipv4 address I can see the success message -
what is Password-based authentication in django and how i can remove it?
I creat a signup form in django using django forms and when i run my code there is field i didnt expect Password-based authentication i did not use it and i have no idea what it is so anyone can tell me what it is and how i can remove it from user signup form? form.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.hashers import check_password class RegisterForm(UserCreationForm): """Form to Create new User""" def __init__(self, *args,hashed_code=None, **kwargs) -> None: super(RegisterForm,self).__init__(*args, **kwargs) self.hashed_code = hashed_code code = forms.CharField(max_length=4, required=True, label="code", help_text="Enter the four-digit code" ) def is_valid(self): """Return True if the form has no errors, or False otherwise.""" if not self.hashed_code: self.add_error("code","you have not any valid code get the code first") elif not check_password(self.data.get("code"),self.hashed_code) : self.add_error("code","code is invalid") return self.is_bound and not self.errors class Meta: model = get_user_model() fields = ["email", "password1", "password2","code"] -
sync_to_async and async def in python
I use djnago with websockets for show the live view in webpage from a camera . My purpose is to show live view without no lag and do a background task that live view doesnt affected . I mean the live view works and the background task works too without conflict . The background task should start in the live view function . I use async def but the live view affected . I try with @sync_to_async decorator for my task function and it works fine ! I want to know difference between these two methods with async def or with decorator also async_to_sync decorator. -
Annotate and filter by related model
I have two models: class ABSLoyaltyCard(models.Model): title = models.CharField( max_length=120, blank=True, ) class CardToOwner(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) card_frame = models.ForeignKey( ABSLoyaltyCard, on_delete=models.CASCADE, related_name="clients", ) owner = models.ForeignKey( Guest, on_delete=models.CASCADE, related_name="cards", ) For example I have owner - Bob(CardToOwner.owner). I need to get all cards from ABSLoyaltyCard, with annotated field 'is_my_card', where 'is_my_card' = True if ABSLoyaltyCard is in CardToOwner with owner = Bob, otherwise - False. What's the good way to do it? -
DetailedView not showing the features when I use object
{% extends 'base/main.html' %} {% block content %} <div class="post"> <div class="postImage"> <img src="{{ object.author.profile.image.url }}" alt="user image" class="postPic"> </div> <div class="postText"> <p><span class="author">{{ object.author }}</span> <span class="date">{{ object.date_posted|date:'F d, Y' }}</span></p> <hr> <h2 class="postTitle">{{ object.title }}</h2> <br> <p class="postDescription">{{ object.content }}</p> </div> </div> {% endblock content %} This is my post_detail.html file from django.shortcuts import render from .models import Post from django.views.generic import ListView, DetailView # Create your views here. def home(request): context = { 'posts': Post.objects.all() } return render(request, 'base/index.html', context) class PostListView(ListView): model = Post template_name = 'base/index.html' context_object_name = 'posts' ordering = ['-date_posted'] class PostDetailView(ListView): model = Post template_name = 'base/post_detail.html' def about(request): return render(request, 'base/about.html', {'title': 'About'}) This is my views.py file I ran the code and every time I run the url file it always comes up blank. Every other part of the page is working but that part where I am supposed to see my post features like the title or the user profile picture, those areas are just blank -
How to customize the django cms plugin
I am using Django CMS Frontend. I want to customize the plugins. For example I want to add some extra fields to the default Card plugin. I tried using Plugin Form So far I have done this. cms_plugins.py class CustomPlugin(CMSPluginBase): form = CardForm name = "Custom Card" render_template = "siteindex/card_render.html" change_form_template = "siteindex/card.html" cache = False def render(self, context, instance, placeholder): context = super().render(context, instance, placeholder) return context plugin_pool.register_plugin(CustomPlugin) cms_forms.py from djangocms_frontend.contrib.card.forms import CardForm from django.db import models class CustomForm(CardForm): subtitle = forms.CharField(max_length=255, required=False, label="title") class Meta: model = CustomCard fields = "__all__" card.html {% extends "admin/cms/page/plugin/change_form.html" %} card_render.html {{ instance.title }}} After that when I try to add a plugin I get this error (https://i.sstatic.net/2f7fjFSM.png) -
How to resolve web app on azure portal gives sometimes the error: Is the server running on host "localhost" (127.0.0.1) and accepting..?
I have a Dockerized Django application that I am developing using Visual Studio Code. The app is deployed as an Azure Web App, and I also have a PostgreSQL database on Azure. However, I am encountering an issue where the site intermittently displays the following error: OperationalError at /admin/ could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? After refreshing the page (F5), the error typically resolves, and the site works properly. However, this issue occurs frequently. Here are the relevant files: version: "3.9" services: web: image: crdierenwelzijn.azurecr.io/web1 build: context: ./ dockerfile: Dockerfile.prod restart: always command: gunicorn DierenWelzijn.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env proxy: image: crdierenwelzijn.azurecr.io/proxy1 build: context: ./proxy restart: always depends_on: - web ports: - 80:80 volumes: - static_volume:/home/app/staticfiles - media_volume:/home/app/media volumes: static_volume: media_volume: The env file looks: DEBUG=0 SECRET_KEY="_q2=%usxw=" DB_NAME="zijn" DB_USER="zijn" DB_PASS="8_Jr" DB_HOST="postgres.database.azure.com" DB_PORT="5432" docker file of the proxy: FROM nginx:1.25 RUN rm /etc/nginx/conf.d/default.conf RUN mkdir -p /home/app/staticfiles RUN mkdir -p /home/app/media COPY nginx.conf … -
Does a serializer remove the base URL from an image
I have these models used to create an advertisement with: class Advertisement(models.Model): INTERVALS = [ ("daily", "Daily"), ("weekly", "Weekly"), ("monthly", "Monthly"), ] title = models.CharField(max_length=50) image = models.FileField(upload_to=ad_directory_path, null=True, blank=True) ad_text = models.CharField(max_length=200, null=True, blank=True) ad_link = models.URLField(null=True, blank=True) start_date = models.DateField() end_date = models.DateField() budget_interval = models.CharField(max_length=20, choices=INTERVALS, default="daily") budget = models.DecimalField(max_digits=5, decimal_places=2) active = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ads") created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "advertisement" verbose_name_plural = "advertisements" db_table = "advertisements" def __str__(self): return str(self.title) class AdExtension(models.Model): advertisement = models.OneToOneField(Advertisement, on_delete=models.CASCADE, related_name="extension", null=True, blank=True) text = models.TextField(max_length=1000, null=True, blank=True) link = models.URLField(null=True, blank=True) class Meta: verbose_name = "ad extension" verbose_name_plural = "ad extensions" db_table = "ad_extensions" def __str__(self): return str(f"{self.advertisement} extension") class ExtensionImage(models.Model): image = models.FileField(upload_to=ext_image_directory_path) extension = models.ForeignKey(AdExtension, on_delete=models.CASCADE, related_name="images") class Meta: verbose_name = "extension image" verbose_name_plural = "extension images" db_table = "extension_images" def __str__(self): return str(f"{self.extension}'s image") An advertisement can have an extension and an extension can have images. When I update an advertisement the response returns the extension images without the base url which is http://localhost:8000. Existing images like the main image of an advertisement is returned correctly id 11 title "Ad number 9" image … -
How to use self-singed certificates on DDG iOS browser
I cannot access a local website I built with Django on my iPhone using DuckDuckGo browser because it does not trust the self singed certificate even though I manually installed it on my iPhone. The error message that I get says: "The certificate for this server is invalid. You might be connecting to a server that is pretending to be "192.168.1.128" which could put your confidential information at risk." I used mkcert on my macBook to generate the certificate, uploaded it to the “server” (everything is running locally on my macBook) and installed it on my iPhone. When using Safari everything is working fine. The certificate is a .pem file. After researching the internet, I tried to follow these instructions on apple.stackexchange.com - but I don’t have the option to "Enable full trust for root certificates" for the newly-installed certificate as it is shown here on support.apple.com. -
Docker fist implementation: not showing Angular frontend
I am trying to set up Docket in this stack: Angular 18.2, Python 3.12.5, Django 5.1, Posgres 16.4. I tried setting up a Dockerfile in each of the Backend and Frontend folders, also I created docker-compose.yaml and .dockerignore in the root folder. After solving various problems it seems to be working, the problem is that I can't see the frontend DOM. The localhost is not reachable. But if I try to run the payers separately I am able to see. So I definitely made some mistakes along the way. I share the files and the folders tree. Dockercompose services: backend: build: context: ../BACKEND/humatic dockerfile: docker/Dockerfile ports: - "8000:8000" volumes: - ../BACKEND/humatic:/app/humatic environment: - DEBUG=True - DATABASE_URL=postgres://postgres:humatic@db:5432/humatic frontend: build: context: ../FRONTEND/humatic dockerfile: docker/Dockerfile ports: - "4200:80" volumes: - ../FRONTEND/humatic:/app/humatic environment: - API_URL=http://backend:8000/api command: /bin/bash -c "npm install && ng serve" db: image: postgres:latest ports: - "5432:5432" environment: POSTGRES_DB: humatic POSTGRES_USER: postgres POSTGRES_PASSWORD: humatic Dockerignore __pycache__ *.pyc *.pyo *.pyd node_modules npm-debug.log Dockerfile (backend) # Usa una versione compatibile di Python FROM python:3.11 # Imposta la directory di lavoro WORKDIR /app/humatic # Copia il file dei requisiti COPY requirements.txt . # Installa le dipendenze, compreso Django RUN pip install --no-cache-dir -r requirements.txt # … -
How do I use the Django admin site query language with a Ms SQL server backend?
When going to any model I tried to use the DjangoQL search syntax to query something like field = "fieldvalue". If I use SQLite as the backend this works fine if I use Ms SQL server it errors out saying query object has no attribute explain_format. My settings.py for the database ENGINE 'mssql' HOST my_host NAME my_name and the options are driver: ODBC Driver 17 for SQL Server host_is_server: True I am successfully able to connect to the server, for example using python manage.py shell I can query tables etc. The error only appears when using the admin page. Any ideas what might be going on. PS I needed to use host_is_server otherwise it wasn't working, not sure why -
Django ORM - Prevent null field being included in the insert statement
I have a Django model resembling the following: class SomeClass(CoreModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) auto_increment_id = models.BigIntegerField(null=True, blank=True, db_index=True) I want to increment the auto_increment_id field directly in the database using DEFAULT value. In fact I modified my table in the test db and when I manually insert a row, this works as expected. When I insert a new record through Django though, this field remains as Null, because the SQL that Django produces includes this field as well with a NULL value. I've tried setting this field to a BigAutoField but it seems this field should be used as a primary key and since I have another primary key, this is not an option. Needless to say, this is a production code and I cannot change my primary key. Any methods to prevent this behaviour? -
Django Form Wizard Not Executing done() Method Despite Valid Form Submission
I’m using the SessionWizardView to implement a multi-step form process for signing documents. However, I’m encountering a perplexing issu where the done() method is not being executed, and as a result, no data is being saved to the database. Im using django 5.0.6. The form process involves 3 steps: User inputs personal details User reviews the document title and details User signs the document, and the signed document should be saved Now after submitting the final form (Step 3), the wizard redirects to the thank_you page as expected. However, none of the participant data, including the signed document, is saved to the database. Additionally, the done() method does not seem to be executed, as none of the print statements or debugging logs inside this method appear in the console.Here is the current implementation of the SignMyselfWizard view: class SignMyselfWizard(SessionWizardView): form_list = FORMS_MYSELF file_storage = file_storage def get_template_names(self): step = self.steps.current if step == 'user_details': return 'sign/user_details_form.html' elif step == 'review': return 'sign/review_document.html' elif step == 'sign_document': return 'sign/sign_myself_wizard.html' return 'sign/default.html' def get_context_data(self, form, **kwargs): context = super().get_context_data(form=form, **kwargs) if 'unique_link' in self.kwargs: document = get_object_or_404( Document, unique_link=self.kwargs['unique_link']) context.update({ 'document': document, 'document_url': self.request.build_absolute_uri(document.docfile.url), 'company': document.company, }) if self.steps.current == 'sign_document': user_details … -
Django migrates data, and an error is reported during the migration, but a table appears in the database, what is going on?
I will connect to three MySQL databases, generally connect to the local database, and then test the database, and there is the online database, if I connect to the local database migration model to generate the migration data successfully, but when I connect to the online database, the field is displayed when the data is migrated (it is a failure during migration), but the corresponding table is generated in the online database, and then I use MySQL When I execute the python manage.py migrate command again, it will show that the table already exists, and it stands to reason that these generated tables will not be recognized by Django, how should this problem be solved? I tried to use --fake to get him to force the endorsement, but it still failed, and now it shows that this table already exists, and deleting the table is not good to delete because of the online database I have a version of Django that is 3.2.3 -
Django DB GeventPool couldn't be imported
I've installed django-db-geventpool when I added it to the settings.py I'm getting this error File "/Users/hbilalkhan/Workspace/Web/Production/Django/IssuesReporting/venv/lib/python3.11/site-packages/django/db/utils.py", line 126, in load_backend raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'django_db_geventpool.backends.postgresql_psycopg2' 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' Settings.py 'ENGINE': 'django_db_geventpool.backends.postgresql_psycopg2', I've also tries psycopg3 'ENGINE': 'django_db_geventpool.backends.postgresql_psycopg3', Versions Django==4.2.14 django-db-geventpool==4.0.7 psycopg==3.2.1 psycopg-binary==3.2.1 psycopg2==2.9.9 psycopg2-binary==2.9.9 -
Passing argument in url
path('edit_items_page/int:item_trackid/',views.edit_items_view.as_view(),name="edit_items_page"), error: Reverse for 'edit_items_page' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_items_page/(?P<item_trackid>[0-9]+)/\Z'] cannot access the argument item_trackid I passed in the url via the django path url