Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker-compose with django and postgresql could not translate host name "db" to address: Name or service not known
I built a system using docker compose with 2 container, one for django and the other one for my database postgresql. I have this error django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution when I am trying the create a django superuser My docker-compose.yml : version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres networks: - mynetwork web: build: . command: bash -c "sleep 10 && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - DB_HOST=db # Définir DB_HOST pour correspondre au nom du service db dans docker-compose.yml depends_on: - db networks: - mynetwork networks: mynetwork: driver: bridge My Dockerfile : # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ In the seeting.py file of my project : import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'dbdo', 'PORT': 5432, #default port you don't need to mention in docker-compose } } The containeurs seem to work correctly, I can see my django app page and navigate. But … -
How to create a button to add items to cart?
This is the page I have created This is the views.py file: from django.shortcuts import render from django.http import HttpResponse from .models import Pizza # Create your views here. def index(request): pizzas = Pizza.objects.all().order_by('price') context = { 'pizzas': pizzas } return render(request, 'menu/index.html', context) And this is the index.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Pizzas</title> <link rel="stylesheet" href="{% static 'menu/style.css' %}"> </head> <body> <a href="{% url 'main:index' %}"><img id='logo' src="{% static 'menu/images/small_logo.png' %}"></a> <h1>Our Pizzas</h1> <ul> {% for pizza in pizzas %} <table> <tr> <td id="one" ><b>{{pizza.name}}</b></td><td id="two">{{pizza.price | floatformat:2}}$</td> </tr> </table> <li id="ing">{{pizza.ingredients}}</li> {% if pizza.vegetarian %} <li style="background-color:#DD7835; padding:3px; width:90px; font-size:13px; text-align:center; border-radius:10px; font-weight:bold; " >VEGETARIAN</li> {% endif %} {% endfor %} </ul> </body> </html> How can I add buttons on my page where the user can add the pizzas to cart and the data is stored in the /admin page? this is my admin.py: from django.contrib import admin from .models import Pizza class PizzaAdmin(admin.ModelAdmin): list_display = ('name','ingredients','vegetarian','price') search_fields = ['name'] admin.site.register(Pizza, PizzaAdmin) # Register your models here. At the backend, the quantity of pizzas that the customer has ordered should be visible. -
How do I use HTMX with Django class based views?
I'm fairly new to htmx and django. I can implement htmx through function-based views OK, as I just call the function and return a partial.html file into the page. Howeverm I don't understand how to make it work with class-based views I'm now using in Django. I'd like to load comments on a blog post when a user clicks the Load comments button. My thought is that I'd need to use htmx to do a swap or insertion into a point on my page where I want the comments loaded. Here is my DetailView where I load the detail of an individual post. class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get(self, request, **kwargs): print("method is being called") return render(request, "partial.html") Here is my partial.html file that I'd like to be loaded into the page once the button on my post_detail.html page is clicked: <h2 class="mt-2 mb-2">Comments:</h2> {% if post.comments.all %} {% for comment in post.comments.all %} <div class="relative grid grid-cols-1 gap-4 p-4 mb-8 border rounded-lg bg-white shadow-lg"> <div class="relative flex gap-4"> <div class="flex flex-col w-full"> <div class="flex flex-row justify-between"> <p class="relative text-xl whitespace-nowrap truncate overflow-hidden">{{ comment.commenter }}</p> <a class="text-gray-500 text-xl" href="#"><i class="fa-solid fa-trash"></i></a> </div> <p class="text-gray-400 text-sm">{{ comment.date_added … -
Column Foreign key is of type bigint but expression is of type uuid in Django
I want to use UUIDField for primary key. This is my model: class Organization(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(max_length=124) All things is good. But when I want to use id of Organization model for ForeignKey in this model: class Member(models.Model): reference = models.ForeignKey('Organization', null=True, on_delete=models.PROTECT) name = models.CharField(max_length=124) I got this error: django.db.utils.ProgrammingError: column "reference" is of type bigint but expression is of type uuid LINE 1: "reference" = 'af104709-... ^ HINT: You will need to rewrite or cast the expression. What can I do? -
Django starts with another view endpoint before finishing the process in the first view endpoint
What I'm trying to do is create a User object first and then another Team Leader object in which the user attribute is linked to the same User object created. However, what happens is the Create Team Leader is being called BEFORE the Create User is done processing. Here is the Team Leader Model: class TeamLeader(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) id = models.AutoField(primary_key=True) firstName = models.CharField(max_length=100,blank=True) lastName = models.CharField(max_length=100,blank=True) email = models.CharField(max_length=100,blank=True) username = models.CharField(max_length=100,blank=True) employeeRole = models.CharField(max_length=100,blank=True) bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blankprofile.png') location = models.CharField(max_length=100,blank=True) def __str__(self): return self.user.username I'm sending two post requests to my APIs using fetch in Javascript. Below is my code for the post requests. The first one creates the User object first, then the next one for the Team Leader object. let userUrl = homeUrl + 'api/createuser/' fetch(userUrl,{ method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({"username": username, "first_name": firstname, "last_name": lastname, "email": email, "password": password1, "employeeRole": employeeRole, "teamLeader": teamLeader, }), } ) if (employeeRole == 'Member') { var regisUrl = homeUrl + 'api/createMember/'; } else { var regisUrl = homeUrl + 'api/createTeamLeader/'; } fetch(regisUrl,{ method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({"username": username, "first_name": firstname, "last_name": lastname, "email": email, "password": password1, "employeeRole": employeeRole, "teamLeader": teamLeader, }), } … -
Django Error - Product Does Not Exist when clicking Buy button for first item in cart (If you have more than one product it works)
I'm a Django beginner working on a Django shopping website. When a user clicks the "Buy" button for a product, it should create an order and remove the product from the cart. However, I'm encountering an issue where I get a DoesNotExist error when trying to buy the first product that is added to the cart (If i add two products then it works). The error says "No Product matches the given query." and it is raised by the placeOrder view. This error only occurs for the first product that is added to the cart. If I add more products to the cart, I can buy them without any issues. I've checked the database and the product IDs are correct. I've also tried clearing the session and cache but it didn't resolve the issue. views.py from django.shortcuts import redirect, render, get_object_or_404 from django.contrib.auth import login, logout, authenticate from .forms import * from .models import Product, Cart from django.http import HttpResponse from django.urls import reverse # Create your views here. def home(request): products = Product.objects.all() context = { 'products': products } return render(request, 'website/home.html', context) # def placeOrder(request, i): # customer = Customer.objects.get(id=i) # form = createorderform(instance=customer) # if request.method == … -
django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name
I want to obtain the password_reset_done page when user has forgotten the password or username.On the login page there is a link written "forgot password or username", when a user clicks that link he will be directed to the password_reset page where an email address is entered.After the user has entered the email,he is supposed to be directed to the password_reset_done page but the above error pops out My urls.py file looks like this from django.contrib import admin from django.urls import path from app1.views import profile, welcome_view urlpatterns = [ path('accounts/', include(('django.contrib.auth.urls', 'auth'), namespace='accounts')), path('accounts/profile/', profile, name ='profile'), path('admin/', admin.site.urls), path('', views.welcome_view, name ="welcome_view"), ] -
I am trying to deploy docker image in to Aws lightsail Container
The problem is related to the Invalid HTTP_HOST header error in Django application. This error occurs when the HTTP_HOST header of an incoming request does not match any of the values specified in the ALLOWED_HOSTS setting in Django application. the error message indicates that the HTTP_HOST header received was '172.26.43.151:8000', and it suggests adding '172.26.43.151' to the ALLOWED_HOSTS list. To address the issue, I made the following changes: In my Django settings file (settings.py), i modified the ALLOWED_HOSTS setting to ALLOWED_HOSTS = ['*'], allowing any host to access your application. This change was made to accommodate the dynamic IP address of the Lightsail container. i updated the Nginx configuration file (default.conf) to listen on port 80 and forward requests to the Django application running on port 8000. i built the Docker image based on the provided Dockerfile, which sets up the necessary dependencies, installs the required packages, and configures Gunicorn as the application server. In Docker Compose configuration file (docker-compose.yml), i specified the port mapping as "80:8000", which maps port 80 of the host machine to port 8000 of the Docker container, allowing incoming requests to reach the Django application. Despite these changes, i still encountered the Invalid HTTP_HOST header … -
Django + Vue.js app: CORS blocks requests from getting to the backend
I am trying to deploy a Django + Vue.js app to an EC2 instance, after confirming that everything works correctly when running locally. Inside my Vue.js components, I have requests that look like this (using axios): const response = await this.$http.get('http://localhost:8000/api/foo'); However, firefox shows the following error in the console: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/api/foo/. (Reason: CORS request did not succeed). Status code: (null). When looking at the Django logs, there is no log of ever getting a GET request, so I believe that the request is being blocked before ever getting to the backend. I am sure that the django backend is listening on port 8000, since I can use wget inside the EC2 instance and get correct results back. The Django backend is configured to allow all CORS origins, I think having the whitelist is overkill but I'm trying to make sure that's not the issue: INSTALLED_APPS = [ ... 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] ALLOWED_HOSTS = ['*'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_HEADERS = "*" CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', 'http://127.0.0.1:8000' ] Since the request is not getting to the backend, I figured that maybe nginx is responsible … -
Not able to highlight my subject_id getting in my request for Django project
When the user clicks on a subject_id on one page, it redirects to a another page and on that page the subject_id in the request url, should be highlighted to the user, but somehow I am not able to see it. Open to suggestions, Added this in my javascript function, is this the right way to do it? if (data.name == {{subject_id|safe}}) { $('#dtBasicExample').DataTable().row(i).addClass('highlight-green'); } -
Control the Error from Meta class in Django model
I'm working with Blog website with Django, I have a model called Post and its like this: class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) txt = models.TextField() created_at = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f"{self.user} {self.title}" class Meta: ordering = ['-created_at'] unique_together = ['title', 'txt'] and so when a user try to create more than one Post with the same title and text it must launch an Error, but I don't know how to control this error and turn it into a proper Error and code will launch the Constraint_failed error and I wanna control this kind of Errors not just in the Admin panel but in the User client side that User can see his mistakes and fix it. can anyone give a tip or solution. thanks. -
Replace image in static folder Django 1.5
I uploaded an image, which saved in the database correctly and I'm able to view it using an tag. Now I wanted to replace the image. I went to the static folder where the image is stored and deleted the old one, then replace it with the new one ( with same name and extension). The problem is when I refreshed my page, it still shows me previous image. What am I not doing correctly pls. I have restarted my machine. Restarted my apache server. But it still shows old image -
django pagination returns nothing
i'm not sure what went wrong here. spent hours trying to figure out. when run the program i can see list of objects displayed but none of pagination.html information is displayed. views.py def post_list(request): post_list = Post.objects.all() p = Paginator(post_list, 2) page_num = request.GET.get('page',1) posts = p.page(page_num) return render(request, 'blog/post/list.html', {"posts":posts}) list.html {% extends "blog/base.html" %} <!DOCTYPE html> <html> <head> {% block title %} My Post{% endblock %} </head> <body> {% block content %} {% for post in posts %} <ol> {{post.title}} by {{post.author}} published= {{post.status}} slug==> {{post.slug}} <span><a href="{{ post.get_absolute_url }}">details</a></span> </ol> {% endfor %} {% include "directory/pagination.html" with pages=posts %} {% endblock %} </body> </html> pagination.html <div class="pagination"> <span class="step-links"> {% if pages.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ pages.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ pages.number }} of {{ pages.paginator.num_pages }}. </span> {% if pages.has_next %} <a href="?page={{ pages.next_page_number }}">next</a> <a href="?page={{ pages.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> -
Render(Deploy) ERROR: Ignored the following versions that require a different python version
I'm trying to deploy an Api using Render but i get this error ERROR: Ignored the following versions that require a different python version: 1.21.2 Requires-Python >=3.7,<3.11; 1.21.3 Requires-Python >=3.7,<3.11; 1.21.4 Requires-Python >=3.7,<3.11; 1.21.5 Requires-Python >=3.7,<3.11; 1.21.6 Requires-Python >=3.7,<3.11 ERROR: Could not find a version that satisfies the requirement pywin32==306 (from versions: none) ERROR: No matching distribution found for pywin32==306 [notice] A new release of pip available: 22.3.1 -> 23.1.2 [notice] To update, run: pip install --upgrade pip ==> Build failed the version of python i'm using is 3.11.2 and i already updated pip so i have the 23.1.2 version I'm new with this so it's my first time trying to deploy, it woude be really helpful if someone can explain what's going on and how i can solve it -
best way to compress uploaded photos and videos with python and django to reduce storage
Hoping I can get some suggestions here, thanks for the help. I am building a django python based web app where users will be able to upload photos and videos that they would take with their mobile phone. At this stage I would be limiting each user to 10 photos or videos, but we have high user volumes so the main concern here is storage space consumption. What are some recommended compression packages that could be used to store the photos and videos? Thanks for any recommendations. I had a look at tinypng which would be fine for images but I dont think it processes videos. I also expect that the file formats for the images and videos could be a range of formats, there is no specific format that I need to store the media files as. -
Can registered users create more users in a django app?
I'm trying to create an app in which a user (not admin) can add more users? Let me explain a little bit... If I log in the app as a user I would like to add clients without the intervention of the clients. Also such clients should be able to log in the app and see the information that I placed in their behalf, for instance their orders. I thought that maybe they can log with their email and drivers license number as password or something like that, information that would be provided at the time of me adding them (a client) to the system -
Generic Django template to display multiple tables
Is there a way to create a generic html table in Django. I want to reuse the same form.html to display entities with different columns. For example in the below code a pass a list of headers, and dynamically create the thead,but I need for each row in the body to get every value. So I need to iterate. Or is there any other approach to reuse templates in a mo generic way instead of build N templates for each table yuo need to display <table class="table table-bordered" id="vendor_table" style="text-align: center;"> <thead class="tables-success"> <tr> {% for header in list_headers %} <th>{{ header }}</th> {% endfor %} </tr> </thead> {% for row in list_values %} <tr> {% for header_name in list_headers %} <th> {{ row.{{ header_name }} }} </th> <--------- {% endfor %} </tr> {% endfor %} </table> -
Images in list in form Django, How?
Dear masters! Please help me with this question. models.py class New_tables(models.Model): TYPEBET_CHOICES = ( ('1','up'), ('0', 'down'), ) type_bet = models.IntegerField(choices=TYPEBET_CHOICES) form.py type_bet = forms.TypedChoiceField(choices=New_tables.TYPEBET_CHOICES) how to make sure that when you select from the list, there are not “up” and “down”, but that instead of them a picture is displayed, preloaded in /media/ ? I didn't find any information on the Internet. -
Can Django ORM calculate market share of specific brands over multiple time periods in a single query?
I have the following Django model: class MarketData(models.Model): category = models.CharField(max_length=64, null=True) brand = models.CharField(max_length=128, null=True) time_period = models.DateField() sales = models.IntegerField(default=0, null=True) I am trying to use Django's ORM to calculate the market share of each brand within each time period of my dataset to output to a line chart. The market share calculation itself is simple: the sales of each brand within the time period divided by the total sales in each time period. I can use Django's ORM to generate a queryset of brands and sales by time period, but I'm struggling to annotate the additional metric of sales for all brands. My current query: sales = MarketData.objects.filter(brand__in=['Brand 1', 'Brand 2']) \ .values('time_period', 'brand') \ .annotate(sales=Sum('sales')) \ .order_by('period', '-sales') My current queryset output: <QuerySet [{'time_period': datetime.date(2020, 6, 30), 'brand': "Brand 1", 'sales': 21734}, {'time_period': datetime.date(2020, 6, 30), 'brand': 'Brand 2', 'sales': 93622}]> How can I add another annotation that includes the sales of ALL brands for that time period, not just the brands specified in the filter, and not just the current brand? I have tried to use a Subquery to get the total market sales by period, but I end up with an aggregate across all … -
Django.auth.authenticate not authenticating user
I am creating an app, and I am trying to manually create the login page so I can add some things that I can't add using the default Django authentication pages. This is what my view looks like: def logIn(request): formClass = LogInForm template = "login.html" if request.method == "POST": auth.authenticate(username=request.POST["username"], password=request.POST["password"]) return redirect("/") return render(request, template, { "form" : formClass }) But, when I print out the user's id after logging in, it returns none. Does somebody know what is going on? -
Why isn't session value persisting with Django Rest Framework (DRF)?
thank you for your time and attention to this query. I am trying to set (key, value) into the request session from one drf function and accessing that (key, value) via the request session in another drf function. Please see the code below for the current implmentation: class FunctionOne(GenericAPIView): permission_classes = (permissions.AllowAny,) authentication_classes = [] def get(self, request, *args, **kwargs): request.session["kcc"] = request.GET.get("code") request.session.modified = True print("kcc", request.session.get("kcc", None)) return redirect("http://localhost:3000/checkout") class FunctionTwo(GenericAPIView): permission_classes = (permissions.AllowAny,) authentication_classes = [] def get(self, request, *args, **kwargs): print(dir(request.session)) code = request.session.get("kcc") if code: return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_404_NOT_FOUND) It is successfully setting the (key, value) into the session in function one and can be seen via the print statement. However when accessing the function two view the (key, value) saved in the session can't be found. I've checked the settings.py "django.contrib.sessions.middleware.SessionMiddleware" is included in the middleware and also these are the current rest_framework settings: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "backend.authentication.FirebaseAuthentication", ], "DEFAULT_RENDERER_CLASSES": [ "rest_framework.renderers.JSONRenderer", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], } Additionally, I am not using the default Sqlite database that is shipped with Django, I have a postgresql database hooked up to the project instead. I would greatly appreciate if pointed in the … -
how to use ckeditor for two fields in django crispy form?
First of all, I have installed CKeditor, not django-ckeditor. I am trying to display two ckeditor for two fields in same model and form. I have customize widget created. Here is my custom widget class CKClassicEditorWidget(forms.Textarea): """CKEditor Classic Editor widget. Custom widget for Django forms, integrating CKEditor Classic Editor as a rich text editor. """ template_name = "widgets/ckeditor.html" and here is the html file. {% load static %} {% with id=widget.attrs.id required=widget.attrs.required %} <script defer src="{% static 'js/ckeditor/ckeditor.js' %}"></script> <style> .ck-editor__editable { min-height: 200px; } </style> <textarea name="{{ widget.name }}" {% for key, value in widget.attrs.items %}{% if key != 'required' %}{{ key }}="{{ value }}"{% endif %}{% if not forloop.last %} {% endif %}{% endfor %}>{{ widget.value|default:'' }}</textarea> <script> document.addEventListener('DOMContentLoaded', function() { ClassicEditor .create(document.querySelector('#{{ id }}'), { toolbar: { language: 'en', items: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'outdent', 'indent', '|', 'blockQuote', 'insertTable', 'undo', 'redo', '|', 'sourceEditing', 'selectAll' ] }, table: { contentToolbar: [ 'tableColumn', 'tableRow', 'mergeTableCells', 'tableCellProperties', 'tableProperties' ] } }) .then(editor => { document.querySelector('#{{ id }}').ckeditorInstance = editor; if ('{{ required }}' === 'True') { const form = document.querySelector('#{{ id }}').closest('form'); form.addEventListener('submit', function(event) { const editorData = editor.getData(); if (editorData.trim() === '') { alert('Content … -
The issue you are facing is related to the usage of the {% block body %} tag in your child template
i am facing issue dont know what to do please help me with that i cant add any html code to my body i want to add html code to my body tag TemplateSyntaxError at / Invalid block tag on line 6: 'endblock'. Did you forget to register or load this tag? Request Method:GETRequest URL:http://127.0.0.1:8000/Django Version:4.2.3Exception Type:TemplateSyntaxErrorException Value:Invalid block tag on line 6: 'endblock'. Did you forget to register or load this tag?Exception Location:C:\Users\91939\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\template\base.py, line 568, in invalid_block_tagRaised during:products.views.indexPython Executable:C:\Users\91939\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\python.exePython Version:3.11.4Python Path:['C:\\shops\\newshops', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\\python311.zip', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\\DLLs', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\\Lib', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0', 'C:\\Users\\91939\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python311\\site-packages', 'C:\\Program ' 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\\Lib\\site-packages']Server time:Fri, 07 Jul 2023 19:43:13 +0000 Error during template rendering In template C:\shops\newshops\products\templates\products\home.html, error at line 6 Invalid block tag on line 6: 'endblock'. Did you forget to register or load this tag? 1{% extends 'base.html' %} {% block title %}hello hi{% endblock %}{% block body2%}34<h1>hello</h1>5<h2>hi</h2>6{% endblock %}7 so can yo please provide me detail explanrtion of this question -
Pass multiple arguments from Django template for loops into Django template filter or tag
I'm building a timetable application and I need to check if there is a certian room available so I want to create a function/template tag/template filter to return me a boolean value which I want to later on pass into Django template if statement. View function: def my_view(request): args = { 'days': Days.objects.all(), 'times': Times.objects.all(), 'rooms': Rooms.objects.all(), } return render(request, 'my_page', args) Template stucture example that I need: {% for day in days %} {% for time in times %} {% for room in rooms %} {% if MY_TAG {{ day }} {{ time }} KWARG={{ room }} %} <p>SOMETHING IF TRUE</p> {% else %} <p>SOMETHING IF FALSE</p> {% endif %} {% endfor %} {% endfor %} I've looked on the official Django docs, SO and other sites and forums for these things. I've found a couple of promising code examples that didn't work but gave me the idea of structure concept for my function. Official Django docs 1 Official Django docs 2 Stack Overflow 1 Stack Overflow 2 The function that I have so far is working but I can't implement it in Django template. My function/template tag: from ..models import Timetables from django import template register = template.Library() … -
Least painful way of not using int4 as primary key in Django user models?
I'm new to Django, and upon running the first migration, it seems the primary key ID of the auth_users table is an int4. Looking through the docs, it seems if I use any kind of custom User model, for example to bigint or uuid, I am opening a can of worms and losing Django Admin functionality and possibly all sorts of auth scaffolding functionality? Is there a standard way of not using int4 that I'm failing to see, let's say using UUID, short of going full custom on the auth backend? Tried custom model extending django.contrib.auth.models.AbstractUser. Django Admin stops working, which seems expected according to documentation. However, auth scaffolding, such as python manage.py createsuperuser also starts throwing errors, such as django.db.utils.IntegrityError: null value in column "id" of relation "users_user" violates not-null constraint. This is when id is a Postgres UUID. Here's the User model: class User(AbstractUser): id = models.UUIDField(primary_key=True)