Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to validate password inside views.py django
I have my own HTML form and I am using AbstractUser to create my own model, the problem that I am facing is when I try to register a new user I need to check whether the password and confirm password field matches. If it does not match, then I need to throw an error message. I have written this below logic in "views.py", the problem is even if the password does not match a new user is getting created in the backend. I am not sure what I am doing wrong here. def registerPage(request): #form = UserCreationForm() user = User() if request.method == "POST": user.first_name = request.POST.get('txtFName') user.last_name = request.POST.get('txtFName') user.username = request.POST.get('txtUserName').lower() user.email = request.POST.get('txtEmail').lower() password1 = request.POST.get('txtPassword') password2 = request.POST.get('txtConfPassword') if password1 == password2: user.set_password(password2) else: messages.error(request, "Password and Confirm password do not match. Try again") user.is_superuser = False user.save() login(request, user) return redirect('home') return render(request,'login_register.html') -
Bulk create many-to-many objets to self
Having model class MyTable(Model): close = ManyToManyField("MyTable") How to bulk create objects to this relation? With tables not related to itself, one could use db_payload =[MyTable.close.throught(tablea_id=x, tableb_id=y) for x,y in some_obj_list] MyTable.close.through.objects.bulk_create(db_payload) What would be the keyword arguments in case where relation is to the table itself? -
Multi peer video call using webrtc and django channel(websockets)
I am trying to build a Multi user video call using webrtc and django channel in a chat room , similar to what discord does ,in that i have successfully implemented it for 2 users . So when user 1(host) starts the call , an "offer" along with "ice candidates " gets sent to connected users in the room . Now i have a "Join Call " button for processing the data from host and sending "answer" and "ice-candidates" back , this is working fine for 2 users , but now in the 3rd user , that user first gets host's offer and without it processing it , the 3rd user gets user 2' answer . So when user 3 clicks on join call , the 3rd user can only see his local stream , and the ongoing call between 1 and 2 is happening without any change . So basically 3rd user is unable to join the ongoing call . How can i resolve this issue at hand ? I am using webrtc for peer connections and offer/answers And i am using Django channels'websocket for signalling -
How to Join (NOT COMBINE) two more django querysets?
I’m new to Django framework, may be this problem seem to be fun to some experienced developers here. So, I have a django model: STATUS_CHOICES = ( (‘CL’, ‘CLOSED’), (‘FR’, ‘FORWARDED’), (‘PE’), ) class References(modles.Model): ref_no = models.CharField(max_length=) date_received = models.DateField() status = models.CharField(max_length=2, choices=STATUS_CHOICES) I am required to query the data in this format:- Year Month #Total Ref. #CLOSED #FORWARDED #PENDING 2023 Jan 3 1 1 1 2023 Feb 1 0 1 0 2023 Mar 1 0 0 1 Sample data: Ref_No (unique) Date_Recieved Status ABC-123 01-Jan-2023 CLOSED BCD-234 01-Feb-2023 FORWARDED DEF-567 01-Jan-2023 PENDING ABC-891 01-Jan-2023 CLOSED DEF-967 01-Mar-2023 PENDING I created three different querysets but don’t know how to join them to produce above results: - # TOTAL q_total = References.objects.all() \ .values('date_received__year', 'date_received__month') \ .annotate(dcount=Count(‘ref_no’)) \ .order_by('date_received__year', ‘date_received__month') # CLOSED q_total = References.objects.filter(Q(status__iexact='CL') \ .values('date_received__year', 'date_received__month') \ .annotate(dcount=Count(‘ref_no’)) \ .order_by('date_received__year', ‘date_received__month') # FORWARDED q_total = References.objects.filter(Q(status__iexact='FR') \ .values('date_received__year', 'date_received__month') \ .annotate(dcount=Count(‘ref_no’)) \ .order_by('date_received__year', ‘date_received__month') # PENDING q_total = References.objects.filter(Q(status__iexact='PE') \ .values('date_received__year', 'date_received__month') \ .annotate(dcount=Count(‘ref_no’)) \ .order_by('date_received__year', ‘date_received__month') Any help would be appreciated. The above is just a small sample problem. -
You cannot access body after reading from request's data stream : Swagger integration with django
Not able to access request.body after adding extend_schema. Where my message are already consumed i am using standard middleware only that comes with django setup from rest_framework import decorators, serializers from drf_spectacular.utils import extend_schema, OpenApiParameter, inline_serializer from drf_spectacular.types import OpenApiTypes from django.views.decorators.csrf import csrf_exempt @extend_schema( request=inline_serializer( name="MemberSerializer", fields={ "loan_ids": serializers.ListField(), }, ), responses=OpenApiTypes.OBJECT, methods=['POST'], ) @decorators.api_view(http_method_names=['post']) @csrf_exempt def post_member(request): request_body = json.loads(request.body.decode('utf-8')) return JsonResponse({'success': True, 'request': request_body}, status=200) Middlewares : "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", i don't want to use request.data to fetch the input request data, Wanted to know where i have consumed the request.body the first time -
Django testing disable app and middle ware to test multiple databases setup with only one testing database
I am using multiple databases where in a special case I am streaming data into a warehouse (by using signals). However, for testing the business logic I don't want to stream warehouse data so I want to disable this app and middleware. But something is wrong since the test still requires multiple database settings: @override_settings(REST_FRAMEWORK={"PAGE_SIZE": 2}) @modify_settings(MIDDLEWARE={'remove': ['dwhstreaming.middleware.LoggingStackMiddleware']}, INSTALLED_APPS={'remove': ['dwhstreaming']}) class TestAPI(TokenAuthenticatedTestAPI): # Test works fine if I add these: # multi_db = True # databases = {'default', 'dwh-stream'} def test_create_client(self): client = deepcopy(SAMPLE_CLIENT) # do something ... Fails with: Database queries to 'dwh-stream' are not allowed in this test -
Issue with passing Django URL parameters while dynamically changing the inner HTML of a Django template using Javascript
I am trying to dynamically change the innerHTML of a Django template using Javascript. There are some anchor tags inside the HTML content. Their href contains Django URL with some parameters. There is some issue with it, but can't figure it out. $.ajax({ url: "{%url 'fact:datalist' %}", type: 'POST', headers: { "X-CSRFToken": token, }, dataType: 'json', data: { csrfmiddlewaretoken: token, seldata: selectedDate, } }).done(function (data) { const pdata = JSON.parse(data) pdata.forEach((key, index) => { const val = key.fields; console.log(val) const nid = val.result_id; trdata = `<tr> <td>${index}</td> <td style="display: none;"> ${nid} </td> <td><a href="{%url 'fact:entry_form' id=${nid} %}"> ${val.pdtcode} </a></td> <td> ${val.process_code} </td> <td> ${val.prev_count} </td> <td> ${val.ok_count} </td> <td> ${val.ng_count} `; if (val.ng_count != 0) { trdata = `<br><a href="{%url 'fact:editform' id=${nid} %}"> Edit </a>`; } trdata = `</td> <td> ${val.unattended_count}`; if (val.unattended_count != 0) { trdata = `<br><a href="{%url 'fact:checkform' id=${nid} %}"> Check </a>`; } trdata = `</td> </tr>`; $('.data_view>tbody').html(trdata) }); }) } The issue exists at the id=${nid} part of every URL. Need some advice to tackle this issue. Thanks in advance -
"ModuleNotFoundError: No module named" error for a local module in django
I have a local custom module that I want to use in my webservice but I got "ModuleNotFoundError: No module named" error. even when my editor can detect the module. At firs I think it was because of crontab that I'm using but even when I change ot to somthing else I still got this error. Even I changed the structure of my project and I still getting this error -
form validation error message not displaying
ther was no displaying error message in website and ther was no any elements for view errors view.py: from . import forms from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout from django.core import validators def user_login(request): form=forms.LoginForm() if request.POST: form=forms.LoginForm(request) # if request.user.is_authenticated: # return redirect('home') return render(request,"login.html",context={'form':form,'message':''}) def home(request): if request.user.is_authenticated: return render(request,"home.html") return redirect(user_login) def user_logout(request): if request.user.is_authenticated and request.META.get('HTTP_REFERER') is not None: logout(request) return redirect(home) forms.py: from django import forms from django.core import validators class LoginForm(forms.Form): name= forms.CharField(validators=[validators.MinLengthValidator(4,"errorororokjjkkj hjkhjkjhk hkhkh j")],widget=forms.TextInput(attrs = {'class':"form-control mb-3",'placeholder':"Username"})) password=forms.CharField(widget=forms.PasswordInput(attrs = {'class':"form-control mb-3",'placeholder':"password"})) login.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>login</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <div class=" w-50 container " style="border-radius: 20px; background-color: darkgrey;"> <h1 class="mt-5 pt-5 mb-0 text-center ">login</h1> <div class="h-100 d-flex align-items-center justify-content-center "> <form class="w-50 m-5 container" method="post" > {%csrf_token%} {{form}} {{message}} <button type="submit" class="btn btn-primary mt-1" onclick="">login</button> </form> <!-- <form class="w-50 m-5 container" method="post" enctype="multipart/form-data" > {%csrf_token%} <label for="exampleFormControlSelect1">Username</label> <input type="text" class="form-control mb-3" placeholder="Username" name="username" required> <p>{{message}}</p> <label for="password">password</label> <input class="form-control mb-3" type="password" name="password" placeholder="password" required></input> <button type="submit" class="btn btn-primary mt-1" onclick="">login</button> </form> --> </div> </div> </div> </body> </html> i want display error without using … -
I have a field with current/permanent_address and I need to use this field with forward slash in my serializer
this is my serializer and I am not able to declare fields in my serilizer with forward slash "address": { "current/permenantAddress": { "PERM_LINE1": "delhi vasant vihar", "PERM_LINE2": "vasant vihar", }, "correspondence/localAddress": { "CORRES_LINE1": "", } } } -
100% CPU Utilization on my VPS - Django app gunicorn
I have a VPS running Nginx, Django, Postgres and a Golang microservice in a Docker compose environment and recently I've noticed it's consistently hitting 100% CPU utilization and not working anymore. I suspect this may be due to a DDoS attack or weird gunicorn behavior. VPS OS: Ubuntu 22.04.2 LTS Observations: The high CPU usage started around yesterday (24hrs ago). Steps Taken: Setup and config ufw, and a digitalocean firewall. NGINX Logs ... 89.44.9.51 - - [29/Sep/2023:05:09:58 +0000] "OPTIONS /webclient/api/MyPhone/session HTTP/1.1" 444 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 3CXDesktopApp/18.13.959 Chrome/112.0.5615.165 Electron/24.3.0 Safari/537.36" "-" 89.44.9.51 - - [29/Sep/2023:05:10:01 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:07 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:12 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:17 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:22 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:27 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" "electron-fetch/1.0 electron (+https://github.com/arantes555/electron-fetch)" "-" 89.44.9.51 - - [29/Sep/2023:05:10:32 +0000] "GET /provisioning/5lbr5h6kse0q/TcxProvFiles/3cxProv_YU8SR32OGF200.xml HTTP/1.1" 444 0 "-" … -
insert the POST list to the db in Django?
We encountered a problem. Can you help? I am sending a list via POST. lists will be recorded in the table in two fields. Send List in HTML. As follows, validate result from html. Your list data are: ('csrfmiddlewaretoken', ['..']) ('x1', ['1', 'Закройный']) ('x2', ['2', 'Закройный']) ('x3', ['3', 'Закройный']) Models.py from django.db import models class Testmodel(models.Model): ws1 = models.CharField(max_length=100, blank=True) ws2 = models.CharField(max_length=100, blank=True) input.html <form action="../validate" method="POST"> {% csrf_token %} {% for work_stations in ws %} {% if work_stations.is_active %} <input name="x{{ work_stations.id }}" value="{{ work_stations.id }}"> <input name="x{{ work_stations.id }}" value="{{ work_stations.category }}"> {% endif %} {% endfor %} <input type="submit" > </form> views.py from django.shortcuts import render from .models import Testmodel def createpost(request): if request.method == 'POST': list_data = (list(request.POST.lists())) #Here I need to save list_data to the database. The following code does not work. mylist = list_data Testmodel.objects.bulk_create([Testmodel(**{ 'ws1' : x[0], 'ws2' : x[1]}) for x in mylist]) -
Django, MySQL tests create all tables, but why is each table empty?
Problem Statement: When I use any test case that tries a db lookup I get a typical db error like "matching query does not exist." I cannot figure out why test db creation creates the tables, but fails to put the data into the tables. Using MySQL db in development works fine. So Far: Performed significant amounts of searching for similar issues posted by others, but failed to find any I used --keepdb and found that all tables successfully create, however, they are all empty; even tables like auth_user. Work around: I can manually add data to the test tables and reach a successful test case with a db query (yay!), however, it is a super pain and not easily repeatable (or sustainable). =========================== Notes: Migrations are regularly deleted from django_migrations table and the migrations directory with subsequent make and fake. The standalone migration file; 0001_initial.py looks good. Using typical database settings, no test db defined, no mirrors. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '***', 'USER': '***', 'PASSWORD': '***', 'HOST': 'localhost', 'PORT': '3306', } } -
Manually validating csrftoken in Django
<script> const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; let submitFormData = () => { const formData = new FormData(); // Add form data // This line may not be required as the header contains it formData.append('csrftoken', csrftoken); const request = new Request( URL, {headers: {'X-CSRFToken': csrftoken}} ); return fetch(request, { method: 'POST', mode: 'same-origin', body: formData }) .then(response => response.json()) .then(response => { data = response['time']; return data; }); } </script> How do I validate csrftoken on the server side in Django / python ? I am not using DRF here. Django 4.2 -
Django ,How can I display account details when I select it?
** for my problem, I find it very complex and I researched it a lot and did not find a solution. I hope for your support I want when I choose the account, whether a parent or a child, to display it with the rest of its details on the other side of the template[![enter image description here][2]][2] ** -
DJango - JS - Ajax - Upload file to NRM/Nexus (another domain) - CORS Issue
PLEASE HELP With the following JS function `function nexusUploader(file) { let filename = file.name, formData = new FormData(); formData.append('package', file); $.ajax({ url: "https://<external domain (NRM/NEXUS)>", type: "PUT", data: formData, contentType: false, cache: false, cors: false , crossDomain: true, secure: true, processData: false, mimeType: "multipart/form-data", headers: { 'X-CSRFTOKEN': $.cookie("csrftoken"), "Authorization": "Basic <KEY>" }, success: function(data) { console.log(data); }, error: function(e) { console.log(e); } }); }` I am getting the following error: Access to XMLHttpRequest at 'https://' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. global.js:37 09/28/2023 22:06:20: {readyState: 0, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} jquery-3.7.0.min.js:2 PUT https:// net::ERR_FAILED -
'MoneyField' object has no attribute '_currency_field' in django-money when running migration
For the following Model, I added a new field gst_amount: from djmoney.models.fields import MoneyField class Invoice(Model): gst_amount = MoneyField(max_digits=14, decimal_places=2, default="0 USD") The migration completed and I can use the field in my views without issue. When I try to run the following data migration: from djmoney.money import Money from django.db import migrations def migrate_invoices(app, _): Invoice = app.get_model("users", "Invoice") for invoice in Invoice.objects.all(): invoice.gst_amount = Money(10, 'AUD') class Migration(migrations.Migration): operations = [ migrations.RunPython(migrate_invoices, migrations.RunPython.noop) ] I get the following error: File "/app/blah/users/migrations/0159_auto_20230929_0113.py", line 9, in migrate_invoices for invoice in Invoice.objects.all(): File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 69, in __iter__ obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 515, in from_db new = cls(*values) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 437, in __init__ _setattr(self, field.attname, val) File "/usr/local/lib/python3.9/site-packages/djmoney/models/fields.py", line 111, in __set__ and self.field._currency_field.null AttributeError: 'MoneyField' object has no attribute '_currency_field' Not sure what I'm missing? -
How do I make these Tables?
We'll have to make these tables in HTML, but I'm not sure how to do them. [[These are the images of the tables. We have to use DJango and add them info there. But we are not sure how to desing the tables ourselves, how to make one cell in a row and then 2 cells.](https://i.stack.imgur.com/Gx1dS.png)](https://i.stack.imgur.com/ggbHz.png) Another example: | Column A | Column B | | -------- | -------- | | Cell 1 | | Cell 2 | Cell 3 | | Check Marck o | | Cell 4 | Image | <table border="1" width="70%"> <caption>Listado Clientes Septiembre 2023</caption > <tr> <th>Codigo de venta</th> <th>Precio del Producto</th> <th>Cantidad</th> <th>Valor unitario</th> <th>Total a pagar</th> </tr> <tr> <td>{{CCodigoVenta}}</td> <td>{{PProducto}}</td> <td>{{CCantidad}}</td> <td>{{ValorUnitario}}</td> <td>{{TTotalPagar}}</td> </tr> </table> That's how we made a table like the third image, but I don't know how to make something like the Cell 1, or puit a check mark for example. qwp -
Issue with outputting tolls using Google routes API
I am able to get toll information correctly using Google routes Api when running the code on localhost. Response on localhost is : {'routes': [{'legs': [{'travelAdvisory': {'tollInfo': {'estimatedPrice': [{'currencyCode': 'INR', 'units': '170'}]}}}], 'distanceMeters': 112558, 'duration': '7729s', 'travelAdvisory': {'tollInfo': {'estimatedPrice': [{'currencyCode': 'INR', 'units': '170'}]}}}]} When the same code is migrated to cloud server , toll information becomes blank. Response on Cloud comes like this : {'routes': [{'legs': [{}], 'distanceMeters': 112558, 'duration': '7729s'}]} Expecting the same response on cloud as it is coming on localhost because code is same. -
Django Rest and Dropzone React "The submitted data was not a file. Check the encoding type on the form."
I've got a react frontend with django backend trying to upload some images to django api enpoint I have 1 model in django but i want to first upload an image and then submit the rest of the data, the issue is when i try to upload the photos i get an error response photos [ "The submitted data was not a file. Check the encoding type on the form." ] I am using Dropzone to upload photos by the way Here is the react component handling uplaod function ImageUploader() { const [fileNames, setFileNames] = useState([]); const handleDrop = async (acceptedFiles) => { try { // Create a new FormData object to send files const formData = new FormData(); acceptedFiles.forEach((file) => { // Append each file to the FormData object formData.append('photos', file); }); // Make a POST request to your photo upload endpoint //axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'; const response = await axios.post('http://localhost:8000/api/quotes/create/', formData, { headers: { 'Accept': 'application/json', 'Content-Type': 'multipart/form-data', }, }); // Handle the response (e.g., show success message) console.log('Upload successful:', response.data.message); // Update the list of file names for display setFileNames(acceptedFiles.map((file) => file.name)); } catch (error) { console.error('Upload failed:', error); } }; return ( <div className="App"> <Dropzone onDrop={handleDrop} accept={{ … -
ModuleNotFoundError: No module named 'simple_history' Pythonanywhere
I have a Django app running on pythonanywhere server. I have installed the requirements.txt and everything is okay, python manage.py migrate also successfully done. now when I reload my app I get following error. 2023-09-29 00:42:43,481: Error running WSGI application 2023-09-29 00:42:43,514: ModuleNotFoundError: No module named 'simple_history' 2023-09-29 00:42:43,514: File "/var/www/app_umrahpro_me_wsgi.py", line 16, in <module> 2023-09-29 00:42:43,514: application = get_wsgi_application() 2023-09-29 00:42:43,514: 2023-09-29 00:42:43,514: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2023-09-29 00:42:43,515: django.setup(set_prefix=False) 2023-09-29 00:42:43,515: 2023-09-29 00:42:43,515: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup 2023-09-29 00:42:43,515: apps.populate(settings.INSTALLED_APPS) 2023-09-29 00:42:43,515: 2023-09-29 00:42:43,515: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate 2023-09-29 00:42:43,516: app_config = AppConfig.create(entry) 2023-09-29 00:42:43,516: 2023-09-29 00:42:43,516: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/apps/config.py", line 193, in create 2023-09-29 00:42:43,516: import_module(entry) 2023-09-29 00:42:43,516: *************************************************** 2023-09-29 00:42:43,520: If you're seeing an import error and don't know why, 2023-09-29 00:42:43,520: we have a dedicated help page to help you debug: 2023-09-29 00:42:43,521: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2023-09-29 00:42:43,521: *************************************************** It should be reloaded without any error -
Docker Error build during Deployment on Railway services
please I had previously deployed my Django project on Railway which worked fine. Unfortunately, when I tried to add up SendGrid mail functionality by using django-sendgrid-v5 package to help me handle that, everything worked pretty well in the development environment including SendGrid mails like Signup user. However, when I deployed it on Railway which uses Nixpacks to manage its default project build, I kept getting this weird error that ENV cannot be blank. I followed their deployment procedures on Python since they have a similar deployment infrastructure to Heroku. I made sure that all the (env) variables needed to run the project in their platform were set correctly. I had checked my settings.py files and my .env files to know whether I was missing anything there, but I could not find the error. I even uninstall the django-sendgrid-v5 which I believed could have introduced the error, still my deployment kept on crashing. Below is the deployment build code which has been persistent. ` ╔══════════════════════════════ Nixpacks v1.16.0 ══════════════════════════════╗ ║ setup │ python310, postgresql, gcc ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ install │ python -m venv --copies /opt/venv && . /opt/venv/bin/activate ║ ║ │ && pip install -r requirements.txt ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ start │ python … -
MultiValueDictKeyError at /register
I keep getting this whenever I try to register a user on my test website using Django please can anyone help me out MultiValueDictKeyError at /register 'email' Request Method: POST Request URL: http://localhost:8000/register Django Version: 4.2.5 Exception Type: MultiValueDictKeyError Exception Value: 'email' Exception Location: C:\Users\user\Envs\myapp\lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: myapp.views.register Python Executable: C:\Users\user\Envs\myapp\Scripts\python.exe Python Version: 3.10.9 Python Path: ['C:\Users\user\Desktop\Python Tutorial\Django tutorials\myproject', 'C:\Users\user\anaconda3\python310.zip', 'C:\Users\user\anaconda3\DLLs', 'C:\Users\user\anaconda3\lib', 'C:\Users\user\anaconda3', 'C:\Users\user\Envs\myapp', 'C:\Users\user\Envs\myapp\lib\site-packages'] here is views.py code def register(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] repeat_password = request.POST['repeat password'] if password == repeat_password: if User.objects.filter(email=email).exists(): messages.info(request, 'Email Already Used') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username Already Used') return redirect('register') else: user = User.objects.create_user(username=username, email=email, password=password) user.save(); return redirect('login') else: messages.info(request, 'Password Not The Same') return redirect('register') else: return render(request, 'register.html',) -
how to pass a string variable in django urls?
so i made a variable named urlname in my django model and want to pass it in my urls like this: path('example/<str:url>/', views.example, name='example'), and in my views i did this: def example(request, url): example = Example.objects.get(urlname=url) context = {'example':example} return render(request, 'example/example.html', context) lets say in the models, urlname has the value 'test'. when i enter the url 'example/test/' in my browser it gives me this error: ValueError at /example/test/ Field 'id' expected a number but got 'test'. i've read and checked my code, im pretty new at coding, i hope i get my answer here and my explanation was not unclear. -
Creating a wrapper for a Python3 based project with Django
Calling for help!! I have a python3 based project (it's a huge one with a lot of command line interfaces and tools/scripts running off of it) that's basically used as a resource repo. This was actually written in python2 and I am in process of migrating it over to python3. The guy who wrote this used django.models as a way to interact with the DB. Mind you, this wasn't a django project! Now, what I am thinking is, how can I migrate this project and get it to use the same everything, by just creating a django app that wraps the models for it, without disrupting anything else?! I don't have any idea regarding where to start this from and am looking forward to suggestions from developers who have done similar sort of work!