Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do all these different languages and libraries work together?
I just got a new job and I am learning a lot of new things. I am learning Git, HTML & CSS, JavaScript, JQuery, Python, & Django. This company from this point on is using a Layered Architecture approach, with a top layer for looks and view, a middle layer for functions and domain, and a bottom layer for databases. My question is, how do all of these languages and libraries work together, what are they used for, and how do each of these function/work together and where they fit in each layer. I have done tutorials on each of these individually, and these tutorials each made there own web app; therefore, I lack the understanding of what they each are used for when used together. I've tried googling and searching the web as to how they work together, but I'm not getting the right answer for the specific libraries and languages I'm supposed to use. Forgive me if I am in the wrong place to ask this question. I am just trying my best to fully understand how I am to use all these things. After my training period here at my new job, I have to take one … -
Store model form in session
I have one model form(ProductForm). In a view I want to take the form data but want to save the form in another view. For this I tried to store it in session like this: formToSave = ProductForm(request.POST,request.FILES) product = formToSave.save(commit=False) request.session['save_product'] = product but getting the following error. 'Product' object is not serializable I used django serializers like this: request.session['save_product'] = serializers.serialize("xml", product) but again got a new error: 'Product' object is not iterable In my first view I have this code: formToSave = ProductForm(request.POST,request.FILES) product = formToSave.save(commit=False) request.session['save_product'] = product In the second view I am trying to get object from session and then trying to save it like this: product = request.session['save_product'] product.save() #saving product permanently Could any one tell me how I can save the model form in another view. -
Django multi-tenancy with automatic database creation for each tenant
So I am working on a Django application that has the following requirements: 1- The app should be able to handle multi-tenants (we call them organizations in our app) with a separate database for each organization/tenant. 2- The application can have a shared database for handling the User model for each organization, thus authentication and login is done through this shared db. 3- After a new organization admin registers for a new account in our application, He/she should be able to -through a form- initialize the creation of a new database for his/her organization, and of course migrate that db and start making CRUD operations on it. Since Django supports multi databases, so there is no problem in doing CRUD operations for any model while pointing django to use the respective database. And since putting all the users in one table in the sahred db and authenticating them from there is ok with our project requirements, so I am not facing a problem with the tightly coupled Authentication backend with the shared database. The problem I am facing is in the required automatic creation of a new database for each organization admin, What I mean by automatic is that the … -
Cannot make form field readonly
I have a formset. It has a field "first_term_comment". I am trying to make this field readonly. But it is not making it readonly. if today < semester.first_term_first_exam_begin_date: form.fields["first_term_comment"].widget.attrs['readonly'] = True If i use disabled attribute it works. But this is not what i need. I need to make it readonly. The object type is : django.forms.models.ModelChoiceField -
Keep getting django.db.utils.ProgrammingError: no results to fetch when running more than 4 processes
I have a script that processes data. When I call it with 1-3 processes it seems to work fine. However, once I get to trying to run it with 6 or more processes django errors out and I get django.db.utils.ProgrammingError: no results to fetch I've read a few threads where they said they fixed it in a later version of psychopg2 so I tried upgrading my package and am currently on version 2.8, but I still get the error. The code that makes the processes for profile_name in profiles_to_run: t1 = Process(target=self.run_profile_for_inspection, args = (odometer_start,odometer_end,inspection,profile_name,robot_inspection_id)) t1.start() list_of_threads.append(t1) thread_count = thread_count + 1 # if thread_count > THREAD_LIMIT: # print('Process cannot handle more than 4 threads currently') # break return list_of_threads def run_profile_for_inspection(self, odometer_start, odometer_end,portal_inspection, profile_name, robot_inspection_id): self.out("Running inspection {} from {}m to {}m for {}".format(portal_inspection.pk, odometer_start, odometer_end,profile_name)) rerun_profile = ReRunProfile(self._options['db_name'],self.out,profile_name, portal_inspection.pk, robot_inspection_id) # rerun_profile.set_odometer_start_and_end(odometer_start,odometer_end) rerun_profile.handle_already_created_inspections() In ReRunProfile the get statement is what it errors out on if theres too many processes def handle_already_created_inspections(self): con = psycopg2.connect(dbname=self.database) time.sleep(10) # print('ReRunProfile', self._odometer_start, self._odometer_end, self.portal_inspection_id, self._profile) robot_inspection_id = self.get_robot_inspection_id(self.portal_inspection_id) portal_inspection = Inspection.objects.get(pk=self.portal_inspection_id) -
Drop down field shows values of all users
I have a form field in Django called Label. My problem is that the field shows the Labels of all users while I only want to show self created labels. models class Label(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) tag = models.CharField(max_length=25) def __str__(self): return self.tag class Birthday(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=25, default="") day = models.DateField() label = models.ForeignKey(Label, on_delete=models.SET_NULL, default=0, null=True, blank=True) def __str__(self): return self.name forms class BirthdayForm(forms.ModelForm): class Meta: model = Birthday fields = ('name', 'day', 'label') class LabelForm(forms.ModelForm): class Meta: model = Label fields = ('tag',) -
getting request time out while loading deep learning model in django view
I have been researching on stack overflow from one week, but i didn't find any solution I created an api like webservice using django, which returns json response, in project view i am loading a deep learning model(loading a .meta graph and ckpt file) which is taking more than one minute to load. yes, it working fine in my local machine, and deployed to heroku. whenever making request to my heroku app it is crashing due to h13 request timeout error, after lots of debugging i came to know its becuase loading tensorflow taking lots of time. its exceeding the request time 30s and its arising error. i have searched to reduce time for loading tensorflow models, even i tried to convert it to .pb file and loading but no use.. please anyone help me out of this issue. How to get rid of request time out error on heroku?? how to reduce the time to load model? or any other cloud platform to host my api with tensorflow support? is there any way to load model once a day and use it everytime?? with tf.Session(graph=tf.Graph()) as sess_fr: saverf = tf.train.import_meta_graph(os.path.join(model, 'model-#####.meta')) saverf.restore(sess_fr, os.path.join(model, 'model-####.ckpt-90')) -
SMTPAuthenticationError at /password-reset/
I am new in Django. I am trying to add a feature in my project that enables user to reset his password through given email. These configurations are in development and not production. This is my configuration in settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') I tried these but nothing seems to be working. I enabled IMAP from gmail settings as well. Can you please help me what am I doing wrong in here! In case if you want to see full error. SMTPAuthenticationError at /password-reset/ (535, b'5.7.8 Username and Password not accepted. https://support.google.com/mail/?p=BadCredentials a24sm3958276ljd.32 - gsmtp') URL: http://localhost:8000/password-reset/ Exception Type: SMTPAuthenticationError b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials a24sm3958276ljd.32 - gsmtp') Exception Location: C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\smtplib.py in auth, line 642 Python Executable: C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.2 Python Path: ['C:\Users\Administrator\Desktop\django_project', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37', 'C:\Users\Administrator\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages'] Server time: Thu, 4 Apr 2019 12:24:22 +0000Learn more at\n5.7.8Request Method: POST RequestDjango Version: 2.1.7Exception Value: (535, Thank you in advance. -
Dropdown menu with submit POST
How to create a dropdown menu, where user can select a name and upon selection a POST send to a url with the name.id selected. The dropbown menu code, populating the name is there but I cannot change the code so it sends the name as POST upon selection. Here is what I have done so far. <form name="searchForm" id="searchForm" method='POST' action="{% url 'views:url' post.id %}"> {% csrf_token %} <div class="input-append"> <div class="btn-group"> <button class="btn dropdown-toggle" data-toggle="dropdown"> - <span class="caret"></span> </button> <ul class="dropdown-menu"> {% for user in current_users %} <li onclick="$('#searchForm').submit()"><a href="{% url 'views:url' post.id %}">{{ user }}</a></li> {% endfor %} </ul> </div> </div> </form> -
Permissions of a user in a group with a custome AbstractUser
I have customer user model with Abstract User that is working well. I basically want to get permissions of a user now but I am getting look up field error: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email'), unique=True, max_length=255) first_name = models.CharField(_('firstName'), max_length=30) display_name = models.CharField(_('displayName'), max_length=30) last_name = models.CharField(_('lastName'), max_length=30, blank=True) date_joined = models.DateTimeField(_('dateJoined'), auto_now_add=True) is_staff = models.BooleanField(_('staff'), default=False) status=models.PositiveIntegerField(default=1,choices=USER_ACCOUNT_STATUS) objects = UserManager() my query is now: Permission.objects.filter( group__user_id=1).exists() but it says user look up/related field is not found. not sure if it helps but my models look like this. members module/app contains User model -
How do i link all my search results to a specific link using Django
I have two class Model in my app, when i make a search i get the contents of the two class Model in my app in the searched results. I can only add just one direct link to a searched class Model. So how can i add a single link to all my class Model searched results? enter code here My Views.py def news_story(request, slug, *args, **kwargs): print(args) print(kwargs) post = get_object_or_404(Post, slug=slug) form = CommentForm(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): #form.instance.user = request.user form.instance.post = post form.save() form = CommentForm() return HttpResponseRedirect(reverse("news_story", kwargs = { 'slug': slug })) comment = Comment.objects.all().order_by("-timestamp") if comment: comment = comment.filter(post=post) try: itm = Post.objects.get(slug=slug) except Post.DoesNotExist: itm = None old_post = Post.objects.all()[:8] new_post = Post.objects.all().order_by("-timestamp")[:3] template = loader.get_template('news_story.html') context = { 'Post': itm, 'post': comment, 'form': form, 'old_post': old_post, 'new_post': new_post, } return HttpResponse(template.render(context, request)) def entertainment_story(request, slug, *args, **kwargs): print(args) print(kwargs) post = get_object_or_404(Entertainment, slug=slug) try: itm = Entertainment.objects.get(slug=slug) except Entertainment.DoesNotExist: itm = None template = loader.get_template('entertainment_story.html') context = { 'Entertainment': itm } return HttpResponse(template.render(context, request)) def search_results(request): query = request.GET.get('q') if query: post = Post.objects.filter( Q(title__icontains=query) | Q(author__icontains=query) | Q(description__icontains=query) ).distinct() entertainment = Entertainment.objects.filter( Q(title__icontains=query) | Q(author__icontains=query) | Q(description__icontains=query) … -
Can we use multiple static_url or static_root in django settings?
I want to add specific assets in a folder and should be able to access with url like /assets/css/main.css Am able to do this with /static/css/main.css but not with /assets/css/main.css What changes do I need to do for django to accept /assets/ path too. Default - STATIC_ROOT = 'app/static' STATIC_URL = '/static/' for accessing assets folders also- STATIC_ROOT = 'app/assets' STATIC_URL = '/assets/' -
Formset form field value is displayed as uuid value
I have a formset. It has a field "first_term_comment". If i display this field in template, i see the actual value with selected dropdown value, as a dropdown select item. But as i apply below code, it show the field with uuid value in the template. if (today < semester.first_term_first_exam_begin_date: form.fields["first_term_comment"].widget = forms.TextInput() form.fields["first_term_comment"].widget.attrs['readonly'] = True It is making the field readonly but it is not showing actual data in the field. It shows the uuid of the data. And it does not show it as dropdown menu. It show as below. But it should be : -
How to get user's result/responses from a interactive video (made on H5P) into our own website (lang: python, framework: Django 2)?
I made an interactive video involving questions/answers and embedded the same in my web application. Now, I would like to know how I can get the user's result ? I found that I can use TinCan API to do that but I am using Python 3.7 version which is not supported by TinCan. Please suggest how i can get and store the user's response data (xAPI statements) in the application backend(SQL). -
Shows different time in admin interface and detailed view
Django 2.1 Settings.py TIME_ZONE = 'EET' USE_TZ = True Models.py in some model XXX there is field: timestamp = models.DateTimeField(_(u'Action DateTime'), auto_now_add=True) def __str__(self): return date_format(self.timestamp , 'SHORT_DATETIME_FORMAT') on a moment of creation 'date' command in terminal show Thu Apr 4 13:47:00 EEST 2019 timestamp entry in database is: 2019-04-04 13:47:00.663416+03 Problem: When I open admin interface with XXX list I see time: 04/04/2019 10:47 a.m. When I open detailed view for this entry, I see: April 4, 2019, 1:47 p.m. What I need is to see: April 4, 2019, 1:47 p.m. also in list -
How to add the cross in a form admin to add an object with django
Hre is my custom django form in admin : class Rent_Form(forms.ModelForm): seller = forms.ModelChoiceField(queryset=Seller.objects.order_by('name')) norm = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple,queryset=Norm.objects.order_by('name'),required=False) equipment = forms.ModelMultipleChoiceField(queryset=Equipment.objects.order_by('name'),required=False) pic = forms.ModelMultipleChoiceField(queryset=Pic.objects.order_by('name'),required=False) class Meta: model = Rent fields = '__all__' But in the admin view i d'ont see the green cross to add an object near all my customs form. How to add the green cross to add object with my form ? Regards -
ImportError: cannot import name _remove_dead_weakref in django virtualenv
After upgrade to 18.04 from 16.04, my django's virtualenv refuses to start: (.djangoenv) mw@desktop:~/theapp$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/home/mw/.djangoenv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 10, in <module> from django.apps import apps File "/home/mw/.djangoenv/local/lib/python2.7/site-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig # NOQA File "/home/mw/.djangoenv/local/lib/python2.7/site-packages/django/apps/config.py", line 4, in <module> from django.core.exceptions import AppRegistryNotReady, ImproperlyConfigured File "/home/mw/.djangoenv/local/lib/python2.7/site-packages/django/core/exceptions.py", line 5, in <module> from django.utils.encoding import force_text File "/home/mw/.djangoenv/local/lib/python2.7/site-packages/django/utils/encoding.py", line 10, in <module> from django.utils.functional import Promise File "/home/mw/.djangoenv/local/lib/python2.7/site-packages/django/utils/functional.py", line 1, in <module> import copy File "/usr/lib/python2.7/copy.py", line 52, in <module> import weakref File "/usr/lib/python2.7/weakref.py", line 14, in <module> from _weakref import ( ImportError: cannot import name _remove_dead_weakref On the djangoenv and outside it $ python --version : `Python 2.7.12` Hoping to resolve the issue, I also install Python 2.7.16 on the desktop, so I get: $ python2.7 --version Python 2.7.16 Answers to the same error in other contexts did not help and my search led to no more clues. So really appreciate your hints. -
how to restrict duplicate value to insert in table before form.save()
I want to restrict duplicate entry of "business name" in my database. As I have created a form and function is taking value from the template and I am saving form data in DB and it is working fine but it is not checking duplicate entries before it inserting into Db. so what I want is code will check "business name" already present in DB or not. If data present with the code should give the message that data already present with this name else data will be saved. This is the model in the project class SupplierModel(models.Model): mine_id = models.ForeignKey(MineDetails, on_delete=models.CASCADE, null=True, blank=True) business_name = models.CharField(max_length=100,null=True,blank=True) business_website=models.CharField(max_length=100,null=True,blank=True) name = models.CharField(max_length=200, null=True, blank=True) mobile_no=models.CharField(max_length=100,default='0000000000',blank=True,null=True) email= models.EmailField() pincode= models.TextField(blank=True, null=True) address= models.CharField(max_length=400, null=True, blank=True) landmark= models.CharField(max_length=400, null=True, blank=True) area= models.CharField(max_length=200, null=True, blank=True) city= models.TextField(default='') state= models.CharField(max_length=100,blank=True) map_loc= models.CharField(max_length=400, null=True, blank=True) pan= models.CharField(max_length=200, null=True, blank=True) gstin= models.CharField(max_length=200, null=True, blank=True) notes= models.CharField(max_length=200, null=True, blank=True) function i wrote in views --------------- @login_required def supplier_add(request, template_name='SupplierDetails.html'): if request.method == 'POST': form = SupplierForm(request.POST) # print("abc") if form.is_valid(): form.save() # return HttpResponse("ok saved") return redirect('inventory_management:supplier_manage') else: form = SupplierForm() # print(form) # duplicates = SupplierModel.objects.values('business_name').annotate(name_count=Count('business_name')).filter(name_count__gt=1) # print(duplicates) # records = SupplierModel.objects.filter(business_name__in=[item['business_name'] for item in duplicates]) return … -
Get data from object/input and send it to django db
I'm insert html code using object and now i need to get info from input by pressing already existing button (in same object) and send this data to django So on my page i tried this <object data="https://www.privat24.ua/rd/send_qr/liqpay_static_qr/qr_ce9c0d63f7d84e298a0128c28ae5bde9"> <embed src="https://www.privat24.ua/rd/send_qr/liqpay_static_qr/qr_ce9c0d63f7d84e298a0128c28ae5bde9"> </object> <button type="submit" class="pay-bt">Next</button> You can go that link and see the same as on my page https://www.privat24.ua/rd/send_qr/liqpay_static_qr/qr_ce9c0d63f7d84e298a0128c28ae5bde9 That is the view on this page As you can see there is an object must be created def reg1st(request): us = request.session['token'] un = CustomUser.objects.get(username=us) context={'username':us} #pay = Pay.objects.create(ddmm=timezone.now(), u_name=us, # token_used=un.referal, # amount=a) #pay.save() return render(request, 'enter/reg1st.html', context) I want to get amount from amount input after I click 'PAY' and create an object 'pay' with this amount after I click 'Next' -
Checksum Failed in payumoney in Django?
I have implemented according to docs https://developer.payumoney.com/redirect/ But i am getting error checksum failed, I am using sandbox test url view.py import hashlib from random import randint from django.shortcuts import render def Home(request): MERCHANT_KEY = "KeytCX7l" key = "keytCX7l" SALT = "salt2TuHze" PAYU_BASE_URL = "https://sandboxsecure.payu.in/_payment" posted = {} # Merchant Key and Salt provided y the PayU. for i in request.POST: posted[i] = request.POST[i] hash_object = hashlib.sha256(str(randint(0,20)).encode('utf-8')) txnid = hash_object.hexdigest()[0:20] posted['txnid'] = "b17ef6d19c7a5b1ee83b" posted['amount'] = 10.00 posted['firstname'] = "Ravi" posted['email'] = "ravibhushan29@gmail.com" # posted['phone'] = "70007240543" posted["productinfo"] = "new product" hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5" posted['key'] = key hash_string = '' hashVarsSeq = hashSequence.split('|') for i in hashVarsSeq: try: hash_string += str(posted[i]) except Exception: hash_string += '' hash_string += '|' hash_string += SALT hashh = hashlib.sha512(hash_string.encode('utf-8')).hexdigest().lower() return render(request, 'payment.html', {"posted": posted, "hash": hashh, "MERCHANT_KEY": MERCHANT_KEY, "txnid": txnid, "hash_string": hash_string, "action": PAYU_BASE_URL}) I have passing value according to docs of payumoney, I have checked hash and hash_sequence as same as: hashSequence = key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5||||||salt. payment.html <html> <head onload="submitPayuForm()"> <script type="text/javascript"> var hash = "{{ hashh }}"; function submitPayuForm() { if(hash =='') { return; } var payuForm = document.forms.payuForm; payuForm.submit(); } </script> </head> <body> <h2>PayU Form</h2> <br/> {% if error %} <span style="color:red">Please fill all … -
Django: Restrict staff user to create groups having more permissions than his own group
I've created a Django app having multiple types of users. There is one Superuser who can access all the data and do the modification stuff. There are few staff users, who have limited access, mostly of view but can add new users and groups. Below is the group permission for the staff user. He can add a new group but cannot change, view or delete existing. But when I try to create a new group, he can assign all the possible permissions to the new group, even though he doesn't have those permissions himself. Below is the view he can see when creating a new group. How can I only show those permissions which the staff user himself have and not to show complete options? I am using Django 2.1 -
forms.py Cannot import model from models.py
I am trying to use django forms... but whenever I try to import a Design model from models.py , I KEEP getting: cannot import name Design Here is my forms.py from django import forms from .models import Design class NewDesign(forms.ModelForm): class Meta: model = Design fields = ['category', 'designImage'] Here is my models.py from django.db import models class Design(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, related_name='design_category', on_delete=models.CASCADE) designImage=models.ImageField() timeuploaded=models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.user) I KEEP GETTING IMPORT ERROR ImportError:cannot import name 'Design' Both models.py and forms.py are inthe same App folder. I don't know why it is not working but it should work....Any help will be appreciated . Thanks -
How to serialize string into a list?
But when im posting the product like this : "product": [ { "product_id": 1, "product_name": "product", "quantity": 1 }, { "product_id": 2, "product_name": "product1", "quantity": 3 } ] I'm getting expected a dictionary but got list serializers.py class CustOrderSerializer(serializers.ModelSerializer): price = serializers.SlugRelatedField(slug_field='price', queryset=Price.objects.all()) # product = serializers.SlugRelatedField(slug_field='product', queryset=Product.objects.all()) area = serializers.SlugRelatedField(slug_field='address', queryset=Area.objects.all()) city = serializers.SlugRelatedField(slug_field='city', queryset=City.objects.all()) coupon = serializers.SlugRelatedField(slug_field='code', queryset=Coupon.objects.all()) # coupon = CouponSerializer() product = ProductSerializer(many=True) class Meta: model = CustOrder fields = '__all__' viewsets.py class CustOrderViewSet(viewsets.ModelViewSet): queryset = CustOrder.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = CustOrderSerializer My serializers.py class CustOrderSerializer(serializers.ModelSerializer): price = serializers.SlugRelatedField(slug_field='price', queryset=Price.objects.all()) # product = serializers.SlugRelatedField(slug_field='product', queryset=Product.objects.all()) area = serializers.SlugRelatedField(slug_field='address', queryset=Area.objects.all()) city = serializers.SlugRelatedField(slug_field='city', queryset=City.objects.all()) coupon = serializers.SlugRelatedField(slug_field='code', queryset=Coupon.objects.all()) # coupon = CouponSerializer() product = ProductSerializer(many=True) class Meta: model = CustOrder fields = '__all__' class CustOrderViewSet(viewsets.ModelViewSet): queryset = CustOrder.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = CustOrderSerializer -
how could i store the values inside the session
x = json.loads(session1) session_id = x['Details'] print(session_id) request.session['session_id'] = session_id the output is showing ['session_id'] = 0xxi236ef like this actual value is not storing -
Create record via id with relationship DRF
I'm fairly new to Django Rest Framework (also Django). I have a Budget and each Budget will have its Series. Whenever I return the Budget I return the relation of Series: BudgetSerializer class BudgetSerializer(ModelSerializer): series = SeriesSerializer() class Meta: model = Budget fields = ('id', 'date', 'created_at', 'document_number', 'total', 'document_type', 'series', 'hash', 'hash_control') SeriesSerializer class SeriesSerializer(ModelSerializer): fiscal_entity = FiscalEntitySerializer() class Meta: model = Series fields = ('id', 'created_at', 'series_prefix', 'document_type', 'starts_in', 'fiscal_entity') Whenever returning a Budget it comes with the Series as intended but whenever I try to create a new Budget it gives the error Series field is required. I guess DRF is expecting a whole new Series object to be able to create that new Series but I wouldn't like to create a new Series but reference an existing one by its id. Something along the lines of: curl -X POST \ http://localhost:8081/v1/budget/ \ -H 'Accept: application/json' \ -H 'Content-Type: application/x-www-form-urlencoded' \ -H 'Postman-Token: 5755d65e-a159-45c9-949e-14724ace41d5' \ -H 'Token: 5D4kFFiXjXeOwM4rrA3xwhL8hYnzK9XXQMo1Fym_suDiTEOdznoYlebaT78F9NUnAE_xobAXuT8leLwZy1acaFZ5yAubqhxbx99xvw4ucHNhd1HMEtLhshO0' \ -H 'cache-control: no-cache' \ -d 'date=2019-02-04&document_number=0202&total=221.23&series=0e4e6251b43849d390bca19c7b722e4d&document_type=PF&created_at=2020-02-04%2023%3A50%3A25&last_document_hash_control=h2kY3j0B%2BO2bF2n5zLzvYLGcpf2OeidqY7GCsG2gusvooqoAJUclCykJz8GqaAqq76rbQYb9ICJRZAd0fXGYYH%2Fi6yox%2FJY0k8YRPGlYLANyqJCMxio80sR%2BZONgH%2FrTk0fykwX4q2%2BuMs7qCOXbksY%2FFB773NJYMWjQz1Jo%2BrI%3D' I have tried several approaches as series = SeriesSerializer(read_only=True) in BudgetSerializer and other approaches that doesn't seem to work. Could a more experienced dev explain why DRF is waiting for a new …