Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UpdateView only possible within 15 minutes
I have a small app. In the model I have: created_at = models.DateTimeField(auto_now_add=True, default = 'time and date created'), Now I want that after 15 minutes of the created_at the UpdateView is no longer executable. however I just can't even display the creats_at class update_post(UpdateView): print(Posts.created_at) model = Posts ... This show only (<django.db.models.fields.DateTimeField>,) -
How can I run multiple Django servers from one Pycharm Project?
I want to be able to run three different Django servers from within 1 Pycharm project, however, when you go into: settings -> languages & frameworks -> Django it seems that you can only set 1 Django project root, 1 Django settings.py file, and 1 Django manage.py file for all the Django servers you have running. Short of creating a new Pycharm project for each Django server, which I do not want to do, is there any way I can have a separate configuration for each of the three Django projects? -
Saving centroid of a (multi)polygon as point geometry in a model
I have two tables, one with multipolygon geometries, the other with a column for point geometries. I want the centroid of the selected polygon to be saved as the point geometry for the other table. class matview_all_administrative_units(models.Model): lau_id = models.IntegerField(primary_key=True) ortsgemeinde = models.CharField(max_length=150) verwaltungsgemeinde = models.CharField(max_length=150) landkreis_bezirk = models.CharField(max_length=150) bundesland_kanton = models.CharField(max_length=150) staat = models.CharField(max_length=150) geom = models.MultiPolygonField(srid=4326) class Meta: managed = False db_table = 'administrative_hierarchy_full_geom' class site(models.Model): sid = models.AutoField(primary_key=True) site_name = models.CharField(max_length=250) site_notes = models.CharField(max_length=2500, blank=True, null=True) municipality = models.ForeignKey('local_administrative_unit', on_delete=models.PROTECT) geom = models.PointField(srid=4326) def __str__(self): return '{}, {} ({})'.format(self.sid, self.site_name, self.municipality) To add a new site, an existing administrative unit must be associated with it and the center of it's polygon should be used as the location/geometry of the site. For now I made this: class NewSiteView(CreateView): model = models.site form_class = forms.NewSiteForm template_name = 'datamanager/newsite.html' success_url = '/sites/' calling this form: from django.forms import ModelForm, HiddenInput from django.contrib.gis.db.models.functions import Centroid from . import models class NewSiteForm(ModelForm): class Meta: model = models.site fields = ['site_name', 'site_notes', 'municipality','geom'] widgets = { 'geom': HiddenInput(), } def clean(self): super().clean() self.cleaned_data['geom'] = Centroid(models.matview_all_administrative_units.objects.values('geom').filter(lau_id=self.cleaned_data['municipality'].lau_id)) however, this leads to this error: So I am basically not calculating a point but a 'centroid object' … -
Django: constraint with nullable multiple field conditions
I have a model in Django/PostgreSQL project and want to add following constraints to three nullable fields: either all fields are NULL, either all of them aren't. Here's code (simplified): class SomeModel(models.Model): ... a = models.IntegerField(nullable=True) b = models.DateTimeField(nullable=True) c = models.DateTimeField(nullable=True) ... class Meta: constraints = [ models.CheckConstraint( check=( (Q(a__isnull=True) & Q(b__isnull=True) & Q(c__isnull=True)) | (Q(a__isnull=False) & Q(b__isnull=False) & Q(c__isnull=False)) ) ) ] If I understand correctly, I've just described two possible states of those three fields. First is "all three are NULL", second is "none of them are NULL". But what I got, actually, is "none of them can be NULL". Django admin panel insists on filling all of the fields, they all are mandatory. How can I fix this behaviour? Thanks! -
After deploy django projcet,emal send doesn't work.Can anyone help me to fix that?
In my django project when ı am working localhost sending mail is working.After that ı deployed my project on aws,but at this time email send doesn't work.Can anyone explain this? My settings/base.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_PORT = '587' # EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_USE_TLS = True -
How can I show mi profile picture?
The photo is uploaded and saved in the database but I can't show the picture in the template. Now, what can I do? Where is the problem? What will be the logic? Settings: STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR] MEDIA_URL = '/media/' Urls: urlpatterns = [ path('admin/', admin.site.urls), path('', include('business_app.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views: def change_profile_picture(request): if request.user.is_authenticated: if request.method == "POST": profile_picture = request.FILES['profile_picture'] if 'profile_picture' in request.FILES else None user = get_object_or_404(User, pk=request.user.pk) if request.user.pk != user.pk: return redirect("/") Profile_picture.objects.create( Profile_picture = profile_picture, USer = request.user, ) return redirect("/") return render(request,'0_index.html') Models: class Profile_picture(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE, related_name="user_propic") Profile_picture = models.ImageField(upload_to="3_profile_picture/",default='3_profile_picture/avatar.png', null=True, blank=True) templates: <img src="static/1_images/3_about.jpg" alt="" width="100" class="img-fluid rounded-circle mb-3 img-thumbnail shadow-sm"> -
Can a textfield in postgres be used with a charfield in django?
I have a table in postgres with a column description that had the type varchar(2000), so in django: description = serializers.CharField(......., max_length = 2000) I want to change the description column in postgres to type text Can I leave the description as a charfield? Or do I have to change it to a textfield? I still want to have max_length specified but change it to 5000, ie: description = serializers.CharField(......., max_length = 5000) I've tried to read the docs: https://www.django-rest-framework.org/api-guide/fields/#charfield, but I didn't see it being stated explicitly. From what I've seen, it says: CharField corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField I'm guessing that means it's ok? I also looked around on stackoverflow: What's the difference between CharField and TextField in Django?, but I didn't see it being stated explicitly either. -
how to store user data from user model inside a database table in django
I have a Buyer table in mysql database and I want to take the username , email, password from User model ( default django model ) and store it inside Buyer table, Buyer model in models.py: class Buyer(models.Model): row_id = models.AutoField(primary_key=True) user_name = models.CharField(unique=True, max_length=50) user_password = models.CharField(max_length=16) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50) email = models.CharField(unique=True, max_length=100) home_phone = models.CharField(max_length=20, blank=True, null=True) mobile_phone = models.CharField(unique=True, max_length=20) personal_id = models.CharField(max_length=30, blank=True, null=True) idtype_fk = models.ForeignKey('Idtype', models.DO_NOTHING, db_column='idType_FK', blank=True, null=True) # Field name made lowercase. personal_id_country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='personal_id_country_FK',related_name='personal_id_country_fk') # Field name made lowercase. address_line_1 = models.CharField(db_column='address_Line_1', max_length=200) # Field name made lowercase. address_line_2 = models.CharField(db_column='address_Line_2', max_length=200, blank=True, null=True) # Field name made lowercase. p_o_box = models.CharField(max_length=20, blank=True, null=True) city = models.CharField(max_length=50) country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='country_FK' , related_name='country_fk') # Field name made lowercase. gender_fk = models.ForeignKey('Gender', models.DO_NOTHING, db_column='gender_FK') # Field name made lowercase. bdate = models.DateField() def __str__(self): return 'User: ' + self.user_name class Meta: managed = False db_table = 'buyer' and after the registration User/Buyer can add more information such as first name , mobile phone etc.. in the profile page -
Django - details of one account showing up on another account
I've have a pet registration system where the customer can log into their account and register their animals. However once you have registered the animal and log out and another user logs in that user can see all the pets of all users. I'm not sure what's causing this. my views.py def customer_profile(request): if request.method == "GET": if request.user.is_authenticated: get_pets = PetRegistration.objects.filter() context = { "pets": get_pets, } return render( request, "registration/customer-profile.html", context=context ) return redirect("login") if request.method == "POST": context = {} return render(request, "registration/customer-signup.html", context=context) def pet_register(request): if request.method == "GET": if request.user.is_authenticated: form = PetRegistrationForm() context = { "form": form, } return render(request, "registration/pet-register.html", context=context) return redirect("login") if request.method == "POST": form = PetRegistrationForm(request.POST, request.FILES) context = { "form": form, } if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect("customer_profile") return render(request, "registration/pet-register.html", context=context) model.py class PetRegistration(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) name = models.CharField(max_length=30) image = models.ImageField(null=True, blank=True) age = models.CharField(max_length=30) animal_type = models.CharField(max_length=30) vaccination_status = models.CharField(choices=STATUS, max_length=20) def __str__(self): return self.name -
Create relation number based on PK in Django
I am trying for a couple of days to find a way to create a relation number based on the PK in models.py when I make a new object. The reason why I try this is, is to have a 8 digit number starting from 00000001 till 999999999. I already tried the following: client.objects.latest('pk') Result NameError: name 'client' is not defined from clients.models import client Result: ImportError: cannot import name 'client' from partially initialized module 'clients.models' (most likely due to a circular import) def save(self, *args, **kwargs): self_pk = self.objects('pk') self.relation_number =self_pk self.save(*args, **kwargs) Result: AttributeError: Manager isn't accessible via Section instances Hope someone can help me with this. -
ValueError: invalid literal for int() with base 10: '-----'ValueError: invalid literal for int() with base 10: ''
Product(product_id2=prod_id2,shop=request.user,product_name=prod_name,category=category.objects.get(id=int(cat)),subcategory=subcategory,price=price,price_not=price_not,desc=desc,gst=gst_l,image1=image1).save() i tried int(float(Cat)) but its showing could not convert string to float: '-----' -
Why django can't recognize 2 path convertors from each other?
I have a django application and I have 2 url paths that are only different in the last part which is the path convertors: path('questions/<pk>', views.QuestionDetailView.as_view(), name='question_detail'), path('questions/<slug:tag_slug>', views.QuestionListView.as_view(), name='questions_by_tag') When I go to 127.0.0.1:8000/questions/1 it's ok and it shows the correct results, but when I go to 127.0.0.1:8000/questions/something(something is a slug) it says page not found!(It must use the seconed url path but it does not!) When I change the paths order it shows the second one correctly and the other one is a problem! Can anybody help me please? -
How to Check data is int, float in python
I know similar questions have been asked and answered before like here: How do I check if a string is a number (float or Int ) in Python? However, it does not provide the answer I'm looking for. What I'm trying to do is this: def is_int_or_float(s): try: a = float(s) return 1 if s.count('.')==0 else 2 except ValueError: return -1 val = input("Enter your value: ") data = is_int_or_float(val) print(data) What if User enters => "22" # Then Above code will gives -1.Please help me to resolve this -
How to save data from an online API to display it in Django rest framework?
I am trying to get pricing API from coinmarketcap and save them or display them locally in Django Rest framework on localhost? What different things should I do in my models.py? What different thing should I do in my views.py? I have created a requests.py with the header from which I want to get data/ API endpoint? How will I connect or store it in my models.py? At the moment my request.py file inside my API folder also gives an error of module import for requests? I have just simply created a request.py with endpoint url for getting data from coinmarketcap, where should I save it to display on drf frontend? import requests headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': ' MY API KEY', } res = requests.get("https://pro-api.coinmarketcap.com/v1/fiat/map", headers=headers) print(res.json()) print(res.text) Views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def getUrls(request): api_urls = { 'Crypto Prices': '/prices', } return Response(api_urls) models.py from django.db import models class Prices(models.Model): symbol = models.CharField(max_length=50) def __str__(self): return self.name -
Redirect to same page after form submitted in views.py not working while using Django paginator
I want to redirect to same page after submitting form which fetches view from views.py. The problem is paginator. After submitting Django form page reloads to page 1. I want browser to stay on the same page after submitting form. Error I get: django.urls.exceptions.NoReverseMatch: 'http' is not a registered namespace. Help would be greatly appreciated! Code calling path in js: let path = window.location.href Fetching api: subedit[i].addEventListener('click', () => { fetch(`/edit/${content[i].id}`, { method: 'POST', headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin', body: JSON.stringify({ post: textarea[i].value, page: path })}).then(() => { editdiv[i].style.display = 'none'; post[i].style.display = 'block'; })}) views.py: def edit(request, post_id): data = json.loads(request.body) content = data.get("post", "") post=Post.objects.get(id=post_id) page = data.get("page", "") if request.method == "POST": if post.user == request.user: post.post=content post.save() return HttpResponseRedirect(reverse(str(page))) -
CSRF verification failed. Request aborted in Django rest framework sending the request from flutter
I've followed everything mentioned in both documentation of Django rest-framework and Flutter http but still getting the error ..here is my code : Django Settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } View @csrf_exempt @permission_classes(["isAuthenticated"]) @api_view(['POST']) def chanage_image(request): data = {} if request.method == "POST": token = request.META['HTTP_AUTHORIZATION'][6:] lang = request.META['HTTP_LANG'] image = request.data['image'] main_user = Token.objects.get(key=token).user app_user = AppUser.objects.get(main_user=main_user) format, imgstr = image.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) # You can save this as file instance. app_user.image = data app_user.save() data = {"success": True, "details": AppUserSerializer( app_user).data, "message": "Image changed" if lang == "en" else "تم تغيير الصورة"} return Response(data, headers=get_headers()) URLS path('chanage_image/', chanage_image,name="chanage_image"), Flutter Request Map<String, dynamic> body = { "image": base64Image, }; Future<UserModel> changePlayerImage(Map<String, dynamic> body) async { return await httpClient.post('api/user/change-image', body: body, headers: {'referer': 'https://www.l-dawri.com/'}).then((response) { print(response.body); return UserModel.fromJson(response.body); }); } but still in the end am always getting this error : CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. -
Django Notify user execution state
When making a call to server I want the server to notify each time a "stage" has been completed instead of waiting complete execution. Let's say I have a call in views.py def some_call(request): final_body = long_process_with_stages() return HttpResponse(json.dumps(finalbody)) # I need to change this # return StreamingHttpResponse(long_process_with_stages()) where def long_process_with_stages(): sleep(30) print("Stage 1 completed") sleep(30) print("Stage 2 completed") sleep(30) print("Stage 3 completed") sleep(30) return "This is the final response" I tried the StreamingHttpResponse but method kept being called even after it finished Is it possible to achieve this? -
Resetting password in authenticationApp
I need the users to give their old password too while resetting the password using the link they receive from django backend. How do I implement this? Thanks in advance. -
Create a register in another table with the id as FK of the first table automatically after creating the register in the first table Django
Models.py class Email(models.Model): id = models.CharField(max_length=200, primary_key=True) subject = models.CharField(max_length=200) message = models.CharField(max_length=2000) time = models.CharField(max_length=50) read = models.BooleanField() starred = models.BooleanField() hasAttachments = models.BooleanField() class Attachments(models.Model): type = models.CharField(max_length=200) filename = models.CharField(max_length=200) preview = models.CharField(max_length=200) url = models.CharField(max_length=200) size = models.CharField(max_length=200) referring_email = models.ForeignKey(Email, related_name='email',on_delete=models.CASCADE, null=True, blank=True) Serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachments fields = '__all__'#·('type','filename','preview','url','size') class EmailSerializer(WritableNestedModelSerializer): #to = ToSerializer(many=True) #froms = FromsSerializer() attachments = AttachmentSerializer(many=True, required=False) class Meta: model = Email fields = '__all__' def create(self, validated_data): #Popeo del JSON los campos Foreign Keys hayAttachments = False if(validated_data.get('attachments') != None): attachments_data = validated_data.pop('attachments') hayAttachments = True #Creo el objeto email a partir del JSON tocado email = Email.objects.create(**validated_data) if(hayAttachments): for attachment_data in attachments_data: attachment = Attachments.objects.create(**attachment_data) attachment.referring_email = email return email When I create an email, I want to automatically create an attachment and put the current email id as foreign key in the attachment table. I tried with this but only creates the attachment and set the FK=NULL, any help will be apreciated. (If you need anymore information, I'll update it) This is the Json from wich I load the data: { "id": "15459251a6d6b397565", "subject": "Commits that need to be pushed lorem ipsum dolor … -
Response.status_code 400 for a simple view test
I'm passing a simple json body to my view but I'm getting a 400 instead of a 200. It should be a really straightforward test but I can't quite figure out what is wrong. Thanks. Url: "api/v2/ada/send", views.sendView.as_view(), name="ada-send", ), View: class sendView(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): body = request.data return Response(body, status=status.HTTP_200_OK) View Test: class AdaSendGet(APITestCase): url = reverse("ada-send") def test_choice_type_valid( self,): user = get_user_model().objects.create_user("test") self.client.force_authenticate(user) response = self.client.post( self.url, { "contact_uuid": "49548747-48888043", "choices": 3, "message": ( "What is the issue?\n\nAbdominal pain" "\nHeadache\nNone of these\n\n" "Choose the option that matches your answer. " "Eg, 1 for Abdominal pain\n\nEnter *back* to go to " "the previous question or *abort* to " "end the assessment" ), "step": 6, "value": 2, "optionId": 0, "path": "/assessments/assessment-id/dialog/next", "cardType": "CHOICE", "title": "SYMPTOM" }, content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_200_OK) Error: self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 400 != 200 -
How to display 2 months in my calendar in Django?
so I'm making a calendar application based on this calendar design and this is how it currently looks However I want to display 2 months side by side in this calendar (in the example above I would want April to be right next to March and the days would go from March 30th, 31st and then April 1st - April 30th). Does anyone know how to do this. utils.py from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Event class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'{week}' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' #cal += f'{self.formatweekheader()}\n' months … -
Django FOREIGN KEY constraint failed, when adding Many To Many Association to Instance for the second time
i am currently trying to teach myself the django framework. Something really odd is happening when trying to connect to object instances via a ManyToManyField. Starting from a fresh Database (object creation in Shell, but same problem in Code): When i create the first object (Product) everything works fine. I create the object and add the other object (ProductTag) to the ManyToManyField of the first one. Now here comes the Problem: after I did that, and try the same thing again with different Instances (or the same ones, as last time) I get an django.db.utils.IntegrityError, which says "FOREIGN KEY constraint failed" Console In/Output of the problem: (InteractiveConsole) >>> from onlineShop.apps.products.models import Product, ProductTag >>> from django.contrib.auth.models import User >>> from onlineShop.apps.profiles.models import Profile >>> p = Profile.objects.first() >>> t = ProductTag.objects.create(name="outdoor", name_verbose="Outdoor") >>> p.save() >>> p <Profile: superuser> >>> t.save() >>> t <ProductTag: Outdoor> >>> prod1 = Product.objects.create(vendor=p, title="test1", price=123.42, description="test1-desc") >>> prod1.save() >>> prod1 <Product: test1> >>> prod2 = Product.objects.create(vendor=p, title="test2", price=223.42, description="test2-desc") >>> prod2.save() >>> prod2 <Product: test2> >>> prod1.tags.add(t) >>> prod1.save() >>> prod1 <Product: test1> >>> prod2.tags.add(t) Traceback (most recent call last): File "C:\Users\lukas\.virtualenvs\Django_Shop-2dmIjN-v\lib\site-packages\django\db\backends\base\base.py", line 267, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above … -
Issue with serializer and api
My problem is that I want to to get category.name instead of category.id in api. class PostSerializer(serializers.ModelSerializer): class Meta: model = models.Post fields = ['id', 'title', 'content', 'category', 'img', 'date_posted'] But when I adding it, there disappears option in POST method to set category. For api view I use generics.ListCreateAPIView def getCategory(self,obj): return obj.category.name category = serializers.SerializerMethodField("getCategory") -
NoReverseMatch at /register Reverse for 'activate' with keyword arguments '{'uidb64': 'MjA', 'token': 'b30qd1-7f95e1136cc4896c8b15fdc839486de
I have this code running for one project and not working for another project. def signup(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): # save form in the memory not in database user = form.save(commit=False) user.is_active = False user.save() # to get the domain of the current site current_site = get_current_site(request) mail_subject = 'Activation link has been sent to your email id' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignupForm() return render(request, 'signup.html', {'form': form}) {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} def activate(request, uidb64, token): User = get_user_model() try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return HttpResponse('Thank you for your email confirmation. Now you can login your account.') else: return HttpResponse('Activation link is invalid!') path('activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/', activate, name='activate'), -
How to fill a Django form with an API response?
I need to create a form of persons, where the camp Name must receive an API response. I created the formulary e rendered the api response in template, but I can´t put it in my formulary, in order to save in my Models camp Name. So, I just want to save my API respone inside my forms and in my database. Views def cadastro(request): url = 'https://gerador-nomes.herokuapp.com/nome/aleatorio' api = requests.get(url) nome_api = ' '.join(api.json()) form = PessoaForm() form.nome = api if request.method == 'POST': form = PessoaForm(request.POST) if form.is_valid(): form.cleaned_data('nome') form.save() return redirect('/') context = {'form': form, 'api': nome_api} return render(request, 'base/pessoa_form.html', context) pessoa_form.html <body> <form action="" method="post"> {% csrf_token %} {{form}} <input type="submit" name="Cadastrar"> </form> </body> </html> Forms from django.forms import ModelForm from . models import Pessoa class PessoaForm(ModelForm): class Meta: model = Pessoa fields = '__all__' Models from django.db import models class Pessoa(models.Model): name= models.CharField(max_length=255, null=True) lastname= models.CharField(max_length=255, null=True) age= models.IntegerField(null=True) birthday_date= models.DateField() email = models.CharField(max_length=255, null=True) nickname= models.CharField(max_length=255, null=True, blank=True) note = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.nome class Meta: ordering = ['nome', 'sobrenome'] I have tried some things of my head but nothing actually worked, like try to access the variable Name in my forms …