Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle file after saving and save that file in django?
I want to user to upload file, and then I want to save that file (that part is working), then I want to calculate data in this document and export it in results.html. Problem is this, I already used return function but I want to do some calculation and save that file and for user to download.How to additionally save edited file, and forward to user to download and to see data? def my_view(request): print(f"Great! You're using Python 3.6+. If you fail here, use the right version.") message = 'Upload as many files as you want!' if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #This part is doing calculations for uploaded file dfs = pd.read_excel(newdoc, sheet_name=None) with pd.ExcelWriter('output_' + newdoc + 'xlsx') as writer: for name, df in dfs.items(): print(name) data = df.eval('d = column1 / column2') output = data.eval('e = column1 / d') output.to_excel(writer, sheet_name=name) return redirect('results') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form, 'message': message} return render(request, 'list.html', context) def results(request): documents = Document.objects.all() context = {'documents': documents} return render(request, 'results.html', context) -
DRF not showing PK field in serializer
Similar to this, I want to show all related information in the serializer output on the HTML page: Model: class Shipment(models.Model): name = models.CharField("name", max_length = 128) date = models.DateField() class DebitSum(models.Model): name = models.CharField("name", max_length = 128) shipment = models.ForeignKey(Shipment, on_delete = models.CASCADE, blank = True, null = True) serializers: class ShipmentSerializer(serializers.ModelSerializer): class Meta: model = Shipment fields = ["pk", "name", "date",] class DebitSumSerializer(serializers.ModelSerializer): shipment = ShipmentSerializer() class Meta: model = DebitSum fields = ["name", "shipent",] This leads to a HTML page where I can fill in a name for the shipment, but not just an ID or PK. I tried altering to: class ShipmentSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Shipment fields = ["id", "name", "date",] The request.data reads as follows: <QueryDict: {'shipment.name': ['2'], ...}> #oviously fails whereas I would want it to look that way: <QueryDict: {'shipment.pk': [2], ...}> -
Getting KeyError in SAML response; django-saml2-auth, django 2.2.2
Error Getting KeyError (see image above) in SAML response, I can see that decoded response says success and I am assuming that this is related to claim mapping but I have commented "ATTRIBUTES_MAP" in setting as it said optional setting. Any help is appreciated. -
Why do we use css files for each APP in Django?
I'm following a Django course on Udemy where the instructor used specific css files for each app he created, my question is very simple: Why do need to create css files for each app? i'm asking this because those specific css files for that particular can affect other styles of the website. Like why can't we just create global css files for the whole website and thats it? -
TypeError __init__() got an unexpected keyword argument 'uploads_to'
I created models for my project but am getting the following error. Help. -
How to approach complex circular relations between models?
I'm trying to set up a database for my media files, but can't find a way to translate the data to models and useful, but not redundant relationships. There are Photos and Videos as models on the media side. class Photo(MediaFile): file = UniqueNameImageField(upload_to="photos/") preview = UniqueNameImageField(upload_to="previews/", blank=True) thumbnail = models.ImageField(upload_to="thumbnails/", blank=True) mediatype = "photo" class Video(MediaFile): file = UniqueNameFileField(upload_to="videos/") preview = UniqueNameFileField(upload_to="previews/", blank=True) thumbnail = models.ImageField(upload_to="thumbnails/", blank=True) mediatype = "video" ... As Metadata I want to store Persons, Quotes, and Releases (contracts with the appearing person). class Person(models.Model): name = models.CharField(max_length=255) age = models.IntegerField(null=True, blank=True) city = models.CharField(max_length=255, blank=True) district = models.CharField(max_length=255, blank=True) occupation = models.CharField(max_length=255, blank=True) def __str__(self): return " ".join([self.name, "("+str(self.age)+")", self.city]) class Release(models.Model): person = models.ForeignKey("Person", on_delete=models.PROTECT) file = models.FileField(upload_to="release_docs/") class Quote(models.Model): person = models.ForeignKey("Person", on_delete=models.PROTECT) #alternative by-line if it should not be name+age alt_by = models.CharField(max_length=255) text = models.TextField() Every Release should be tied to a person. Every Quote should be tied to a person. But then every Person, Release, and Quote will be tied to the Photos and Videos. The tricky part is this: Not every release counts for every photo a person is in, but rather just for a specific set of photos … -
Django-polymorphic child with foreign key to another child
I have a polymorphic model of which one of the children is dependent on another child. Below you can see a simplified version of these models. from django.db import models from polymorphic.models import PolymorphicModel class Poly(PolymorphicModel): name = models.CharField(max_length=100) class ChildA(Poly): some_field = models.CharField(max_length=100) class ChildB(Poly): some_other_field = models.CharField(max_length=100) childa = models.ForeignKey(ChildA, on_delete=models.CASCADE) When I run migrations, the error is: poly.ChildB.childa: (models.E006) The field 'childa' clashes with the field 'childa' from model 'poly.poly'. What am I doing wrong? -
How to get all the duplicated records in django?
I have a model which contains various fields like name, start_time, start_date. I want to create an API that reads my model and displays all the duplicated records. -
How do I access a property attribute of a Django model through a QuerySet filter in Django Views?
I have a model: class IpdReport(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) package=models.ForeignKey(Package, on_delete=CASCADE) The Patient model looks like this: class Patient(models.Model): name=models.CharField(max_length=100) mr_uid=models.CharField(max_length=9) #A gender field needs to be added here later @property def patient_number(self): if self.pk: return "{}{:04d}".format('PN/D/', self.pk) else: return "" def __str__(self): return self.name+"-"+self.patient_number Now, I want to filter data of IpdReport to in a views function to display a table based on the property attribute of the Patient model, that is, patient_number. Here's what I tried but it didn't work: def sort_by_pt(request): if request.method=='POST': pn=request.POST.get('enter_patient_number') report=IpdReport.objects.filter(patient__patient_number=pn) total1=report.aggregate(Sum('realization__amount_received')) total2=report.aggregate(Sum('realization__deficit_or_surplus_amount')) context={'report': report, 'total1':total1, 'total2':total2} return render(request, 'account/ipdreport.html', context) else: sort=EnterPatientNumber() return render(request, 'account/sort.html', {'sort':sort}) The error it threw: Related Field got invalid lookup: patient_number What are my options to achieve it? -
Total price of items in the cart
Hello I have a problem I can not get total price in my template. I have no idea what i did wrong. Even if I set cart.total = 10 in views.py it does not apply. It is just 0.00 or does not display anything. models.py class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = models.DecimalField(default=0.00, decimal_places=2, max_digits=11) @property def total_price(self): return self.OrderItem_set.aggregate( total_price=Sum(F('quantity') * F('item__price')) )['total_price'] or Decimal('0') HTML: {% extends 'shop/base.html' %} {% block content %} <div class="container"> {% include 'shop/navbar.html' %} <div> {% for item in cart %} <li>User: {{ item.order_user }}<li/> <li>Items: {% for order_item in item.order_items.all %} {{ order_item.order_item.title}} {% endfor %} <li/> <li>Is ordered: {{ item.ordered }}<li/> <li>Total: {{ item.total }}<li/> {% endfor %} </div> <td class="num">{{ cart.total_price|floatformat:"2" }}</td> </div> {% endblock content %} -
Using a xml file for front end on a website
I am creating a blogging website. I have already done the backend in Django. I decided to purchase a template for the front end and they sent me an XML file instead of HTML files. How possible is it for me to install and customize it on my domain? And if its possible, how should I do it? -
how to calculate the sum of annotations
this is my view: def shop_orders(request): orders = Order.objects.filter(items__shop=request.user.user_profile_shop).prefetch_related( Prefetch('items', queryset=OrderItem.objects.filter(shop=request.user.user_profile_shop ).annotate(ord_total=ExpressionWrapper( F('price') * F('quantity'), output_field=DecimalField()) # how to sum all ord_total ), to_attr='items_from_specific_shop')).order_by('-created').distinct() return render(request, 'account/paneli/shop/orders/shop_orders.html', {'orders': orders}) how to sum all ord_total -
How to allow only the author of the article in the Django UpdateView to access the article update page?
How to allow only the author of the article in the Django UpdateView to access the article update page? #views.py class ArticleUpdate(LoginRequiredMixin, UpdateView): model = Article template_name = 'articles/update_view.html' context_object_name = 'article_update' form_class = ArticleForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['securities_types_list'] = StocksETFsBonds.objects.all() context['tags_list'] = Tag.objects.annotate(articles_quantiy=Count('taggit_taggeditem_items')).order_by( '-articles_quantiy')[:10] return context -
using forloop.counter to access array elements in django templates
I have a form element form.category and an array categories being passed to a django template like this <ul id="cat_options"> {% for x in form.category %} <li class="results" id="results_{{forloop.counter}}" name=''> {{x}} </li> {% endfor %} </ul> here the length of form.category is same as categories now I want to give name attribute to every li element like <li class="results" id="results_{{forloop.counter}}" name={{categories.forloop.counter}}>. But this doesn't seem to work. I have also tried name="{{categories}}-{{forloop.counter}}". Thank you -
how to access react or django on the browser inside ubuntu ec2 instance
I have built a django and react application folder structure full_stack | | backend / | ------- > frontend / in my computer i can serve them on local separately on 127.0.0.1:8000 for the backend and 127.0.0.1:3000 for the frontend but i noticed that when i push the full_stack folder that include both application into an AWS EC2 instance, even though inside the terminal after spinning up them individually there is no error and it is served, nothing is render when i try to access them on the browser using the public IPV4 DNS:3000 and public IPV4 DNS:8000. (public IPV4 DNS image below) is there something that i am doing wrong here? How do i access each app started in ec2 on the browser? Please note there is no docker or docker-compose associated to it. just the applications directly. Thank you in advance -
Django query sort by all satisfying a condition and then all the others
I have two models City and Contact. class City(models.Model): name = models.CharField(max_length=40) class Contact(models.Model): name_surname = models.CharField(max_length=60) preference = models.IntegerField(default=0, choices=PREFERENCE) city = models.ManyToManyField(City) Given a city "A" I am trying to query my DB to get a list of All contacts that have "A" as a city order by preference And after that all contacts that don't have "A" as a city order by preference So basically if my Contact table (name, city, preference) had something like Tom,NY,2 John, LA, 5 Mike, NY, 1 Richard, SF, 4 and the city I am considering is NY, the query would return: Mike, NY, 1 Tom,NY,2 Richard, SF, 4 John, LA, 5 -
Upgrade SQLite version inside a python3.6 venv without root or affecting the global packages
First off, I know similar questions have been answered, but I can't find any solutions for my particular constraints. If there is one, please point me to it. I'm trying to start a django project. However, I can't run the development server. The problem seems to be the SQLite version. I have 3.7.17 installed, django requires 3.9 or later. So I need to upgrade it. The problem is I'm using one machine from many, used by multiple developers all working on different projects, but sharing the same global python packages. So whatever changes I need to make, need to be inside my venv. And I don't have root access on the machine. Also, I don't plan on using SQLite as the DB for the project, so if that means I can somehow bypass this requirement, that would be fine as well. However, I assume, in that case I'll need to somehow transfer the django admin app to my DB of choice as well? Note: I'm quite new to web development or programming in general, so a dumbed down explanation would be greatly appreciated. Thanks. -
try & except not working in Djnago APIView
I have written logic to delete an item in the apiview of Django. The logic is to assign that item to a variable and by using Try and Except. It works fine when there is an object but when there is no object I got an error saying "leads.models.Lead.DoesNotExist: Lead matching query does not exist." I should be getting a message of Deal doesn't exist with 400 status as I had that inside Except. I am getting 500 errors in the post. def delete(self, request,pk, *args, **kwargs): id = pk lead = Lead.objects.get(id=id) # abc.delete() # return Response({"message": "Lead has been deleted"}, # status=status.HTTP_200_OK) try: lead = Lead.objects.get(id=id) if lead.delete(): return Response({ "message": "Deals has been deleted" },status=status.HTTP_204_NO_CONTENT) except lead.DoesNotExist: return Response({ "message": "Deal doesnt exist" },status=status.HTTP_400_BAD_REQUEST) My urls is: path('lead/<int:pk>', ChunksLeadCreate.as_view()), I hope this code is enough to fix the issue. -
DRF + SerializerMethodField with Foreign Key
Unlike this question I do not only want to read the data from my SerializerMethodField but also write in it: Model: class Artist(models.Model): name = models.CharField("name", max_length = 34) note = models.CharField("additional info", max_length = 128, blank = True, null = True) class Album(models.Model): name = models.CharField("name", max_length = 34) artist = models.ForeignKey(Artist, on_delete=models.CASCADE) Serializer: class AlbumSerializer(serializers.ModelSerializer): artist = serializers.SerializerMethodField("get_artist") def get_artist(self, obj): return [obj.artist.pk, obj.artist.name, obj.artist.note] class Meta: model = Album lookup_field = "name" fields = ["name", "artist",] read_only_fields = ["name",] ViewSet: class AlbumViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = AlbumSerializer lookup_field = "name" def get_queryset(self): return Album.objects.all() def retrieve(self, request, artist = None): query = Album.objects.filter(artist = artist) results = AlbumSerializer(data = query, many = True) results.is_valid() return Response(results.data) def put(self, request, name): print("------->", name, request) return Response("test") Getting data from the API works just fine, but when calling api/nevermind I see all the album data but not the dropdown for artist in the browsable API view of DRF. -
How to use django-filter to make a filter with reverse foreign key value?
I have a models class TDebtor(models.Model): first_name = models.CharField(max_length=250, blank=True, null=True) surname = models.CharField(max_length=250, blank=True, null=True) middle_name = models.CharField(max_length=250, blank=True, null=True) iin = models.CharField(max_length=50, blank=True, null=True) alive = models.BooleanField(blank=True, null=True) birth_date = models.DateField(blank=True, null=True) class TDebtData(models.Model): agr_num = models.CharField(max_length=250, blank=True, null=True) id_num = models.CharField(max_length=250, blank=True, null=True) loan_amount = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) principal_amount = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) id_debtor = models.ForeignKey('TDebtor', models.DO_NOTHING, related_name="debtor_debt_data") views.py class ProductList(ListAPIView): queryset = TDebtor.objects.prefetch_related(Prefetch('debtor_debt_data', queryset=TDebtData.objects.select_related('id_debtor'))) for i in queryset: print(i.debtor_debt_data.agr_num) serializer_class = TDebtorSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['iin', 'first_name', 'surname', 'middle_name', 'birth_date', 'alive'] if I'll make a filter with the fields of TDebtor it's okay, but how I can filter with agr_num?, I mean if I'll send agr_num=1238HFD32 it will return me TDebtor that has this agr_num -
Using an django-sass-processor library in django but refuses to apply the style because its MIME type is not a supported stylesheet
I'm using Sass for my Django(3.2.6) website with the help of libraries called django-compressor and django-sass-processor to compile it to a .css file. It works fine during development but when I try to disable the DEBUG mode in the settings the error will pop-up. Refused to apply style from 'http://127.0.0.1:8000/static/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Setting up the library I've added the following code to my settings.py (between ---- lines): # Application definition INSTALLED_APPS = [ -------------------------------------------------------------------- 'sass_processor', -------------------------------------------------------------------- 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'openfiles.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [str(BASE_DIR.joinpath('templates'))], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'openfiles.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Manila' USE_I18N = True USE_L10N = True USE_TZ = True # … -
Django model - calculate field on save does not work
This is the model I have: class Order(models.Model): """ Model for orders """ order_statuses = [ ("PR", "Accepted"), # The default status has to be the first (with index = 0) ("PS", "Status 1"), ("VY", "Status 2"), ("ZR", "Status 3"), ("OK", "Status 4") ] customer_name = models.CharField(max_length=255) customer_email = models.EmailField(blank=True) ordered_foods = models.ManyToManyField(Food) table = ForeignKey(Table, on_delete=CASCADE) status = models.CharField(choices=order_statuses, default=order_statuses[0], max_length=2) total_price = models.FloatField(editable=False, default=0) def save(self, *args, **kwargs) -> None: """ This calculates the total_price of the created order """ if not self.id: super(Order, self).save(*args, **kwargs) self.total_price = self.calculate_total_price super(Order, self).save(*args, **kwargs) @property def calculate_total_price(self) -> float: print('Total price:', self.total_price) print('All prices of the foods in order:', self.ordered_foods.values_list('price', flat=True)) total_price = 0 for ordered_food in self.ordered_foods.values_list('price', flat=True): total_price += ordered_food print('Price ordered food:', ordered_food) print('Total price:', total_price) return total_price def __str__(self) -> str: return f"{self.id} / {self.customer_name} / {self.table.name} {self.table.number} / STATUS: {self.status} / {self.total_price}" What I'm trying to achieve is, that the total_price of my Order model will get immediately calculated after a user clicks the Save button. The code I pasted above works only if I create the Order (after which the total_price is 0) and then I just re-save it again. However, this does not … -
Invalid Endpoint Error using heroku and MinIO
I am have a django site and I published it with heroku. The files are stored in a local docker container with MinIO. I am using django-storages for connecting to the MinIO Storage as it supports AWS S3, with the AWS_S3_ENDPOINT_URL = "(Computer IP):9000/". In my local computer it works fine with (Computer IP):9000/. And when I use localhost on my computer it works with no problem. But in heroku says invalid endpoint. I have port forwarded the 9000 and 9001 Ports and allowed them through the firewall. What did I get wrong? Error Log ValueError at /admin/users/profile/add/ Invalid endpoint: (Computer IP):9000/ Request Method: POST Request URL: (Heroku IP) Django Version: 3.2.5 Exception Type: ValueError Exception Value: Invalid endpoint: (Computer IP):9000/ Exception Location: /app/.heroku/python/lib/python3.9/site-packages/botocore/endpoint.py, line 287, in create_endpoint Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.6 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Mon, 30 Aug 2021 09:37:06 +0000 Settings.py - AWS Info 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 = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_ENDPOINT_URL = "(ComputerIP):9000/" DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Thank you! -
How to retrieve first not null query set Django
I'm trying to get unique, not null data in my model. Ex : I have Django Model Query set data like {{id : 1,organisation :None},{id : 1,organisation :Google},{id : 2,organisation :Facebook},{id : 2,organisation :None}} Expected Result : {{id : 1,organisation :Google},{id : 2,organisation :Facebook}} Is there any way to get the first, not null value in Queryset based on the organization key? Thanks in advance. -
best way to create feature field for a product in Django
a Mobile device has many features in different types. RAM=4: int fingerprint=yes : boolean camera=face detection, touch focus, panorama ... how to create field for features, create an app for features and declare each feature type ? : class IntFeature(models.Model): title = models.CharField() value = models.IntegerField() class BoolFeature(models.Model): title = models.CharField() value = models.BooleanField() class CharFeature(models.Model): title = models.CharField() value = models.CharField()