Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django The current path didn’t match any of these
Good day, I have made a simple calculator in Django displaying on the url path('', vieuws.home, name='home'), It uses a function from the views.py file to render the answer and then display it using the result.html file. This works perfect. But I want to make more calculators on different urls and then it does not work anymore. I put the same calculator on the path('count/', views.count, name='count'),. I renders the page good but to pass in the result.html page for the answer does not work and gives a 404 error, something wrong with the url path. I have tried to change order in the urls and change order in the views.py file but I can not figure out how to solve the problem. I hope it's okay to add the link of the project to see the code on github, https://github.com/Roelofplanet/Django-calculator Thanks! Regards, Roel -
Download load button on django project not working with apache server
I am having problems with my download button on my website which should allow vistors to get a copy of my CV. It was working while through all the stages of building the site, however when running it with apache2 a blank tab just opens up. This is the layout of the project: enter image description here the html code: enter image description here the views.py: enter image description here my dango_project.config on server: enter image description here and the error log I get when I click the button: enter image description here I am new to configuring an apache server so I am guessing its somthing to do with my .config file? Any help or pointing in the right direction would be much appreciated Thank you I am just expecting the user to be able to download a copy of my CV. Was working when running manage.py server on local host and linux server. Every other part of the site works, like sending forms uploading images/text. -
OperationalError at /admin/useraccounts/student/ :no such column: useraccounts_student.user_id
I am trying to connect my User table to these three user access from models. But when I view the models in django admin it gives me an error unless the OnetoOnefield is removed. I am just a beginner to this python framework so please bear with me. I can view the other models except for the 3 user models for this app. This is what the models looked liked (I don't have view.py yet because I am still figuring out if the models worked fine) models.py ` from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): is_student = models.BooleanField(default=False) is_validator = models.BooleanField(default=False) is_provider = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) class Meta: db_table = 'useraccounts_user' class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ##Added this avatar = models.FileField address = models.CharField(max_length=50) gwa = models.FloatField(max_length=100) graduated_at = models.CharField(max_length=100) year = models.DateField() class Validators(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE)##Added this avatar = models.FileField address = models.CharField(max_length=50) class Provider(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE)##Added this company_address = models.CharField(max_length=100) phone_no = models.CharField(max_length=11) company_website = models.CharField(max_length=100) avatar = models.FileField class Admin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE)##Added this avatar = models.FileField(upload_to='avatars') ` -
Logout Across Tabs in django [closed]
I need user will logout automatically in all tabs when logged out in one open tab of browser without page refresh. How can I implement this in django ? -
Not redirecting to desired URL on Django even after the configuration
This is my django project. I added my APP's url in project.urls. I also added my app's name in INSTALLED_APPS but yet all I see is only admin/ page. practise.urls hello.urls even after entering right url, it dont recognize, the list only says /admin I searched but couldn't find solution. All the urls that I am adding in urlpatterns are not being recognized except for admin. -
How can I implement an audio CAPTCHA reader with django-simple-captcha in Django?
I'm looking to enhance the accessibility of my Django web application by integrating an audio CAPTCHA reader alongside the text-based CAPTCHA provided by django-simple-captcha. While the text-based CAPTCHA is effective for most users, some users may have difficulty reading the text due to visual impairments or other reasons. I've read the documentation, but I can't understand how to implement... https://django-simple-captcha.readthedocs.io/en/latest/advanced.html#captcha-sox-path -
Not sure why when I press signup it just returns to the blank form, and when i try to log in it does nothing
views urls trying to create a new user with the sign up page, but it just returns a blank form. i created a superuser and am able to login in that and it works fine but cant figure out the problem with the signup page... -
Is there a signal available in Djoser specifically?
Is there a signal available in Djoser specificall or would I need to create a custom signal to handle actions upon a user's first registration using Google login? The user_registered of(djoser) signal doesn't seem to be functioning when registering with Google login. https://djoser.readthedocs.io/en/latest/signals.html thanks -
Transition to Backend Engineer roles [closed]
I am currently a Site Reliability Engineer, but I am interested in transitioning to more backend-focused roles that involve coding. Could you provide some advice on how to prepare for these positions and where to begin? I started with learning FastApi and Django since I know python. I also know a bit of golang. -
How can I display the DateTimeField in the django template as it's display in the admin when I create a view?
This is my model: class Event(models.Model): title = models.CharField(max_length = 255) club = models.CharField(max_length=70) event_image = models.ImageField(upload_to="event_images", default='aqsa_copy.jpeg', blank=True) date = models.DateTimeField(null = True) location = models.CharField(max_length=30) first_name = models.CharField(max_length=15) This is how it displayed in the admin: I want to make it like this at the template, and be able to pick a date and time. But what I got for now is that: Please help me if you can? -
how to implement render in view controller after get request Django
I have the following template in which I added a get request function openProject(projectId) { fetch(`/segmentation/test/`, { method: 'GET', headers: { 'Content-Type': 'application/json' }, mode: 'same-origin', }) .then(response => { if (response.ok) { console.log("Всё супер"); } else { console.error('Ошибка при открытии проекта'); } }) .catch(error => { console.error('Произошла ошибка:', error); }); } and the next view in it I collect all the information about images and tags that relate to this project def test(request): projectId = request.GET.get('projectId') if projectId: project = Project.objects.get(pk=projectId) _tags = project.tags.all() _images = project.images.all() print(_images) polygons = [] colorPol = [] for i in range(len(_images)): polygons.append([]) colorPol.append([]) for i in range(len(_images)): for rect in Rect.objects.all().filter(inImage=i+1): tempArr = [] colorPol[i].append(rect.tag.Name) for p in rect.points.all(): tempArr.append([p.x, p.y]) polygons[i].append(tempArr) else: _tags = [] _images = [] polygons = [] colorPol = [] return render(request, 'segmentation/testDraw.html', {'tags': _tags, 'images': _images, 'title': 'Test Draw', 'rectForImage': polygons, 'colorPolArr': colorPol}) My urls: app_name = 'segmentation' urlpatterns = [ path('test/', test, name='testDraw'), path('projects/', project_show, name='project_show'), ] please help me solve this problem I tried changing the request to post, but as far as I understand it doesn’t matter -
Django Automatic Field Creation
Is there a way to automatically generate a new field when a model that is foreignkeyed is created class Metric(models.Model): name = CharField(null = True, blank = True, max_length = 200) abbreviation = CharField(null = True, blank = True, max_length = 10) def __str__(self): try: return self.name except Exception as e: return str(e) class Test(models.Model): name = CharField(null = True, blank = True, max_length = 200) metrics = ManyToManyField(Metric, null = True, blank = True) def __str__(self): try: return self.name except Exception as e: return str(e) class TestVariable(models.Model): independent_variable = ForeignKey(Variable, null = True, blank = True,on_delete = models.CASCADE, related_name = "independent_variables") dependent_variable = ForeignKey(Variable, null = True, blank = True, on_delete = models.CASCADE, related_name = "dependent_variables") test = ForeignKey(Test, null = True, blank = True, on_delete = models.CASCADE) def __str__(self): try: return self.name except Exception as e: return str(e) So if I created a new Metric, is there a way to automatically add a field to TestVariable for example, if I created a Metric for standard deviation, it would automatically create a field in TestVariable to take a numerical value of the standard deviation. -
Datetime format for forms and databases
I am having difficulty unifying the format for all the dates, in my database, the format is year month day, and in my form is year month day min second. I want the date format to be unified but i seem to cant do it. def get_unavailable_dates(request, car_id): try: busy_dates = BusyDate.objects.filter(car_id=car_id) unavailable_dates_list = [busy_date.start_date.strftime('%Y-%m-%d') for busy_date in busy_dates] except BusyDate.DoesNotExist: unavailable_dates_list = [] busy_dates_json = [{'title': 'Busy', 'start': busy.start_date, 'end': busy.end_date} for busy in busy_dates] return JsonResponse(busy_dates_json, safe=False) def save_busy_dates(request): if request.method == 'POST': car_id = request.POST.get('car_id') busy_dates = request.POST.getlist('busy_dates[]') # Assuming busy_dates is sent as a list # Iterate over busy_dates list and create BusyDate instances for date_str in busy_dates: busy_date = BusyDate(car_id=car_id, start_date=date_str.date(), end_date=date_str.date()) busy_date.save() # Save the instance to the database return JsonResponse({'status': 'success'}) else: return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)``` I tried to add .date() where possible -
Incognito/Private Browsing Not Working for Google OAuth2 Authorization URL
When I navigate to http://127.0.0.1:8000/auth/o/google-oauth2/?redirect_uri=http://127.0.0.1:4200/google, I receive the following response "authorization_url": "https://accounts.google.com/o/oauth2/auth?client_id=xxxxxxxx&redirect_uri=http://127.0.0.1:4200/google&state=xxxxxxx&response_type=code&scope=https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+openid+openid+email+profile" However, when I attempt to open this URL(authorization_url) in an incognito/private browsing window, it does not work. i have set CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True and "SOCIAL_AUTH_ALLOWED_REDIRECT_URIS": ["http://127.0.0.1:4200/google"], i have [23/Apr/2024 22:07:31] "POST /auth/o/google-oauth2/ HTTP/1.1" 400 53 -
Django server throwing a MultiValueDictKeyError even though the value of the parameter is present
I have a Django endpoint that runs a query that updates a row in my database using the image_name. I am storing that image name in the client session storage and retrieving it and sending it to the endpoint. The endpoint then runs the function upload_to_db() on the data and returns success or failure based on the updating of the database. The problem is, this function is continuously throwing me a MultiValueDictKeyError error over the image name specifically in this line: img_name = request.POST["image_name"] Despite this, the function is running and the values get updated as needed but I still get this error. class paymentClass(APIView): def get(self, request): return render(request, "payment.html") def post(self, request): email = request.POST["email"] pid = request.POST["pid"] img_name = request.POST["image_name"] # if not all([email, pid, img_name]): # body = {"errorMessage": "Missing parameters"} # return JsonResponse(body, status=400) result = upload_to_db(email, img_name, pid) print(result) if result == "success": return JsonResponse({"message": "created successfully", "image_name": img_name}, status=201) else: body = {"errorMessage": result} return JsonResponse(body, status=400) I have tried printing the image name, which shows the right name. I have made sure that the image is passed on to the server correctly as well. -
I have a problem with static files in Django. I tried all the configurations and I can't use the cs or js
I'm trying configure the static files and you already tried to do everything but nothing works and I don't know what else to doSTATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] `{% extends 'base.html' %} {% load static %} {% block content %} homa {% endblock %}` .home { background-color: #f0f0f0; padding: 20px; /* Otros estilos aquí */ } solve it and be able to use the static files -
Django admin panel shows field max length instead of field name
I know it is a little bit weird but I see field max length instead of field name in admin panel as below: My model: class SituationFlag(models.Model): name=models.CharField(30) slug=models.SlugField(null=False,blank=True, unique=True,editable=False,max_length=30) description =models.CharField(200) cssclass=models.CharField(30) def __str__(self) -> str: return self.name def save(self,*args,**kwargs): self.slug=slugify(self.name) super().save(*args,**kwargs) Also I'm using that SituationFlag model with many-many relationship in other model as below: class Subject(models.Model): title=models.CharField(max_length=200) description = models.TextField() is_active=models.BooleanField(default=True) slug=models.SlugField(null=False,blank=True, unique=True,db_index=True,editable=False,max_length=255) category=models.ForeignKey(Category,on_delete= models.SET_NULL,null=True) situation_flag=models.ManyToManyField(SituationFlag) def __str__(self) -> str: return self.title def save(self,*args,**kwargs): self.slug=slugify(self.title) super().save(*args,**kwargs) What am I missing here? Any help would be much appreciated. -
Field value not being populated except when it's being debugged
I'm having a weird problem where normally field_val should be set to some particular value but is being set to "". When I debug in vscode and look into the value from the debugger, inspecting it (possibly triggering something), suddenly the variable becomes available. When I'm not debugging the value is empty string. I couldn't understand what's happening here. Is there some kind of lazy evaluation that I'm missing in django forms? I'm trying to keep the submitted value in the datalist when the form submission fails. Trying to take that value from the self.instance which is an instance of my django db model basically. class DatalistFieldMixin: def make_field_datalist(self, field_name, choices, choice_format=lambda c: c): field_val = getattr(self.instance, field_name) or "" # Create the datalist widget while setting the html "value" attribute. # And set the widget as the form field. if self.fields.get(field_name): widget = DatalistWidget( choices=[choice_format(c) for c in choices], attrs={"value": field_val}, ) self.fields[field_name].widget = widget class ObjectAdminForm(DatalistFieldMixin, forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.make_field_datalist( field_name="display_unit_id", choices=BroadsignDisplayUnit.objects.all(), choice_format=lambda c: ( c.display_unit_id, " - ".join((str(c.display_unit_id), c.display_unit_name)), ), ) -
Trouble Sending Data from ESP32 to Django Project on Local Computer
I'm trying to send data from my ESP32 to a Django project deployed on my computer. However, the ESP32 seems cannot fetch the address of Django project, here are details: My computer and ESP32 chip are connected to the same Wi-Fi network. The Django project is running on 127.0.0.1:8000, and I'm attempting to send data from the ESP32 to xxx.xxx.xxx.xxx:8000/suitcase/esp32_test (where xxx.xxx.xxx.xxx is my computer's IP address). However, the ESP32 was unable to successfully transmit data to this address, Django local terminal didn't show anything about ESP32's message. I've tried changing the server address in the ESP32 code to 127.0.0.1:8000, but it apparently didn't resolve the issue. What could be causing this problem and how can I troubleshoot it? The esp32 code: #include <HardwareSerial.h> #include <HTTPClient.h> #include "WiFi.h" #define GPSRX_PIN 16 #define GPSTX_PIN 17 #define GPS_SERIAL Serial2 const String serverAddress = "xxx.xxx.xxx.xxx:8000/suitcase/esp32_test"; void initWiFi(String ssid, String password) { WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.print("***********Connecting to WiFi .."); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(1000); } Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); Serial.println(WiFi.RSSI()); } bool HaveUsefulData(String data){ if(data.startsWith("$GNGLL")){ return true; }else{ return false; } } String ExtractProxy(String data){ int commaIndex = data.indexOf(','); if (commaIndex != -1 && data.length() > commaIndex + 13) { … -
file not found with PyInstaller and Django
I'm using PyInstaller for a Django application, with some difficulties I was able to generate the .exe file and the application starts, but when I try to see any page I get TemplateDoesNotExist error. Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\path\to\project\dist\vale_remote\_internal\src\dashboard\templates\dashboard\pages\dashboard.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\path\to\project\dist\vale_remote\_internal\src\interview\templates\dashboard\pages\dashboard.html (Source does not exist) django.template.loaders.filesystem.Loader: C:\path\to\project\dist\vale_remote\_internal\src\vale_remote\templates\dashboard\pages\dashboard.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\path\to\project\dist\vale_remote\_internal\django\contrib\admin\templates\dashboard\pages\dashboard.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\path\to\project\dist\vale_remote\_internal\django\contrib\auth\templates\dashboard\pages\dashboard.html (Source does not exist) If i go to '_internal' folder i see no 'src' folder, I don't know if I have to change the path to the templates or I should create this src folder somehow. In my 'normal' folder structure (not the PyInstaller generated) the template django is looking for is in project/dashboard/templates/dashboard/pages/dashboard.html -
AttributeError: type object 'Task' has no attribute 'models'
It says my object Task has no attribute models, I tried to check if i had anywhere bad case but I don't think i have. views.py: from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages from .forms import CreateTask from .models import Task def Home(request): return render(request, "Home.html") def task_view(request): current_user = request.user.id task = Task.models.all.filter(user=current_user) context = {"task": task} return render(request, "task_view.html") def task_creation(request): form = CreateTask() if request.method == "POST": form = CreateTask(request.POST) if form.is_valid(): task = form.save(commit=False) task.user = request.user task.save() return redirect("/Home/task_view/") context = {"form":form} return render(request, "task_creation.html") models.py: from django.db import models from django.contrib.auth.models import User import datetime class Task(models.Model): title = models.CharField(max_length=100, null=True) description = models.CharField(max_length=5000, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) error block: Django version 5.0.2, using settings 'task_manager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /Home/task_view/ Traceback (most recent call last): File "C:\Users\lubos\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lubos\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\lubos\OneDrive\Plocha\task_manager\tasks\views.py", line 16, in task_view task = Task.models.all.filter(user=current_user) ^^^^^^^^^^^ AttributeError: type object 'Task' has no … -
CKEditor in React - Upload images correctly, but the editor alerts opposite
The image is correctly send to the server and gets upload, but for some reason the editor shows an alert that says 'Cannot Upload'. This is the React Component where I have the config of CKEditor: import { CKEditor } from "@ckeditor/ckeditor5-react"; import ClassicEditor from "@ckeditor/ckeditor5-build-classic"; const PostEditor = ({ onChange, value }) => { return ( <CKEditor editor={ClassicEditor} config={{ ckfinder: { uploadUrl: "http://127.0.0.1:8000/api/image/list/", }, upload: { dataType: "multipart", }, }} data={value} onChange={(event, editor) => { const data = editor.getData(); // console.log(event); // console.log(editor); console.log(data); onChange(data); }} /> ); }; export default PostEditor; This is the error: CKEditor5 Upload Error The explorer where I selected the image doesn't showed up in the recording. As you can see, the editor make a post request whenever you try to add some image to the post, as it should be, then the image gets uploaded, but the editor can't read the image, I don't know why. Maybe I'm missing some configs so the editor can track the url? It is my first time using CKEditor. Any help would be useful, thanks! Upload images to CKEditor. Images uploaded to backend server and charge them in the post. CKEditor: Upload Error. Although the images were … -
Bokeh, how do i remove datetimes without corresponding values?
hope you are doing well, i would like to render a chart without the long lines present, which correspond to the values that do not have the corresponding pair. Here is the function that is generating my chart, hope i does not scary you: def get(self, request): user=request.user historical_me=FinancialInstrument.objects.all() form = self.form_class(historical_me=historical_me) retrive=HistoricalData.objects.all() get_symbol=retrive.filter(instrument__symbol="BTUSD").order_by('datetime') fields=get_symbol.values('datetime','opening_price','closing_price','min_price','max_price','volume') df=pd.DataFrame.from_records(fields) x_values = [key.datetime for key in get_symbol] y_values = [float(key.opening_price) for key in get_symbol] source = ColumnDataSource(data=dict(dater=x_values,pricer=y_values)) plot = figure(title="New title", width=780, height=400, x_axis_label="Date", y_axis_label="Max Price", x_axis_type="datetime") plot.line(x='dater',y='pricer', source=source,line_width=3) unique_dates = HistoricalData.objects.order_by('datetime').values_list('datetime', flat=True).distinct() plot.line(x='datetime', y='opening_price', source=source, line_width=3) plot.toolbar.autohide = True script, div = components(plot) if user.is_authenticated: return render(request,self.template_name, {'form':form,'days_of_month': [i for i in range(1,32)], 'script':script, 'div':div, }) return redirect('home') ``` This is the chart it produces, i need an approach to suppress those long lines, which correspond to the dates that do not have a corresponding value. [![The corresponding chart have these long lines, which i would line to suppress][1]][1] [1]: https://i.stack.imgur.com/QNreK.png -
TypeError at /signup/ join() argument must be str, bytes, or os.PathLike object, not 'dict'
"def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user=form.save() login(request,user) return redirect(frontpage) else: form=UserCreationForm() return render('core/signup.html',{'form':form})" when ı running this code block ı return a error "TypeError at /signup/ join() argument must be str, bytes, or os.PathLike object, not 'dict'" how can ı fix it? ı wanna make a sign up form -
Django pre-signed url file uploads architecture MVC
I'm trying to implement file uploads using pre-signed URLs using Django. I've got the upload part working, however, I'm not sure what the architecture should look like for standard MVC application. Assume this model: class Document(models.Model): file = models.FileField() extra_field = models.CharField() Render GET page with file upload form. User modifies <input type='file'> and the browser makes a request to /api/get-presigned-url which returns PUT URL for file upload Browser uploads a document to PUT URL. These 3 steps are clear. The next steps are completely unclear and I'm not sure how to then save this already uploaded document to my Document model. If I submit the form with Filefield set - the file is uploaded into server-side which we're trying to avoid using pre-signed URLs. If I modify the form to have file_url and set it to pre-signed PUT URL - it works but it's not secure as user can just modify the file name and access any file in the bucket. What would be the recommended architecture for using pre-signed URLs with Django standard MVC pattern with GET/POST requests.