Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can save the data into database in python django which in list form and list is collection of dictionaries?
Hello everyone I am beginner in python django framework and I am stucked in the program please help me. Thanks in Advance. Problem: I am fetching data using requests method and containing every data in dict form and then append it to the list. Now i want to save all the data of the dict into the database as per my models but here I am unable to do that please help me. here is my models code class Question(models.Model): question_title = models.CharField(max_length=300) question_tag = models.CharField(max_length=250) question_url = models.URLField(max_length=300) question_view_count = models.CharField(max_length=50, null=True, blank=True) question_answer_count = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.question_title Here is my views.py file to search the question and save it to database In views.py i am storing data in list which is coming in dict form so basically data is in dict form so how can i perform a loop by which data save into database according to my models.py from the dict form. def questionSearch(request): if request.method == 'GET': question_title = request.GET.get('title',) question_tag = request.GET.get('tag',) url = 'https://api.stackexchange.com/' + f'2.2/search/advanced? order=desc&sort=activity&q={question_title}&accepted=False&answers=1&tagged= {question_tag}&site=stackoverflow' resp = requests.get(url) resp = resp.json() questions = [] question_data = {} for i in resp["items"]: if i["is_answered"]: question_data = { 'question_url': … -
Django: the detail page is not showing(template error)
am working on a Django project where showing the details of post and amount here is my models.py of post class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("Loader:my_job", kwargs={"pk": self.pk}) this is my second models which I inherit Loader post class price(models.Model): my_post = models.ForeignKey(Loader_post, related_name='prices',on_delete=models.CASCADE, null=True, default='') user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, default='') driver_price = models.CharField(max_length=150, null=True) driver_name = models.CharField(max_length=150, null=True) approved_price = models.BooleanField(default=False) status = models.BooleanField(default=False) def get_absolute_url(self): return reverse("Driver:Driverview") def __str__(self): return self.driver_price this is the view.py of both list and details view class offer_view(ListView, SelectRelatedMixin): context_object_name = 'offern' model = Loader_post template_name = "offer.html" def get_queryset(self): qs = Loader_post.objects.filter(user=self.request.user) return qs class offer_view_detail(DetailView): context_object_name = 'offernew' model = Loader_post template_name = "offer_detail.html" here is my HTML page of list view ...when someone clicks on it it shows the detail of next post offer.html {% for my in offern %} <a href="{{my.id}}/">{{my.sender_name}}</a> {% endfor %} and when someone clicks on its route to the detail page .. but it shows template doesn't exist this is my detail page ie. offer_details.hml <p>{{offernew.sender_name}}</p> <p>{{offernew.receiver_name}}</p> {% … -
How can I implement this many to many relationship to self in Django?
I have a repair GUIDE model which has an attributes that takes 'Prerequisites' which can be other guides, so I need to implement a many to many model where each 'Guide' can have many 'Guides' as prerequisites also those guide in prerequites may have their own prerequisites and also one particular guide may be prerequisite guide to more than one guides. Something like in this image.A picture depicting the relationship -
How to query data from mongoDB in Python view when format of data is not a valid filter?
When a user enters a JIRA number from the UI, I get Crucible links that are in the format of - ['https://crucible05.cerner.com/viewer/cru/CCS-28483', 'https://crucible05.cerner.com/viewer/cru/CCS-28520'] In my database, I have crucible links that are present in the format of - ['https://crucible05.cerner.com/viewer/cru/CCS-26041#CFR-2549576', 'https://crucible05.cerner.com/viewer/cru/CCS-26092#CFR-2553342'] (Note the part with the hash which is not present in the data I get above) I need to match all the crucible links that I get from my UI with the ones that are present in the db. I am able to do this matching of links by comparing with substrings using this piece of code - if [e for e in links if e in '\n'.join(crucible_db)]: matching = [e for e in links if e in '\n'.join(crucible_db)] print(matching) Where, links - List of crucible links that I got from the UI crucible_db - List of all the crucible links present in the db If it helps, my Python model looks like this - class reviewComments(models.Model): reviewID = models.CharField(max_length=20, blank=True) commentID = models.CharField(max_length=20, primary_key=True) solution = models.CharField(max_length=50) comment = models.TextField() dateCreated = models.DateField() type = models.CharField(max_length=20, blank=True) crucibleLink = models.URLField(blank=True) authorID = models.CharField(max_length=20) reviewerID = models.CharField(max_length=20) def __str__(self): # pragma: no cover return self.commentID I retrieved all the crucible … -
Django CMS: Aldryn News & Blog Issue
TypeError at /en/ from_db_value() missing 1 required positional argument: 'context' Request Method: GET Request URL: http://127.0.0.1:8000/en/ Django Version: 3.0.5 Exception Type: TypeError -
ValueError: Cannot assign <QuerySet [<Driver: Test Driver>, <Driver: Another Driver>, <Driver: Third Driver>]>
I have a DRF API that is supposed to feed a frontend Android and IOS app. The API has three types of users namely: Driver, Client and Admin. The client is supposed to create a booking record and get assigned a driver automatically by the API. Based on availability days and times. At the moment every day (Sun, Mon, Tue, Wed, Thu, Fri) is a working day and working hours range from 7:00 am to 9:00 pm with working hours inclusive of transition being an hour. For example, booking of 9:00am will take an hour, hence finishing time will be 10:00am, all factors inclusive. Many drivers can have work at the same time. The app should give feedback to the user if they try booking already picked slots. My problem at this time is to loop through already existing drivers from drivers table, left join them to the booking table and and assign them one by one. I was able to assign one driver a job. But when I added drivers, it became difficult. There is something I am not getting well and I do not know what it is. Here are my models. """ models.py """ from django.urls import … -
Django, console shows double GET for a single page request
I'm developing a django server and every time i request a page it appears two GETs for the same page request. The problem isn't from the code because i sent my project to a couple of friends and they run it without any problem and without the double GET's. Even other projects that are not mine and they shouldn't have any kind of problems it happens the same thing when i am the one to run it. I tried to reinstall django and python but it remains the same. Anyone have any idea what can it be? This is what happens when I enter a blank page with the minimum possible code -
Django ( 3.0.3 ) images inserted in my html projects
I’m working with Django and I have problems with images inserted in my html projects I follow many suggestions but nothing works In html I use: {% load static %} body{background: url("{% static 'images/barcelona_1.jpg' %}"); font-family: arial;} <img src="{% static 'images/GreenStart.png' %}" height="130" width="400" alt=""> In urls.py I add: from django.conf import settings from django.conf.urls.static import static urlpatterns = […. ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In settings.py I add: STATIC_DIR = os.path.join(BASE_DIR, 'static/') STATIC = os.path.join(BASE_DIR, 'static/') STATICFILE_DIRS = [ STATIC_DIR, ] -
Get location from firebase database and show on django web server map
Hi Experts i need your helpIn my project i develop a mobile tracking system, Project based on android app and Django web server, So UntilBy using android application i'm able to send continuously location coordinates to Firebase database but problem is...I wan't my Django web server to get location coordinates contiuesly from firebase database and show on Map and move map marker every time when location change, and i don't have any idea how i do this. please tell me how to i achive my task, and if by using firebase database it's not possible then obviously there is an another way. Many Thanks -
How to do form validation with Django?
This is a simple form that is present in my template(comment.html). <form id="my_form" action="{% url 'a' pk=id %}" method="POST"> {% csrf_token %} <input id="in" required minlength="5" name="message" type="text"><br> <button id="click" title="add your comment" type="submit">Comment</button> </form> As you can see there is an input tag inside form whose name is "message".My problem is that when user get this page on his/her computer as a response means they can simply see this form code on their browser. Let assume a user changed the value of the name attribute of input tag and submit the form then I don't get the value of 'message'. Can you tell me how i can write a view to validate my form on the server-side? So that my website stays safe from a malicious user and from a hacker? -
Django URL is not working on anchor tag via ajax call
i'm working on Python Django and i created a view which write and download the csv file. Now i done with Type, URL and data in ajax call and also pass the javascript function in anchor tag. Now issues occur, When i click on button, all data showig on alert, which i want to export in csv but there is no csv download. The download URL is generating in console. when i copy paste this URL in browser and hit enter, so it download the csv file and all data export successfully which i was actually want. The main issue between anchor tag and ajax call in javascript function. Any Dev can resolve my issue? views.py class ServeCSV(ViewBase): TEMPLATE_NAME = None ACTION_ID = None def get(self, request, *args, **kwargs): all_ids = request.GET['id'] all_ids = json.loads(all_ids) data = models.TimeSheet.objects.filter(id__in=all_ids) print(data) ''' print(type(request.GET['id'])) data = query_cache.model_get_or_404(models.TimeSheet, qobj=Q(id__in=ids)) t_id = int(kwargs.get('id')) data = query_cache.model_get_or_404(models.TimeSheet, qobj=Q(id=t_id)) #progress = query_cache.progress_for_student(provider) #data = models.TimeSheet.objects.all() ''' response = HttpResponse(content_type='text/csv') response[ 'Content-Disposition' ] = 'attachment; filename="timesheet.csv"' writer = csv.writer(response) writer.writerow(['TimeSheet info']) writer.writerow( [ 'Activity', 'Client Initials', 'Date', 'Start Time', 'End Time', 'Hours', 'Reviewed', 'Description', ] ) writer.writerow([]) for rows in data: writer.writerow( [ rows.activity.name, rows.client_initials, rows.date_display, rows.start_display, rows.end_display, … -
Run command conditionally while deploying with amazon ECS
I am having a django app deployed on ECS. I need to run fixtures, a management command needed to be run inside the container on my first deployment. I want to have access to run fixtures conditionally, not fixed for first deployment only. One way I was thinking is to maintain a variable in my env, and to run fixtures in entrypoint.sh accordingly. Is this a good way to go about it? Also, what are some other standard ways to do the same. Let me know if I have missed some details you might need to understand my problem. -
How to filter Django ArrayField using lookup
The data present in the ArrayField like below { "submit_candidate" : [ { "requirement" : [ { "name_id" : 14 } ], "candidate" : [ { "name_id" : 2, "rate" : null, "rate_types" : null, "types" : null, "availability" : null, "address" : [ ], "benfit" : false } ] } ], } My Model class SubmittedCandidateInfo(models.Model): requirement = models.ArrayField(model_container=RequirementInfo) candidate = models.ArrayField(model_container=CandidataInfo) def __str__(self): return str(self.requirement[0]) class SubmittedCandidate(models.Model): submit_candidate = models.ArrayField(model_container=SubmittedCandidateInfo) def __str__(self): return str(self.submitted_candidate_id) class Meta: verbose_name_plural = "submitted_candidates" db_table = "submitted_candidate" I'm using this below query to get job_id. SubmittedCandidate.objects.filter(submit_candidate__0__requirement__0__name__job_id=14) But its throwing me error django.core.exceptions.FieldError: Unsupported lookup '0' for ArrayField or join on the field not permitted. -
How do i compare the variable "e[i].value" & " {{result.Corrans}}" in the below code , I am new to Javascript
So i have created a online test in django framework using sqlite3. Exam is the name of the table which has 6 columns - Question , 4 Options & 1 Correct answer. result.Corrans => is the variable which holds the value of the Correct answer from the database. e[i].value => is the variable which gives the value entered by the user. I am facing problem in comparing these two variables due to which i can't set a counter for correct answers to get score of test. The code is <!DOCTYPE html> <head> <title>Online Test</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function() { $("#but1").click(function() { $(".rb").show(); $(".rb").attr("disabled",true); }); }); function getanswers() { document.getElementById("UserAnswers").innerHTML=""; var e=document.getElementsByTagName('input'); for(i=0;i<=e.length;i++) { if(e[i].type=="radio") { if(e[i].checked) { document.getElementById("UserAnswers").innerHTML+= "Q " +e[i].name+"Selected ans is :"+e[i].value+"<br/>"; } } } } </script> </head> <body> <center> <h1> Class VI - Test </h1> <h2>Subject - Social Studies</h2> </center> <div style="padding-left: 30px;"> {% for result in Exam %} <table> <tr> <td>{{result.id}} ) {{result.Question}} ?</td> </tr> <tr> <td><input type="radio" id="Option1" class="rb" name="{{result.id}}" value="{{result.Option1}}">{{result.Option1}}</td> </tr> <tr> <td><input type="radio" id="Option2" class="rb" name="{{result.id}}" value="{{result.Option2}}">{{result.Option2}}</td> </tr> <tr> <td><input type="radio" id="Option3" class="rb" name="{{result.id}}" value="{{result.Option3}}">{{result.Option3}}</td> </tr> <tr> <td><input type="radio" id="Option4" class="rb" name="{{result.id}}" value="{{result.Option4}}">{{result.Option4}}</td> </tr> <tr> <td><label id="corans" class="rb" style="display: none; color: green;"><b>The Correct … -
Django REST Framework received JPEG file as a String to ImageField
I have a model in Django like: from django.db import models from django.contrib.auth.models import User from datetime import datetime # Create your models here. class UserDetails(models.Model): def getFileName(self, filename): return 'profile_pics/'+str(self.user.id)+'/'+filename user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) profile_picture = models.ImageField(upload_to=getFileName, blank = True) country = models.CharField(max_length = 50, default='India') gender = models.CharField(max_length=10, default='NA') birthday = models.DateField(default=datetime.now()) phone = models.CharField(max_length=15) verified = models.BooleanField(default=False) def __str__(self): try: return self.user.username except: return 'Deleted User - '+str(self.phone) Then, I created a REST API that accepts Multipart requests to create a new user as well as save the user_details for the user. I am making the multipart POST request from my app in Flutter with the Image for the profile picture. The image is coming in the body of the request as a String instead of coming in as a file, where I could have read it with request.FILES['profile_picture']. The body of the request that I am getting by doing a print(request.data) is as follows: Data: <QueryDict: { 'username': ['jonsnow'], 'first_name': ['Jon'], 'last_name': ['Snow'], 'email': ['jonsnow@got.com'], 'password': ['jonsnow'], 'country': ['UK'], 'gender': ['Male'], 'birthday': ['2020-4-28'], 'phone': ['5198189849'], 'profile_picture': ['����\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00��\x00�\x00\t\x06\x07\x08\x07\x06\t\x08\x07\x08\n\n\t\x0b\r\x16\x0f\r\x0c\x0c\r\x1b\x14\x15\x10\x16 \x1d"" \x1d\x1f\x1f$(4,$&1\'\x1f\x1f-=-157:::#+?D?8C49:7\x01\n\n\n\r\x0c\r\x1a\x0f\x0f\x1a7%\x1f%77777777777777777777777777777777777777777777777777��\x00\x11\x08\x019\x01�\x03\x01"\x00\x02\x11\x01\x03\x11\x01��\x00\x1c\x00\x00\x02\x03\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x04\x02\x05\x06\x01\x07\x00\x08��\x00Q\x10\x00\x02\x01\x03\x02\x03\x05\x04\x06\x06\x07\x07\x03\x03\x01\t\x01\x02\x03\x00\x04\x11\x12!\x051A\x06\x13"Qa2q��\x14B����\x07#3Rr�\x154Sbs��\x16$C����5��%c�DtEFd����\x17��\x00\x1a\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06��\x00(\x11\x01\x01\x00\x02\x01\x04\x02\x02\x02\x02\x03\x01\x00\x00\x00\x00\x00\x01\x02\x11\x03\x12!1A\x04\x13\x14Q\x05"aqBR�\x15��\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00�Cl�0ɵX��¸�iB�k; ...\uebe8?��'] }> And print(request.FILES) is coming as: Files: <MultiValueDict: {}> So, I made the Multipart REST … -
Empty list inside QueryDict is actually is not empy
I have a QueryDyct object (request.data) in my method and want to do some modifications on so I have copied it: data_dict = data.copy(). On creating an empty list in it, it creates list of list: data_dict['emails'] = [] data_dict['emails'].append('foo@mail.com') data_dict['emails'].append('bar@mail.com') Instead of crating an empty list and append data into it, it creates list of list, and appends data into inner list: On PyCharm watch it is shown as: Why it behaves like this? And for the further processing it is treated (by django validator) as an email with address ['foo@mail.com', 'bar@mail.com'], but I want to have two different emails with appended addresses. How can I construct normal empty list in QueryDict ? -
Trying to send email by smtplib in django project but fatal python error occurs and compiler terminates. How can i solve this issue?
I am trying to send email using smtplib in my django 1.11 project but "Fatal Python error: Cannot recover from stack overflow." errors occurs and compiler terminates without to exception . How can i solve this issue? This same code was working before, I have not updated my python version nor updated my django version but the same code is not working now. I am using python version 3.6.8, django version 1.11 and my IDE is eclipse. def emailSendingFunctionTest(Subject, Message, EmailAddress, leadCaptureEmailStatusId, assignedToId): sender = Constants.EmailConfig_Email() MESSAGE = MIMEMultipart('alternative') MESSAGE['SUBJECT'] = Subject receivers = EmailAddress HTML_BODY = MIMEText(Message, 'html') MESSAGE.attach(HTML_BODY) try: server = smtplib.SMTP(Constants.EmailConfig_SMTP()) server.starttls() server.verify(EmailAddress) server.login(Constants.EmailConfig_Email(), Constants.EmailConfig_Password()) server.sendmail(sender, receivers, MESSAGE.as_string()) server.quit() finally: cursor.close() conn.close() except smtplib.SMTPException as e: print(str(e)) except Exception as ex: print(str(ex)) I am calling this function from an other function like this: emailSendingFunctionTest(subject, message, emailAddressAssignedTo, leadCaptureEmailStatusId, newLead["assignedToId"]) I have attached the screenshot of errors i am facing: I need help to solve this issue as soon as possible. Thanks in advance. -
Difference between staff_member_required and user_passes_test
I've a doubt about the use of this two decorators. In my project I've some view in which I will allow the access only to the staff member. These are restricted area in which a staff can create a post or modify something about the user profile. This area is the admin area of my web site but is not a default django admin. I've create a backend area that doesn't use django admin site. I've this view: MODE 1 from django.contrib.admin.views.decorators import staff_member_required @staff_member_required(login_url='login') def staff_site(request): some code here MODE 2 from django.contrib.auth.decorators import user_passes_test @user_passes_test(lambda u:u.is_staff, login_url='login') def staff_site(request): some code here What is the right way that I must use for my aim? -
Use serializer in itself Django
How can I use my serializer for an instance in the serializer. So in itself Ex: class CompanySerializer(serializers.ModelSerializer): parent = CompanySerializer class Meta: model = Company fields = ("id", "name", "parent") Django doesn't recognize it and asks to create a CompanySerializer.. -
why model attribut is necessary for update view but not create view?
here in the below code in the CreateView theres no mention of model , but since we have mentioned form_class it automatically uses the model class mentioned in the form_class which is Book.but why doesnt it do same with the Update view . in UpdateView if i remove the model attribute it gives error: UpdateBook is missing a QuerySet. Define UpdateBook.model, UpdateBook.queryset, or override UpdateBook.get_queryset(). required code: models.py: class Book(models.Model): name = models.CharField(max_length=50) picture = models.ImageField() author = models.CharField(max_length=30, default="Anonymous") email = models.EmailField(blank=True) describe = models.TextField(default="Good Book") def __str__(self): return self.name views.py: class Upload(CreateView): form_class = BookCreate template_name = "libraryapp/upload_form.html" success_url = reverse_lazy('libraryapp:index') class UpdateBook(UpdateView): model=Book form_class = BookCreate template_name = "libraryapp/upload_form.html" success_url = reverse_lazy('libraryapp:index') -
Linking enum values when used in Django choices
I'm writing a Django web app to allow doctors to manage their pending licenses, certifications, and access to scientific journals in one dashboard. I've created a model JournalEntry that represents information shown on the dashboard about a journal they are subscribed to, with information like renewal date and subscription type built into the model. It is the case that there are certain choices for journal name, so the name field on the JournalEntry model is a CharField: class JournalEntry(models.Model): name = models.CharField( null=False, choices=JOURNAL_NAME_CHOICES, max_length=256) renewal_date = models.DateField( verbose_name="Date of Renewal", auto_now=False, auto_now_add=False, blank=True, null=True, ) sub_cost = models.FloatField( blank=True, null=False, max_length=6, verbose_name='Subscription Cost', ) icon_link = models.CharField( null=True, max_length=1024, blank=True) with the choices defined in an enum at the top like this: JOURNAL_NAME_CHOICES = [ ('NEJM', 'New England Journal of Medicine'), ('JVS', 'Journal of Vascular Surgery'), ] I want to have an icon image associated with each journal we allow for (eg the logo of the New England Journal of Medicine should show up next to the name on the entry on the dashboard), but I'm not sure how I can get the logo image url (say, a google images link) to be associated with the Journal name such … -
Pytest assert django context_data
I'm trying to create pytest for a view, where I added form in get_context_data function def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context["form"] = CommentForm return context I made something like this def test_post_detail_view_queryset(self, client, supply_post): response = client.get(reverse('post_detail', kwargs={'slug': supply_post.slug})) assert response.context['form'] == True But i receive error TestPostDetailView::test_post_detail_view_queryset - AssertionError: assert <class 'comments.forms.CommentForm'> == True. Anyone knows how to resolve it? -
redirect to payment page is blocked by cors policy
i have an django rest api when i redirect user to payment page and i get this Access to XMLHttpRequest at 'https://<bank address>' (redirected from 'https://<my website>') from origin 'https://my origin' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. this is my settings.py INSTALLED_APPS = [ 'corsheaders', # other apps ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # other middlewares ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = [ # 'DELETE', 'GET', 'OPTIONS', # 'PATCH', 'POST', 'PUT', ] i have tried every solution in other related questions. -
NoReverseMatch : How to add foreign key in reverse function?
Getting "Reverse for 'detail' with keyword arguments '{'pk': }' not found. 1 pattern(s) tried: ['picture/(?P[0-9]+)/$']" #views.py class ItemDelete(DeleteView): model = Pic success_url = reverse_lazy('picture:detail', kwargs={'pk': Pic.album_id}) #urls.py urlpatterns - [ # /picture/<album_id>/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), ] #models.py class Pic(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=100) caption = models.CharField(max_length=100) is_favorite = models.BooleanField(default=False) def get_absolute_url(self): return reverse('picture:item-detail', kwargs={ 'id': self.album_id , 'pk': self.pk}) def __str__(self): return self.caption -
Django two models in one view with ajax?
I have created a view that give me the possibility to fill a form using an Ajax call. This the code: # models.py class CrudUser(models.Model): name = models.CharField(max_length=30, blank=True) address = models.CharField(max_length=100, blank=True) age = models.IntegerField(blank=True, null=True) # Views.py from .models import CrudUser from django.views.generic import View from django.http import JsonResponse class CreateCrudUser(View): def get(self, request): name1 = request.GET.get('name', None) address1 = request.GET.get('address', None) age1 = request.GET.get('age', None) obj = CrudUser.objects.create( name = name1, address = address1, age = age1 ) user = {'id':obj.id,'name':obj.name,'address':obj.address,'age':obj.age} data = { 'user': user } return JsonResponse(data)' But if I want to add a new models in my CreateCrudUser how could I do it? Ad example the following one: # models.py class Dog(models.Model): name = models.CharField(max_length=30, blank=True) eyes_color= models.CharField(max_length=100, blank=True) age= models.IntegerField(blank=True, null=True)