Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django app sending message to SQS, but worker not executing
I have an AWS SQS set up named celery-celery and I am sending tasks to the SQS queue via Celery when I call an API. I can see that the messages are getting to the SQS queue (https://sqs.us-east-1.amazonaws.com/718854804674/celery-celery) b/c there is are available messages in the queue, and a new one is added to the queue whenever I call the API. However, the messages never go away, and they never execute. They just sit in the queue as an available message. I am running a Django application on Beanstalk. I am calling the api: /api/print-hello-world/ Which nvigaes to the url: path('print-hello-world/', print_hello_world_task, name='print_hello_world') and then to the view: def print_hello_world_task(request): # return JsonResponse({'status': 'API is working'}) print("Received request to start timer task") logger.info("Received request to start timer task") task = print_hello_world.delay() # This triggers the Celery task asynchronously print(f"Task started with ID: {task.id}") return JsonResponse({'status': 'Task started', 'task_id': task.id}) Which then calls the task in tasks.py: @shared_task(queue='celery-celery') def print_hello_world(): return "Executed" This is my Procfile: web: gunicorn --workers 1 rvm.wsgi:application worker: celery -A rvm worker -l debug --loglevel=DEBUG --queues=celery-celery --logfile=/var/log/celery/celery.log -E This is my CELERY_ related elements of settings.py: AWS_ACCESS_KEY = os.getenv('AWS_ACCESS_KEY') AWS_SECRET_KEY = os.getenv('AWS_SECRET_KEY') CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = … -
How to stop a celery task if user unloads?
My website allows users to translate files. I want to add a failsafe in case a user decides to unload the webpage(whether by reloading, navigating away or closing the tab). My backend is django plus celery[redis]. Currently, after a user begins the translation task my frontend polls the backend every 5 seconds to see if the task is still running. Here is the corresponding JS for reference: function pollTaskStatus(taskId) { currentTaskId = taskId; console.log(currentTaskId) pollInterval = setInterval(() => { const xhr = new XMLHttpRequest(); xhr.onload = function() { if (xhr.status == 200) { const response = JSON.parse(xhr.responseText); if (response.status === 'completed') { console.log('sent'); showTranslationComplete(response); clearInterval(pollInterval); // Stop polling once completed isTranslating = false; // Set to false when translation is complete } } else { showError('An error occurred.'); clearInterval(pollInterval); // Stop polling on error isTranslating = false; // Set to false on errors } }; xhr.onerror = function() { showError('Connection error. Please check your network connection and try again.'); clearInterval(pollInterval); // Stop polling on network error isTranslating = false; // Set to false on network error }; xhr.open('GET', `/translate/poll_task_status/${taskId}/`, true); xhr.send(); }, 5000); // Poll every 5 seconds } I know it is unreliable to run functions during/after an unload … -
Pass multiple type of data in AJAX request with Django
I have this Ajax call : var serializedData = $(this).serialize(); $.ajax({ type:"POST", url: "/my_url_view/", data: serializedData , var_id_sales_document:$("#id_id_sales_documents").val() , success: function(data){ $("#result").text(data["result"]); } }); What I'm trying to do is to pass serializedData to save the form but I also need to get var_id_sales_document to re-use it in my view like this : var_id_sales_document = request.POST.get('var_id_sales_document') Normally I used to pass data in my ajax like this $.ajaxSetup( { data: {item1: $('#item').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, }); But like this I don't know how to pass serialized data ... I tried many things on the forum but I didn't find how to cumulate those kind of datas. -
ManytoMany fields generating "no such table:<tablename>" error where <tablename> is related to no model in models.py
I'm sorry if question title is confusing or not clear but i didn't have a better way of writting it. I have a django app root, in models.py i created a model Post containing 3 manytomany fields ; File, Video and Picture and some other fields and while trying to populate the model i get this error message django.db.utils.OperationalError: no such table: root_post_Picture. I already ran python manage.py sqlmigrate root 0001_initial and saw no table with such name and it's not surprising since root_post_Picture corresponds to none of my models . I think it is related to the manaytomanyfields i created since the name root_post_Picture seems to be a combination of the tables root_post and root_picture from my database. views.py def postcreation(request): Videoarray=[] Picturearray=[] Filearray=[] form=AbsolutePostForm(request.GET) file = Fileform(request.FILES) pic = PictureForm(request.FILES) vid = VideoForm(request.FILES) if request.method=="POST": file = Fileform(request.FILES) if "File" in request.POST: if file.is_valid(): File=Files(Post_type="posts",Post_id=get_id_generation("postids.txt"),File=request.FILES["File"]) File.save() Filearray.append(File) print("file") return HttpResponse("file") pic = PictureForm(request.FILES) if "Picture" in request.FILES: if pic.is_valid(): Picture = Pictures(Post_type="posts", Post_id=get_id_generation("postids.txt"),Picture=request.FILES["Picture"]) Picture.save() Picturearray.append(Picture) print("pic") return HttpResponse("picture") vid = VideoForm(request.FILES) if "Video" in request.FILES: if vid.is_valid(): Video = Videos(Post_type="posts", Post_id=get_id_generation("postids.txt"),Video=request.FILES["Video"]) Video.save() print("vid") Videoarray.append(Video) if "Postcoment" in request.POST: form = AbsolutePostForm(request.POST) if form.is_valid(): post=form.cleaned_data["Postcoment"] Main=Post(post=post) Main.save() for obj … -
How to delete images when removing post in Summernote?
Using Summernote on the Django project to add/remove posts via the Admin interface, I can find no solution for removing images from the Media Root. None of the similar responses found on SO work. Works fine on images outside of Summernote - installed django-cleanup What's the best way to delete image(s) when removing a post via Admin? -
connect to the hikvision camera with python
i want to get sream video from hikvision camera and show it on the webpage using django . i did it but it has delay for 2 or 3 seconds . i try with both rtsp and http protocol . http with port 80 is better than rtsp in delay . is there another way to connect to the camera with no delay ? i change camera configuration many times . if frame rate is higher than 4 the delay is increasing but with under 4 frame rate its delay is about 2 seconds .do you have suggestion?also i use substream config to use protocol http. self.Capture = cv2.VideoCapture("http://user:pass@ip:port/ISAPI/Streaming/channels/102/httpPreview") -
Django 1.8 and MSSQL 2022
Is there a way to connect a project in Django 1.8 to MSSQL 2022, using django_pyodbc_azure librery allows me connect to MSSQL 2016, is there another librery that allows me do this?