Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to Filter Model Instances and also Related Objects for Each Instance. Nested Filtering?
I have three models, Genre, Movie and Review. Each genre can have multiple movies, and each movie can have multiple reviews. I have been trying to filter the related objects of a Genre instance such that the queryset contains only active movies, and each of those active movies contains only active reviews. models.py class Genre(models.Model): name = models.CharField(max_length=160) class Movie(models.Model): genre = models.ForeignKey(Genre, null=True, on_delete=models.CASCADE, related_name='movies') title = models.CharField(max_length=160) active = models.BooleanField(default=True) class Review(models.Model): movie = models.ForeignKey(Movie, null=True, on_delete=models.CASCADE, related_name='reviews') author = models.CharField(max_length=150) active = models.BooleanField(default=True) Basically, I am looking for something roughly like genre1.movies.filter(active=True).reviews.filter(active=True), if something of this sort of possible. How can I obtain a queryset from a Genre instance which contains only active movies and reviews? Thank you for your time! -
Django Media assets in Forms, how to defer/async JS assets
The official docs explain how to automatically adds assets for certain widgets., from thier example: from django import forms class CalendarWidget(forms.TextInput): class Media: css = { 'all': ('pretty.css',) } js = ('animations.js', 'actions.js') What it does not describe is how to make JS assets deferred or async loaded, e.g. <script defer src="https://myserver.com/static/animations.js">/script> -
Docker, Django, Gunicorn, Nginx, and a 502 bad gateway error
I am relatively new to Docker and have ran into an problem that I cant seem to find a solution for. I have two Docker stacks that are running Nginx and Django however, one of the stack is reachable via web browser and the other times out with a bad gateway error. Both stacks are running on the same server but on different ports the stack that runs on port 8000 is reachable the stack that runs on 8010 throws the 502 error. I have verified that the ports are open on the host and that I am able to ping from the Nginx container to the Django container. I have also spun up each stack separately which ended with the same results. I am running out of ideas so, any insight would be appreciated. Server: VM - Red Hat Enterprise Linux Server release 7.9 (Maipo) Docker version 20.10.3, build 48d30b5 Working Docker-compose file version: '3.3' services: web: build: context: ./ dockerfile: Dockerfile command: sh -c "python manage.py makemigrations && python manage.py migrate && gunicorn laitteiden_saatavuus.wsgi:application -w 3 --bind 0.0.0.0:8000" volumes: - static_volume:/home/app/web/static expose: - 8000 - 1433 env_file: - ./laitteiden_saatavuus/.env networks: - database - nginx_network depends_on: - db db: … -
Django multiple image upload but displayed where I tag them
So I can upload Images but I have a problem in which I am putting all my HTML into the TextArea and uploading my images above but I want to display the images where I want on my post instead of some pre-formatted template. So I want my pages to be unique in the layout. Meaning I will want images I upload to be displayed at random point. I'm aware I could hardcode in links but I would rather have Django do it for me. Is there a way in which I can get tags or IDs for the images I upload so I can upload them where I want in the HTML I input into the TextArea -
Django admin shows all the records in the table in a many to many relationship, instead of related fields
So in this project there organizations. Each user can be a manager in multiple organizations. Each user can also be a member of multiple organizations. When I go to the "user page" in django admin (e.g. I click to users and than click to that user), I expect to see a list of organizations that user is a manager, and another list of organizations that user is a member. Instead, for any user, I see a list of ALL the organizations in both the managership and membership list, as in the image below. E.g. the list is not filtered by their user id. What I am doing wrong? How can I fix this? Thanks. My UserAdmin is like: @admin.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = ( ... (_("Managerships"), {"fields": ("managerships", )}), (_("Memberships"), {"fields": ("memberships", )}), ) list_display = ["username", "name", "is_superuser"] search_fields = ["name"] My user model is like this: class User(AbstractUser): ... managerships = models.ManyToManyField(Organization, related_name='managerships',blank=True) memberships = models.ManyToManyField(Organization, related_name='memberships',blank=True) ... And Organization model is like: class Organization(models.Model): name = models.CharField(max_length=200) ... -
Django Selenium functional testing with celery in docker
BACKGROUND: I have a Django application and i want to write tests for it. I have written a docker-compose.yml file so that i can be deployed on server quickly and easily. The application works with the help of celery and redis as its broker. The entire process of selenium testing is also being done via docker where i deploy selenium hub and nodes of chrome and firefox. PROBLEM: When i run the python manage.py test app_name.tests.test_forms my fixtures are loaded and selenium connection is successful, class of the test inherits from StaticLiveServerTestCase. But when i call a celery task from the app_name.tasks.task_name.delay(), obviously after importing it, I noticed that the tasks runs on the my celery worker container that is for the production app and makes the changes that the task is supposed to do in the test database, it does it in the production database. I have tried multiple possible solutions, like adding this above the test class @override_settings(CELERY_TASK_EAGER_PROPAGATES=True,CELERY_TASK_ALWAYS_EAGER=True,BROKER_BACKEND='memory') also tried to starting celery_worker in the test's thread using the following in the setUpClass: cls.celery_worker = start_worker(app,perform_ping_check=False) cls.celery_worker.__enter__() and in tearDownCass: cls.celery_worker.__exit__(None, None, None) and get this following error: ERROR/MainProcess] pidbox command error: AttributeError("'NoneType' object has no attribute 'groups'") … -
To calculate the date in Django
I would like to know how to calculate and print the date in Django. Attached below is model.py. I need to calculate and print out how many days are left based on the date_date of the registered product table. I'd appreciate it if you could tell me how. class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() -
Django export excel file without saving it
Currently I am exporting an excel file, however, before it gets exported, I create an xls file on the host machine. To create the excel file, I use tablib. My export view looks like this: @login_required def export_xls(request): # some irrelevant code data = convert_json_to_dataset(json_data) table = data.export('xls') with open('/tmp/students.xls', 'wb') as f: f.write(table) response = FileResponse(open('/tmp/students.xls', 'rb'), as_attachment=True, filename="test.xls") return response What I am trying to achieve is to avoid writing always to /tmp/students.xls. I tried using BytesIO, however that did not work out. @login_required def export_xls(request): # some irrelevant code data = convert_json_to_dataset(json_data) table = data.export('xls') buffer = BytesIO() buffer.write(table) response = FileResponse(buffer.read(), as_attachment=True, filename="test.xls") return response Currently I am always overwriting the file, however, I will change the naming of the file and that will cause multiple files to be created, which I would like to avoid. -
Create a ChoiceFilter with all the unique values in a specific field (Django)
Say I have a car-model #models.py class Car(models.Model): brand = models.CharField(max_lenght=16) and a user have added the following cars: ["kia","ford","kia","bmw","audi","audi"] I would like to create a filter such that the user has a drop-down (or sort of) with the given brands i.e [kia,for,bmw,audi] to be chosen as a filter. I have tried using the ModelChoiceFilter but that seems to require, a ChoiceField in the model, where the choices are specified, but that is not the case here, since the user is free to write what-ever brand they like. -
Why is my django group showing an empty Queryset
I have this project and I want to be able to allow only members in a particular group to view it. But the problem is that in my admin panel, there are two groups there but when I run request.user.groups.all() I get an empty list? I'm using django 3.2 -
Improper Deep Copy of Model Instance still affecting the Original Instance
I have two models, Movie and Review. Review has a foreign key field related to Movie. I have been trying to make a deep copy of a Movie instance so I can edit the Review objects associated with that instance without those edits affecting the original and being saved to the database. models.py class Movie(models.Model): title = models.CharField(max_length=160) class Review(models.Model): movie = models.ForeignKey(Movie, null=True, on_delete=models.CASCADE, related_name='reviews') author = models.CharField(max_length=150) active = models.BooleanField(default=True) views.py # Create and save movie object movie = Movie(title="Nightcrawler") movie.save() # Create and save two review objects review1 = Review(movie=movie, author="John", active=True) review2 = Review(movie=movie, author="Rob", active=False) review1.save() review2.save() # Create deep copy of movie instance movie_copy = copy.deepcopy(movie) print("Original before change: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.") inactive_reviews = movie_copy.reviews.filter(active=True) print("There are " + str(len(inactive_reviews)) + " inactive reviews.") # Remove inactive reviews from deep copy movie_copy.reviews.remove(*inactive_reviews) print("Deep copy after change: has " + str(len(movie_copy.reviews.all())) + " reviews.") # Check if original movie instance was altered print("Original after change has " + str(len(movie.reviews.all())) + " reviews.") print("Author of the first review is: " + str(movie.reviews.first().author)) The output of the views.py code is as follows: Original before change has 2 reviews. … -
django app listening on localhost:8000 vs 0.0.0.0:8000
I have a Django app running on Google Kubernetes Engine.If I run the enter the pod , and run netstat -l command. It shows that the service is listening on localhost:8000 I ran the same service on Elastic Kubernetes service on AWS. There the service didn't respond to the outside requests when the container was listening on localhost:8000. I had to run python manage.py runserver 0.0.0.0:8000, so that container listens on all the network interfaces. On AWS , the output of netstat -l looks like this I want to understand, that Why the same app was running on the google Kubernetes engine, but not on EKS, and I had to specifically define to listen on 0.0.0.0:8000. Why the google Kubernetes engine listens to outside traffic , when the netstat -l shows that it is listening on localhost:8000 -
Getting error on terminating Django server using Threading and Schedule
I'm trying to use Schedule on the background using threads in my Django application as it was described in Oz123's answer, everything works fine without any problem, except when I'm trying to use commands from the terminal (e.g. python manage.py makemigrations or python manage.py runserver ) they will not end and finished until I'm sending keyboardInterupt. Then it will give me the following error: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 1388, in _shutdown lock.acquire() p.s.: for python manage.py runserver I have to send KeyboardInterupt two times. one for ending the server, then the second one will end the function and raise the mentioned error. My application is using one schedule in the background which is happening every hour to check a model for specific changes. So, there is no stop to this schedule and I want to run it until the server is running (forever). Is there any way to solve this problem? It is so much annoying to press KeyboardInterupt (CTRL + C) for ending every command. -
Change a future date every five days
I am working on a point of sale app in Django in which the customer books a product and it is delivered in 45 days. I can get the delivery date while booking using the following: from datetime import datetime, timedelta DELIVERY_IN_DAYS = 45 delivery_on = datetime.today() + timedelta(days=DELIVERY_IN_DAYS) delivery_on = delivery_on.strftime('%Y-%m-%d') now I want the delivery_on to remain same for 5 days and change on the 6th day. can I do it without using a background celery job? Thanks in advance. -
What's wrong with {% if join_detail.designated_code == element.designated_code %}?
I am a student learning Django. I want to display value_code as follows, but there is a problem that it does not appear. I don't know where the heck is the problem. To represent value_code, designated_code.designated_code is expressed in this way, but all information in the model is not output or output. I want to print only the value corresponding to the if statement. It would be really appreciated if you could tell us what the problem is and how to solve it. Model.py from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse # 회원 class Member(AbstractUser): username = models.CharField(primary_key=True, max_length=20, verbose_name='아이디') name = models.CharField(max_length=20, verbose_name='이름', default='') password = models.CharField(max_length=64, verbose_name='비밀번호') phone = models.CharField(max_length=64, verbose_name='전화번호') def __str__(self): return self.username class Meta: verbose_name = ('Member') verbose_name_plural = ('Members') # 카테고리 class Category(models.Model): category_code = models.AutoField(primary_key=True) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, allow_unicode=True) class Meta: ordering =['category_code'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_in_category', args=[self.slug]) # 상품 class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() … -
Django autocomplete light only works in the admin section
I'm trying to insert the autocomplete in the select to speed up the request. The problem is that it only works in the admin section. Autocomplete in admin section In the user's view, however, it doesn't work at all. Autocomplete not working in user view -
How to integrate Sales force and Django?
I have to complete a task as bellow:- I have to implement salesforce integration. Which include fetching user token from salesforce using OAuth2. Once you have the token I need to fetch the list of Users, Accounts, and Contacts from salesforce and store it in the database. I need to write the code in Django and not supposed to use any existing third-party salesforce integration app? Please suggest me resourses or algorithm to achieve the solution.. Thanks in advance. Hope to here from you soon.. -
How to collect multiple payment from customer and calculate with remaining balance in Django?
info I am trying to create a monthly installment app using Django. I don't know how I could calculate Property' price with amount. I want to calculate the property price with the Payment amount and get the remaining price and save it to database. Customer has multiple payments so every month i get new payment from single customer and compare with remaining amount and get new remaining amount. i don't know how can i do that? models.py class Property(models.Model): area = models.CharField(max_length=255) price = models.IntegerField(default=0) class Customer(models.Model): name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) remaining = models.IntegerField(default=0) def save(self, *args, **kwargs): self.remaining = self.prop_select.price super().save(*args, **kwargs) class Payment(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True, related_name='payment') amount = models.IntegerField(default=0) def save(self, *args, **kwargs): self.customer.remaining - self.amount super().save(*args, **kwargs) self.customer.save() -
How to connect my REST API to another API
I have a REST API written in django-rest-framework. I want to connect it to another REST API that has a database set up with postgresql. My API extends the base User model and provides some additional features. I do not want to create new tables for users, but just use the existing users in the second API. Do you have any suggestion how to do so? -
geting eror while addong mysql table to html form in django ProgrammingError (1146, "Table 'insert.insertemp_empinsert' doesn't exist")
This is django code in views.py so when I run this I get programing error and my database is MySql from django.shortcuts import render from Insertemp.models import EmpInsert from django.contrib import messages from django.http import HttpResponse def Insertrecord(request): if request.method=='POST': if request.POST.get('productname')and request.POST.get('f1')and request.POST.get('f2')and request.POST.get('f3')and request.POST.get('f4')and request.POST.get('f5'): saverecord=EmpInsert() saverecord.productname=request.POST.get('productname') saverecord.f1=request.POST.get('f1') saverecord.f2=request.POST.get('f2') saverecord.f3=request.POST.get('f3') saverecord.f4=request.POST.get('f4') saverecord.f5=request.POST.get('f5') saverecord.save() messages.success(request,'Record Saved Successfully...!') return render(request,'Index.html') else: return render (request,'Index.html') -
Loading images from an AWS bucket media folder to a HTML pdf template
I am trying to generate a PDF file out of a post created by a user, and include an image, which I want to store in an AWS bucket. This is how it was working with my own file system My function to generate a pdf in views.py: def form_render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') form = get_object_or_404(Post, pk=pk) template_path = 'form/pdf2.html' context = { 'form': form } # Create a Django response object, and specify content_type as pdf response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="report.pdf"' # find the template and render it. template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response And rendering the image in the html template <div> <img src="{{form.image.path}}"> </div> Now after uploading the files in a bucket it doesn't seem to work. The image is being stored there after uploading the post, but when creating the PDF the image is not displayed.(And it gives me an error: This backend doesn't support absolute paths). I tried to change the image source in the HTML template but it still didn't work. -
Pass Django Form to js
I am new to django and I want to write an easy Django application with Django 2.3 and Python 3.7. I am using in my view.py (if more of my code is needed, I can provide it): context["form"] = MyForm(request.POST, request.FILES) return render(request, "myhtml.html", context) My forms.py also looks very simple: class MyForm(forms.Form): name = forms.CharField() address = forms.CharField() I want to build in my application a button in which the form appears, but I do not want to hide the form by display: none; Is it possible to give the form over in a format that I can use JavaScript to build the form or do I always need to build the form in HTML and manipulate it afterwards with JS? Is it reasonable to return the Form as JSON.Response or does Django always return the Forms as HTML strings and not JS elements? -
How do i display django class based view api on bootstrap template?
I am working on a photography website and i have created a rest api for blog but i am facing trouble how to display the api on template. My project structure enter image description here This is my view.py of Blog from rest_framework.response import Response from rest_framework import permissions from rest_framework.views import APIView from rest_framework.generics import ListAPIView, RetrieveAPIView from blog.models import BlogPost from blog.serializers import BlogPostSerializer from rest_framework.renderers import TemplateHTMLRenderer class BlogPostListView(ListAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostDetailView(RetrieveAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostFeaturedView(ListAPIView): queryset = BlogPost.objects.all().filter(featured=True) serializer_class = BlogPostSerializer lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostCategoryView(APIView): serializer_class = BlogPostSerializer permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category = data['category'] queryset = BlogPost.objects.order_by('-date_created').filter(category__iexact=category) serializer = BlogPostSerializer(queryset, many=True) return Response(serializer.data) This is urls.py of Blog from django.urls import path from .views import BlogPostListView, BlogPostDetailView, BlogPostFeaturedView, BlogPostCategoryView urlpatterns = [ path('', BlogPostListView.as_view(), name='bl'), path('featured', BlogPostFeaturedView.as_view()), path('category', BlogPostCategoryView.as_view()), path('<slug>', BlogPostDetailView.as_view()), ] This urls.py of application from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from portfolio import urls, views from blog import urls from django.conf … -
How to use bootstrap with django-ckeditor?
I just want to add the bootstrap class form-control to my ckeditor form. Thank you in advance. -
RuntimeError at URL , while reloading with action attribute
I am a Django beginner, trying to build a website I am trying to redirect user to the the same page after submitting a form using action attribute but its giving me an error these are the project files Project urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', admin.site.urls), path('',include('firmpage.urls')) ] App urls.py from django.contrib import admin from django.urls import path,include from firmpage import views admin.site.site_title = "Dashoard" admin.site.site_header = "Admin Panel" admin.site.index_title = "Database manager" urlpatterns = [ path('/',views.home,name='home'), path('',views.home,name='home'), path('home/',views.home,name='home'), path('about/',views.about,name='about'), path('services/',views.services,name='services'), path('contact/',views.contact,name='contact') ] App views.py from django.shortcuts import render,HttpResponse from firmpage import models def home(request): return render(request,'index.html') def contact(request): if request.method == 'POST': print(request.POST) name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] description = request.POST['desc'] print(name,email,phone,description) contactObject = models.contact(name=name,email=email,phone=phone,desc=description) contactObject.save() print("data written succesful") return render(request,'contact.html') def services(request): return render(request,'services.html') def about(request): return render(request,'about.html') contact.html {% extends "base.html" %} {% block title %}Contact{% endblock title %} {% block contactactive %}active{% endblock contactactive %} {% block body %} <script> function myFunction() { alert("Submitted successfully."); } </script> <div class="container my-3"> <h1 class="text-center">Contact Me</h1> <form action="/contact" method="post"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="name" class="form-control" id="name" name="name" placeholder="Your Name"> </div> <div …