Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Move Placeholder To Top on Focus And While Typing in django default form?
Register Page:- <div class="login-area"> <form method="POST" class="login-form" > <h3>Sign Up</h3> <br> {% csrf_token %} <div class="form-group textinput"> {% for fields in form %} {{fields}} <br> {% endfor %} </div> <button class="btn btn-primary" type="signup">SignUp</button> </form> <div> </div> </div> Forms.py:- class UserRegisterForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'validate','placeholder': 'Enter usrname'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder':'Password'})) fullname = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Enter fullname'})) email=forms.EmailField(widget=forms.TextInput(attrs={'placeholder':'Enter Email'})) password2 = None class meta: model = User fields = ['fullname','username','email','password1'] -
Django cached template loader: exclude template from cache, or clear cache without restart
I use Django's cached template loader to speed up my site: TEMPLATE_LOADERS = ( ('django.template.loaders.cached.Loader', ( .... )), ) Is there a way to exclude specific templates from being cached? I have a template that I change a fair amount and I'd like to avoid having to restart my project every time I make a change to the template. Or, maybe a way to clear all cached templates without restarting the project? I did see this Resetting cache for Django cached template loader. Maybe that can be used to exclude a template but, if so, I'm not seeing how to use it. -
Get different data from Django views In table
I have CBV like this: class MyTableViews(TemplateView): template_name = "table.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['tables'] = Table.objects.all() return context And I have tables like this: <table id="t_add_row" class="table"> <thead> <tr> <th>Header1</th> <th>Header2</th> <th>Header3</th> <th>Edit</th> </tr> </thead> <tbody> {% for item in tables %} <tr> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td>{{ item.address }}</td> <td> <button type="button" class="edit" data-target="#rowEditModal">x</button> </td> </tr> {% endfor %} </tbody> </table> That table produce something like this: |Header1| Header2 | Header3 | Edit | | 1 | Name1 | Address1 | x | | 2 | Name2 | Address2 | x | | 3 | Name3 | Address3 | x | And I have modal form in same templates, that targeted from above table for ID=#rowEditModal: <div class="modal-content" id="rowEditModal"> {% for t in tables %} <div class="modal-body"> <form> <div class="form-group"> <label for="message-text" class="control-label">Header1:</label> <input type="text" class="form-control" id="header1" value="{{ t.id }}"> </div> <div class="form-group"> <label for="message-text" class="control-label">Header2:</label> <input type="text" class="form-control" id="header2" value="{{ t.name }}"> </div> <div class="form-group"> <label for="message-text" class="control-label">Header3:</label> <input type="text" class="form-control" id="header3" value="{{ t.address }}"> </div> </form> </div> <div class="modal-footer"> <button id="btn-updaterow" class="btn">Update</button> </div> {% endfor %} </div> But when I click Edit button (x) for each row then it display same data … -
Django rest_api and React
I am creating an am using Django and React. I have created custom user model api in Django using rest-framework, but i am confused about the whole login and signup system. Do we create login and signup modules in Django or React. Can anyone please guide me through it, or suggest any tutorial. -
Why the datas are differents between posgresql and elasticsearch?
I have a problem with django-elasticsearch-dsl. The value of a ImageField is modified, when this value is indexed in elasticsearch. My model : class Pro(models.Model): [...] photo1 = models.ImageField(upload_to='photos/') My document : [...] class Django: model = Pro # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'photo1', ] The result : In posgresql database : photo1 : "photos/default.jpg" In elasticsearch : photo1 : "/media/photos/default.jpg" Why "/media" is added ? I use easy_thumbmail like this : {% thumbnail pro.photo1 240x166 crop %} It's works when pro.photo1 == "photos/default.jpg" but not when pro.photo1 == "/media/photos/default.jpg" -
AssertionError: The field '' was declared on serializer '' but has not been included in the 'fields' option. optional
Im, using Django Rest Framework to make an APIRest but I got this error when trying to make a simple crud for the discount resource This is my model class Discount(BaseModel): """ Discount Model. """ code = models.CharField(max_length=50) rate = models.DecimalField( max_digits=3, decimal_places=2) class DiscountStatus(models.TextChoices): ENABLED = 'ENABLED' DISABLED = 'DISABLED' REDEEMED = 'REDEEMED' status = models.CharField("status", choices=DiscountStatus.choices, default=DiscountStatus.ENABLED, max_length=10) insurance_company = models.ForeignKey("sanitas.InsuranceCompany", on_delete=models.CASCADE) appointment = models.ForeignKey("sanitas.Appointment", verbose_name="appointment", on_delete=models.CASCADE, blank=True, null=True) class Meta(): """ Meta class. """ db_table = 'discounts' This is my serializer class DiscountModelSerializer(serializers.ModelSerializer): """ Insurance company model serializer. """ insurance_company = InsuranceCompanyModelSerializer(many=False, read_only=True, allow_null=True, required=False) insurance_company_id = serializers.IntegerField(allow_null=True, required=False,) appointment = AppointmentModelSerializer(many=False, read_only=True, allow_null=True, required=False) appointment_id = serializers.IntegerField(allow_null=True, required=False) class Meta(): """ Meta class. """ model = Discount fields = ( 'id', 'code', 'rate', 'status', 'appointment' 'insurance_company' 'insurance_company_id' 'appointment_id' ) And this is my Viewset class DiscountViewset(viewsets.ModelViewSet): """ Schedule items will be the time unit to manage appointments. """ queryset = Discount.objects.all() serializer_class = DiscountModelSerializer @action(methods=['post'], detail=False) def generate(self, request): """ Create dicounts in bulk. """ rate = 1 - request.data['rate'] / 100 insurance_company = get_object_or_404(InsuranceCompany, pk=request.data['insurance_company_id']) count = 0 amount = request.data['amount'] response = [] while count < amount: code = insurance_company.code + randomString(8) discount = … -
How can I add a comment to user on an app that has a relationship many-to-many with another model that has a relationship with other?
I get a huge stuck. now I have many of models which has a relationship between them at many apps I 'll explain that as following: - The first model is (UserProfile) that has (one to one) relation with (User) model also, I have (UserAsking) that has relation (ForeignKey) with (UserProfile) and last part is (Comment) That has (Many to many) relations with (UserAsking). in this case, I want to make a comment and this comment that has a relationship with UserAsking model. I'm in trouble, how can I do that? I find that (many-to-many) is different from any another relationship and I can't get the instance as an argument in (Comment) model if anyone can give me any help? thank you in advance account/models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save CHOICE = [('male', 'male'), ('female', 'female')] class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) overview = models.TextField(editable=True, blank=True, default='You have no an Overview yet') city = models.CharField(max_length=20, blank=False) phone = models.IntegerField(default=0, blank=True) sex = models.CharField(max_length=10, default='male', choices=CHOICE) skill = models.CharField(max_length=100, default='You have no skills yet') logo = models.ImageField(upload_to='images/', default='images/default-logo.jpg', blank=True) def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(receiver=create_profile, sender=User) community/models.py … -
NOT NULL constraint failed: food_app_recipe.user_id in django
I am getting this error i don't know what's the issue. I am very beginner in django. The error here is NOT NULL constraint failed: food_app_recipe.user_id when i trying to post data from template. Help with the error here Here is my Models.py from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=20,null=True) email = models.CharField(max_length=100,null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Recipe(models.Model): name = models.CharField(max_length=50,null=True) steps = models.TextField(max_length=1000,null=True) image = models.ImageField(null = True, blank = True) ingredients = models.CharField(max_length=100, null=True) description = models.TextField(max_length=1000,null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name Here is my forms.py from django import forms from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Recipe class SignupForm(UserCreationForm): username = forms.CharField(max_length=30) email = forms.EmailField(max_length=200) class Meta: model = User fields = ['username','email','password1','password2'] class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name','steps','image','ingredients','description'] Here is my Views.py from django.shortcuts import render, redirect from .forms import SignupForm,RecipeForm from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import User,Recipe # views here @login_required(login_url='blog-login') def add_recipes(request): user = request.user form = RecipeForm(instance=user) if request.method == "POST": print('printing post:',request.POST) form = RecipeForm(request.POST,request.FILES) if form.is_valid(): … -
Data structure keeping the order of ManyToMany items
For example, There are two lines and a few stations. Line X Station A - Station B - Station C - Station D Line Y Station E - Station F - Station B - Station G Line X and Y are crossing at Station B So my tables are like this below Line Table 1 X "LineX" 2 Y "LineY" Station Table 1 A X 2 B X,Y 3 C X 4 D X 5 E Y 6 F Y 7 G Y Models are like this (This is django but using doctrine are almost same.) class Line(models.Model): name = models.CharField(unique=True,max_length=255) def __str__(self): return self.name class Station(models.Model): name = models.CharField(unique=True,max_length=255) lines = models.ManyToManyField(Line) def __str__(self): return self.name In this case, you can get the stations of LineX easily. SELECT from station table where line (which include) Y return A,B,C,D However for LineY it returns B,E,F,G but B is not the top. It's third station. I think I should add some column to maintain the order of each lines. What is the best practice for structure keeping the order of manytomany items? I am familliar with Doctorine2 and django models. I would appreciate any help of you. -
Group all queryset baes on perticular value present in queryset
I have model: class Pizza(model.Models): name = models.Charfield(max_length=100) type = models.Charfield(max_length=50) and my data is like: id name type 1 a x 2 b y 3 c x 4 d x 5 e y And I want result like that: result = {"x": [<queryset: a>, <queryset:c>, <queryset:d>], "y": [<queryset:b>, <queryset:e>]} in one query -
Can I subtract or add two or more columns' values with "dictsort" filter in Django templates?
I have this code {% for answer in question.answers.all|dictsortreversed:"upvoters.count" %} ... {% endfor %} where each answer has 2 ManyToMany fields of Users, upvoters and downvoters. The code above sorts question.answers.all by the number of upvoters. What I want is to sort question.answers.all by the difference between the number of upvoters and the number of downvoter (or number_of_upvoters - number_of_downvoters) Basically, I want something like this: {% for answer in question.answers.all|dictsortreversed:"upvoters.count - downvoters.count" %} ... {% endfor %} -
Multiple forms in single forms in Django?
I have been looking at the documentation and thought maybe inline-formsets would be the answer. But I am not entirely sure. What I want is I have Total five models. class User(AbstractUser): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) age = models.IntField(max_length=100) dob = models.DateField(max_length=12) address = models.CharField(max_length=200) def __str__(self): if (self.user.first_name != None): return self.user.first_name else: return self.user.username class StudentBranch(BaseModel): student = models.ForeignKey(Student, on_delete=models.CASCADE) branch = models.ForeignKey(Branch, on_delete=models.CASCADE) class StudentSubject(BaseModel): student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) class SubjectBook(BaseModel): subject_name = models.ForeignKey(StudentSubject, on_delete=models.CASCADE) book_name = models.CharField(max_length=100, blank=True) author = models.CharField(max_length=100, blank=True) publisher = models.CharField(max_length=100, blank=True) published_in = models.CharField(max_length=10, blank=True) StudentBranch, StudentSubject will have more entries per user and last two model wanted to be nested StudentSubject can have many SubjectBooks. All Models under one submit button. I tried some examples with 2 models but in my code i have many models -
Django - model, queryset filtering - How to filter multiple models but render in order
It's a bit tricky to describe the puzzle but please bear with me: Model.py So I've got 3 models: Category, SubCategory and Item. You probably can tell their relationship to each other by the names: A category -> many subcategories -> many many items, OR A category -> many many items The page (the template) is rendered in such order as well: --- Category --- -- Subcategory -- Item Item Item Item Item Item -- Subcategory -- Item Item Item Item Item Item --- Next Category (doesn't have a subcategory) --- Item Item Item Item Item Item Item Item Item filters The users would be able to choose from 1. categories and subcategories, 2. brands/manufacturers of the items, 3. input min and max price difficulty: I find it difficult to filter the queryset based on multiple models, passing a valid queryset and context to render the page. For example: User has chosen Category 1 (which has got 3 Subcategories, each has 10 items): Category.objects.filter(pk=1); Then, User chooses brand B, and Brand is a model as well, each item has a ForiegnKey of brand: Item.objects.filter(brand__name=B); Now I'm not sure how to pass the context or rather 'what' to pass as the … -
How can i validate a serializer field with ModelSerializer. Does the validate() method get called on create or do i have to call the method
I have a serializer (ModelSerializer) where i need to validate a field which will be passed to the validate method. CompanySerializer class CompanySerializer(serializers.ModelSerializer): def validate_vat_number(self, vat_no): vatlayer = "http://apilayer.net/api/validate?access_key={api_key}&vat_number={VAT_NUMBER}".format(api_key=settings.VATLAYER, VAT_NUMBER=vat_no) vatlayer = json.loads(vatlayer) if vatlayer['valid'] is not True: raise serializers.ValidationError("VAT number not valid") return vat_no class Meta: model = Company fields = ('profile', 'name', 'address', 'currency', 'id_number', 'vat_number', 'vat_company_name', 'email', 'phone', 'fixed_phone') My question is, does the validate_vat_number method get called when the create method is triggered, and if so, how do i pass the vat_no parameter? If not, where do i call this method? And is it possible to do it without overwriting the create method? My view class CompanyAPI(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer It would be perfect if i could somehow validate without using @action in the view since that makes another endpoint. My goal is to validate and save the object with one post request -
Django Rss Feed add image to description
I am trying to use Django rss feeds to view feeds on rss viewer app. i used from django.contrib.syndication.views import Feed to create rss feeds but it only had 3 fields title, description and link i added custom fields by using from django.utils.feedgenerator import Rss201rev2Feed and it generates the extra fields with no issues but when i open it with a rss viewer it doesn't show those extra fields or the image My question is how can i make those extra fields show up in app ? does it not show up because app only shows title, description and link and those other fields are not processed ? so how can i embed image and other fields in description so it shows up (most importantly image show up) ? i have went over documentation many times can't seem to get it right. here is the view code from Django app class CustomFeedGenerator(Rss201rev2Feed): def add_item_elements(self, handler, item): super(CustomFeedGenerator, self).add_item_elements(handler, item) handler.addQuickElement(u"image", item['image']) handler.addQuickElement(u"seller_name", item['seller_name']) handler.addQuickElement(u"price", item['price']) class LatestPostsFeed(Feed): title = "www.marktplaats.nl" link = "/feeds/" description = "Updates on changes and additions to posts published in the starter." feed_type = CustomFeedGenerator def items(self): return Check_Ads_One.objects.order_by('title')[:5] def item_title(self, item): return item.title def item_description(self, … -
Best practice to display Celery tasks activity to front end user in Django
What is the best practice to display information to user during and at the end of a celery task. My user ahve the ability to generate Celery tasks via forms, I would like too give them access to a listview where they can see what the tasks as done, generate during the execution of the tasks, and if it is finished. Does I have to generate a table in my database whit these informatiosn to be able to display these informations, I would like something like django-loger-viewer but for front-end user. -
admin.site.register(Question) doesn't work
i am new to Django and python, and i want to start django admin with official exercises i'm okay with running server. but questions doesn't show up. my code is : admin.py from django.contrib import admin from .models import Question admin.site.register(Question) thank you for reading my question -
Join query on non primary key foreign key column in Django
I have two model, making unique key column as foreign key to other table. class Employee(models.Model): EmployeeId = models.IntegerField(unique=True) Employee_Name = models.CharField(max_length=100) class Release(models.Model): EmployeeId = models.ForeignKey(Employee, on_delete=models.CASCADE, to_field="EmployeeId") when i am trying join query it is doing join on primary key column on Employee table. below is the join query I am expecting join on Employee.EmployeeId =Release.EmployeeId r=Release.objects.all().select_related('EmployeeId') but above query gives print(str(r.query)) Output: 'SELECT "app_release"."id", "app_release"."EmployeeId_id", "app_employee"."id", "app_employee"."EmployeeId", "app_employee"."Employee_Name" FROM "app_release" INNER JOIN "app_employee" ON ("app_re lease"."EmployeeId_id" = "app_employee"."id")' which i don't want i.e, instead of ON ("app_release"."EmployeeId_id" = "app_employee"."id")' i want ON ("app_release"."EmployeeId_id" = "app_employee"."EmployeeId")' -
How to add variable in Django model
I want to add variable in Django model and I don't want to save it to database at the same time I want to return this variable to user when calling the endpoint. this is what i found in the web, but the problem is the variable is not rerun to user class User (models.Model): f_name = models.CharField(max_length=255) l_name = models.CharField(max_length=300) full_name = '' How to rerun the full_name to user when he call the api ? -
Using the value of Javascript variable in django template to render template context
Please do not mark this question as invalid. I didnt find any question in stackoverflow with the problem mentioned below. I have a django template. I pass the following context to it context = { '1_title': 'Title 1', '2_title': 'Title 2', '3_title': 'Title 3', '4_title': 'Title 4', } return render(request, 'index.html', context) I have a html file where i have a dropdown. The dropdown have values like 1,2,3,4. I have registered a onClick function to it. I need to achieve this functionality. I will get the value in onClick function. Then i will concatenate the received value with _title and store to it a javascript variable. Now i need to use that javascript variable to reference django context. I am not able to achieve this. I have googled and did extensive searching in stackoverflow. None seem to answer my question. the javascript function look like this function getContextValue(value) { var key = value + '_title'; return {{ key }} } If I select 1 in the dropdown, then the above function will have key as 1_title. I need to return the 1_title value from context which is Title 1. For me it doesn't work and returns 1_title only. I have … -
Starting and stopping to access location tracking of my cell phone
I am working on a project now a days which provides a lot of features related to location and all other stuff. I want to add a functionality of starting and stopping location tracking. I want to track the location of the android app user having the start and stop controls on my website. whenever I want I can start tracking the android application user and whenever I want I can stop it. A notification pop up will be shown to the android application user about location track. I have tried to find something similar but couldn't find any. any help will be really appreciated. -
ModuleNotFoundError: No module named 'App Name' when using Django and Gunicorn on a heroku server
What I am trying to do here is setup a sample django app in heroku server. When running the app with gunicorn I get this error This is what's in the log. 2020-02-14T12:11:30.549141+00:00 heroku[web.1]: State changed from crashed to starting 2020-02-14T12:11:41.607618+00:00 heroku[web.1]: Starting process with command `gunicorn leadmanager.wsgi --log-file -` 2020-02-14T12:11:44.346394+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-02-14T12:11:44.347348+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [4] [INFO] Listening at: http://0.0.0.0:54007 (4) 2020-02-14T12:11:44.347349+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [4] [INFO] Using worker: sync 2020-02-14T12:11:44.351554+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [10] [INFO] Booting worker with pid: 10 2020-02-14T12:11:44.359278+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [11] [INFO] Booting worker with pid: 11 2020-02-14T12:11:45.104994+00:00 heroku[web.1]: State changed from starting to crashed 2020-02-14T12:11:44.664943+00:00 app[web.1]: [2020-02-14 12:11:44 +0000] [11] [ERROR] Exception in worker process 2020-02-14T12:11:44.664951+00:00 app[web.1]: Traceback (most recent call last): 2020-02-14T12:11:44.664953+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-02-14T12:11:44.664953+00:00 app[web.1]: worker.init_process() 2020-02-14T12:11:44.664954+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-02-14T12:11:44.664954+00:00 app[web.1]: self.load_wsgi() 2020-02-14T12:11:44.664955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-02-14T12:11:44.664955+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-02-14T12:11:44.664955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-02-14T12:11:44.664956+00:00 app[web.1]: self.callable = self.load() 2020-02-14T12:11:44.664956+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-02-14T12:11:44.664957+00:00 app[web.1]: return self.load_wsgiapp() 2020-02-14T12:11:44.664957+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-02-14T12:11:44.664957+00:00 … -
Django rest framework response items by category
I'm using Django rest framework serializer to return plans for a mobile application. For now my serializer response looks like this: [ { "id": 1, "nome": "Test", "localizacao": "Example - MG", "instituicao": "Example", "modalidade": "Example", "categoria": "Category 1", "frequencia_semanal": 1, "carga_horaria": 2, "quantidade_alunos": 2, "valor_unitario": "12.00", "taxa_matricula": "12.00", "informacoes_adicionais": "" } ] I need to separate plans by category so response structure must look like this: [ "Category 1": [ { "id": 1, "nome": "Test", "localizacao": "Example", "instituicao": "Example", "modalidade": "Example", "frequencia_semanal": 1, "carga_horaria": 2, "quantidade_alunos": 2, "valor_unitario": "12.00", "taxa_matricula": "12.00", "informacoes_adicionais": "" } ] ] The "categoria" value, must be keys and all plans belonging to that category must be contained in the key. there is my models.py class Plano(models.Model): PUBLICO_ALVO_MENORES = 1 PUBLICO_ALVO_ADOLESCENTES = 2 PUBLICO_ALVO_ADULTOS = 3 PUBLICO_ALVO_TODOS = 4 PUBLICO_ALVO_CHOICES = ( (PUBLICO_ALVO_MENORES, 'Menores'), (PUBLICO_ALVO_ADOLESCENTES, 'Adolecentes'), (PUBLICO_ALVO_ADULTOS, 'Adultos'), (PUBLICO_ALVO_TODOS, 'Todas as idades'), ) nome = models.CharField(max_length=200) localizacao = models.ForeignKey('Localizacao', on_delete=models.PROTECT) instituicao = models.ForeignKey('Instituicao', null=True, on_delete=models.PROTECT) modalidade = models.ForeignKey('PlanoModalidade', verbose_name='Modalidades', on_delete=models.PROTECT) categoria = models.ForeignKey('PlanoCategoria', verbose_name='Categorias', on_delete=models.PROTECT) publico_alvo = models.SmallIntegerField(choices=PUBLICO_ALVO_CHOICES, null=True) frequencia_semanal = models.PositiveSmallIntegerField(verbose_name='Frequência semanal') carga_horaria = models.PositiveSmallIntegerField(verbose_name='Carga horária diária') quantidade_alunos = models.PositiveSmallIntegerField(verbose_name='Quantidade de alunos') valor_unitario = models.DecimalField(decimal_places=2, max_digits=18, verbose_name='Valor unitário') taxa_matricula = models.DecimalField(decimal_places=2, max_digits=18, verbose_name='Taxa matrícula') informacoes_adicionais … -
What's the difference between 'verbose_name' and 'name' fields in a constructor of the Model class?
What's the difference between 'verbose_name' and 'name' fields in a constructor of the Model class? class Account(models.Model): name = models.CharField("Name of Account", "Name", max_length=64) I found that "Name of Account" is verbose_field and "Name" is name. I know verbose_field is used for a field name in Admin page. But I don't know where the name field is used for? createdAt = models.DateTimeField("Created At", auto_now_add=True) And why does the name not used in this field? -
Django says name 'form' not defined, but import exists
I have a user form and a profile form as below: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django_countries.fields import CountryField from .models import Profile class RegisterUserForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=100) class Meta: model = User fields = ['username','first_name','last_name','email','password1','password2'] class RegisterProfileForm(UserCreationForm): address = forms.CharField(max_length=120) postcode = forms.CharField(max_length=30) countrycode = forms.CharField(max_length=3) class Meta: model = User fields = ['address','postcode','countrycode'] These are imported into views.py in the code below and if valid... from django.shortcuts import render,redirect from django.contrib import messages from .forms import RegisterUserForm,RegisterProfileForm,UserUpdateForm,ProfileUpdateForm from django.contrib.auth.decorators import login_required def register(request): if request.method == "POST": u_form = RegisterUserForm(request.POST) p_form = RegisterProfileForm(request.POST) if u_form.is_valid and p_form.is_valid: from django import forms username = form.cleaned_data.get('username') first_name = form.cleaned_data.get('first_name') However, when I post the form I get "Name Error at register... name 'form' is not defined" and the offending line of code is: username = form.cleaned_data.get('username'), in other words as soon as I reference form.cleaned_data, django objects. This used to work. In desperation I imported django.forms just before referencing forms.cleaned_data (it wasn't there before) but unsurprisingly I still get "Name Error at register... name 'form' is not defined". Can anyone tell me what I might be …