Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to have multiple users in django with different attributes
I started using Django and what I want accomplish is a custom user model. I want three types of users and each one will have some attributes in common and also ones that are unique to each user. For example a customer will have a "comments" attributes while staff and admin won't. From what I read in the following article I would have to customize my user model so I do not have to suffer down the line if I want to make any changes. The article also shows how to make the email the username which is what I want but I am not sure if this is the best approach as I have no idea if it fits my use case. More specifically I do not know how to make each user have different attributes. From the following question I know I would need to have an attribute that describes the type of user but how would I link it to a profile? When creating users is my main concern, regular customers can register on the register page while admin and staff can be created by another admin only (I plan to use a custom made admin page … -
I have expirience strange error WebSocket
We are using Redis to send notifications in Django to users when there post is liked. After huge upgrade everything is working except of this: WebSocket connection to 'wss://PATHs/token' failed: I cannot open this path wss://PATHs/token locally and have no direction. -
Django initial loading of page taking too long
Hi I am a beginner at Django and I am working on a project that lists 100 companies in each page along with there contacts and also the amount of items sold. Here is an example: As you can see the initial loading time of the page is very high. But when I refresh the page it refreshes very fast because I am using caching. Here are some of my other files: models.py from __future__ import unicode_literals from django.db import models class Company(models.Model): name = models.CharField(max_length=150) bic = models.CharField(max_length=150, blank=True) def get_order_count(self): orders = self.orders.count() return orders def get_order_sum(self): orders = Order.objects.filter(company=self) total_sum = sum([x.total for x in orders]) return total_sum class Meta: ordering = ['-id'] class Contact(models.Model): company = models.ForeignKey( Company, related_name="contacts", on_delete=models.PROTECT) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150, blank=True) email = models.EmailField() def get_order_count(self): orders = self.orders.count() return orders class Order(models.Model): order_number = models.CharField(max_length=150) company = models.ForeignKey(Company, related_name="orders", on_delete=models.CASCADE) contact = models.ForeignKey(Contact, related_name="orders", on_delete=models.SET_NULL, blank=True, null=True) total = models.DecimalField(max_digits=18, decimal_places=9) order_date = models.DateTimeField(null=True, blank=True) added_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return "%s" % self.order_number views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView from mailer.models import Company, Contact, Order class IndexView(ListView): … -
Python doesn't remove file and raises no exception in Django view
I want to remove a file in django view as follows: class RemoveAPI(APIView): def get(self, request): ... os.remove(path='/opt/project/back_media/exports/excel_export.xlsx') return Response("deleted") The code runs without raising any exceptions but, when I see media directory, the file is there yet. I mean the file is not deleted. Note 1: if I add another os.remove(path='/opt/project/back_media/exports/excel_export.xlsx') before return statement, python raise FileNotFound error while file is in the media directory. Note 2: this is a django project that runs with Docker Compose. -
Django FloatField object has no attribute Error
I was creating a form in which user will input float number. My Code: class ApartmentForm(forms.ModelForm): ... val1= forms.FloatField( required=True, widget=forms.FloatField(), ) val2= forms.FloatField( required=True, widget=forms.FloatField(), ) But I am getting this error. AttributeError at /post/ 'FloatField' object has no attribute 'is_hidden' -
CSS Custom Button Colors
I'm trying to change the color of this specific button to blue (the facebook button which is called btn btn-primary mb-2), however, I'm unable to access its class file. Here is the HTML code and button CSS <div class ="login"> <div class="form"> <form class="login-form"> <input type="text" placeholder="Username" /> <input type="password" placeholder="Password" /> <p class="forgot-password"><a class= "fgt-password" href="">Forgot Password</a></p> <button class="login-btn">Login</button> <h7>--------------------------------- OR ---------------------------------</h7> <button class="btn btn-primary mb-2"> <a href="{% url 'rango:facebook_login' %}">Login with Facebook</a> </button> </form> </div> </div> And this is the CSS code .form button { font-family: "Lato", sans-serif; text-transform: uppercase; outline: 0; background: #006600; width: 100%; border: 0; padding: 15px; color: #FFFFFF; font-size: 14px; -webkit-transition: all 0.3 ease; transition: all 0.3 ease; cursor: pointer; } I tried .btn-primary or .form btn-primary but none work. Any ideas how I can access the class through CSS? -
__init__() got an unexpected keyword argument 'headers' (Django 3.2)
In my django web app, I create a .csv file from a list in my views.py and I want the user to be able to download it when the button is pressed. However, when this is run, I get the error that 'headers' is an unexpected argument. This is the code in my views.py: output = ['a', 'b', 'c'] response = HttpResponse(content_type='text/csv', headers={'Content-Disposition': 'attachment; filename="myfile.csv"'}) writer = csv.writer(response) writer.writerows(output) return response I have no idea why this doesn't work, since I have used identical code elsewhere with success in the past. Does anyone know if this could be a browser support issue? -
Why my django heroku app is not getting any staticfile. [error 404]
Everything of my django app is working fine on local machine with debug set to false DEBUG=False ,but after deploying on heroku app is running but not loading any static file.On logs it's showing status=404 for eg. static/style.css, for all static files. Can anyone please guide. I'm not using whitenoise or any staticfileshandler. my settings.py import os from pathlib import Path import django_heroku BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'key' DEBUG =False ALLOWED_HOSTS = ['127.0.0.1','myappname.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.myappConfig', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } import dj_database_url db_from_env=dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT=os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'myapp/static'), ) DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT … -
Values not loading/filling in appropriate form fields in Browsable Page in Django rest framework
I have these nested serializers, in which the fields are not appropriately maped to html form fields in browsable API page of django rest_framework, class NestedtLocationSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = Location geo_field = 'geometry' fields = ( 'type', 'is_mobile', 'name', 'address', 'geometry', ) class NestedFloorplanSerializer(serializers.ModelSerializer): class Meta: model = FloorPlan fields = ( 'floor', 'image', ) class DeviceLocationSerializer(serializers.ModelSerializer): location = NestedtLocationSerializer() floorplan = NestedFloorplanSerializer() class Meta: model = DeviceLocation fields = ( 'location', 'floorplan', 'indoor', ) with the above serilaizers, I am getting this:- Response:- But in the html form fields the values of is_mobile, type, name are not loading in the html form fields:- Is there any way, I can controll the mapping of these fields to values?? -
stack inline 2 models each other which have a common onetoone field to another model
class User: .... class Profile: user = models.OneToOneField(User, on_delete=models.CASCADE) class Job: user = models.OneToOneField(User, on_delete=models.CASCADE) I have stackinline profile and job within the user model directly. but trying to stackinline Job under Profile model didnt work -
Docker is not saving django media files into project 'media' directory on production
App Description I have an app with django-gunicorn for back-end and reactjs-nginx with front-end all containerized as well as hosted on aws ec2 instance. Problem On development environment, media files are being saved in the 'media' directory permanently. Tho, those files are only saved on the current running docker container on production time. As a result, the files will be removed when I rebuild/stopped the container for a new code push. Expectation I wanted to store the file on the 'media' folder for permanent use. Important code settings.py ENV_PATH = Path(__file__).resolve().parent.parent STATIC_ROOT = BASE_DIR / 'django_static' STATIC_URL = '/django_static/' MEDIA_ROOT = BASE_DIR / 'media/' MEDIA_URL = '/media/' docker-compose-production.yml version: "3.3" services: db: image: postgres restart: always #Prevent postgres from stopping the container volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - 5432:5432 nginx: restart: unless-stopped build: context: . dockerfile: ./docker/nginx/Dockerfile ports: - 80:80 - 443:443 volumes: - static_volume:/code/backend/server/django_static - ./docker/nginx/production:/etc/nginx/conf.d - ./docker/nginx/certbot/conf:/etc/letsencrypt - ./docker/nginx/certbot/www:/var/www/certbot depends_on: - backend # Volume for certificate renewal certbot: image: certbot/certbot restart: unless-stopped volumes: - ./docker/nginx/certbot/conf:/etc/letsencrypt - ./docker/nginx/certbot/www:/var/www/certbot entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'" backend: restart: unless-stopped build: context: . dockerfile: ./docker/backend/Dockerfile … -
How to show a text by pushing a button on the same webpage, button is on a popup on Folium map
As you all know we can print a text on the same webpage by this code on the HTML: <body> <button onclick="myFunction()">Click me</button> <h1 id="myHeader"></h1> <script> function myFunction() { document.getElementById("myHeader").innerHTML = "hi"; } </script> </body> In my code the button is on the popup on the Folium map which looks like this: So, I would like to write "hi" on the h1 tag, onclick function for this button "More info!" on the same page: in HTML file: <h1 id="myHeader">SSSSSS</h1> <div> <form name="AAA" > <center> {{ map| safe }} </center> </form> </div> <script> function showsth() { document.getElementById("myHeader").innerHTML = "hi"; } </script> And I am using Django, so, the I predefined the popup like this: In views.py: popup_t = (... + '<button onclick="showsth()">More info!</button>' ) test = folium.Html(popup_t, script=True) popup = folium.Popup(test, min_width=150, max_width=500) So, when I click on the button, I didn't get any response just like I showed in the first HTML code. Do you have any idea about the problem? -
Django Login page looping
I created a user base with login and registration page, and everything worked fine, i was able to click on the logout button and it would log me out to the login page, but now it stopped, and I cant seem to even access The login page as I get the following error in CMD: [04/Aug/2021 17:21:22] "GET /Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Login/%25253Fnext%25253D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Login/%25253Fnext%25253D/Login/%2525253Fnext%2525253D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Login/%25253Fnext%25253D/Login/%2525253Fnext%2525253D/Login/%252525253Fnext%252525253D/Logout/ HTTP/1.1" 302 0 [04/Aug/2021 17:21:22] "GET /Login/?next=/Login/%3Fnext%3D/Login/%253Fnext%253D/Login/%25253Fnext%25253D/Login/%2525253Fnext%2525253D/Login/%252525253Fnext%252525253D/Login/%25252525253Fnext%25252525253D/Logout/ HTTP/1.1" 302 0 What I understood is that it redirects you to your login page, which isn't public. Which then redirects you again back to the login page, so on and so on. But I cant understand what is wrong with my code. VIEWS: @login_required(login_url='Login') def Auditor(request): model = datas.objects.filter(qs_login=request.user) form = auditForm() if request.method == "POST": form = auditForm(request.POST) if form.is_valid(): form.save() # <-- Add this to get the updated data instance context = {'items': model, 'form': form} return render(request, "main/auditform.html", context) @login_required(login_url='Login') def auditFormPage(request, pk): model = datas.objects.filter(qs_login=request.user) form = … -
Graphql bottleneck performance with nested query (Django + React ) makes frontend app unusable. Please help :'(
For this project Im using Python+Django and GraphQL (graphene) in the backend, MySQL as database and React.js for the frontend. In the frontend, after user logs in, I have the following query to be executed: const GET_ORGANIZATION = gql` query getOrganization($orgId : Int!) { organization(id:$orgId){ id name user{ id username firstName lastName email dateJoined lastLogin isActive trainings { id name sessions { id name category createdAt totalSteps completedAt user { id } eventSet { id category description object errorSeverity performedAt } } } } courses{ id name description trainings{ id name user{ id username isSuperuser isStaff isActive email } sessions{ id name category createdAt completedAt user{ id username } eventSet { id category description object errorSeverity performedAt } } } } } }`; As you can see, it has several levels nested. The problem comes when I go into sessions and events . I am not super expert with graphQL but I always thought the selling idea of GraphQL was that you can use all these nested fields in one single query. Well, it's not. Here are few images why: It takes over 30 seconds for the response to come. Digging a bit more into the slow_log of my database, … -
How to fix CORS Error on Django and Django REST Framework
I sometimes get CORS Error from the server, when I turn on a VPN I get 200 and when I change the VPN or when I turn it off I get CORS Error again, How can I fix CORS Error on Django and DRF. I have tried some ways and some references like: How can I enable CORS on Django REST Framework https://dzone.com/articles/how-to-fix-django-cors-error#:~:text=A%20request%20for%20a%20resource,has%20blocked%20by%20CORS%20policy. https://github.com/adamchainz/django-cors-headers but it isn't solved. what shall I do? -
Select a particular data using xpath
This is the element from a webpage <div class='someclass'> <section> <h4>Skills</h4> <p>Python, java, django</p> </section> <section> <h4>Prerequisites</h4> <p>Coding</p> </section> </div> I am trying to extract the skills from this using xpath. How can I achieve it? my answer should be: Python, java, django -
Django - After login, I get an error message saying This page isnt working on Google Chrome
I get an error message on the web browser after trying to login to my application. The error message is - This page isn’t working d1bbcb8e2c574d65bcfc28f937c87503.vfs.cloud9.us-east-2.amazonaws.com redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS My views is below # Views from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render, redirect from django.contrib import messages from powercons_app.EmailBackEnd import EmailBackEnd def loginPage(request): return render(request, 'login.html') def doLogin(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: user = EmailBackEnd.authenticate(request, username=request.POST.get('email'), password=request.POST.get('password')) if user != None: login(request, user) user_type = user.user_type #return HttpResponse("Email: "+request.POST.get('email')+ " Password: "+request.POST.get('password')) if user_type == '1': return redirect('admin_home') # elif user_type == '2': # # return HttpResponse("Staff Login") # return redirect('staff_home') # elif user_type == '3': # # return HttpResponse("Client Login") # return redirect('client_home') else: messages.error(request, "Invalid Login!") return redirect('login') else: messages.error(request, "Invalid Login Credentials!") #return HttpResponseRedirect("/") return redirect('login') def get_user_details(request): if request.user != None: return HttpResponse("User: "+request.user.email+" User Type: "+request.user.user_type) else: return HttpResponse("Please Login First") def logout_user(request): logout(request) return HttpResponseRedirect('/') #Admin View from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.contrib import messages from django.core.files.storage import FileSystemStorage #To upload Profile Picture from django.urls import reverse … -
Django - How to ignore autmoatic model language filter
My application have three different languages I want to ignore the model translation automatic filter by the framework to get all data and not by activated translate. # LANGUAGES LANGUAGES = ( ('ru', _(u'Русский')), ('en', _(u'English')), ('cn', _(u'漢語')) ) def get_queryset(self): queryset = super(ModelView, self).get_queryset().order_by('-pub_date').only('city_ru') return queryset Before queryset get executed I've tried translate.activate('ru') to get 404 not found if user tried to switch to another language, but I want to keep the same data for all languages no matter if the user switched or not the text on website will be translated but data will still the same. -
Get sql query value in Django
how can I get only the value of the following query. I just want to get the value of name, and not a dict, since in laravel you can use the -> get () in django that I can use. with connection.cursor() as cursor: cursor.execute("SELECT name FROM person WHERE id=2") fila=cursor.fetchall() Thanks. -
Data migrations for OneToOneField in django with data in tables already
I have a case model that I added a OntToOneField to Example: zoho_api = models.OneToOneField( ZohoAPIState, default=create_new_zoho_api_state, related_name='referral_profile', on_delete=models.CASCADE ) During development there was no data in the tables and the migration worked fine. But trying to migrate with data in the tables gives me the following errors: Errors Says DETAIL: Key(zoho_api_id)=(some guid) is duplicated. How do I get around this issue? -
Items remain in the lists even after using del statement
I'm building an app using Python and Django and I'm facing a problem with some variables. Below are simpldified portions from my code to explain the problem (you can access the complete code in the repo): # resources.py class HREmployeeResource(ModelResource): def after_import_row(self, row, row_result, row_number=None, **kwargs): row_result.employee_code = row.get('Employee Code') if not kwargs.get('dry_run'): import_type = row_result.import_type employee_code = row_result.employee_code instance = kwargs.get('instance') # we need the ones belong to these 2 companies in the report if instance.company in ['Company 1', 'Company 2']: self.report.setdefault(import_type, []).append(employee_code) # views.py import gc from resources import HREmployeeResource def import_hr_file(request): if request.method == 'POST': hr_file = request.FILES['hr-file'] data = get_import_data(hr_file) hr_resource = HREmployeeResource() result = hr_resource.import_data(data, dry_run=True) if not result.has_errors(): result = hr_resource.import_data(data, dry_run=False) ImportStatus.objects.create( date=timezone.now(), status='S1', data=hr_resource.report ) del result, hr_resource, data gc.collect() return redirect('core:import-report') return render(request, 'core/upload-hr-file.html', {}) The ModelResource class is from a third-party library called django-import-export and the import_data method belongs to this class, you could find the code of the method here. When I run the view import_hr_file for the first time everything is working fine, but when I execute it the second time I find that the old items still exist in the lists of the report dict of the … -
how to request session value in template django
i want to fetch a session value directly in myy template i have fom by which i request session and after that i am viewing that session in another html my views.py where session got created class Product_detail(View): def get(self, request, item_id,): item = Item.objects.filter(id=item_id) category_list = Categories.objects.all() items = Item.objects.order_by('-update_at') return render (request, 'product_detail.html',{"items" : item, 'category_list': category_list, 'item': items }) def post(self, request, item_id): item = request.POST.get('item') size = request.POST.get('Size') cart = request.session.get('cart') if cart: cart[item] = size else: cart = {} cart[item] = size request.session['cart'] = cart print(request.session['cart']) return redirect('products:detail', item_id=item_id) my views.py in which i want ot render session class Cart(View): def get (self, request): cart = request.session.get('cart', None) if not cart: cart = {} # or however you define your empty cart request.session['cart'] = cart ids = (list(cart.keys())) ids = (list(request.session.get('cart').keys())) item = Item.get_items_by_id(ids) print(item) return render(request, 'cart.html', {'items': item }) my html code {% for item in items %} <tbody style="margin-bottom: 20px;"> <tr> <th scope="row">{{forloop.counter}}</th> <td> <img src="{{item.first.url}}" alt="" height="100px"></td> <td>{{item.name}}</td> **<td>{{request.session.cart}}</td>** <td>{{item.price|currency}}</td> <td> <a href="#">Remove</a> </td> </tr> </tbody> {% endfor %} </table> </div> </div> so my session list has two values in it one is id and other is its size so want … -
Django FileField does not save unless in debug mode
I'm trying to upload files in Django 3.2 and am having a weird problem where the files save to the MEDIA_ROOT folder when I have the debugger on and set a breakpoint. But if I just run the project, then the files don't save. I cannot workout what is going on, but I would guess some sort of timing/threading issue? Any help appreciated. I have put my code below. I'm using FormModels to generate the forms and a Formset to allow multiple images to be uploaded. Models class TimestampedModel(d_models.Model): created_date = d_models.DateTimeField(auto_now_add=True) updated_date = d_models.DateTimeField(auto_now=True) class Meta: abstract = True class Case(TimestampedModel): class CaseType(d_models.IntegerChoices): One = 0, d_translation.gettext_lazy('One') Two = 1, d_translation.gettext_lazy('Two') # __empty__ = d_translation.gettext_lazy('Other') reference = d_models.CharField(max_length=32, editable=False) case_type = d_models.IntegerField(choices=CaseType.choices) def get_file_path(instance, file): return '{0}/{1}_{2}'.format(datetime.datetime.today().strftime('%Y-%m-%d'), uuid.uuid4().hex, file) class SourceMedia(TimestampedModel): class SourceMediaType(d_models.IntegerChoices): Image = 0, d_translation.gettext_lazy('Image') Video = 1, d_translation.gettext_lazy('Video') case = d_models.ForeignKey(Case, on_delete=d_models.CASCADE) mime_type = d_models.CharField(max_length=50, null=True) media_file = d_models.FileField(upload_to=get_file_path) Forms: class CaseForm(d_forms.ModelForm): def __init__(self, *args, **kwargs): super(CaseForm, self).__init__(*args, **kwargs) class Meta: model = models.Case fields = ['case_type'] class SourceImageForm(d_forms.ModelForm): @classmethod def create_formset(cls, extra, max_num): formset = d_forms.modelformset_factory(models.SourceMedia, form=SourceImageForm, extra=extra, max_num=max_num) return formset class Meta: model = models.SourceMedia fields = ['media_file'] View def case_create(request): source_media_formset = forms.SourceImageForm.create_formset(extra=5, … -
Dependent Chained Dropdown Select List with Django - Not working
I am trying to build a dependant dropdown in a django form, but it is not working. I have followed videos and tutorials, but got no luck. I would like to select a brand of a car (make) and then a model of a car. The model depends on the car's brand, of course. I have followed this tutorial https://python.plainenglish.io/python-and-django-create-a-dependent-chained-dropdown-select-list-b2c796f5a11 Status: The "Make" dropdown works fine. The "Model" dropdown is never showing anything. It just does not work, but no error is shown... :S models.py from django.db import models from django import forms class Vehicle(models.Model): make = forms.CharField(max_length=30) model = forms.CharField(max_length=30) ...omitted forms.py from django import forms from .models import Vehicle import json def readJson(filename): with open(filename, 'r') as fp: return json.load(fp) def get_make(): """ GET MAKE SELECTION """ filepath = '/Users/alvarolozanoalonso/desktop/project_tfm/tfm/JSON/make_model_A.json' all_data = readJson(filepath) all_makes = [('-----', '---Select a Make---')] for x in all_data: if (x['make_name'], x['make_name']) in all_makes: continue else: y = (x['make_name'], x['make_name']) all_makes.append(y) # here I have also tried "all_makes.append(x['make_name']) return all_makes class VehicleForm(forms.ModelForm): make = forms.ChoiceField( choices = get_make(), required = False, label='Make:', widget=forms.Select(attrs={'class': 'form-control', 'id': 'id_make'}), ) ...omitted class Meta: model = Vehicle fields = ['make', 'is_new', 'body_type', 'fuel_type', 'exterior_color', 'transmission', 'wheel_system', 'engine_type', 'horsepower', … -
How do I allow partial updates via POST request in Django?
Working on a small Django app and I've been asked to set up partial updates via POST request. I'm aware that PATCH works for partial updates out of the box but I don't have access to the front end and that's not what I've been asked to do. I was told it's a quick one line change, so I'm assuming I have to update the serializer as explained in the DRF docs (https://www.django-rest-framework.org/api-guide/serializers/#partial-updates) but I'm not sure where to do that exactly. Serializers: from rest_framework import serializers from cat.models import Cat class CatSerializer(serializers.ModelSerializer): class Meta: model = Cat fields = ( 'id', 'name', 'breed', 'birth_date', 'added_at', 'description') Viewset: from rest_framework import viewsets from cat.serializers import CatSerializer from cat.models import Cat class CatViewSet(viewsets.ModelViewSet): queryset = Cat.objects.all().order_by('-birth_date') serializer_class = CatSerializer