Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Design Decision - Should Django tests be state-less or state-full?
So, I am facing this dilemma of designing Django unit tests. I can either make the tests so that they do not depend on each other but this would either mean 2 things: I undo what I did in the test itself and for all the tests. I design the tests in such a way that they don't depend on each other. The second options is I can make the tests state-full as in a real use case scenario. A real user generally never undoes what was done before before performing another operation on the database right? Although I agree, state-less tests are in general better due to the fact that more things can be tested in CI as each test is an independent unit, I think for the database tests, state-full might be a better option. Please share your opinion. Thanks A Fellow StackOverflower -
django cross site redirection crsf token security
Ive been trying to integrate a payment method for my website, it requires verification from an external webpage (bank), it requires a response_url, from which the status and dat wil be posted back on my site, when it operates django gives me an error requiring a csrf token for posting a form, I found a workaround setting @csrf_exempt, but I asume its not the optimal solution, since is less secure, what is the correct solution for csrf token solicitaiton when posting from an external page? def pay_started(request): usu = CuentaUsusario.objects.get(usuario=request.user) response_url = 'http://xxx.xxx.x.xx:8000/cuentas/pay_inscr_finish/' if request.method == 'POST': username = request.POST.get('user_name') email = request.POST.get('email') response_url = request.POST.get('response_url') req = request.POST resp = MallInscription.start(user_name=username,email=email,response_url=response_url) return render(request,'c_cuentas/pay_started.html',{'usu':usu,'resp':resp,'req':req}) return render(request,'c_cuentas/pay_started.html',{'usu':usu,'response_url':response_url}) @csrf_exempt def pay_inscr_finish(request): if request.method == 'POST': req = request.POST token = request.POST.get('TBK_TOKEN') resp = MallInscription.finish(token=token) ttoken = resp.transbank_user authoriz_code = resp.authorization_code tarjeta = resp.card_type ult_dig = resp.card_number return render(request,'c_cuentas/pay_inscr_finish.html',{ 'utl_digit':utl_digit, 'tarjeta':tarjeta, 'ttoken':ttoken, 'authoriz_code':authoriz_code}) -
Is there a way to set a context variable's value within js or html when using Django?
I'm working on a website using python django as a back end, and am currently trying to pull values from a HTML form and pass it to a django form. This is due to only certain fields needing access to data from the database and needing JS on the page to show/hide based on the values of certain selects in the HTML. What I need to do is to set the value of an object's attribute that is passed in from the views.py <script> output = document.getElementById("example"); {{ form.fieldImChanging.value }} = output.value; </script> ... <form action="" method="POST" class="row gy-2 gx-3 align-items-center"> <label for="example">TestField</label> <input type="text" name="example" maxlength="16" size=20 required=""> ... <input class="btn btn-success col-3 mt-2" type="submit" value="Submit"> <a href="{% url '*snipped url*' *snipped vars* %}" class="btn btn-secondary col-3 mt-2">Back</a> </form> Where the trouble lies is in getting that context variable to set, because as of right now that will just create a variable named after whatever the default value of fieldImChanging is in the django form. Is there a way to do this with django at all? -
How to use DetailView correctly?
So, I'm trying to create a Django Application using generic views such as ListView and DetailView. ListView work fine but when I try to detail any of item from ListView i didn't get the DetailView Page. I just get the error: Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['escala_app/medicos/int:pk/'] Here is my code. views.py: class MedicosListView(ListView): model = Medicos template_name = 'escala_app/medicos_list.html' class MedicosDetailView(DetailView): model = Medicos context_object_name = 'medicos_details' template_name = 'escala_app/medicos_detail.html' urls.py urlpatterns = [ url('medicos/update_medicos/<int:pk>', views.MedicosUpdateView.as_view(), name='update'), url('medicos/register/', views.MedicosCreateView.as_view(), name='register'), url('medicos/', views.MedicosListView.as_view(), name='medicos'), url('medicos/<int:pk>/',views.MedicosDetailView.as_view(),name='detail'), ] and the html to redirect to detailview: <ol> {% for medico in medicos_list %} <p><li><a href="{% url 'escala_app:detail' medico.pk %}">{{medico.nome}} {{medico.sobrenome}} </a></li></p> {% endfor %} </ol> -
Video with custom controls not Playing on iOS (safari & chrome)
I'm developing a platform with Django which hosts videos that are uploaded directly on a server. I'm testing the app and the result I got is that the videos are playing fine on Desktop but they are not playing on mobile iOS (safari & chrome), instead they are playing in mobile with android 10. The videos follow the proper format (mp4) and encoding standards (H264, AAC). I've read different topics that talk about the proper way to trigger and play a video (ex.1 ex.2) on iOS, but even if I'm following this guideline I'm unable to trigger the video to play when pressing the play button. I've no idea what's wrong with it. Here is the code: <div class="c-video"> <video class="video" id="video" src="{{ video.video.url }}" type='video/mp4' poster="{{ video.image.url }}"> </video> <div class="controls"> <div class="bar"> <div class="dragger"></div> <div class="barline"></div> </div> <div class="buttons"> <button id="play-pause"></button> </div> <div class="volume-slider"> <input id="vol-control" type="range" min="0" max="100" step="1" oninput="SetVolume(this.value)" onchange="SetVolume(this.value)"></input> </div> </div> </div> <script> var video = document.getElementById("video"); var btn = document.getElementById("play-pause"); btn.addEventListener('click', function(e) { if (video.paused || video.ended) video.play(); else video.pause(); }); </script> I've also tried to trigger the play event directly from the button as follow but nothing changed: <div class="buttons"> <button id="play-pause" onclick="togglePlay();"></button> … -
export table contain image in python django
I'm learning to use python django. There is a condition that I need to export the table data to excel format. I use jquery datatable library (https://datatables.net/) to export table data to excel. But when the table contains images, export to excel does not display the images but still contains data other than images. In general, does export excel not allow export tables with image contents or is there another library that I can use? -
Why is collectstatic adding back files I deleted to my Wagtail project?
So I'm deploying a Wagtail project to a droplet on DigitalOcean and the collectstatic step keeps failing because of a post-processing failure. I didn't need the directory that was failing, so I removed it from my project. But somehow that old directory keeps coming back every time I try to run collectstatic and the post-processing keeps failing on a file that no longer exists but seems to be haunting my server somehow. Here are the things I have tried: Deleting the static directory entirely Deleting the offending directory from my repository and running git clean to remove all untracked files from my server Deleting my entire project directory, creating a new virtualenv and cloning a fresh copy of my project with the offending directory removed Logging off my server and logging back on again Running collectstatic --clear (which doesn't seem to delete anything when I run it) Quitting terminal and restarting that, then logging back onto my server Destroying my entire droplet then creating a new one, creating a new virtualenv and cloning a fresh copy of my project without the offending directory in it. Whenever I run collectstatic, it still is somehow adding back the offending directory I deleted … -
Django Class based Form only updating the final post value
As the title states, I have a table that I'm attempting to update that only updates the final value in the post, from what I understand if I want to update multiple records I must iterate over my request object and update a form instance with the specified ID in my db. Before submission all records have a price_checked of 0. and then after - you can see the final value from the post request updates all the records! postgres table The code in question that updates my model form instance. def post(self,request): if request.method=='POST': for key in request.POST.getlist('product_id'): product_update = ProductTable.objects.get(id=key) form = ProductUpdateForm(request.POST,instance=product_update) print(form) if form.is_valid(): form.save() messages.success(request,message='price checked...') return redirect('product') is anyone able to assist? I've been at this point for over 2 weeks. models/form/view for reference. models.py from django.db import models class ProductTable(models.Model): id = models.AutoField( primary_key=True, editable=False ) product_name = models.TextField(max_length=255,null=False) price = models.DecimalField(max_digits=6,decimal_places=2,null=False) from_date = models.DateTimeField() to_date = models.DateTimeField(null=True) price_checked = models.IntegerField(default=0,null=False) def __str__(self : str) -> str: return f"{self.product_name} - {self.id} with a price check of {self.price_checked}" forms.py from django.forms import ModelForm from .models import ProductTable class ProductUpdateForm(ModelForm): class Meta: model = ProductTable fields = ('price_checked',) views.py from typing import Any, Dict from … -
Django Crispy Forms; Does not load button
I'm just have an issue with Crispy Forms; I cannot get a button to load. I've checked a ton of other StackOverflow forms, but all the examples I've followed, nothing seems to work. example forms.py from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django import forms from .models import ExampleModel class ExampleModelForm(forms.ModelForm): def __int__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.add_input(Submit('submit', 'Submit')) class Meta: model = ExampleModel fields = ['content', 'title'] example views.py def get_form(request): if request.method == 'POST': form = ExampleModelForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/success/') else: form = ExampleModelForm() return render(request, 'example_form.html', {'form': form}) example example_form.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% crispy form %} {% endblock %} My form loads beautifully, but I just cannot get the button to show. I've looked at the docs and I don't see what I am doing differently. Maybe it just doesn't play well with ModelForms? I don't know. I've tried changing the location of def__init__... to be below the Meta class. I defined super() to be super(ExampleModelForm, self) and self.helper = FormHelper(self). I even tried to change {% crispy form %} to {% crispy form form.helper %} in the html file. It … -
Django - Can I add a calculated field that only exists for a particular sub-set or occurences of my model?
Imagine that you have a model with some date-time fields that can be categorized depending on the date. You make an annotation for the model with different cases that assign a different 'status' depending on the calculation for the date-time fields: #Models.py class Status(models.TextChoices): status_1 = 'status_1' status_2 = 'status_2' status_3 = 'status_3' special_status = 'special_status' class MyModel(models.Model): important_date_1 = models.DateField(null=True) important_date_2 = models.DateField(null=True) calculated_status = models.CharField(max_length=32, choices=Status.choices, default=None, null=True, blank=False,) objects = MyModelCustomManager() And the manager with which to do the calculation as annotations: # managers.py class MyModelCustomManager(models.Manager): def get_queryset(self): queryset = super().get_queryset().annotate(**{ 'status': Case( When(**{'important_date_1' is foo, 'then': Value(Status.status_1)}), When(**{'important_date_2' is fii, 'then': Value(Status.status_2)}), When(**{'important_date_1' is foo AND 'importante_date_2' is whatever, 'then': Value(Status.status_3)}), # And so on and so on ) } ) return queryset Now, here's where it gets tricky. Only one of these sub-sets of occurrences on the model requires an ADDITIONAL CALCULATED FIELD that literally only exists for it, that looks something like this: special_calculated_field = F('important_date_1') - F('importante_date_2') #Only for special_status So, basically I want to make a calculated field with the condition that the model instance must belong to this specific status. I don't want to make it an annotation, because other instances … -
How can I calculate the remaining balance of a customer in Django?
info: I am trying to make an app like monthly instalment. When i create a file of Customer. The price of the Property purchased will be add in Customer remaining balance automatically. My app logic is multiple payments for a single customer. I want to add all payments amount in collec_amount and collect_amount will be detuct from the remaining balance. If i delete any payment object from a customer then the remaing balance will be automatically updated before deleting the object. Problem: The code below calculation is not working properlly. when i try to update the exiting payment the calculation create a mess. if anybody have a better solution to the reported post. I would be grateful for any help. models.py class Property(models.Model): area = models.CharField(max_length=255) price = models.IntegerField(default=0) class Customer(models.Model): name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) remaining = models.IntegerField(default=0) collect_amount = models.IntegerField(default=0) def save(self, *args, **kwargs): self.remaining = self.prop_select.price self.remaining -= self.collect_amount super().save(*args, **kwargs) class Payment(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True, related_name='payment') amount = models.IntegerField(default=0) def save(self, *args, **kwargs): self.customer.collect_amount += self.amount self.customer.save() super(Payment, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.customer.collect_amount -= self.amount self.customer.save() super(Payment, self).delete(*args, **kwargs) -
Format a template form in django
I have a form and I want to view in it that shape with HTML where I have a model with these fields: duration, project, and remarks. DURATION PROJECT REMARKS --------------------------------------------------------- 3.0h Django Created models --------------------------------------------------------- 1.0h Django Setup project --------------------------------------------------------- 1.75h ML Meeting with a client --------------------------------------------------------- -
Check callback status of an api request
I need to get the status of a transaction made to an API. According to the documentation After the customer completes the payment, the status is reported asynchronously to the callback URI (optional) if it was specified. I have the callback URL, but I don't know how to access it after the transaction has been made. This is my code to carry out the transaction def post(self, request, *args, **kwargs): self.object = self.get_object() ammount = int(self.object.price) * int(request.POST.get("qty")) req_pay = Api().req_pay("981111111", "johndoe@mail.com", str(ammount)) return HttpResponseRedirect(req_pay.json().get("redirectUrl")) After this it redirects me to a page where the user must complete the payment or cancel. And then the status is reported asynchronously to the callback URI How can I get the status of the transaction after the payment is made or canceled? Regards -
I am deploying my work to heroku, I have this error .. (path="/" and path="/favicon.ico" ) ps: I am using python-django-rest_framework
You can check image of the error here https://i.ibb.co/6N6CvFH/heroku-log-tails.png I have two apps and project URL of first app URL of second app URL of my project Setting.py file -
HTML convert time value to proper formatting when pre-populating input field
I am trying to pre-populate a time field on an input form, and I'm getting the field from a database. I was successful in finding how to do this with the date field by putting this in my value attribute: "value="{{shipment.pickup_date|date:'Y-m-d'}}">" Is there a similar conversion I can make with a time value? I've tried "HH:mm:ss", "H:m:s", to no avail. -
Django logout function stopped working when creating userprofile function
I am learning Django by creating a project. The problem I am facing is that the user logout function stopped working after I created another function to view user profile in view.py. Here are my codes in view.py from django.shortcuts import render, redirect from django.urls import reverse, reverse_lazy from django.http import HttpResponseRedirect from django.contrib.auth import login, logout, authenticate from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from techuser.models import UserProfile from techuser.forms import RegistrationForm # Create your views here. # Decorator def login_executed(redirect_to): """This Decorator kicks authenticated user out of a view""" def _method_wrapper(view_method): def _arguments_wrapper(request, *args, **kwargs): if request.user.is_authenticated: return redirect(redirect_to) return view_method(request, *args, **kwargs) return _arguments_wrapper return _method_wrapper @login_executed('tech_blog:index') def registrationview(request): form = RegistrationForm() if request.method == 'POST': form = RegistrationForm(data=request.POST) if form.is_valid(): user = form.save() login(request, user) return HttpResponseRedirect(reverse_lazy('tech_blog:index')) context = { 'form': form, } return render(request, 'registration.html', context) @login_executed('tech_blog:index') def loginview(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(data=request.POST) username, password = request.POST.get('username'), request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('tech_blog:index')) context = { 'form': form, } return render(request, 'login.html', context) # Logout Function Which I am facing problem @login_required def logoutview(request): logout(request) return HttpResponseRedirect(reverse('tech_blog:index')) … -
Heroku config variables visible via CLI but not via code
I have set config vars for a free-tier Django app on Heroku. They can be seen via the CLI and at the settings page on Heroku. I set the DISABLE_COLLECTSTATIC variable to 1, for example, so that git push to Heroku would finish successfully (and it did). However, I cannot access the variables from code via Python’s os.environ, and $ env via Heroku’s ps:exec does not show them, including DISABLE_COLLECTSTATIC. These variables are not specific to a particular third-party’s add-on. They are named only with alphanumeric characters and the underscore character. I created a Django beginner’s tutorial app to reduce the problem to a minimum and then test it but got the same result. -
Django Upload multiple images from a single button using forms
Have been doing a lot of research but I cant seem to find much information on this. I have a simple blog app where users are able to create a blog post via a model form. I would like users to be able to upload multiple images to their blog from a SINGLE button. Most of the solutions I have found are using the admin panel or are just creating multiple buttons. None are using forms along with a button. I figure the best way to go about this would be to create a new model with a FK to the blog model but I cannot seems to come up with a proper implementation. If you could please point me in the right direction it would be greatly appreciated. -
Persisting Selected Option In Django Template Post-Refresh
I looked at multiple examples in stackoverflow on preserving the selected option in a dropdown after a page refresh. However, the dropdown continues to reflect the first item (CSS) in LANGUAGE_CHOICES. Here is what I have in api.py LANGUAGE_CHOICES = [ {'display_name': 'CSS', 'value': 'css'}, {'display_name': 'Go', 'value': 'go'}, {'display_name': 'Java', 'value': 'java'}, {'display_name': 'Javascript', 'value': 'javascript'}, {'display_name': 'Python', 'value': 'python'}, {'display_name': 'Ruby', 'value': 'ruby'}, ] Django Template file: example.html, iterating on LANGUAGE_CHOICES <label class="label setting-label"for="language">Language</label> <select id="language" name="language"> {% for lang in self.LANGUAGE_CHOICES %} <option value="{{lang.value}}" {%if lang.value == language.value%} selected {% endif %}> {{lang.display_name}} </option> {% endfor %} </select> The iteration on LANGUAGE_CHOICES creates the dropdown correctly, but it is not preserving the selected value after Save button is clicked. Resources: How do I iterate over the options of a SelectField in a template? Django Select Option selected issue -
How do I avoid duplicate queries in Django admin for a get_queryset() overwrite in a ModelAdmin page
I overwrote get_queryset and get the results I require. The problem is however that the page takes quite long to load. Upon checking the SQL debugger, it became apparent that two the same queries are executed and a third similar query. Does anyone have a reason why and how this could be avoided? Thank you kindly in advance. SQL: QUERY TIMELINE TIME (MS) ACTION + SELECT ••• FROM "django_session" WHERE ("django_session"."expire_date" > '''2021-07-13 20:49:27.015683''' AND "django_session"."session_key" = '''26huoisce3p4p3ef0f37vysjzo55uu3h''') LIMIT 21 1.18 Sel Expl + SELECT ••• FROM "auth_user" WHERE "auth_user"."id" = '1' LIMIT 21 0.58 Sel Expl + SELECT ••• FROM "inventory_product" LEFT OUTER JOIN "bolData_invoice_line" ON ("inventory_product"."id" = "bolData_invoice_line"."product_id") GROUP BY "inventory_product"."id") subquery 2 similar queries. Duplicated 2 times. 1625.29 Sel Expl + SELECT ••• FROM "inventory_product" LEFT OUTER JOIN "bolData_invoice_line" ON ("inventory_product"."id" = "bolData_invoice_line"."product_id") GROUP BY "inventory_product"."id") subquery 2 similar queries. Duplicated 2 times. 1449.67 Sel Expl + SELECT ••• FROM "inventory_product" LEFT OUTER JOIN "bolData_invoice_line" ON ("inventory_product"."id" = "bolData_invoice_line"."product_id") GROUP BY "inventory_product"."id", "inventory_product"."ean", "inventory_product"."hscode_id" ORDER BY "return_rate" DESC, "inventory_product"."id" DESC LIMIT 100 1387.94 Sel Expl``` PYTHON/DJANGO: ```@admin.register(ProductProxy) class ProductProxyAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(ProductProxyAdmin, self).get_queryset(request) qs = qs.annotate( total_sales=Coalesce(Sum('invoice_line__invoiced_quantity', filter=Q(invoice_line__invoice_linetype__id=3)),0.0), total_returns=Coalesce(Sum('invoice_line__invoiced_quantity', filter=Q(invoice_line__invoice_linetype__id=7)), 0.0)) \ .annotate( return_rate=ExpressionWrapper(F('total_returns')* … -
Why is DRF serializer returning errors with required fields?
When I make a post request to register a user, the data sent is complete and in order, but the RegisterationSerializer serializer returns an error for the username and password fields. The error reads This field is required. for both fields. My first guess was that the serializer is not receiving the data sent but that's false but the serializer receives the data. What am I doing wrong? Could the validated_data parameter in the create method not be populated. I tested it by printing it out on the terminal when making a request but it didn't print. For the model, I'm using the built-in user model. Serializer from django.contrib.auth.models import User from rest_framework import serializers class RegisterationSerializer(serializers.ModelSerializer): """Registeration serializer""" class Meta: model = User fields = ["id", "username", "first_name", "last_name", "email", "password"] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data["username"] first_name = validated_data["first_name"] last_name = validated_data["last_name"] email = validated_data["email"] password = validated_data["password"] user = User.objects.create_user( username=username, first_name=first_name, last_name=last_name, email=email, password=password, ) return user Views from authentication.serializers import RegisterationSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework.authtoken.models import Token class RegisterationView(APIView): """Registeration View""" def post(self, request): serializer = RegisterationSerializer(data=request.data) # Generate tokens … -
Re-saving a model instance in Django not working, but update() does work
Going a bit crazy with something that stopped working in my Django app (Django 3.2.5, Python 3.9.6) - here's a simplified version: class MyModel(models.Model): attribute_1 = models.CharField(max_length=1, default='0') myModel = MyModel() myModel.save() print(myModel.attribute_1) # OUTPUTS '0' myModel(attribute_1='1') myModel.save() print(myModel.attribute_1) # OUTPUTS '1' The second save() is not being saved, if I retrieve myModel from the database elsewhere I get attribute_1 equal to 0. This, however, does work as I expect it to: myModel = MyModel() myModel.save() MyModel.filter(pk=myModel.pk).update(attribute_1='1') Am I missing something incredibly obvious here? -
Django Model Bidirectional Many to Many Declaration?
I have two models, article and publication, in which I declare a manytomany field within Article. However, I also want to have a reference from publication to articles as well. Is the best way to just declare another ManyToManyField, i.e. Articles = models.ManyToManyField('Article'), and if so, how do I make it so that it's linked to that linking table? class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField('Publication') class Publication(models.Model): title = models.CharField(max_length=30) articles = ??? -
Django Rest Framework (DRF) Refuses to Validate Data with Foreign Keys in Update (PUT) Request
Using Django REST Framework (DRF), I am trying to follow the DRF documentation for nested serializers provided by this link. For the moment, let's assume that my code looks like the following: models.py class PvlEntry(models.Model): pvl_project = models.OneToOneField("review.ProjectList", on_delete=models.CASCADE, related_name='pvl_project') pvl_reviewer = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='+') pvl_worktype_is_correct = models.BooleanField(blank=False, null=False) pvl_hw_description = models.TextField(blank=False, null=False) class ProjectList(models.Model): """ """ project_number = models.IntegerField(blank=False, null=False, unique=True) project_manager = models.CharField(blank=False, max_length=255, null=False) project_name = models.CharField(blank=False, max_length=255, null=False) project_description = models.CharField(blank=True, max_length=1024, null=True) views.py class PvlEntryListCreateAPIView(ListCreateAPIView): """ This view is leveraged for jsGrid so that we can have jsGrid produce a JavaScript enabled view for actions like editing and filtering of the project vetting list. """ queryset = PvlEntry.objects.all() serializer_class = PvlEntrySerializer name = 'listcreate-pvlentry' def get_queryset(self): qs = self.queryset.all() return qs class PvlEntryRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): """ Leveraged for jsGrid """ queryset = PvlEntry.objects.all() serializer_class = PvlEntrySerializer name = 'rud-pvlentry' serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'first_name', 'last_name', 'email' ] class ProjectListSerializer(serializers.ModelSerializer): class Meta: model = ProjectList fields = '__all__' class PvlEntrySerializer(serializers.ModelSerializer): pvl_project = ProjectListSerializer() pvl_reviewer = UserSerializer() def update(self, instance, validated_data): print(validated_data) return super(PvlEntrySerializer, self).update(self, instance, validated_data) class Meta: model = PvlEntry fields = '__all__' Now, I understand that as this … -
How to include a `@cached_property` in a Pandas DataFrame built from a Django Queryset?
I have a django queryset that includes 3 "columns" of type @cached_property. I would like to be able to convert that queryset to a pandas dataframe so that I can do some cool stuff like, allow it to be downloaded in excel format, etc. But, unless I comment out the cached properties from the field list supplied to .values(), I get an exception like: django.core.exceptions.FieldError: Cannot resolve keyword 'enrichment_fraction' into field. Choices are: compounds, formula, id, msrun, msrun_id, name, peak_data, peak_group_set, peak_group_set_id Here's the relevant snippet of code: res = PeakGroup.objects.filter(q_exp).prefetch_related( "msrun__sample__animal__studies", "msrun__sample__animal", "msrun__sample", "msrun__sample__tissue", "msrun__sample__animal__tracer_compound", ) fieldsforpandas = [ "name", "msrun__sample__id", # Used in link "msrun__sample__name", "msrun__sample__tissue__name", "msrun__sample__animal__tracer_labeled_atom", "msrun__sample__animal__id", # Used in link "msrun__sample__animal__name", "msrun__sample__animal__feeding_status", "msrun__sample__animal__tracer_infusion_rate", "msrun__sample__animal__tracer_infusion_concentration", "msrun__sample__animal__tracer_compound__name", "msrun__sample__animal__studies__id", # Used in link "msrun__sample__animal__studies__name", # Cached properties... "enrichment_fraction", "total_abundance", "normalized_labeling", ] forpandas = res.values(*fieldsforpandas) df = pandas.DataFrame.from_records(forpandas) print(df) If I comment out those last 3 cached properties, there's no exception and the df prints to the log just fine. Here's an example of one of the cached properties in the model: @cached_property def total_abundance(self): return self.peak_data.all().aggregate( total_abundance=Sum("corrected_abundance") )["total_abundance"] That one's one of the simpler ones. Is there a way to include the cached properties in the dataframe or am …