Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why is python not recognized in cmd as a internal, external or batch file
so, i was trying to use django in python, at first it was running manage.py it worked normally, but as soon as i edited some code, CMD started saying this C:\Users\pert\PycharmProjects\chatapp\web> python manage.py runserver 'python' is not recognized as an internal or external command, operable program or batch file. so, why is cmd saying 'python is not recognized, i am sure my code was correct, i watched it at youtube, but what is going on, also i have had python for 3 years now, and it never gave me this error, also i was using pycharm and at youtube, he used sublime, is it just a problem with IDE's -
How to log api calls into databse using django?
I don't know how to log all the API calls like API name, API call time, API call success/fail status into my sqlite3 database. Please help me I have no idea about this. -
Django UserAdmin, save_model override function doesn't return updated user groups
I need to do some actions after saving a user in the django admin user form. Specifically, inside the save_user method of UserAdmin, I need to check if the user belongs to a certain group after creation. When I print the user groups after saving a new user model with a "Doctor" group, the group doesn't seem to be updated inside the save_model function. Here's the sample code for clarification: def is_doctor(self, user): z = user.groups.filter(name='Doctors').exists() if not z: z = user.groups.filter(name='Doctor').exists() return z def save_model(self, request, obj, form, change): super(UserAdmin, self).save_model(request, obj, form, change) user = User.objects.get(pk=obj.pk) print(f'is doctor: {User.objects.is_doctor(obj)}') print(f'is doctor new user: {User.objects.is_doctor(user)}') print('Printing groups of newly created user...') groups = user.groups.all() groups_count = groups.count() for group in groups: print(group['name']) print(f'This user has {groups_count} groups') After saving a user with a "Doctor" group like the image below: It prints the following: is doctor: False is doctor new user: False Printing groups of newly created user... This user has 0 groups The doctor group that was added isn't updated in creation of a new user object. Is this normal or have I missed something? -
Django valid URL in url file not being found . Instead a circular error is being shown
This my views file where I am trying to use a usercreationform from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy class UserRegisterView(generic.CreateView): form_class = UserCreationForm template_name = 'registration/register.html' success_url = reverse_lazy('home') And this is my url file where I point to this view from .views import UserRegisterView from django.urls import path url_patterns = [ path('register/', UserRegisterView.as_view(), name="register"), ] Now when I try to run the server , I am getting this error for some reason django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'members.urls' from does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. This does not make any sense . There is already a url pattern in it pointing to my view . -
How to reset password in django2 without django Authentication
Please help me for reset password without django authentication in django2. My views is: #password reset def resetpass(request): mail_forms = PassResetForm() if request.method == 'POST': mail_forms = PassResetForm(request.POST) if mail_forms.is_valid(): mail = mail_forms.cleaned_data['mail'] user_info = UserInfo.objects.get(email=mail) user_mail = user_info.email context = { 'mail_forms':mail_forms, } return render(request, 'login/pass_reset_mail.html', context) -
Django Live data view to web page
I want to display the csv data to web page. The data from the csv is live which means the continuously added to the csv. Meanwhile the webpage needs to display the updated data as well. How can i do that? The csv file located in the local machine. -
Django Bootstrap Modal form CSRF verification failed
I was trying a bootstrap model form in django detailview using form mixin, but while submitting the form I am receiving Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. error please find my code below. Thank you for any help you can provide. views.py class PostDetail(FormMixin, generic.DetailView): model = Post form_class = SubscriberForm template_name = 'post_detail.html' #for related post start #post_rel = Post.objects.filter(status=1) #post_related = Post.tags.similar_objects().filter(status=1).order_by('-created_on')[:3] #post_related = post_rel.tags.similar_objects()[ : 3] #post_related = Post.tags.similar_objects().filter( #).order_by('-created_on')[:3] #Post = get_object_or_404(Post) #post_related = [Post.tags.similar_objects()][:3] context = { 'tag':Post.tags, } def post(self, request, *args, **kwargs): form = SubscriberForm(request.POST) if form.is_valid(): try: sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() return render(request, "post_detail.html", {'form': SubscriberForm(), 'model': Post, 'email': sub.email, 'action': 'added'}) except: return render(request, "post_detail.html", {'existing_email': sub.email, 'action': 'already added', 'duplicate': 'duplicate', 'form': SubscriberForm(), 'model': Post}) template.html <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">New message</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {% if form %} <form method="post" style="padding-left: 14px;"> <div class="row" style="padding-top: 30px; padding-bottom: 30px;"> <div class="col-lg-12"> <div class="input-group" style="border-radius: 4em;"> {% csrf_token %} {{form}} <button class="btn btn-lg btn-default" style="background-color: white; color:#0412DE; font-weight: … -
When to use Django Workers, Queues, and Tasks rather than Python Threading or Concurrent?
Assume on a Django projects, we want to update a user profile along with sending him/her an email notifying changes, in this case two different solutions would come in mind: using python concurrent library to run both tasks use something like Django Q the project also needs "Scheduled Tasks" to be run daily or weekly, so a job Que library is a must, but I thought I could use python concurrent library for making functions run concurrently and something like Advanced Python Scheduling, this also came in mind when I realized Dramatiq does not support scheduling tasks. now my question is : What are benefits of using Django Task Queuing apps over using python core libraries like concurrent? -
Annotate on two prefetched_related tables deep in Django
My issue is similar to the following question, but that doesn't quite cover the scenario I'm looking for. Combine prefetch_related and annotate in Django I have the following models: class Item(models.Model): name = models.CharField(max_length=100) class Recipe(models.Model): name = models.CharField(max_length=20) output_item = models.ForeignKey(Item, null=True, blank=True, on_delete=models.SET_NULL) class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) item = models.ForeignKey(Item on_delete=models.CASCADE) quantity = models.IntegerField() class StorePrice(models.Model): store_name = models.CharField(max_length=20) item = models.ForeignKey(Item, null=True, blank=True, on_delete=models.SET_NULL) price = models.IntegerField() I'm trying to display the following details about a single recipe: The recipe name The name and quantity of each ingredient linked to the recipe The lowest price available for that ingredient, and the name of the store So far I have the following query... Recipe.objects.filter(id=5)\ .select_related('output_item')\ .prefetch_related( 'output_item__storeprice_set', 'ingredient_set', 'ingredient_set__item', 'ingredient_set__item__storeprice_set', ).first() This accomplishes goals 1 and 2, but now I need to add the annotation to achieve #3. The lowest price should be calculated per ingredient, but so far I've only been able to have it apply at the recipe level, by adding the following. .annotate(lowest_store_price=Min('ingredient__item__store_price__price')) -
Create a dynamic form (not only in number of items but structure) in Django
I am new to django and I am struggling to develop the following. I have a survey app in which an admin user can provide to create a new survey template a CSV with a variable number of questions and answers per question, wich may be True or False indistinctly. This is stored using these three different models: class Survey(models.Model): survey_name = models.CharField(max_length=50, unique=True) answer_key = models.CharField(max_length=250) score_key = models.CharField(max_length=250) date = models.DateTimeField(auto_now_add=True) class Question(models.Model): survey = models.ForeignKey(Survey, on_delete=models.CASCADE) text = models.CharField(max_length=250) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=250) valid = models.BooleanField(default=False) I know how to retrieve the associated objects for a given survey in a view and show them a template, but not how to represent them in a form, since the number of questions and answers per question are not known beforehand. Also not sure how this would be read when processing the POST. Any hint would be much appreciated. Thanks! -
django admin site download to excel
I already install django-import-export, i dont get any error on exporting data to excel, but why is it when i open the excel file, some data is number? especially the foreignkey? this is my admin.py from import_export.admin import ExportActionMixin @admin.register(CustomerPurchaseOrder) class CustomerPurchaseOrderAdmin(ExportActionMixin, admin.ModelAdmin): list_filter = ("process", "deliverySchedule", "inputdate") list_display = ('profile', 'customer_Purchase_Order_Detail', 'process', 'deliverySchedule', 'deliveryDate', 'paymentmethod', 'requestedDate',) ordering = ('id','requestedDate') pass my models.py class CustomerPurchaseOrder(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") customer_Purchase_Order_Detail = models.ForeignKey('CustomerPurchaseOrderDetail', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer Purchase Order") process = models.ForeignKey('Process', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Process") .... def __str__(self): suser = '{0.profile}' return suser.format(self) -
How can i access model method in django admin class
I've one proxy model like this. class Category(GenericCategory): class Meta: proxy = True verbose_name = "Category" verbose_name_plural = "Categories" @property def get_content_type(self): return ContentType.objects.get_for_model( self.__class__, for_concrete_model=False ) Now i want to access get_content_type method in django admin class so that i can filter data in django admin. -
Invalid block tag : 'boostrap_form', django.template.exceptions.TemplateSyntaxError
Getting this error when i'm trying to use bootstrap4 i've only copy and pasted the sections but i included the imports up the top. boostrap4 is also registered as an INSTALLED_APPS: in settings.py django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 927: 'boostrap_form', expected 'endblock'. Did you forget to register or load this tag? {% extends 'base.html' %} {% load static %} {% load bootstrap4 %} {% block bodyblock %} <form method="post" class="form-control"> <div class="col-md-4"> <div class="form-group"> {% csrf_token %} {% boostrap_form form %} </div> </div> -
not receive error response for reservation API endpoint
I wrote the rest api end point for reservation. it checks availability of the room and if it isn't available respond with error. The point that the code runs and if statement check works well and no new object is created but I cannot see the response error. This is my views.py: class ReservationViewSet(viewsets.ModelViewSet): """Manage Reservation in database""" queryset = Reservation.objects.all() serializer_class= serializers.ReservationSerializer def get_queryset(self): """return a list of Reservations""" return self.queryset.order_by('-id') def perform_create(self, serializer): """create a new Reservation if available""" Room_ID = self.request.data.get('RoomID') Start_Date= self.request.data.get('StartDate') End_Date= self.request.data.get('EndDate') Check1 = Reservation.objects.filter(RoomID=Room_ID).filter(StartDate__gte=Start_Date).filter(StartDate__lte=End_Date) Check2 = Reservation.objects.filter(RoomID=Room_ID).filter(EndDate__gte=Start_Date, EndDate__lte=End_Date) Check3 = Reservation.objects.filter(RoomID=Room_ID).filter(StartDate__gte=Start_Date).filter(EndDate__gte=Start_Date).filter(StartDate__lte=End_Date).filter(EndDate__lte=End_Date) if (Check1 or Check2 or Check3): serializer.is_valid(raise_exception=True) print("it is not allowed") return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: serializer.save() this is urls.py: from django.urls import path, include from rest_framework.routers import DefaultRouter from reservation import views router = DefaultRouter() router.register('', views.ReservationViewSet) app_name='Reservatiom' urlpatterns=[ path('', include(router.urls)), ] This is my serializer.py from rest_framework import serializers from core.models import ListingOwner, Room, Reservation from room.serializers import RoomSerializer class ReservationSerializer(serializers.ModelSerializer): """"Serializer for making a new Reservation""" RoomID = serializers.PrimaryKeyRelatedField(queryset=Room.objects.all(),many=True) class Meta: model = Reservation fields=('id','ReserverName','StartDate', 'EndDate', 'RoomID' ) -
Django Create file in MEDIA_ROOT folder and save it to FileField
Currently I want to create a file under MEDIA_ROOT folder and save it to FileField. I searched on SO website, tried the method on django-how-to-create-a-file-and-save-it-to-a-models-filefield and other, but looks it saved absolute path on my db. My Model class Voice(models.Model): xxx other field textFile = models.FileField(null=True,blank=True,default=None,upload_to='text_file', unique=True) Update textFile field as following: @receiver(post_save, sender=Voice) def create_text(sender,**kwargs): xxx f = open(settings.MEDIA_ROOT + '/text_file/'+ text_file,'w') queryset = Voice.objects.all() queryset.filter(pk=voice.pk).update(textFile=File(f)) f.close() And I find it save something like this on db: "textFile": "http://127.0.0.1:8000/media/Users/usersxxx/Documents/xxx/media/text_file/t5" while not: "http://127.0.0.1:8000/media/text_file/t5", -
Display the form for all foreign key data as text field
I have created this model: class LinePipeRate(models.Model): dia = models.ForeignKey(Diameter, on_delete=models.CASCADE) method = models.ForeignKey(Method,related_name='line_pipe_rate', on_delete=models.CASCADE,null=True,blank=True,) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) linepipe_rate = models.FloatField(default=0,null=True,blank=True) Following is my Form: class LinePipeRateForm(forms.Form): currency = forms.ModelChoiceField(queryset=Currency.objects.all()) dia= forms.IntegerField() rate = forms.IntegerField() I want to take user input for all the diameters in single form so, In the template, I have displayed form as follows: <table> <tr> <td><label for="{{ wizard.form.currency.id_for_label }}">Currency </label>{{wizard.form.currency}}</td> </tr> </table> <table> <thead> <tr> <th>Diameter in inch</th> <th>Rate</th> </tr> </thead> {% for dia in diameter %} <tr> <td><input type="text" id="{{ wizard.form.dia.id_for_label }}" name="dia" value={{dia.dia}} readonly="readonly"></td> <td>{{ wizard.form.rate }}</td> </tr> {% endfor %} </table> This is the format in which I want to display the form, but I am not able to save the data in the model. Please help me. -
Temporary MEDIA_ROOT for testing not working
For the purpose of testing user media uploads, I have created a temporary MEDIA_ROOT in my test module so that the development directory doesn't become polluted with mock images. I have stumbled upon this and how Django happens to achieve the same task of creating/destroying a temporary MEDIA_ROOT: https://github.com/django/django/blob/master/tests/file_uploads/tests.py#L26 When the tests are ran however, I get the following error \test_models.py", line 17, in <module> MEDIA_ROOT = mkdtemp(prefix="media/") File \Python\Python37\lib\tempfile.py", line 366, in mkdtemp _os.mkdir(file, 0o700) FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\..\\..\\..\\..\\Temp\\media/0_axhu0o' How can I get the test to pass so that path of image file is stored relative to the temporary MEDIA_ROOT with that directory having the same name of media/? tests.py MEDIA_ROOT = mkdtemp(prefix="media/") @override_settings(MEDIA_ROOT=MEDIA_ROOT) class TestPhotoModel(TestCase): @classmethod def setUpData(self): os.makedirs(MEDIA_ROOT) user = User.objects.create_user("Testuser") test_image = SimpleUploadedFile( "test_image.jpg", content=b"", content_type="image/jpeg" ) freezer = freeze_time("2020-12-31") freezer.start() data = { "source": test_image, "title": "Test Image", "upload_date": datetime.date.today, "likes": 0, "photographer": user } self.photo_instance = Photo.objects.create(**data) def test_photo_count(self): self.assertEqual(Photo.objects.count(), 1) def test_image_upload_path(self): self.assertEqual( self.photo_instance.source.path, "media/uploads/2020/12/31/test_image.jpg" ) @classmethod def tearDownClass(cls): rmtree(MEDIA_ROOT) super().tearDownClass() -
UNIQUE constraint failed, when pressing submit button. (Django)
For some reason when I press the submit button to save a UserRegisterForm object I get an error: UNIQUE constraint failed, even though the info does submit to the database. It is extra odd because when I press the enter key to submit the data, the program functions perfectly fine. I am watching a tutorial and the code is copied verbatim. I would appreciate any help, thanks! views.py: def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) Register.html: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="#">Sign In</a> </small> </div> </div> {% endblock content %} The tutorial I am following(Demonstrated around 31:29): https://www.youtube.com/watch?v=q4jPR-M0TAQ&list=PL-osiE80TeTtoQCKZ03TU5fNfx2UY6U4p&index=6. -
how can i convert manytomanyfield dropdown into input field?
i am using two forms for updating book and lesson name too. the {{book_update}} is working fine but {{lesson_form_list}} it's not working as a required it is empty []. how do i use {{lesson_form_list}} as a input field, when i try to apply my code it's blank. i want to make a small variation in the existing method that is instdad of dropdown i want to introduce throug input field. models.py class Book(models.Model): title = models.CharField(max_length=10) created = models.DateTimeField(auto_now_add=True) lesson = models.ManyToManyField(Lesson) forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ['title', 'lesson'] class LessonForm(forms.ModelForm): result_values = forms.CharField(max_length=10) class Meta: model = Lesson fields = [ 'name', 'result_values', 'expected_values' ] views.py def book_update_form(request, pk): book = get_object_or_404(Book, pk=pk) b_form = BookForm(request.POST or None, instance=book) l_form = [LessonForm(request.POST or None, prefix=str( lesson.pk), instance=lesson) for lesson in book.lesson.all()] if request.POST and b_form.is_valid() and all([lf.is_valid() for lf in l_form]): b_form.save() for lf in l_form: lesson_form = lf.save() return redirect('dashboard') context = { 'book_update': b_form, 'lesson_form_list': l_form } return render(request, 'patient/report.html', context) update_form.html <div class=" form-group"> <label for="id_title">book</label> {{book_update}} </div> <div class=" form-group"> <label for="id_lesson">Lessons</label> {{lesson_form_list}} </div> -
how to re deploy updates to elastic bean stalk, issue with allowed hosts django
It seems like eb deploy is the solution. But notice this error: Invalid HTTP_HOST header: 'hiddenforstackoverflow'. You may need to add 'hiddenforstackoverflow' to ALLOWED_HOSTS. however, I go to my allowed hosts in my django settings. ALLOWED_HOSTS = ['hiddenforstackoverflow'] the HTTP_HOST header is the same as the one django is complaining about. I run eb deploy all day and nothing changes. Is there a cache or something? -
DJANGO get objects in sql like join
Context: I'm forcing my self to learn django, I already wrote a small php based website, so I'm basically porting over the pages and functions to learn how django works. I have 2 models from django.db import models class Site(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Combo(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) dead = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) siteID = models.ForeignKey(Site, on_delete=models.PROTECT) class Meta: unique_together = ('username','password','siteID') def __str__(self): return f"{self.username}:{self.password}@{self.siteID.name}" When creating a view, I want to get the Combo objects, but I want to sort them first by site name, then username. I tried to create the view, but get errors about what fields I can order by Cannot resolve keyword 'Site' into field. Choices are: dead, id, password, siteID, siteID_id, timestamp, username def current(request): current = Combo.objects.filter(dead=False).order_by('Site__name','username') return render(request, 'passwords/current.html',{'current':current}) Since I'm not necissarily entering the sites into the database in alphabetical order, ordering by siteID wouldn't be useful. Looking for some help to figure out how to return back the list of Combo objects ordered by the Site name object then the username. -
Adding new pages in Django from existing data
I am trying to simply add a new 'blog' page in Django, which should replicate the home page. The home page is working fine, and if I view the URLs for my app, it looks like the following: urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] In my understanding of Django, I could add a 'blog' page by adding the following: urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('blog/', views.PostList.as_view(), name='blog'), #ADDED LINE ] However going to my http://127.0.0.1:8000/blog/ page returns a 404 error. With Django debugging enabled, I get the following message: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Raised by: main_site_app.views.PostDetail From what I can observe, there is nothing additional that the index page has that the blog doesn't. Is there a step I'm missing here that is preventing the /blog/ page from showing up? -
How can i export data from Django to use excel as a calculator to later show the results in my Django website?
I have created a form using Django, and i would like to use the input data from this form in an excel template that i have, this template has many complicated formulas and way too many at that. I would like to export the input data of the form do all the calculations using the excel sheet and then later import the results in my Django website. i have tried using xlutils.copy to edit the file with the new data but by doing this it eliminates all formulas. How would i be able to do this? I am also new at Django so i'm not exactly sure where to put the command to export the data. I would be extremely grateful if someone could help me. from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.shortcuts import redirect import sys; sys.path import pandas as pd import numpy as np from openpyxl import load_workbook # Create your models here. class Pregunta(models.Model): genero = (('Hombre', 'Hombre'), ('Mujer', 'Mujer')) res = (('Verdadero', '1'), ('Falso', '2'), ('Blanco','3')) nombre = models.CharField(max_length=255, null= True) edad = models.IntegerField( null=True, blank=True) fecha = models.DateField(null= True) sexo = models.CharField(choices = genero,max_length=6, null= True) estado = … -
Exception Value: '<' not supported between instances of 'NoneType' and 'datetime.datetime'
I am trying to validate that the DateTime of an object cannot be earlier than yesterday. No matter what I do, I keep getting the same TypeError. Django Version: 3.0.5 Exception Type: TypeError Exception Value: '<' not supported between instances of 'NoneType' and 'datetime.datetime' Python Version: 3.8.2 models.py class Visit(BaseModel): start_utc = models.DateTimeField('Visit Start') end_utc = models.DateTimeField('Visit End') def clean(self, *args, **kwargs): super(Visit, self).clean() if self.start_utc < timezone.now() - timedelta(1): raise ValidationError("Visits cannot start in the past!") if not self.end_utc > self.start_utc: raise ValidationError("Visits cannot end before they have started!") forms.py class VisitForm(forms.ModelForm): start_utc = forms.DateTimeField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'})) end_utc = forms.DateTimeField(widget=forms.widgets.DateTimeInput(attrs={'type': 'datetime-local'})) -
Save items from Form in a list in Django
I'm trying to compare names inserted in an InlineForm before saving them. But I'm having some issues trying to save the names into a list and then compare them. Here is what I've tried to do. form.py class ColabForm(forms.ModelForm): class Meta: model = Colaboradores fields = '__all__' colaborador_projeto = forms.CharField(label="Colaborador do Projeto", widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', } )) def clean(self): colaborador_projeto = self.cleaned_data.get('colaborador_projeto') lista_erros = {} verifica_nome(colaborador_projeto) if lista_erros is not None: for erro in lista_erros: mensagem_erro = lista_erros[erro] self.add_error(erro, mensagem_erro) return self.cleaned_data validation.py def verifica_nome(colaborador_projeto): lista = colaborador_projeto.split() nomes = ''.join(lista) lista_nome = [] nome = '' for i in range(len(nomes)): nome += nomes[i] if i == (len(nomes)-1): lista_nome.append(str(nome)) Instead of getting a list with the names in different possitions, all the names are saved on list[0]. How can I fix it?