Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Node as opposed to Django for running big python scripts
I am building an app that requires running a python script that implies a significant wait time. I am having a hard time deciding whether I should stick with Django or should dive into Nodejs, due to the fact that I find plugging in my front end (React) a pain point, and because I would like to work with Apollo Server. What is your opinion? Is Nodejs not suited for running such python scripts? Thank you! -
See django template in pytest failure output
During rendering a Django template my pytest based test fails. I would like to see two things: The name of the template, and a snippet of the part which caused this exception. Maybe I am blind, but I don't see it: tests/magic/test_render_search.py:8 (test_render_foo_search_results) @pytest.mark.django_db def test_render_foo_search_results(): portal = PortalFactory.create() foo = fooFactory.create(name='dummy') foo_index.sync_foo(foo.id) foo_index.commit() > html = render_foo_search_results('name=dummy', portal=portal) test_render_search.py:16: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../../magic/templatetags/render_search.py:17: in render_foo_search_results return get_foo_search_results_context( ../../magic/render_util.py:62: in get_foo_search_results_context html_data = cached_foo_render(search_results, ../../magic/render_util.py:41: in cached_foo_render rendered = render_to_string(template, { ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/loader.py:62: in render_to_string return template.render(context, request) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/backends/django.py:61: in render return self.template.render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/base.py:171: in render return self._render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/test/utils.py:96: in instrumented_test_render return self.nodelist.render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/base.py:937: in render bit = node.render_annotated(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/base.py:904: in render_annotated return self.render(context) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/template/defaulttags.py:443: in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) ../../../.pyenv/versions/venv3.9.2/lib/python3.9/site-packages/django/urls/base.py:90: in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
How to display data from a model method
Good evening community I am new to programming and I have been working on a Django project to enhance my skills. I would like to display data from a method model in my templates. Here is the project's model, class Company(models.Model): #Company data company_name = models.CharField(max_length=100) outstanding_shares = models.IntegerField() share_price = models.DecimalField(max_digits= 5, decimal_places=2) revenue = models.IntegerField() expenses = models.IntegerField() total_assets = models.IntegerField() total_liabilities = models.IntegerField() current_assets = models.IntegerField() current_liabilities = models.IntegerField() operating_cashflows = models.IntegerField() capex = models.IntegerField() #Date of creation created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now= True) def __str__(self): return self.company_name #Company methods def net_income(self): return self.revenue - self.expenses Here is the Views file, def tools(request): submitted = False form = CompanyForm() if request.method == 'POST': print(request.POST) form = CompanyForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/simple_investing/tools?submitted=True') else: form = CompanyForm if 'submitted' in request.GET: submitted = True context = {'form': form, 'submitted': submitted} return render(request, 'simple_investing/tools.htm', context) Here is the forms file, class CompanyForm(ModelForm): class Meta: model = Company fields = ('company_name', 'outstanding_shares', 'share_price', 'revenue', 'expenses', 'total_assets','total_liabilities', 'current_assets','current_liabilities', 'operating_cashflows', 'capex') widgets = { 'company_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder' : 'Company name'}), 'outstanding_shares': forms.NumberInput(attrs={'class': 'form-control', 'placeholder' : 'Shares outstanding'}), 'share_price' :forms.NumberInput(attrs={'class': 'form-control', 'placeholder' : 'Share price'}), 'revenue' :forms.NumberInput(attrs={'class': 'form-control', 'placeholder' : 'Revenue'}), … -
django-allauth: reset password email, send the key instead of a link?
With django-allauth, to change password, user go to /password/reset/ and input a email address and confirm (user is redirected to /password/reset/done/ afterwards). Then the user receive an email. User get a link (password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/) with a key from the email, and through that link, user can change password. However, I'd like to reduce the pages user have to open. Here're what I want: instead the reset link, send to user the key only overwrite password_reset_done.html to add a key input form (method="GET") user enter the key and confirm, and get redirected to password/reset/?key=xxx 2 is easy to implement, but I don't know how to implement 1 and 3. Here is the password reset email django-allauth send by default. There's only a password_reset_url. How to replace it with the generated key? And how could I overwrite the url from password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/ to password/reset/?key=(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)? -
django-background-task - A specific kind of task are not running whereas other tasks still run
I have been using django-background-task for a while but the last background-task function I just added is not working. I created a new backgroud_task as below in a marketplace/tasks.py from background_task import background @background(schedule=1) def background_pair_new_account(lv_external_id: str, lv_siren: str, lv_vat_number: str, lv_pack: str) -> None: print(lv_external_id, lv_siren, lv_vat_number, lv_pack) The background task is called as below: from marketplace.tasks import background_pair_new_account background_pair_new_account("12345678", "789234678", "FR01789234678", "full") The background task is well created in backend: TASK NAME TASK PARAMS RUN AT marketplace.tasks.background_pair_new_account [["12345678", "789234678", "FR01789234678", "full"],{}] 28 juillet 2021 09:59 But when I run python manage.py process_tasks, my task doesn't run. However the other tasks still works. What are the reasons why a task would not run even if the execution date is passed, the task is not locked and no error is mentionned ? -
Dictionary web app in Django - how to switch languages so that word in search bar don't delete
I am working on Dictionary web application - similar to Google translate. I have this problem: there are only have two languages, eng and cro and search bar in which user types word that requires translation. When user starts typing, for example some english word, and sees that dictionary is set to CRO-ENG, user needs to switch dictionary to ENG-CRO. But then, word which user started to type when dictionary was set to CRO-ENG deletes. I know it is because ENG-CRO and CRO-ENG are two separately pages but I need that text which is typed in search bar stays there despite switching between languages. There is a part of code (search bar) from eng-cro.html page: {{form.errors}} <form method="GET" action="" autocomplete="off" {% if srch %} value="{{ srch }}" {% endif %}> <div class="search"> <input type="text" name="srch" placeholder="search" id="search" autocomplete="off" list="ddlautocomplete_eng" /> <datalist id="ddlautocomplete_eng"> {% for result in dicty%} <option>{{result.engWord}}</option> {% endfor%} </datalist> </div> </form> There is a part of views.py (after searching, user gets a list of words which starts with the word he search): def eng_to_cro(request): words = Dictionary.objects.order_by('engWord') srch = request.GET.get('srch') if srch: words = words.filter(engWord__istartswith=srch) else: words = None args = {'words': words, 'srch': srch} return render(request, 'app/eng-cro.html', … -
Celery configuration in settings.py file
Can anyone explain about these lines in celery RabbitMQ in Django. Which time it will be use ? I ran 2 tasks(addition operation and endpoint in django) in celery RabbitMq without these lines successfully. So Please explain when it will be used in settings.py and celery rabbitmq CELERY_BROKER_URL = 'amqp://localhost' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' Thanks in advance -
Using Django's Case/When queryset conditions to set more than one value?
I have two values that depend on the same case when condition in my sql call. Currently I duplicate the condition to set each value separately, but can I combine the two identical cases to set both values at once? -
How to use the DateTimeFilter in django-filter, passing it a custom 'method' parameter?
I am trying to call an endpoint configured as such: https://www.nottherealurl.com/foods?transaction_datetime=2020-01-01,2020-01-30 I am trying to filter the foods that were sold during a given time between a start date and an end date. In this case, between 2020-01-01 and 2020-01-30. I have a model called Food and it has a field called transaction_datetime. class Food(CustomMixin): ... other fields ... food_type = models.CharField( max_length=25, null=True, blank=True, choices=FOOD_TYPE_CHOICES, ) transaction_datetime = models.DateTimeField( null=False, editable=False, ) ... other fields ... I have a view setup as such: class FoodView(ListAPIView): serializer_class = FoodSerializer filter_backends = ( filters.OrderingFilter, filters.SearchFilter, filters.DjangoFilterBackend ) filter_class = FoodFilter ordering_fields = ( 'name', 'amount', 'transaction_datetime', '=food_uuid', ) ordering = ('-transaction_datetime',) search_fields = ordering_fields def get_queryset(self): return ( Food.objects.prefetch_related('ingredients').filter(deleted_at__isnull=True) The FoodFilter is configured as such. class FoodFilter(django_filters.FilterSet): food_type = django_filters.CharFilter(method='filter_by_food_type') transaction_datetime = django_filters.DateTimeFilter(method='filter_by_transaction_datetime') def filter_by_food_type(self, queryset, name, value): print("RAN") # printed when I call the appropriate endpoint as stated below value_list = [x.strip() for x in value.split(',')] return queryset.filter( food_type__in=value_list ) def filter_by_transaction_datetime(self, queryset, name, value): print("HELLLOOOO") # this does not show up at all when attempt to call endpoint to filter by transaction_datetime value_list = [x.strip() for x in value.split(',')] start_date = value_list[0] end_date = value_list[1] return queryset.filter(transaction_datetime__range=[start_date, end_date]) class … -
Is there any alternate way that is much quicker than append in python?
I have thousands of data that need to listed using django api in json format. when I try to append the data's to a list it takes more time. is there any alternate way and quickest way to get around this ? -
I want to pass variable from base template ( basic.html which have navigation and footer) to child template(index.html)
I was trying to pass my unicategory variable which I want to show in my navigation of all the templates which I extend (basic.html which contains footer and header) and index.html which is my home page. so the idea is this I have passed the variable in unicategory function and render it in basic.html to show all unique categories in my navigation bar of. i have extended basic.html in index.html and when i use loop to show the unicategory variable its does not working basic.html <nav>`{% for i in unicategory%} <li><a href="{% url 'Stores:categories' i.scategory %}">{{i.scategory}}<span> ( {{i.posts_count}} ) </span></a></li> {%endfor%}` </nav> basic views def basic(request): stores = stores_model.objects.all() unicategory = stores_model.objects.values('scategory').distinct().order_by().annotate(posts_count=Count('scategory')) context = {'stores':stores , 'unicategory':unicategory } return render(request,'Home/basic.html',context) i want to extend this template in index.html as header and i want to show this category on index page also. index.html {% extends 'Home/basic.html'%} {% block body %}------some front page code-----{% endblock %} index.views stores = stores_model.objects.all() context = {'stores':stores } return render(request,'Home/index.html',context) -
python code to zip and download a folder with images
I would like to download images that are uploaded in Django. Currently, I am zipping the folder and storing it in one of the Django folders first and then downloading it. After that, I delete the zipped folder which is in my Django app. Is it possible to zip a folder and directly download it without saving it in my Django folder. zip_path = os.path.join(settings.MEDIA_ROOT, str(project), str(project) + "_images.zip") def make_archive(source, destination): base = os.path.basename(destination) name = base.split('.')[0] format = base.split('.')[1] archive_from = os.path.dirname(source) archive_to = os.path.basename(source.strip(os.sep)) # print(source, destination, archive_from, archive_to) shutil.make_archive(name, format, archive_from, archive_to) shutil.move('%s.%s' % (name, format), destination) make_archive(src_path, zip_path) file_path = zip_path if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/force-download") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) os.remove(file_path) if "selected" in request.POST: shutil.rmtree(src_path) -
Django ajaxmixin image upload
I am absolutely new to Django. The following codes are from a Git project. Here is a great example of Ajax Creatview. I can work with it very well. How do I add self.request.FILES here, for uploading / saving images. I also addedenctype = "multipart / form-data" in the form. I added self.request.FILES to AjaxValidForm class but it didn't work. Any help will be appreciated. Thanks in advance. class SubscriberCreate(LoginRequiredMixin, AjaxCreateView): model = Subscriber form_class = SubscriberForm ajax_modal = 'billing/subscriber_form.html' ajax_list = 'billing/subscriber/subscriber_list.html' class AjaxContextData: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) filter = self.kwargs [filter.pop(key, None) for key in ['pk', 'id', 'uuid', 'slug']] # context['object_list'] = self.get_queryset().filter(**filter) context['%s_list' % self.model.__name__.lower( )] = self.get_queryset().filter(is_deleted=False).filter(**filter).order_by('-id') return context class AjaxValidForm: def form_valid(self, form): data = dict() context = self.get_context_data() if form.is_valid(): form.save() data['form_is_valid'] = True data['form_id'] = form.instance._meta.model_name data['html_list'] = render_to_string( self.ajax_list, context, self.request) data['message'] = 'Successful saved.' else: data['form_is_valid'] = False data['message'] = 'Form validation error!' data['html_form'] = render_to_string( self.ajax_modal, context, request=self.request) if self.request.is_ajax(): return JsonResponse(data) else: return super().form_valid(form) class AjaxCreateView(AjaxContextData, AjaxValidForm, CreateView): def get(self, request, *args, **kwargs): self.initial = self.kwargs self.object = None context = self.get_context_data() if request.is_ajax(): html_form = render_to_string(self.ajax_modal, context, request) return JsonResponse({'html_form': html_form}) else: return super().get(request, *args, **kwargs) -
Django Query "not in" M2M
I got these three models: class Crcheck(models.Model): crlist = models.ForeignKey("crlists.Crlist", on_delete=models.CASCADE) persons = models.ForeignKey("persons.Person", on_delete=models.CASCADE) ... | id | crlist_id | persons_id | | 41 | 2 | 64 | | 42 | 3 | 64 | class Cuslistprofile(models.Model): customer= models.ForeignKey("customers.Customer",on_delete=models.CASCADE) crlist = models.ManyToManyField("crlists.Crlist") ... class Crlist(models.Model): dbname=models.CharField(max_length=200) ... as a result of the M2M Django generates this table "cuslistprofiles_cuslistprofile_crlist" | id | cuslistprofile_id | crlist_id | | 9 | 4 | 2 | | 13 | 4 | 3 | | 14 | 4 | 5 | | 19 | 4 | 7 | what I want to achieve is to get all the crlist values that are in "cuslistprofiles_cuslistprofile_crlist" but missing in "crcheck". In this particular example I want to retrieve 5 and 7. How can I achieve that in Django ORM? Thanks in advanced -
Pip cannot install anything on ubuntu server
I had deleted an existing virtual environment. I created a new one and activated it. Now I am trying to install site packages using pip install -r requirements.txt But I keep getting the error Cannot fetch index base URL https://pypi.python.org/simple/ Could not find any downloads that satisfy the requirement BeautifulSoup==3.2.1 (from -r requirements.txt (line 1)) Now I know that the packages are really old but this is running on python 2.7.6. I am also not able to install anything through pip. I have tried pip install numpy But it shows the same errors. As per the similar questions answered before the suggestion is to use https://pypi.python.org which I have already done but still facing these errors. Would love to hear your suggestions. -
What is the use of -r in the pip install command? [duplicate]
What is the use of -r in this install command? pip install -r requirments.txt -
'QuerySet' object has no attribute 'price'
I am a student learning Django. I write code like this 'QuerySet' object has no attribute 'price' This is the situation in which this error occurs. I am attaching the code I wrote. Any help would be greatly appreciated. I want to write an if statement to save when the price in Designated is equal to the sum of Value.extra cost and Designated(Rep_price='True'), but it doesn't work as I thought. What is the problem? Models.py class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') name = models.CharField(max_length=32) extra_cost = models.IntegerField() def __str__(self): return self.name class Meta: ordering = ['value_code'] class Designated(models.Model): designated_code = models.AutoField(primary_key=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') price = models.IntegerField() rep_price = models.BooleanField(default=True) class Meta: ordering = ['designated_code'] def __str__(self): return str(self.designated_code) class Element(models.Model): element_code = models.AutoField(primary_key=True) designated_code = models.ForeignKey(Designated, on_delete=models.CASCADE, db_column='designated_code') value_code = models.ForeignKey(Value, on_delete=models.CASCADE, db_column='value_code', null=True, blank=True) class Meta: ordering = ['element_code'] def __str__(self): return str(self.element_code) class Join(models.Model): join_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') part_date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.join_code) class Meta: ordering = ['join_code'] Views.py def join_create(request, id): current_category = None designated = Designated.objects.all() element = Element.objects.all() value_object = Value.objects.all() categories … -
Retrieve Similar Objects by Tags in Django
In the book Django 3 by Example (Chapter 2), the author suggests the following to retrieve posts similar to 'current post' based on tags (via the taggit module). post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4] I understand the flow: Get a list of all the IDs for the tags in the current post. Filter all posts basis the list derived above, and exclude the current post. Add a calculated field to the posts derived above that specify the number of tags they have in 'common' with current post. For example, if current post has tags 'one' and 'two', and another post has 'two' and 'three', the calculated field should be same_tags = 1 (i.e. 'two') Here's where I am confused: In point 2 above, will I get a QuerySet that has duplicate posts. For example, if a post has 2 tags in common with the current post, will the resulting QuerySet have 2 instances of the post? I tried this in shell, and this is what it seems to return. For example, if post has two tags in common with current post, it will be included twice. But I am not sure why this should be the … -
question_on_approve() missing 1 required positional argument: 'created'
I am trying to add points once the question is posted on the models. But it is showing question_on_approve() missing 1 required positional argument: 'created'. @receiver(pre_save, sender=question) def question_on_approve(sender, instance, created, **kwargs): if not created: oldQuestionObj = question.object.get(pk=instance.pk) questionObj = instance if oldQuestionObj.status != 1 and questionObj.status == 1: Points.objects.create(point=somepointfromPointsTableForQuestionAsked) -
I have a model form in django, whenever i submit the form i am getting both the custom success message and the default one how to suppress the default
obj.save() messages.success(request,'{} is successfully updated'.format(obj.template_name)) here the obj.save() saves all the changes in database. and then I am printing my custom message after it. -
Add packages outside of pip to elastic beanstalk
I am trying to install django-betterforms on elastic beanstalk using the setup.py. The git repo is located at : github.com/jpic/django-git.betterforms On the local machine,its fine,but I cant seem to get elastic beanstalk to install it. I have added this line in the requirements.txt: -e git://github.com/jpic/django-git.betterforms I get this in the logs: Extracting django_betterforms-1.2.2-py3.8.egg to /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages django-betterforms 1.2.2 is already the active version in easy-install.pth Which states that django-betterforms is installed. Also, on doing cat easy-install.pth I get : ./django_betterforms-1.2.2-py3.8.egg But,later in the logs AWS throws : ModuleNotFoundError: No module named 'betterforms' Also, if I try to ssh into the environment and try to import betterforms,python can't find it. -
How to save image in django database?
I have a newclaim form which allows user to upload a picture The current problem I faced is whenever I try to upload a new picture, it is not stored on my database (which is my models.py) How do I solve this? This is my views.py # Submit a new Claim def newclaim(request): context = initialize_context(request) user = context['user'] if request.method == 'POST': receipt = request.FILES['receipt_field'] ins = SaveClaimForm(receipt=receipt) ins.save() print("The Data has been written") return render(request, 'Login/newclaim.html/', {'user':user}) This is my newclaim.html <form action="/newclaim/" method="post" enctype="multipart/form-data"> <div> <input id="receipt" type="file" name="receipt_field" style="display: none; visibility: none;"> </div> </form> This is my saveclaimform models class SaveClaimForm(models.Model): receipt = models.FileField(upload_to='receipts/%Y/%m/%D', validators=[FileExtensionValidator(allowed_extensions=['jpg','png'])]) -
`python manage.py runserver` shows an old webapp page I developed
I am learning Django so I've created many Django webapps under one directory. For example, \webapps \polls \polls \api \manage.py ... \ponynote \ponynote \frontend \manage.py ... I didn't use a virtualenv for developing django apps. I don't know whether it's the reason that causes the problem as below. App 1 python manage.py runserver works all fine. (default port 8000) App 2 python manage.py runserver still shows the App 1 page. Method I tried: change the port python manage.py runserver 8001, it shows App 2 page. try to find the process ID PID, and kill it. No sign of port 8000. However, this isn't the best solution since I can't change the port everytime when developing a new django app. Does anyone have a clue why this happens? Kudos. -
ERROR: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied
Settings.py file contains # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['project-crm.herokuapp.com', '127.0.0.1'] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' #SMTP Configurations 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') #S3 Bucket CONFIG AWS_ACCESS_KEY_ID= os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY= os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME= '******' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_HOST = 's3.ap-south-1.amazonaws.com' AWS_S3_REGION_NAME="ap-south-1" I got stuck on this error someone please help. I have added AmazonS3FullAccess under user permission. Also edited Block public access in S3 bucket. I also set environment variables in Heroku but this error still comes. -
Django Rest Framework (DRF) sets JSON field to Empty in the to_internal_value function
So I am trying to upload file AND Post JSON data to my API following this solution. I have created the Parser, placed it in my viewset. I even receive the image and the JSON data in the to_internal_value function, which i think runs AFTER the parser parses the data. How ever, as soon as the to_internal_value function is run, the location field is set to empty. I overrided the function to see whats happening, and it seems the field.get_value function is returning the empty value. Here's the parser: class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # for case1 with nested serializers # parse each field with json for key, value in result.data.items(): if type(value) != str: data[key] = value continue if '{' in value or "[" in value: try: data[key] = json.loads(value) except ValueError: data[key] = value else: data[key] = value qdict = QueryDict('', mutable=True) print(data) qdict.update(data) return parsers.DataAndFiles(qdict, result.files) Here's the Serializer: class AssetSerializer(serializers.ModelSerializer): """ Serializes data recieved/retrieved to/from endpoints concerning Assets. """ asset_location = LocationSerializer(required=False,allow_null=True) asset_devices = serializers.PrimaryKeyRelatedField(many=True,queryset=Device.objects.all(),required=False) parent = serializers.PrimaryKeyRelatedField(queryset=Asset.objects.all(),required=False) busy_ranges = serializers.CharField(required=False) time = serializers.ReadOnlyField( source='datetime') status = serializers.CharField(source="current_status",required=False) class Meta: model = Asset fields …