Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: is it possible to set DateInput widget limits for maximum and minimum dates?
my Date widget in forms.py looks like this: class DateInput(DateInput): input_type = 'date' class TaskCreateForm(ModelForm): class Meta: model = TaskModel fields = '__all__' exclude = ('task_project',) widgets = { 'task_baseline_start': DateInput(), 'task_baseline_finish': DateInput(), 'task_scheduled_start': DateInput(), 'task_scheduled_finish': DateInput(), 'task_real_start': DateInput(), 'task_real_finish': DateInput(), } The problem is whenever someone introduces a date too far into the future/past, some other parts of the application get all messed up (like graphs and other stuff). I've tried the following: class DateInput(DateInput): input_type = 'date' attrs = {'min': '2020-01-01'} But the widget keeps accepting dates before 2020-01-01. Am I missing something here? Thanks a lot! -
How to install a golang package in a docker file?
I'm new in docker and I want to setting-up a docker-compose for my django app. in the backend of my app, I have golang packages too and run that in djang with subprocess library. But, when I want to install a package using go install github.com/x/y@latest and then copy its binary to the project directory, it gives me the error: package github.com/x/y@latest: cannot use path@version syntax in GOPATH mode I searched a lot in the internet but didn't find a solution to solve my problem. Could you please tell me where I'm wrong?\ here is my Dockerfile: FROM python:3.8.11-bullseye # set work directory WORKDIR /usr/src/toolkit/ # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Install packages RUN apt-get update \ && apt-get -y install --no-install-recommends software-properties-common libpq5 python3-dev musl-dev git netcat-traditional golang openvpn freerdp2-x11 tigervnc-viewer apt-utils \ && rm -rf /var/lib/apt/lists/* RUN go install github.com/x/y@latest && cp pacakge /usr/src/toolkit/toolkit/scripts/webapp/ # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy entrypoint.sh COPY ./entrypoint.sh . RUN sed -i 's/\r$//g' /usr/src/toolkit/entrypoint.sh RUN chmod +x /usr/src/toolkit/entrypoint.sh # copy project COPY . . # run entrypoint.sh ENTRYPOINT ["/usr/src/toolkit/entrypoint.sh"] -
Django Queryset filtering based on each entry
Given the Django model below of a car traveling along a certain road with the start and end times: class Travel(models.Model): car = models.CharField() road = models.CharField() start = models.DateTimeField() end = models.DateTimeField() I want to identify the set of cars X that had been in the same road as the target car x for at least m minutes. How should I obtain the required set of cars X? My attempt: So let's say I use filtering to obtain the set of travels T that x had been in. T <-- Travel.objects.filter(car=x) I then brute force with: for t in T: possible_travels <-- filter Travel.objects with car=/=x, road=r.road, start < r.end, end > r.start confirmed_travels <-- further filter possible_travels with the overlapping region being at least m minutes long confirmed_cars <-- confirmed_travels.values('cars').distinct() However, the problem is that it may involve many DB hits by querying in a loop. Also, confirmed_cars gives a QuerySet object. So it seems I need to somehow append these QuerySet objects together. I saw other posts doing things like converting to list then appending and finally converting back to QuerySet but some people say it is not a good way, should I be doing something like … -
Creating a Django Model for a recipe #2
This is a follow-up question to Creating a Django Model for a recipe. I am able to select multiple ingredients for a single recipe, but my code only allows for one general quantity selection that associates with all ingredients selected. For example: (BLT recipe) I can select Bacon, Lettuce, and Tomato, but I am not able to have different quantities for each (i.e. Bacon(1), Lettuce(1), Tomato(2). class Recipe(models.Model): '''A recipe class to input new recipes''' recipe = models.CharField(max_length=50) ingredient = models.ManyToManyField(Ingredient) quantity = models.CharField(max_length=1) cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL) def __str__(self): return self.recipe class Ingredient(models.Model): '''All ingredients for any recipe or individual selection''' ingredient = models.CharField(max_length=50) department = models.ForeignKey(Department, null=True, on_delete=models.SET_NULL) def __str__(self): return self.ingredient -
Data isn't displayed in my ag-grid (vuejs) for some reason
I've been tasked to do some modifications on an old django + vuejs & ag-grid project. It is quite hard to do it, because the docs are a bit scarcer for the frameworks versions used for this project. (for example, django is 1.9, python is 2.7. We will migrate those later) I need some help understanding why my ag-grid (on vuejs) doesnt display anything. I've just started working on this project so I'm not sure if every function in here is needed (I took the code from another file). Please start reading columnDefs, gridOptions and the document.addEventListener (in those I added code) My table is blank: Here's the JS code which does the requests: const DOUBLE_KEY_INTERVAL = 400; const columnDefs = [ { field: 'Book number', pinned: 'left', }, // { field: 'Dossier', pinned: 'left', }, // { field: 'Dossier type', pinned: 'left', }, // { field: 'Date', pinned: 'left', }, // { field: 'Present to client', pinned: 'left', }, // { field: 'Client list', pinned: 'left', }, ] const gridOptions = { onSortChanged: saveState, onFilterChanged: saveState, onColumnVisible: saveState, onColumnPinned: saveState, onColumnResized: saveState, onColumnMoved: saveState, onColumnRowGroupChanged: saveState, onColumnValueChanged: saveState, onColumnPivotChanged: saveState, onColumnGroupOpened: saveState, onNewColumnsLoaded: saveState, onGridColumnsChanged: saveState, onDisplayedColumnsChanged: saveState, onVirtualColumnsChanged: … -
How to change django model.py PhoneNumberField format?
I would like to change the django PhoneNumberField() to take the following format 0712345678 instead of +14151234567 models.py contact_number = PhoneNumberField() -
How to retrieve 1 table objects that is related to 2 ForeignKey?
I would like to show in my template in each cell the name ("nombre") of the client ("cliente") with his payment {{pago.cantidad_pagada}} , the problem is that as I am doing it {{presupuesto.cliente.nombre}}, I show all the names that I have in my table and they are repeated in each of the cells, I imagine that it is due to the use of "for", but I don't know of another way to display the data. presupuestos.html <tbody> {% for pago in pagos %} <tr> <td> {% for presupuesto in presupuestos %} {{presupuesto.cliente.nombre}} {% endfor %} </td> <td> {{pago.cantidad_pagada}} </td> </tr> {% endfor%} </tbody> pagos/models.py class Pagos(models.Model): numero_transaccion=models.IntegerField() estimate=models.ForeignKey(Presupuestos, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.numero_transaccion}' presupuestos/models.py class Presupuestos(models.Model): cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.cliente}' clientes/models.py class Clientes(models.Model): nombre = models.CharField(max_length=200, blank=True) def __str__(self): return f'{self.nombre}' views.py def presupuestosIndex(request): presupuestos = Presupuestos.objects.all() pagos=Pagos.objects.all() return render(request, "Presupuestos/presupuestos.html", {'presupuestos':presupuestos,'pagos':pagos}) -
cursor "_django_curs_1696_sync_2" does not exist
I accidentally deleted my migrations. I later makemigrations and migrate but when I access certain parts of the app that have ForeignKey references, I get cursor "_django_curs_1696_sync_2" does not exist. How on earth would I go about getting this corrected. This is happening in development and so I fear pushing to production because the same error will arise.? I tried looking at similar questions but couldn't get one to help solve my problem. -
How to access the profiles of a custom type of users in Django?
I'm a newbie to Django. In my project I have created a custom user (ArtHubUser) model with proxy types of users. I am trying to create a ListView that displays all the profiles (UserProfile) of the one type of users (type Artist). So far, my view looks like that: class DashboardArtistsView(views.ListView): model = Artist template_name = 'art/dashboard_artists.html' context_object_name = 'artists_objects' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) artists = Artist.objects.all() context['artists'] = artists return context However, this only gives me access to the info stored in the custom user database, and not to the fields belonging to the user's profile. How do I define context so I can load info from the profiles of all the users belonging to the Artists user group in the template? -
Why in Django-rest-framework it gives authentication failed response
I have someViews like below: class SomeView(generics.ListAPIView): serializer_class = SomeSerializer permission_classes = [AllowAny] and in settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.FileUploadParser', 'rest_framework.parsers.FormParser', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning', } And When I request without any Authorization header it works fine. But When I add Bearer Authorization header it response "detail": "Given token not valid for any token type", "code": "token_not_valid", I gave permission_classes=[AllowAny]. Why? I thought there is no difference between sending or not sending tokens. Because I set permission_class=[AllowAny]. In ASP.NET there is no like this problems. In ASP.NET If I set AllowAny permission this endpoint open for everyone regardless of whether you send a Token or not. -
Dynamic Length Form handling and Data Collection in Django
I have a form in which the number of input fields keeps changing and depends on a parameter that I pass. This means that I can't go to forms.py and create a Form class because that requires me to define the input parameters beforehand. Here is how I am defining the form. <!-- Table to Display the original sentence and take the input of the translation --> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Original Sentence</th> <th scope="col">Translation</th> </tr> </thead> <form name="translated-text-form" class="form-control" action="" method="post"> {% csrf_token %} <tbody> {% for sentence in sentences %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ sentence.original_sentence }}</td> <td><input type="text" name="translated-{{sentence.id}}" value="{{ sentence.translated_sentence }}" /></td> </tr> {% endfor %} <tr> <td colspan="2"> <br> <p style="text-align: center;"> <input class="btn btn-secondary" type="submit" value="Save Translations"/> </p> </td> </tr> </tbody> </form> </table> This is the form output The user will add some text in the rightmost column and I want to save that text with a particular sentence.id in my Sentence model. This is what my model looks like class Sentence(models.Model): """ Model which holds the details of a sentence. A sentence is a part of a Wikipedia article which is tokenized. Fields: project_id: The ID of the … -
Django url reversing error - reverse with keyword arguments not found
The error I am getting This method is not working. It should be working without using reverse function. The URL pattern: urlpatterns = [ path('sectiondetails/<str:pk>/', views.getSectionEvents, name='sectionevents'), path('studentdetails/<str:pk>/', views.studentdetails, name='studentdetails'), path('studentpersonalevents/<str:pk>/', views.studentpersonalevents, name='studentevents') ] Html link: <li class="nav-item"> <a class="nav-link" href="{% url 'sectionevents' pk=section.id %}">Class Events</a></li> <li class="nav-item"> <a class="nav-link" href="{% url 'studentevents' pk=student.id %}">Personal Events</a></li> The error I get: Reverse for 'studentevents' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['studentpersonalevents/(?P[^/]+)/\Z'] -
Why in Django there is difference between json and formdata
I have someview like below def SomeView(request): someArrayData = request.data.getlist('something', None) And I am using Postman for testing my endpoints. When I send array with formdata request.data.getlist works. But when I send array with raw data type application/json getlist not works. Instead of getlist I must use request.data.get. But in ASP.NET there is no difference. I could send via formdata or application/json both works. -
Can I get some help, my css static file isn't loading as I expected?
I'm following a tutorial on building Django Ecommerce Website and apparently I might have messed up somewhere I cant quite figure out. The main.css file seems to be loading incorrectly. Please help. I had encountered it before but found a solution. Unfortunately it stopped loading main.css correctly This is the main.css body{ background-color: hsl(0, 0%, 98%); } h1,h2,h3,h4,h5,h6{ color:hsl(0, 0%, 30%); } .box-element{ box-shadow:hsl(0, 0%, 80%) 0 0 16px; background-color: #fff; border-radius: 4px; padding: 10px; } .thumbnail{ width: 100%; height: 200px; -webkit-box-shadow: -1px -3px 5px -2px rgba(214,214,214,1); -moz-box-shadow: -1px -3px 5px -2px rgba(214,214,214,1); box-shadow: -1px -3px 5px -2px rgba(214,214,214,1); } .product{ border-radius: 0 0 4px 4px; } .bg-dark{ background-color: #4f868c!important; } #cart-icon{ width:25px; display: inline-block; margin-left: 15px; } #cart-total{ display: block; text-align: center; color:#fff; background-color: red; width: 20px; height: 25px; border-radius: 50%; font-size: 14px; } .col-lg-4, .col-lg-6, .col-lg-8, .col-lg-12{ margin-top: 10px; } .btn{ border-radius: 0; } .row-image{ width: 100px; } .form-field{ width:250px; display: inline-block; padding: 5px; } .cart-row{ display: flex; align-items: flex-stretch; padding-bottom: 10px; margin-bottom: 10px; border-bottom: 1px solid #ececec; } .quantity{ display: inline-block; font-weight: 700; padding-right:10px; } .chg-quantity{ width: 12px; cursor: pointer; display: block; margin-top: 5px; transition:.1s; } .chg-quantity:hover{ opacity: .6; } .hidden{ display: none!important; } This is settings.py … -
starting Django project using cron
I have a Django project which I want to start every time the device reboots. I can start the Django application manually using the following 4 commands cd /home/pi/reg-sign source djenv/bin/activate cd /home/pi/reg-sign/mysite python manage.py runserver 192.168.4.1:8000 But I cannot get this working in a crontab line. So far I have; @reboot cd /home/pi/reg-sign && /home/pi/reg-sign/djenv/bin/python /home/pi/reg-sign/mysite/manage.py python runserver 192.168.4.1:8000 however this does not start the server. Any help would be much appreciated. Many thanks, -
How to fix CORS 405 on next/vercel frontend w django/heroku backend?
I've got a next app running on a Django backend hosted on Heroku. I recently converted it from pure React to Next, and deployed it on Vercel (earlier Firebase hosting).. I've tried everything I can think of but I can't resolve the CORS 405 I'm getting. I'm still don't have a good grip on CORS in general, but I've read all I could find on it.. My Django/Py skills are VERY novice.. is there something obvious I'm missing here? Or do any of you have a clue on how I should proceed to resolve this? // Headers from console/network on attempted axios get(it works locally, and has been working before I tried to deploy to Vercel): // General: // Request URL: herokuAppUrl.com // Request Method: GET // Status Code: 405 // Referrer Policy: strict-origin-when-cross-origin // Response headers: // Allow: DELETE // Connection: keep-alive // Content-Length: 19 // Content-Type: text/plain; charset=utf-8 // Date: Tue, 26 Apr 2022 15:48:53 GMT // X-Content-Type-Options: nosniff // Request headers: // Accept: application/json, text/plain, */* // Accept-Encoding: gzip, deflate, br // Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 // Connection: keep-alive // Host: git.heroku.com // Origin: https://my.vercel.app // Referer: https://my.vercel.app/ // Sec-Fetch-Dest: empty // Sec-Fetch-Mode: cors // Sec-Fetch-Site: cross-site // Sec-GPC: … -
Creating a Django Model for a recipe
I am trying to create a Django model for a recipe database. I'm having trouble writing a model that will account for a variable amount of ingredients(not every recipe has the same amount of ingredients). Here is what I have so far: class Recipe(models.Model): '''A recipe class to input new recipes''' recipe = models.CharField(max_length=50) ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL) quantity = models.CharField(max_length=1) cuisine = models.ForeignKey(Cuisine, null=True, on_delete=models.SET_NULL) def __str__(self): return self.recipe I'm stuck trying to figure out how to associate one recipe with multiple ingredients in the database. Right now, I've only managed to create one ingredient per recipe. The foreign keys are for other created classes that describe individual ingredients and cuisines. -
How to make multi-tenant apps in django?
Info: I want to make multi-tenant app in django like facebook. facebook allow a single user create multple pages. In my case: Each page is a tenant. The user is creating a schema while the user creating a page. I am using django-tenants to make multi-tenant app in django. django-tenants Is working with subdomain (pageName.example.com). But i want to access tenant as (example.com/pageName/) and i want to allowed the user permission to Edit the page(tenant) which users are registered in public schema user table. -
Django: No module named 'base.context_processors.defaultdjango'; 'base.context_processors' is not a package
i am trying to add a context processor in django setting.py file, and this is the line i am adding TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'base.context_processors.default' # this line here is what i added 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] but it keeps showing this No module named 'base.context_processors.defaultdjango'; 'base.context_processors' is not a package error. When i comment that line out the error goes away but i keep getting this error No module named 'base.context_processors.defaultdjango'; 'base.context_processors' is not a package -
use django "include" inside a js function
I am doing a search page in which parameters are sent by ajax and then upon reception of the queryset I rebuild my cards. The whole thing is classic and working ok, here is a simplified version of the thing. Lots of lines killed or modified since it is not really the subject of the post let getobject = async (value,url) => { var res2 = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify({ value: value, }) }) let data2 = await res2.json(); videoitems.innerHTML = '' modalbin.innerHTML = '' data2["data"].forEach(async item => { if (item.ext == '.mp4') { const dynamicreation = async () => { let dyncontent3 = await createnewcard(item) let placing = await videoitems.appendChild(dyncontent3); } const nooncares2 = await dynamicreation() } else if (item.ext == ".pdf") { const dynamicreation2 = async () => { let dyncontent4 = await createnewcard(item) let placing2 = await videoitems.appendChild(dyncontent4); } const nooncares4 = dynamicreation2() } }) } the createnewcard function var createnewcard = item => { var dyncontent = document.createElement("div"); dyncontent.innerHTML = `<div class="m-2 extralarge-modal video${item.id}"> <div data-reco="${item.id}" class="extralarge-modal bg-white rounded-lg border border-gray-200 shadow-md dark:bg-gray-800 dark:border-gray-700"> <div class="p-5"> <p class="mb-3 font-normal text-gray-700 dark:text-gray-400"> ${item.title} </p> </div> … -
Django redirect not working in my view function
From my crop crop_prediction view I am trying to redirect it to 'http://localhost:8000/Efarma/crop_detail/' page but instead of this it render the current html page ,the home page which is also the starting page of this website. Some error is showing in my console '[26/Apr/2022 22:31:29,457] - Broken pipe from ('127.0.0.1', 62868)' but I have no idea what is it. To go to crop_detail page i have to manually put it in search box. urls.py:- from django.urls import path, include from .import views urlpatterns = [ path('', views.home), path('crop_prediction/', views.crop_prediction), path('crop_detail/', views.crop_info) ] views.py:- def home(request): return render(request, 'Efarma/index.html') def crop_prediction(request): global resultJson, firebase print(request.POST) print(request.GET) if request.method == "POST": N = float(request.POST.get("nitrogen")) P = float(request.POST.get("phosphorus")) K = float(request.POST.get("potassium")) ph = float(request.POST.get("ph")) rainfall = float(request.POST.get("rainfall")) city = request.POST.get("city") if weather_fetch(city) != None: temperature, humidity = weather_fetch(city) data = np.array([[N, P, K, temperature, humidity, ph, rainfall]]) print(temperature, humidity, "--------kkk-------") my_prediction = pickle.load( open('CropRecommendation\model\model.pkl', 'rb')) final_prediction = my_prediction.predict(data) value = final_prediction[0] firebase = firebase.FirebaseApplication( 'https://e-farma-5dc42-default-rtdb.firebaseio.com/') predicted_crop_info = firebase.get(value, None) predicted_crop_info["crop"] = value resultJson = dumps(predicted_crop_info) return redirect('http://localhost:8000/Efarma/crop_detail/') else: return redirect('http://localhost:8000/Efarma/crop_detail/') def crop_info(request): print(resultJson) return render(request, "Efarma/crop_detail.html", {"result": resultJson}) error:- -
Running multiple independent docker containers for web services
I'm trying to run a few services on my server, by using separate docker image for each service: nginx - with a configuration for all available services below and access to the files on the server - should be always running Wordpress - for hosting a Wordpress web page (and probably PHP?) - will be almost always running on the server Django - for hosting a Django web page - will be sometimes running only Flask RESTful API - maybe in the future will be added I'm using docker-compose to configure nginx and django app, but I cannot run only nginx container without django (I've tried to use links and depends_on in docker-compose.yml). So long story short - I want to be able to add, run and stop containers for web services independently. -
In Django, is there a way you can limit a user to registering for an event only once?
I'm a newbie to Django, trying to build site to allow people to register for football matches. At the moment, a user can register multiple times for the same match, which is obviously not ideal! Is there a way that I can identify if the currently logged in user has already registered, and then replace the register button with a message telling them that they have already registered? I guess I need some kind of Boolean value in my EventDetail view, and then I can make a conditional statement in the template, but I'm unsure as to how to implement this. I hope this question is clear, it's my very first post! views.py: class EventDetail(View): def get(self, request, id, *args, **kwargs): event = get_object_or_404(Event, pk=id) registrations = Registration.objects.filter(event=event) total_participants = 0 for person in registrations: total_participants += 1 if person.guest: total_participants += 1 remaining_spaces = event.max_participants - total_participants template = "event_detail.html" context = { "event": event, "total_participants": total_participants, "registrations": registrations, "remaining_spaces": remaining_spaces, } return render(request, template, context) template {% extends "base.html" %} {% block content %} <p>{{ event.title }}</p> <p>{{ total_participants }} / {{ event.max_participants }} ({{ remaining_spaces }} spot{{ remaining_spaces|pluralize }} remaining!)</p> {% if total_participants < event.max_participants %} <a … -
Django - How to pass current url parameters if any to a new url after pressing a button
My current page has a filter that the user can fill if wanted. In the same page there is a button that redirects the user to a new url that downloads a file. My question is: How i can pass the first page url parameters and pass them to the new url/view? If i add them in my url and they are not filled then i have an error. -
django.templates.exceptions.TemplateDoesNotExist
Even in the settings.py, I have added the INSTALLED_APPS section but still, it is not working. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', # this is for the authentication 'django.contrib.contenttypes', # this tells about the MIME type 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # it help us to host the static files 'HelloWorld', ]` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]