Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query taking a long time to run
I have created a query in get_context of a Class Based View from which I generate a dict I send into a Django template to display alongside a formset. The number of records returned is about 40 and it takes about 5 seconds to run - which will translate to 30 or 40 seconds with a full set of data. Looking at Django Debug Toolbar SQL queries, it is continuing to run 40 additional queries despite adding what look like the correct select_related and prefetch_related for the reverse related table to my queryset. My models (simplified for this example): class Item(models.Model): name = models.CharField(max_length=20, primary_key=True) description = models.CharField(max_length=35, blank=True, null=True) def __str__(self): return f"{self.name}" class ItemLocSite(models.Model): name = models.CharField(max_length=10, primary_key=True) models.CharField(max_length=10) class Meta: def __str__(self): return f"{self.name}" class ItemLoc(AbstractAddArchive): item = models.ForeignKey(Item, on_delete=models.PROTECT) iloc = models.ForeignKey(ItemLocSite, on_delete=models.SET_NULL, null=True, blank=True, related_name='iloc') nloc = models.ForeignKey(ItemLocSite, on_delete=models.SET_NULL, null=True, blank=True, related_name='nloc') cp_date = models.DateField(null=True, blank=True) posted_by = models.ForeignKey(User, on_delete=models.PROTECT, max_length=10, null=True, blank=True) class Meta: def __str__(self): return f"{self.item}" class ItemInfo(AbstractAddArchive): item = models.ForeignKey(Item, on_delete=models.PROTECT) log_entry = models.ForeignKey(Log, on_delete=models.PROTECT, null=True, blank=True) c = models.CharField(max_length=2, blank=True, null=True) crec_log_entry = models.ForeignKey(InvLog, on_delete=models.PROTECT, related_name='crec_log_entry', blank=True, null=True) csts = models.ForeignKey(ItemSts, on_delete=models.PROTECT, null=True, blank=True) cfill = models.IntegerField(blank=True, null=True) comment1 = … -
How can I use python magic on Heroku as well as local windows machine?
My django project uses python-magic. In order to get magic working on my local windows machine, I've had to install python-magic-bin, otherwise I faced the error "ImportError: failed to find libmagic. Check your installation". But when I push this dependency to my Heroku (linux) server, my build fails with the error "Could not find a version that satisfies the requirement python-magic-bin==0.4.14. No matching distribution found for python-magic-bin==0.4.14." I'm importing magic as "import magic". I've seen another answer here on an old post which said the issue came from using "from magic import magic", but that's not the case here. What do I need to do to get python-magic working on both setups? I dont want to have to remember to keep python-magic-bin out of the requirements.txt for the remote server. -
Accessing current user location and showing all the users near it
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to access user's current location and showing all the user that are nearby of the User. The Problem :- I don't know how to access the current location of user and show all the users near it. What i am using to access location :- I am using GeoDjango , GeoLocation , PostGis , gis to access location of user. All the requirements are successfully installed. models.py from django.contrib.gis.db import models from django.db.models import Manager as GeoManager class Location(models.Model): place_name = models.CharField(max_length = 80,default='') latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) location = models.PointField(null=True, blank=True) objects = GeoManager() def __unicode__(self): return self.place_name def save(self, *args, **kwargs): if self.latitude and self.longitude: self.location = Point(self.longitude, self.latitude) super(Foo, self).save(*args, **kwargs) views.py from django.contrib.gis.geos import Point from django.contrib.gis.measure import Distance lat = 52.5 lng = 1.0 radius = 10 point = Point(lng, lat) def location(request): near_users = Location.objects.filter(location__distance_lt=(point, Distance(km=radius))) context = {'near_users':near_users} return render(request, 'mains/near_users.html', context) When i run the code in browser then it shows nothing. What have i tried I tried places = Loc.objects.distance(user_location).first() method but it didn't worked … -
Django prevent direct url access
lets say I have a "Success Page" view. .urls urlpatterns = [ path('success/', views.inquiry_success, name='inquiry-success') ] .views def success(request) return render(request, 'success_page.html', {}) I can access this view directly by typing mysite.com/success in the browser even without going through the subsequent process that should result in showing that page. How do I prevent that? -
Two Serializers.py import each other
I have 2 apps in my django project and I have to import their serializers on each other. app1.serializer.py import food.app1 import serializers app2.serializer.py import food.app2 import serializers I am getting the error related to the circular import issue. I there any way I can import the serializer? -
How to start Count from 0 in django annotation?
I have the following code to count tickets related to each event. class EventManager(models.Manager.from_queryset(EventQuerySet)): def get_queryset(self): attendees_count = Sum(Case( When(~Q(ticket__ticket_number=""), then=1), output_field=models.IntegerField() )) return super(EventManager, self).get_queryset().annotate(attendees_count=attendees_count) the When(~Q(ticket__ticket_number=""), then=1) part exculdes all tickets which do not have a ticket number. It works well for events where is more than one valid ticket (if 4, shows 4). However, when there is no ticket associated, it returns 1. Behaviour is like so; 0 related tickets - returns 1, 1 related ticket - 1, 2 related tickets - 2 etc. How to start counting from 0? so 0 related tickets - returns 0? -
Is it possible to allow a user to create a group and then add users to a group without the admin aspect?
Currently testing what i can do with django, I get that I'm able to query set users but Is it possible to allow users to add people to groups that they've created. Any group-related documentation I've found for django has been admin based. Does this require creating a new model for group? -
Django - How to send location info from template (that uses Maps Javascript api) to database
I have a simple django project that currently only displays a map with the users location that updates every 30 seconds. The location is found using googles Maps Javascript api within the template. What I need to do is send the location info to the database from the html template every time the location updates. Any answers I've seen to similar stuff use forms that require some sort of user interaction. What I need is for the info to be automatically sent to the database every time the location is updated without any user interaction. Basically, is there a way to continuously send a variable created in a templates javascript back to the database without user interaction? (The django project only has one page that only gets and shows the user location on a map so it is very basic at the moment.) -
Django - can we make a model inherit itself?
I wonder whether we can make a model that have a child inheriting the same class like: class A(models.Model): #something class B(models.Model): parent = models.ForeignKey(A, on_delete=models.CASCADE) #and some B will have class B as a child -
Django Update Session Variable with AJAX
I am making a restaurant application and I am making takeaway functionality.I currently have the basket quantity in a session variable that updates whenever the user adds an item to the basket. When they add to the basket, the whole page is refreshed. This is done by passing the FoodItem ID through the URL's via GET requests. I wish to implement AJAX in this scenario so that the session variable updates on the template and the whole page does not refresh. Current response when session variable updates: return HttpResponseRedirect("/takeaway_menu/") Url for updating the session variable: path('basket/update/<int:food_id>/', update_basket_view, name='update_basket'), Each food item form in template: <form method="get" action="{% url 'update_basket' food.id %}"> <label for="quantity">Quantity</label> <button id="increment" name="increment" type="button" onclick="decreaseQuantity(this)">-</button> <input class="quantity" id="quantity" name="quantity" type="number" value="1"> <button id="increment" name="increment" type="button" onclick="increaseQuantity(this)">+</button> <input type="submit" value="Add to Cart"> </form> how I am displaying session variable in template <a id="basket" href="{% url 'basket' %}">Basket: {{ request.session.item_quantities }} items <i class="fa fa-shopping-basket" aria-hidden="true"></i></a> Is it possible to do? I can't figure out a way to do this. -
foreign key linked field "Author" of a table "skills" is always empty in the database
I am building a web application where students can see the job posts posted by tutors. tutors can login into the site and post jobs. I created a "my post" page for tutors to see all their posts and Edit, Delete them. It seems that a foreign key field "author" comes empty in the database after posting a job which makes the post not to show up in my posts. Please help. Here is my models.py for Skills: class Skill(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) teacher_name = models.CharField(max_length=50) skill_type = models.CharField( max_length=30, choices=SKILL_CHOICES, ) name = models.CharField(max_length=65) duration = models.IntegerField() cost = models.IntegerField() location = models.CharField(max_length=65) def __str__(self): return str(self.skill_type + " " + self.name) Here is my urls.py urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), path('post/<int:id>', views.post, name='post'), ] views.py for postskill and post(postskill is a modelform) @login_required def postskill(request): if request.method == 'POST': print(request.user.id) print(request.user.username) form = PostRecord(request.POST) if form.is_valid(): data = form.cleaned_data s = Skill( # author = request.user.id, teacher_name = request.user.username, skill_type = data.get('skill_type'), name = data.get('name'), duration = data.get('duration'), cost = data.get('cost'), location = data.get('location'), ) s.save() allskills = Skill.objects.all().order_by('name') return render(request, 'home.html', {'skills': allskills}) … -
Pending request to 3rd party API freezes all other django requests/endpoints
I use Django 2.2.6, python 3.7 and requests 2.25.1. Since I have started consuming a 3rd party APIs, I have noticed that if the request to this 3rd party API takes too long to respond, in the meanwhile all my Django endpoints are freezed, waiting for it. For instance, lets say I have these 2 endpoints in my Django: ENDPOINT A - GET a certain product (e.g. /product/{id}/): def get_product(request, id): product = Product.objects.get(pk=id) return JsonResponse(product) ENDPOINT B - POST a payment to a 3rd party API (e.g. /product/{id}/payment/): import requests def pay_for_product(request): payload = json.loads(request.body) response = session.post(url='https://api.paymentprocessorXPTO.com/pay/',data=payload) content = json.loads(response.content) return JsonResponse(content) For code simplicity reasons, I would like the ENDPOINT B to wait for the 3rd party API response syncronously and send it back to the user, as the code above. Thus I have not tried or wished for using a queue (e.g. celery / django-rq). The problem is: with the current code, if the session.post(...) in ENDPOINT B takes for example 20 seconds, all my Django endpoints are unavailable for 20 seconds. For instance, while a payment is being made by a client, all other client's GET product requests (ENDPOINT A) will take 20 seconds instead … -
How to instantiate a class just after starting Django server and access its members later in views.py
I want to define a class PacketCount in Django. class PacketCount: def __init__(): self.count_pkts = 0 def count_pkts(): #logic to count the number of packets I want to instantiate the object of PacketClass and continuously run the function count_pkts() just after starting starting the Django server using the command python manage.py runserver. views.py contains the following function: def index(request): # access PacketCountObj.count_pkts # return HttpResponse to display the value of PacketCountObj.count_pkts urls.py contains the following: urlpatterns = [ path('', views.index, name='index'), ] I am unable to figure out a way to automatically instantiate PacketCount class, call PacketCountObj.count_pkts() (possibly using a thread) on starting the Django server and then access PacketCountObj.count_pkts inside the views.py. I do not want to use databases, django sessions etc. -
Best free realtime database for android app
Hi am a novice user in android am plan to create a android app with realtime database, please some body refer which farmework/tool is best for develop android app and also refer Free realtime database. basically its a app with CRUD operation if anybody have sources please refer to me.. -
How to Configure Gunicorn - Heroku
I have deployed a Django application on Heroku. I am using ClearDB - MySQL as Database and trying to populate database with excel file containing data. I have succcessfully implemented and tested the webapp on localhost using phpmyadmin. The deployed application throws me an application error everytime I try to upload the excel file. Error Logs I have tried to update gunicorn configuration but have failed as I do not know how to do that I have tried reading the documentation and have tried running server but there is no effect whatsoever and I have a hunch that it is because something else to be done as it is deployed on heroku not a linux server independently. I need help on urgent basis. It will be highly appriciated if you can help me solve this issue or point me in the right direction. The actions I am performing is: reading a excel file in a dataframe cleaning and separating data into multiple tables. running df.to_sql() to upload multiple tables one by one to the MySQL database. No. of rows approximately ~ 400+ -
How do I do conditional rendering in Django Rest framework?
For example, if "localhost:8000/member/memberlist?wantjson=True" is returned in json format or If "localhost:8000/member/memberlist?wantexel=True", I want to write a code that returns to exel. How do I do it here? This is my code.. class MemberViewSet(XLSXFileMixin, ReadOnlyModelViewSet): def get_renderers(self): self.renderer_classes = [XLSXRenderer, JSONRenderer] for renderer in self.renderer_classes: print(renderer) return [renderer() for renderer in self.renderer_classes] @action(detail=False, methods=["get"], url_path="memberlist") def memberlist(self, request): result_json= request.data('wantjson') result_exel= request.data('wantexel') if result_json : self.renderer_classes= JSONRenderer elif result_exel: self.renderer_classes= XLSXRenderer resultList = Member.objects.all() serializer = MemberSerializer(resultList, many=True) return Response(serializer.data) -
searching multiple tags django taggit
I wanna add a tag system that i could search for multiple tags i know i could use taggit but it doesnt allow for a multiple tag searching and i want to select tags from a list and add multiple tags like this one from groups here is my tags genres =( ("FPS", "FPS"), ("RPG", "RPG"), ("Action-Adventure", "Action-Adventure"), ("Anime", "Anime"), ("Series/Movie Games", "Series/Movie Games"), ("Indie", "Indie"), ("Online", "Online"), ("Coop", "Coop"), ("Great Story", "Great Story"), ("Great Environment", "Great Environment"), ("Horror", "Horror"), ("Underrated", "Underrated"), ("Third Person", "Third Person"), and here's models class Post(models.Model): picture = models.CharField(max_length=100,default='') names = models.CharField(max_length=100,default='') critique = models.TextField(default='') score = models.IntegerField(default=50) genre = models.CharField(max_length=100,choices=genres,default='____') -
create an appointment app with registered user and non registered user in Django
I want to create an appointment app with Django with the following condition: doctors and reception can add appointments for registered patients patient who already register can add appointment only for them self doctors and reception can add appointments for non register patient(Temporary patient, for example) in the first and the 2nd condition, no need for adding information about the patient (because he adds them) in the 3rd doctor and reception have the ability to add information i'm trying with this but for now i'm stuck here is my models.py class User(AbstractUser): STATUS_CHOICES = (('paitent', 'paitent'), ('Doctor', 'Doctor'), ('reception', 'reception'), ('temporary', 'temporary')) STATUS_CHOICES_2 = (('yes', 'yes'), ('no', 'no')) type_of_user = models.CharField(max_length=200, choices=STATUS_CHOICES, default='paitent') allowd_to_take_appointement = models.CharField(max_length=20, choices=STATUS_CHOICES_2, default='yes') def is_doctor(self): if self.type_of_user == 'Doctor': return True else: return False def is_paitent(self): if self.type_of_user == 'paitent': return True else: return False def is_reception(self): if self.type_of_user == 'reception': return True else: return False def is_temporary(self): if self.type_of_user == 'temporary': return True else: return False def can_add_appointement(self): if self.allowd_to_take_appointement == 'yes': return True else: return False class Profile(models.Model): BLOOD_GROUPS = [ ('O-', 'O-'), ('O+', 'O+'), ('A-', 'A-'), ('A+', 'A+'), ('B-', 'B-'), ('B+', 'B+'), ('AB-', 'AB-'), ('AB+', 'AB+'), ] GENDER_CHOICES = (('M', 'Male'), ('F', … -
Case Insensitive search with POstgres Similar To
I have such query in my Django code cond = self.text_query(field.id, f''' EXISTS( SELECT * FROM {self.fieldvalue_db_view} WHERE entry_id = {self.db_table}.id AND {self.fieldvalue_db_view}.field_id = {field.id} AND {self.fieldvalue_db_view}.{text_search_column} SIMILAR TO %(pattern)s ) ''', dict(pattern='%' + val + '%')) When val = '%%john smith%%' or val = '%%john%smith%%' it did not return a result like 'John smith', but if val = '%%john%smith%|%smith%john%%' it returns results with 'John smith'. How this case sensitiveness can be solved? Thanks, -
How to execute PostgreSQL query in Django
I am trying to fetch the PostgreSQL table onto HTML using Django, When I execute the spatial query in the query Tool of PostgreSQL I got the perfect results, but When I'm trying to execute the same script from Django getting all rows of data. Thank you for helping in advance. SQL query which is working perfectly SELECT * FROM jhk_schls as point,jhk_urban as polygon WHERE ST_Within(point.geom, polygon.geom) Django Script def search(request): if request.method == "POST": first_layer = request.POST.get('first_layer') spati_func = request.POST.get('spa_func') second_layer = request.POST.get('secon_layer') within_fun = 'select * from' + " " + str(first_layer) + " " + 'as point,' + str(second_layer) + " " + 'as polygon' + " " + 'WHERE' + " " + str(spati_func)+'(point.geom, polygon.geom)' cursor = connection.cursor() cursor.execute(within_fun) data = cursor.fetchall() return render(request, 'geoit/search.html',{ 'data':data}) return render(request,'geoit/search.html') HTML <span>Select Layer</span> <select name="first_layer"> <option value="-1" disabled selected >Please select</option> Layer<li><option value="jhk_schls">jhk_schls</option></li> </select> </br> <span>Spatial Functions</span> <select name="spa_func"> <option value="-1" disabled selected >Please select</option> Layer<li><option value="ST_Within">ST_Within</option></li> </select> </br> <span>Select Layer</span> <select name="secon_layer"> <option value="-1" disabled selected >Please select</option> Layer<li><option value="jhk_urban">jhk_urban</option></li> </select> <input type="submit" value="submit"> </p> </div> </form> <button type="submit" value="submit"><i class="fa fa-search"></i> </button> </form> <p></p> <center> <table> {% for item in data %} <tr> <td>{{ item.0 … -
StreamingHttpResponse doesn't block other requests in wsgi but does on channels asgi
Recently I wrote a django wsgi server. it has a webcam stream and at the same time handles requests like get users or save image and other stuff. in the wsgi vesion the server worked flawlessly. at the sametime that the stream was showing footage the other requests could be handled and the server wasn't blocked. but when i switched to channels asgi because i wanted the websocket feature all fell apart. when the stream started the entire server froze and not even the websocket connected. even if the websocket was connected before the stream when the stream starts nothing works. WSGI Version def get_stream(): cap = cv.VideoCapture(0) while True: frame, _ = cap.read() valid, img = cv2.imencode('.jpg', frame) yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + img.tobytes() + b'\r\n\r\n') @api_view(['GET']) def stream(): return StreamingHttpResponse(get_stream(), content_type='multipart/x-mixed-replace;boundary=frame') @api_view(['GET']) def get_users(): .... ASGI Version def get_stream(): cap = cv.VideoCapture(0) while True: frame, _ = cap.read() valid, img = cv2.imencode('.jpg', frame) yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + img.tobytes() + b'\r\n\r\n') @api_view(['GET']) def stream(): return StreamingHttpResponse(get_stream(), content_type='multipart/x-mixed-replace;boundary=frame') @api_view(['GET']) def get_users(): .... class consumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, code): self.close() def receive(self, text_data=None, bytes_data=None): pass -
JsonRespone() not working in django when using formvalidation.io
I am using formvaladation.io for HTML form validation and I save data using ajax when I press the submit button data inserted successfully into the database, but JsonResponse() print dictionary like {'saved':1} to the webpage instead of giving javascript alert, then I figure out this thing happens because of I using formvalidation.io, when I don't use form validation it's working properly and JsonResponse return data to ajax success function and give javascript alert in the page. so I think there is some mistake in the form validation javascript file, I request you to help further in my code. HTML FILE <form method="post" id="patient"> {% csrf_token %} *** // All input tags are here i am not able to show it because there are many input box *** <div class="card-footer"> <div class="d-flex justify-content-end"> <input type="submit" class="btn btn-light-success btn-lg mr-2 font-weight-bold"> <input type="reset" class="btn btn-light-danger btn-lg font-weight-bold"> </div> </div> </form> Ajax call from HTML FILE <script> $(document).on('submit', '#patient', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url ' Patient: add ' %}', data: $("#patient").serialize(), dataType: 'json', success: function (data) { if (data.saved === 1) { alert("Data Saved"); } } }); }); </script> patient_valadation.js FILE var form = document.getElementById('patient'); document.addEventListener('DOMContentLoaded', function(e) { … -
Django filters form doesn't change the list of hotels
i have a search view that takes input from a search bar and returns a list of hotels in search_results.html class SearchResultsView(ListView): model = Hotel template_name = 'search_results.html' context_object_name = 'hotels_list' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = HotelFilter(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self): if not self.request.session['myCountry']: self.request.session['myCountry'] = self.request.GET.get('myCountry') self.request.session['myCity'] = self.request.GET.get('myCity') or '' self.request.session['myDeparture'] = self.request.GET.get('myDeparture') self.request.session['myArrival'] = self.request.GET.get('myArrival') self.request.session['myPeople'] = self.request.GET.get('myPeople') country = self.request.GET.get('myCountry') or self.request.session['myCountry'] city = self.request.GET.get('myCity') or self.request.session['myCity'] start_date = self.request.GET.get('myDeparture') or self.request.session['myDeparture'] end_date = self.request.GET.get('myArrival') or self.request.session['myArrival'] people = self.request.GET.get('myPeople') or self.request.session['myPeople'] results = Hotel.objects.raw('select h.id, h.single_rooms_number - coalesce(sum(r.single_rooms_number), 0) as SR, ' 'h.double_rooms_number -coalesce(sum(r.double_rooms_number), 0) as DR, ' 'h.twin_rooms_number - coalesce(sum(r.twin_rooms_number), 0) as TR, ' 'h.triple_rooms_number -coalesce(sum(r.triple_rooms_number), 0) as TRR, ' 'h.apartments_number - coalesce(sum(r.apartments_number), 0) as AR ' 'FROM globe_hotel h ' 'LEFT JOIN (SELECT * FROM globe_reservations WHERE start_date >= %s or end_date <= %s) r on h.id=r.hotel_id_id ' 'LEFT JOIN globe_city ci on h.city_id_id=ci.id ' 'LEFT JOIN globe_country ct on ct.id=ci.country_id_id ' 'WHERE LOWER(ct.name::text) = LOWER(%s) ' 'GROUP BY h.id ' 'HAVING coalesce(h.single_rooms_number, 0) - coalesce(sum(r.single_rooms_number), 0) + ' '(coalesce(h.double_rooms_number, 0) - coalesce(sum(r.double_rooms_number), 0))*2 + ' '(coalesce(h.twin_rooms_number, 0) - coalesce(sum(r.twin_rooms_number), 0))*2 + ' '(coalesce(h.triple_rooms_number, 0) -coalesce(sum(r.triple_rooms_number), 0))*3 + ' … -
Unable to display custom error message in django template
I am new in python django framework. I am trying to display custom validation error message in registration form template but i am not able to display custom validation error message in registration template. Please review my code below and let me know what i am doing wrong in my project. Thanks views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import CreateUserForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required def index(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Your account was created.') return redirect('login') context = {'form': form} return render(request,'register.html',context) form.py from django.db import models from django.forms import ModelForm, fields from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), error_messages = {"required":"The first name field is required"}) last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}),required=False) username = forms.CharField(widget = forms.TextInput(attrs={'class': 'form-control'}), error_messages = {"required":"The username field is required"}) email = forms.EmailField(widget=forms.TextInput(attrs={'class':'form-control'}), error_messages = {"required":"The email field is required"}) password1 = forms.CharField(label = 'Password',widget=forms.PasswordInput(attrs={'class':'form-control'}), error_messages = {"required":"The password field is required"}) password2 = forms.CharField(label = 'Password Confirm',widget=forms.PasswordInput(attrs={'class':'form-control'}), error_messages ={ "required":"The password confirm field is required"}) class Meta(UserCreationForm.Meta): … -
Why my form.py can't read field HEIGHT from models?
I am trying to run my app, however I get this error: NameError: name 'HEIGHT' is not defined This is my models.py: from django.db import models from django.forms import ModelForm HEIGHT = [ ('XS', 'Extra Small'), ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ('XL', 'Extra Large')]class Dog(models.Model): class Dog(models.Model): name = models.CharField(max_length=20) age = models.IntegerField(null=False) weight = models.IntegerField(null=False) height = models.CharField(max_length=2, choices=HEIGHT, null=False) class DogForm(ModelForm): class Meta: model = Dog fields = ['name', 'age', 'weight', 'height'] This is my forms.py: from django import forms class DogForm(forms.Form): name = forms.CharField(max_length=20) age = forms.IntegerField() weight= forms.IntegerField() height = forms.CharField(max_length=2, widget=forms.Select(choices=HEIGHT)) What am I doing wrong?