Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to download an updated file by admin in Django
what i am trying to do is: Admin uploads a PDF file from admin panel. (1) It needs to go to the specified template. (2) And it should be downloaded by pressing download button in the template. So here are codes: (1) class Reports(models.Model): name = models.CharField(max_length=100, null=False, blank=False, verbose_name="File Name") report = models.FileField() (2) <tr> <td>"File Name must be showed in here"</td> <td class="text-center">PDF</td> <td class="text-center lang-tr-src"><a href="What way should i give here?" target="_blank"><i class="fas fa-file-download"></i></a></td> <td class="text-center lang-en-src"><a href="" target="_blank"><i class="fas fa-file-download"></i></a></td> </tr> In the website there will be one report for every month. I want to list them in the template and make them downloadable. Should i write a view for that(if yes how it should be?) or what should i do? -
python static variable value is switching between old value and new value after frequently request in production-environment
service.py class TestProduction: test_varible = None views.py @public def display_value(request): # calling API-2 return HttpResponse(json.dumps({"code": 1, "msg": str(TestProduction.test_varible )}), content_type="json") api.py @public def set_value(request): # calling API-1 value = request.POST['value'] TestProduction.test_varible = value return HttpResponse(json.dumps({"code": 1, "msg": str(TestProduction.test_varible )}), content_type="json") the above code is tested with the postman it working fine in the development-environment but in production-environment case1 first time assign a value in TestProduction.test_varible it returns a value which is right case2 again assign a new value to the same variable TestProduction.test_varible and frequently hit the API it switching the result some time old and new value Results API-1 assign 50 API-2 return 50 in every call API-1 assign 60 API-2 return sometimes 60 and sometimes 50 in every call -
Creating List APi for two models having many to one relationship
Here I have two models Ailines and Flight Details. The second model is many to one reln with Airlines model. When I create ListAPi view for Flight Details, the airline name doesnt appear on the apis, instead only id(pk) appears. Check the picture below, airlines only has number not airline name. class Airlines(models.Model): Airline_Name = models.CharField(max_length=200, unique= True) Email = models.EmailField(max_length=200, unique= True, help_text='example@gmail.com') Address = models.CharField(max_length=200) Phone_Number = PhoneField(help_text='Contact phone number') def __str__(self): return self.Airline_Name class FlightDetails(models.Model): Flight_Name = models.CharField(max_length=200) Aircraft_name = models.CharField(max_length=200) airlines = models.ForeignKey(Airlines, null=True, on_delete=models.CASCADE) Destination = models.CharField(max_length=200, verbose_name = "To") Destination_Code = models.CharField(max_length=200) Destination_Airport_name = models.CharField(max_length=200) Here we can see in airlines it says 1, instead of airlines name.How can we solve it?? -
Selenium script in django running with gunicorn server failed
I have a selenium script and the run on when a API call and the API built with django. Everything is working very well in my both local server and cloud But the problem is, when i run the app with gunicorn instead of python3 manage.py runserver It fires me too many error: and this is my gunicorn /etc/systemd/system/site.service code: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/var/www/workorder Environment="PATH=/var/www/workorder/env/bin" ExecStart=/var/www/workorder/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/var/www/workorder/site.sock -m 007 workorder.wsgi:application [Install] WantedBy=multi-user.target and i run this with Nginx reverse proxy and this is my chrome driver example code: options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') driver = webdriver.Chrome(options=options) driver.get(url) As i said, my selenium script method in api view so when the endpoint call, then it run the selenium script. but it It fires me this error: and when i add the chromedirver link: driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options=options) and it gives me this error: I am not getting whats wrong with this. When run the server with python manage.py runserver, it works very well but when i run it in backround, it gives me error Even it gives me when i run it with gunicorn and nginx server. Can anyone please help … -
Running Django server from Jenkins pipeline in Docker container
I am trying to setup a Jenkins pipeline that deploys a Django project and runs the Django's development server in background. I would like to separate it into 3 steps, Build, Test, Run. Everything is fine except the last step, indeed, when I setup it like this: ... stage('Run') { steps{ dir('auto'){ sh 'pwd' sh '/usr/bin/python3.8 manage.py runserver 0.0.0.0:8000' } } } the server starts well, I can access to the project through http://127.0.0.1:8000 but the job is not ending. I have tried to bypass this issue to have the server running in background using nohup $: ... stage('Run') { steps{ dir('auto'){ sh 'pwd' sh 'nohup /usr/bin/python3.8 manage.py runserver 0.0.0.0:8000 $' } } } but the server is not reachable at http://127.0.0.1:8000 I am a Jenkins beginner and maybe this is not the right way to have a process running in background. -
DJANGO - Call a TKINTER program using a button
I made a program using python TKINTER, and now I need to run it in a Web application, so that everyone in the company can access it. That's when I found out that DJANGO does this kind of service! But I'm being beaten up here to call the TKINTER program when a button is pressed. Can anyone give me a light? Is it doable? I wanted something very simple, just a button on the web to run TKINTER .... -
Problem direction typing in ckeditor codesnippet
I have a problem with the code snippet plugin Both typing and output are cluttered The output of the print("Hello") code is: image image please help -
get one object in queryset iteration
I have two models, A and B, and B is ForienKey relationship to A. I want to check each object in queryset and if it has certain fields then I want to display it in template. Below is my template example: {% for a in a_qs %} <tr> <th>{{ a.b_set.first.a_field }}</th> <th>{{ a.b_set.first.another_field }}</th> {% endfor %} They work fine, but I want to apply something like get method in queryset. Below is what I want to achieve: {% for a in a_qs %} <tr> <th>{{ a.b_set.get(a_field_in_B='hello').a_field }}</th> <th>{{ a.b_set.get(a_field_in_B='hello').another_field }}</th> {% endfor %} I understand that something above is not possible and I want to give some change to my views or models, but I don't know where to start. Below is something like my views.py snippet: a_qs = A.objects.all() a_obj = a.b_set.get(a_field='something') # a is not defined yet. I want every a in a_qs to be checked Thanks for your advice in advance. -
Stream multiple files at once from a Django server
I'm running a Django server to serve files from another server in a protected network. When a user makes a request to access multiple files at once I'd like my Django server to stream these files all at once to that user. As downloading multiple files at once is not easily possible in a browser the files need to be bundled somehow. I don't want my server having to download all files first and then serve a ready bundled file, because that adds a lot of timeloss for larger files. With zips my understanding is that it can not be streamed while being assembled. Is there any way to start streaming a container as soon as the first bytes from the remote server are available? -
NoReverseMatch at /collection/6/
I'm a beginner at Django/programming in general. I have a problem with a redirecting url button on one of my HTML pages. Basically I have a collection page where one can add plants. The collection page displays all of the added plants and an add plant button for the user to enter another one to the database. Then when you click on a plant, you see the plant, the picture you added, and the nickname. There is also other data that can be added, for that I made a CreateView that adds details such as date purchased and notes. Now this page works and when I go to the URL manually I can update a plant. However when I want to add an 'add details' button to my html file of a specific plant, I get this error that I just cannot solve. Here is some mandatory code: Models.py class PlantDetail(models.Model): """This class contains various types of data of added plants""" """links the details to one plants""" from datetime import date plant = models.ForeignKey(Plant, on_delete=models.CASCADE) date_purchased = models.DateField(default=date.today) notes = models.TextField() def __str__(self): """Return the detail input from the user""" return self.notes def age(self): """Return the age of the plant … -
Django - Change records in pandas dataframe
with tkinter and pandas I have created a program where I can import csv files, and then using python script correct the file (delete columns, change rows, delete duplicates etc.) and then export a new csv. the script I use - https://gist.github.com/Dackefejd/972f4c37861df3cda3398e29f9a17344 I now want to get the same function through a Web application. Found Django who with the help of pandas seems to fulfill my purpose. My question: is there any good way to correct panda's data frame in Django? For example, delete columns / rows I have looked at tablib, but is there anything to recommend? If I am unclear, you are welcome to ask questions -
return a splitted long sting in a table field in django queryset
I am using mySQL as the database of my django project. One filed of a table in this db has text values seprated by , like: tags = "Django, MySql, C, C++, Python, Cython" I need to check if there is my desired string in the above field when I am filtering query set: this is my query: my_tag = "C" posts = Post.objects.filter(tags__icontains=my_tag).order_by('-date_created') The above query also return Cython but I just expect C and that's because tags text is not splitted by ,. How can I find a sting in a text, In regular python there is str.split(',') or regex however in django I don't know! -
How to compare database values with forms.py value in django
How to compare database reseved_start_time value with forms.py reserved_start_time form value. models.py class Reservation(models.Model): Power_System = 0 Water_System = 1 Blade = 2 STATUS = ( (Power_System, _("Power System")), (Water_System, _("Water System")), (Blade, _("Blade Server")), ) user = models.ForeignKey("auth.User", on_delete=models.CASCADE) username = models.CharField(max_length=20, blank=True) lastname = models.CharField(max_length=20, blank=True) email = models.EmailField(max_length=50, blank=True) reserved_start_date = models.DateField(default=timezone.now) reserved_start_time = models.TimeField(blank=True, null=True) reserved_end_time = models.TimeField(blank=True, null=True) status = models.SmallIntegerField(choices=STATUS, default=Power_System) updated_datetime = models.DateTimeField(auto_now=True) def __str__(self): return str(self.reserved_start_date) if reserved_start_time section return "Try the another starting time" message when database values dont have any time which write in the form screen. forms.py class ReservationForm(forms.ModelForm): class Meta: model = Reservation fields = ["username","lastname","email","reserved_start_date","reserved_start_time","reserved_end_time","status"] def clean(self): username = self.cleaned_data.get("username") lastname = self.cleaned_data.get("lastname") email = self.cleaned_data.get("email") reserved_start_time = self.cleaned_data.get("reserved_start_time") reserved_end_time = self.cleaned_data.get("reserved_end_time") if not username: raise forms.ValidationError("Adınızı Giriniz") if not lastname: raise forms.ValidationError("Soyadınızı Giriniz") if not email: raise forms.ValidationError("Email Adresini Giriniz") if not reserved_start_time: raise forms.ValidationError("Başlangıç Saatinizi Giriniz") if not reserved_end_time: raise forms.ValidationError("Son Saatinizi Giriniz") if email: validator = EmailValidator("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") validator(email) if reserved_start_time: rezersvasyon_zamani = Reservation.objects.get(reserved_start_time=reserved_start_time) for reservasyon in rezersvasyon_zamani: if reservasyon.reserved_start_time not in reserved_start_time: raise forms.ValidationError("Try the another starting time") values = { "username": username, "lastname": lastname, "email": email, "reserved_start_time": reserved_start_time, "reserved_end_time": reserved_end_time, } return values -
How rel_db_type() method works in django?
Django documentations says, It returns the database column data type for fields such as ForeignKey and OneToOneField that point to the Field, taking into account the connection. I have gone through the Custom Model Field documentation. But I am not able to understand this part. How does ForeignKey and OneToOneField calls this method of another field. -
UNIQUE constraint failed: Users.username error in Django
For some unknown reasons, I am facing that error I have searched for some of the possible errors but those I have tried doesn't work I tried user = form.save(commit=False) maybe it would work but no positive result Here is the error log Environment: Request Method: POST Request URL: http://localhost:8000/accounts/register-result Django Version: 3.1.2 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.accounts', 'apps.result'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'apps.result.middleware.LoginRequiredMiddleware'] Traceback (most recent call last): File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) The above exception (UNIQUE constraint failed: Users.username) was the direct cause of the following exception: File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\django-new\resultLab\apps\accounts\views.py", line 32, in register_school user = User.objects.create_user(username=username,email=email,password=password) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\contrib\auth\models.py", line 146, in create_user return self._create_user(username, email, password, **extra_fields) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\contrib\auth\models.py", line 140, in _create_user user.save(using=self._db) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 754, in save force_update=force_update, update_fields=update_fields) File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 792, in save_base force_update, using, update_fields, File "C:\Users\Habib\Documents\django\django-new\resultLab\venv\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) … -
net::err_content_length_mismatch 200 (ok) django, apache
My django website sometimes cannot open images and the error message is "Failed to load resource: net::ERR_CONTENT_LENGTH_MISMATCH". However, when I open the link next to the error message on a new tab, the image is loading. I am using Apache not nginx Could someone help me with this problem? -
How does django's ORM get one to one fields without having to call a function
So let's say I have a django model like so: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) After creating this one to one field, the profile object can be accessed by doing user_instance.profile I've enabled logging for the ORM to see the queries sent to the database using this in my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'), 'propagate': False, }, }, } I then opened the shell using python3 manage.py shell and executed the following: firstuser = User.objects.first() This resulted in the following query logged out: SELECT "users_user"."id", "users_user"."password", "users_user"."last_login", "users_user"."is_superuser", "users_user"."username", "users_user"."is_staff", "users_user"."is_active", "users_user"."date_joined", "users_user"."name", "users_user"."email", "users_user"."join_date", "users_user"."date_of_birth" FROM "users_user" ORDER BY "users_user"."id" ASC LIMIT 1; args=() Further I did: firstuser.profile And got this query logged out: SELECT "users_profile"."id", "users_profile"."user_id", "users_profile"."status", "users_profile"."institute" FROM "users_profile" WHERE "users_profile"."user_id" = 1 LIMIT 21; args=(1,) So, how does django execute a query when I request a related object without having to call any functions within my own code. Is there a python method to override behaviour of how attributes from a class are read? Thanks in advance! -
graphene-django add additional argument for DjangoObjectType and pass it to get_queryset
I have added an additional argument called user_type to disposal_request query, and I want to use this argument to add another filter but when I passed it to get_queryset function. I get the following error: get_queryset() missing 1 required positional argument: 'user_type' I'm not sure how to pass the argument properly. import graphene import graphene_django from app.disposer.models import DisposalRequest from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required class UserType(graphene.Enum): as_collector = "as_collector" as_disposer = "as_disposer" class DisposalRequestsType(graphene_django.DjangoObjectType): latitude = graphene.String() longitude = graphene.String() class Meta: model = DisposalRequest exclude = ("location",) filter_fields = [ "uuid", "disposal_status", ] interfaces = (graphene.Node,) convert_choices_to_enum = False @classmethod @login_required def get_queryset(cls, queryset, info, user_type): user = info.context.user if user_type == UserType.as_collector: print("as_collector") return queryset.filter(collector=user) elif user_type == UserType.as_disposer: print("as_disposer") return queryset.filter(disposer=user) def resolve_latitude(self, _): return self.location.x def resolve_longitude(self, _): return self.location.y class DisposalQueries(graphene.ObjectType): disposal_requests = DjangoFilterConnectionField( DisposalRequestsType, user_type=UserType() ) -
Django 3: Filter queryset for letter or non-letter
In my database I have a table with items who's titles can start with a letter or a non-letter-character. For example a number or an "@" or a "#". The model looks like this: class Items(models.Model): title = models.CharField(max_length=255) body = models.TextField In my view I would like to separate the model into two objects. One objects that contains all the item with a title starting with a letter and an other object with all the other items: class ItemsView(TemplateView): template_name = "index.html" def get_context_data(self, **kwargs): alpha_list = Items.objects.filter(title__startswith=<a letter>) other_list = Items.objects.filter(title__startswith=<not a letter>) context = { "list_a": alpha_list, "list_b": other_list } return context I have been consulting the documents, stackoverflow and the holy google, but so far I have not been able to find a solution. Any help is very much appreciated. -
Sorting filtered results based on word occurrence using Django Model Filter
Platform: Django 1.1, Python 3.6 on a Linux server, backend is MySQL. I'm after a fairly common functionality but I need guidance to where/how to begin this: I have a model object called Article. I'm trying to implement a search function that retrieves articles based on searched terms, and then sort based on occurrences of words in the searched term. In Article, I have the following fields that I'd like to sort or 'prioritise' based on: - name, a text field - keywords, also a text field but would contain comma-separated words - article_text, a text area field that will contain the article itself I want to basically sort the most relevant article to the least relevant, based on the searched terms input against name, keywords, and occurrences of words in article_text. In my views.py I have this function that triggers on request.POST: form_data['search_term'] = request.POST.get('search_term') #removing question mark from term search_term = search_term.replace("?","") #Converting terms to a list of words, then converting all words to lowercase search_terms_list = search_term.split(' ') search_terms_list = [x.lower() for x in search_terms_list] #Fetching results results = Article.objects.filter(reduce(lambda x, y: x | y, [Q(name__icontains=word) | Q(keywords__icontains=word) | Q(article_text__icontains=word) for word in search_terms_list])) I am retrieving … -
Calling a script to save form data in google sheets from django app using js
I am making a web app and I have one form in it. I want to store the data that a person enters, in the form to be mapped in google sheets. The script successfully saves the data onto the sheet but upon saving I am redirecting the user to a new page. The problem is when I attach the code of data mapping, the redirection doesn't work but if I comment the code where I am calling the script, the redirection starts working. # here is the code where i have made the form in HTML file using crispyforms <form method="POST" id="submit_info" class="bg-light p-4 p-md-5 contact-form" name="google-sheet"> {% csrf_token %} {{form|crispy}} <div class="form-group text-center"> <input type="submit" value="Send Message" class="btn btn-primary center py-3 px-5"> </div> </form> This is the js code that executes to save the data onto google sheets <script> const scriptURL = 'https://script.google.com/macros/s/AKfycbwN9jxAQwA9f7qF_tvUbpuRpIhObeAJT8nAqwIRrDZYMPqbyf6j/exec' const form = document.forms['google-sheet'] form.addEventListener('submit', e => { e.preventDefault() fetch(scriptURL, { method: 'POST', body: new FormData(form)})}) </script> This is the code where I am handling the redirection and saving in django views.py file: def store(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() return redirect('thankYouPage') # a second webpage where user should be … -
How to create multiple objects with different values with forloop in django?
I need to create two models from a single template. Creating Product model is fine. The Product model has the ManyToOne relation with ProductVariant. But I got problem while creating ProductVariant model. request.POST.getlist('names') this gives me the result like this ['name1','name2] and the same goes for all. I want to create ProductVariant object with each values. How can I do this ? Also I think there is a problem while stroing a HStoreField. request.POST.getlist('attributes') gives the value like this ['a:b','x:z'] so I converted it into dictionary(but not sure it works). models class ProductVariant(models.Model): name = models.CharField(max_length=255, blank=False, null=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) attributes = HStoreField() price = models.FloatField(blank=False, null=False, default=0.0) views product = product_form.save() attributes = request.POST.getlist('attributes') names = request.POST.getlist('name') up = request.POST.getlist('price') weight = request.POST.getlist('weight') print(names, 'names') # converting attributes into the dictionary for the HStore field for attribute in attributes: attributes_dict = {} key, value = attribute.split(':') attributes_dict[key] = value ProductVariant.objects.create(name=name,...) # for each value I want to create this. -
Pass value to CSS style Tag from Django View
I have this View where I generate a percentage value that depends on some logic in the backend. def my_view(request): #[..other stuff..] perc_value = 80 # this changes with the logic above context = {'perc_value': perc_value} return render(...) In my HTML I need to render a progress-bar that will be filled with perc_value, like this: <div class="progress progress-xl mb-2"> <div class="progress-bar" role="progressbar" style="width: {{ perc_value }}">{{ perc_value }}%</div> </div> I have found this similar question (link), which is pretty old and I can't find a way to make it work. What's the best way for this kind of problem? -
Save method of Django model does not update fields of existing record even if force update
I am trying to update the record that already exists in the database and therefore I use this code if 'supplierId' not in req.keys(): return JsonResponse({'code': 0, 'msg': "supplier was not selected", 'result': ''}, safe=False) if 'assigneeId' not in req.keys(): assigneeId = User(0) else: assigneeId = User(req['assigneeId']) if 'responsibleId' not in req.keys(): responsibleId = User(0) else: responsibleId = User(req['responsibleId']) if 'redistributionMethod' not in req.keys(): redistributionMethod = 0 else: redistributionMethod = req['redistributionMethod'] if 'allCost' not in req.keys(): amount = 0 else: amount = req['allCost'] procurement_doc = ProcurementDocJournal.objects.get(id=pk) print(procurement_doc) procurement_doc.docType = req['docType'] procurement_doc.status = req['status'] procurement_doc.companyId = Company(req['companyId']) procurement_doc.datetime = req['datetime'] procurement_doc.supplierId = Partner(req['supplierId']) procurement_doc.assigneeId = assigneeId procurement_doc.warehouseId = Warehouse(req['warehouseId']) procurement_doc.responsibleId = responsibleId procurement_doc.redistributionMethod = redistributionMethod procurement_doc.amount = amount procurement_doc.comment = req['comment'] procurement_doc.save() where req contains a request something like this { 'docType': 3, 'status': 1, 'companyId': '2', 'warehouseId': '3', 'assigneeId': '5', 'supplierId': '12671', 'responsibleId': '5', 'datetime': '2020-04-01 08:01:00', 'comment': '' } As you can see there is a print which assures me that I selected the correct row when I noticed that these records are not updated I searched for causes and found this question where the guy who asked says The message field was missing from the model definition in … -
Got AttributeError when attempting to get a value for field `name` on serializer
I'm new with this django rest framework thing and I'm having a problem showing one of my models in the api interface. I have 3 models that are related License, Profile and Rules. I can see Profile and License clearly but Rules (which is related with profile and license) gives me the next error: Got AttributeError when attempting to get a value for field name on serializer LicenseSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Rule instance. Original exception text was: 'Rule' object has no attribute 'name'. This is my model file: models.py: class License(LogsMixin, models.Model): """Definicion de modelo para licencias""" name = models.CharField( "Nombre de la licencia", max_length=100, null=False, blank=False) billable = models.BooleanField(default=False) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) class Profile(LogsMixin, models.Model): """Definición de modelo para Perfiles""" name = models.CharField( "Nombre de la perfil de usuario", max_length=100, null=False, blank=False ) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) class Rule(LogsMixin, models.Model): """Definición de modelo para Reglas""" FIELDS = [ ('user_name', 'Nombre de usuario'), ('user_code', 'Codigo de usuario') ] string = models.CharField("Cadena de referencia", max_length=100, null=False, default="", blank=False) profile = models.ForeignKey(Profile, null=False, default=None, on_delete=models.DO_NOTHING) license = models.ForeignKey(License, null=False, default=None, on_delete=models.DO_NOTHING) field = models.CharField("Campo …