Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bt table filter extension:- how to filter dropdown value filter out?
How to filter dropdown value based on new data on first filter. Like only $0 needned in second dropdown value Simple table value filter then based on filtered result value dropdown value come to UI. Thanks I see the github code for bt table filter extension but i didn't identify any idea -
Mypy: properly typing a Django mixin class when accessing a method on super()
Django has a quirk where it doesn't validate models by default before writing to the database. A non-ideal situation that devs try to work around by creating a Mixin class for example: https://www.xormedia.com/django-model-validation-on-save/ The idea of that workaround is that you can inherit this mixin to your custom defined Django models whenever you want to add validation-on-save to it. That approach works, but I'm trying to upgrade those old examples to a properly typed example. Below is my current code: from typing import Any, TypeVar from django.db import models DjangoModel = TypeVar('DjangoModel', bound=models.Model) class ValidateModelMixin: """Use this mixing to make model.save() call model.full_clean() Django's model.save() doesn't call full_clean() by default. More info: * "Why doesn't django's model.save() call full clean?" http://stackoverflow.com/questions/4441539/ * "Model docs imply that ModelForm will call Model.full_clean(), but it won't." https://code.djangoproject.com/ticket/13100 """ def save( self: DjangoModel, force_insert:bool=False, force_update:bool=False, *args: bool | str | None, **kwargs: bool | str | None, ) -> None: """Override the save method to call full_clean before saving the model. Takes into account the force_insert and force_update flags, as they are passed to the save method when trying to skip the validation. Also passes on any positional and keyword arguments that were passed … -
prefill previous file field data in django form
i have two file fields in django form and i want set prefill data for fields. when form open again dont need fill again file field. this is my form field self.fields['total_trial_balance'].widget.attrs.update({'class': 'filestyle', 'id': 'total_trial_balance'}) self.fields['Certain_trial_balance'].widget.attrs.update({'class': 'filestyle', 'id': 'Certain_trial_balance'}) this is i try to do form = TaxReturnLegalUpdateForm(instance=tax_return, request=request) but i just got currently file name in my templateenter image description here -
Why Hosted Site showing blank page in azure-django hosting?
I am trying to deploy my django app using azure(app services) through vs code. It is Showing deployment successful but hosted site showing blank page. I used VS Code. Downloaded azure studio extension and deployed my django project. -
Is this the right way of creating Multi User Access for Django?
I actually confused right now on how to implement the Multi-User Access with Django v5.3. I am actually new in this backend and I would like to create a login where users can redirect to specific dashboards based on their accesslevel type (Providers,Admin,Validator,Students). Here is the app that I made so far... I have no views yet because I am not confident enough to my models.py but I hope this is good enough. 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 Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) 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) avatar = models.FileField address = models.CharField(max_length=50) class Provider(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) 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) avatar = models.FileField(upload_to='avatars') -
how to use multiple model in single serializer or how to make combined serializer but not extended approch
i'm implementing API in which i have to store data in multiple database table and i can not change the schema , so here i have implement the serializers by multiple inharite approch. here is my serializers: class Organization_1_Serializer(serializers.ModelSerializer): def __init__(self, instance=None, data=..., **kwargs): super(Organization_1_Serializer, self).__init__(instance, data, **kwargs) class Meta: model = Organizations fields = "__all__" class Organization_2_Serializer(serializers.ModelSerializer): def __init__(self, instance=None, data=..., **kwargs): super(Organization_2_Serializer, self).__init__(instance, data, **kwargs) class Meta: model = Organization_2 fields = "__all__" class OrganizationSerializer(Organization_1_Serializer, Organization_2_Serializer): def __init__(self, instance=None, data=..., **kwargs): super(OrganizationSerializer, self).__init__(instance, data, **kwargs) def create(self, validated_data): return super().create(validated_data) def update(self, instance, validated_data): return super().update(instance, validated_data) i want to create POST api in which i can simple pass the resquest.data to the OrganizationSerializer and serializer will manage the things according to the model. my concern to use ModelSerializer instead Serializer that single api contain 3-4 tables fields and each table has the appox 20-25 columns to manage. using serializers.Serializer or accept ModelSerializer it's becoming so complex. please help me to solve this issue aur suggest right approch to do so. Thank you in advanced -
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) { …