Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Unable to implement SimpleJWT
I am working on implementing Simple JWT authentication in Django. I followed the documentation and everything worked fine on my local machine. Now when I was replicating the steps on the server, an error occurred. To give a background, some migration files were deleted earlier, and makemigrations command was giving errors since dependencies were non-existent. Now I went on to this step of rotating refresh tokens, unaware of the fact that some migration files are missing, and ran the migrate command. Now after running the migrate command, Django started throwing errors, but the two token tables (token_blacklist_blacklistedtoken, token_blacklist_outstandingtoken) it creates, were created (obviously with a missing column). Now the TokenObtainPairView API started working, but I thought it can fail since we have a missing table column. So I did the following steps to revert back to the previous version. uninstalled djangorestframework-simplejwt Restored the settings.py Deleted the two token tables from DB using drop table command Now, when I'm following the documentation, I am not able to create the token table again, as the migrate command is telling me there is nothing to migrate. Generally, the applied migrations are registered in django_migrations table, but the token tables migrations were not listed … -
How do I get a visible default value for a field based on two fields, one from the same model and one from another model, in Django?
Following are my two models: class SomeThing(models.Model): name=models.ForeignKey(Name, on_delete=CASCADE) total_fee=models.DecimalField(max_digits=7, decimal_places=2, default=0) class AnyThing(models.Model): name=models.ForeignKey(Name, on_delete=CASCADE) discount=models.DecimalField(max_digits=5, decimal_places=2, default=0) net_fee=models.DecimalField(max_digits=7, decimal_places=2, default="Something.total_fee-discount") I want the net fee to be visible to the user in real time as he is filling up the form. The field must calculate the net fee by subtracting discount in the same model from the total fee in the previous one. Is there any Django-way for achieving it? -
how to use filter in query twice in django
I am trying to filter some data using this query, get_members = PaymentDetails.objects.filter(participants_name=Participants.objects.filter(participants_name=Profile.objects.get(user=request.user))) but I am getting this error The QuerySet value for an exact lookup must be limited to one result using slicing. My models looks like this class Committee(models.Model): committee_creator = models.ForeignKey(Profile, on_delete=models.CASCADE) committee_name = models.CharField(max_length=100) class Participants(models.Model): participants_name = models.ForeignKey(Profile, on_delete=models.CASCADE) participants_committee_name = models.ForeignKey(Committee, on_delete=models.CASCADE) class PaymentDetails(models.Model): participants_name = models.ForeignKey(Participants, on_delete=models.CASCADE) participants_paid_status = models.BooleanField(default=False) participants_amount_paid = models.IntegerField() -
Django dynamic formset with Jquery Ui autocomplete
Hi there I am fairly new to django and need to add dynamic formsets with autocomplete functions for every from. I am not entirely sure what I am doing wrong i have tried a few approaches and this is my most recent! I have function called AutoproductComplete which receives the id of the current formset form input that i want to add the auto complete to. It doesnt work, no errors, not sure why. I also did it after the after method so assume the form has been added to the DOM?' 'html' <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer"> <div class="input-group" style="padding:5px;"> {{form.productName}} {{form.orderQuantity}} <div class="input-group-append"> <button class="btn btn-success add-form-row" style="margin:5px;">+</button> </div> </div> </div> {% endfor %} <br> <div class="row spacer"> <div class="col-12 offset-9"> <button type="submit" class="btn btn-block btn- dark">Create Order</button> </div> </div> </form> JavaScript ''' function AutoproductComplete(id){ const products = []; console.log("This is working") console.log(id) {% for instance in products %} products.push("{{instance.product_name}}") {% endfor %} $(id).autocomplete({ classes: {"ui-autocomplete-input": "highlight"}, source: products, minLength: 1, }); }; AutoproductComplete("id_form-0-productName" ) function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var id = "" var total = $('#id_' + prefix … -
Django templates _set.all two sub table
I have two tables I want to check if there is data or not! {% if user.children_set.all.groups_set.all.exists %} -
How do you handle a PATCH request from HTMX in Django?
I would like to send a PATCH request to my app but I'm not sure how to consume the request in Django. I am currently getting the following error. AttributeError: 'WSGIRequest' object has no attribute 'PATCH' The input field in the HTMX file looks like this (I also made sure to send the CSRF token): <input hx-patch="{% url 'my_update' myobj.id %}" hx-swap="none" /> This is the Django View class MyHtmxView(View): def patch(self, request, *args, **kwargs): form = MyForm(request.PATCH) if form.is_valid(): form.save() # return an okay status? 200? else: return HttpResponse(self.form_invalid(form)) Django is receiving the request, but isn't sure what to do with request.PATCH. I can see in the Django docs that there is a HttpRequest.GET and HttpRequest.POST but no HttpRequest.PATCH https://docs.djangoproject.com/en/3.2/ref/request-response/#httprequest-objects. What's the best way to handle the PATCH? -
How to display products in child loop related to products in main loop with django?
The main loop displays product Card (B, C, D...) related by brand (or category) of product A. In product card B, C, D... That is, a sub-loop, showing up to 3 products with the same (exact) model as product B, C, D... Is there a way to do that for the DetailView. I also want to apply that to the tags on the category page (ListView). With the code in the parent loop it works fine, however the code in the child loop it doesn't work properly. My codes are as below (code has been shortened): Models.py class Modelp(models.Model): name=models.CharField(max_length=100, blank=True, null=True,) slug = AutoSlugField(max_length=100, populate_from='name') class Meta: verbose_name_plural='Models' def __str__(self): return self.name class Product(models.Model): title = models.CharField( verbose_name=_("title"), help_text=_("Required"), max_length=200 ) slug = models.SlugField(max_length=200, unique=True) modelp=models.ForeignKey(Modelp, blank=True, null=True, on_delete=models.CASCADE) category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.RESTRICT) brand = models.ForeignKey(Brand, blank=True, null=True, on_delete=models.CASCADE) store = models.ForeignKey(Store, null=True, blank=True, on_delete=models.CASCADE) popularity = models.IntegerField(verbose_name=_("Popularity"), default=0) class Meta: verbose_name = _("Product") verbose_name_plural = _("Products") def __str__(self): return self.title def get_absolute_url(self): return reverse('product-detail', kwargs={'slug': self.slug}) views.py class ProductDetailView(DetailView): template_name = 'product_detail.html' model = Product def get_template_names(self): if self.request.htmx: return 'product/all_variations.html' return 'product_detail.html' def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context_related_brand = Product.objects.filter(brand=self.object.brand).exclude( slug=self.kwargs['slug'])[:6] context_related_modelp = … -
Acess context from request in Django
How can we access the context passed in template in method views? def method_A(request): context = {"name":"sample"} html_template = loader.get_template('some_template.html') return HttpResponse(html_template.render(context, request)) Template as <div> {{name}} <a href="method_B">Redirect</a> </div> def method_B(request): # Here how to get context which was present earlier context = {"second":"second"} html_template = loader.get_template('template_B.html') return HttpResponse(html_template.render(context, request)) How we can get context in method based views in django.? So that it can be used in another templates. -
Django API split data by unique ID
I am making Django API. I collected place and review data using crwaling program. I want to split review data by building name(unique key), but it seems all reviews are saved together and is spread to all URL. models.py from django.db import models import uuid # Create your models here. from django.utils.text import slugify def generate_unique_slug(klass, field): origin_slug = slugify(field, allow_unicode=True) unique_slug = origin_slug numb = 1 while klass.objects.filter(slug=unique_slug).exists(): unique_slug = '%s-%d' % (origin_slug, numb) numb += 1 return unique_slug class BuildingData(models.Model): building_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, allow_unicode=True, default=uuid.uuid1) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) #building_time = models.CharField(max_length=50) def save(self, *args, **kwargs): if self.slug: # edit if slugify(self.building_name, allow_unicode=True) != self.slug: self.slug = generate_unique_slug(BuildingData, self.building_name) else: # create self.slug = generate_unique_slug(BuildingData, self.building_name) super(BuildingData, self).save(*args, **kwargs) class ReviewData(models.Model): building_name = models.CharField(max_length=50) review_content = models.TextField() star_num = models.FloatField() urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), path('api/buildingdata/<str:slug>/', ReviewListAPI.as_view()) ] A part of crwaling program if __name__=='__main__': for item in building_dict: BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call']).save() #BuildingData(building_name = item['place'], building_loc = item['location'], building_call = item['call'], building_time = item['time']).save() for item … -
Django filters custom date format for DateFilter
Can we customize date format for DateFiler in django_filters. Right now DateFilter accepts yyyy-mm-dd. Can we change it to mm-dd-yyyy? -
How to reference a serializer in Djano
I have two serializers for both Product and Ingredient models, I want to use both relations in the frontend side. As products in Ingredient model (ingredient.products) and I want the same in Product model (product.ingredients), so how can I get it? This is my code, class IngredientSerializer(serializers.ModelSerializer): # products = serializers.SerializerMethodField() //this line doesn't work class Meta: model = Ingredient fields = '__all__' class ProductSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True, required=False) class Meta: model = Product fields = '__all__' And the Ingredient modal, class Ingredient(models.Model): products = models.ManyToManyField('Product', related_name="ingredients", null=True) name = models.CharField(max_length=100, blank=True, null=True) image = models.ImageField(blank=True, null=True) -
Django session is not creating in browser of computer Seems like antivirus blocking to create session session is creating if turn off antivirus [closed]
Django session is not creating in the browser seems like session creation is blocking by antivirus .(Session is working fine with non protected Browser) What may be the route cause of the issue . do we need to follow any standard to create session with out any blockage by antivirus ? -
Filter distinct objects from ManyToMany within ManyToMany
I have following Models in my Django DRF app. class FilterValue(models.Model): code = models.Charfield(…) class ProductVariant(models.Model): filters = models.ManyToManyField("FilterValue", blank=True, …) class Product(models.Model): variants = models.ManyToManyField("ProductVariant", blank=True, …) category = models.ForeignKey("Category", blank=True) And I’m trying to define function on Category model which will return all objects of FilterValue attached to all ProductVariants of all Products that are assigned in the category. Since I’ll have loads of different ProductVarints I can’t get away with nested loops since it’d be really slow. I had multiple attempts to solve it. I can of course get all Products within a Category using: products = Product.objects.filter(category=self) But then I get stuck on the fact that I actually need to filter nested ManyToMany object since I need all ProductVariants of all Products in the QuerySet and then - in the another level I need all ManyToMany FilterValue objects of each ProductVariant. Thank you. -
Create model instance only if its user id field is equal to the logged-in user's id
In a django rest framework app, there's a TextViewSet. The Text object structure is as follows: { text: text_value, author: author_id } When creating a new Text instance, I want to check if the supplied author_id equals the currently logged-in user's id. I've read this question: When to use Serializer's create() and ModelViewset's perform_create(), but still can't decide whether to override Serializer's create(), ModelViewset's create() or perform_create() methods. What's the right method to override? -
How to automatically check if the subscription of the user has expired and to make changes in the model?
I am making a website, where the user chooses a plan that have diferrent durations such as 7days, 14days, 21days. However the plan does not get activated immediately. After the user completes the registation process he has to accept an agreement, and then depending on the type of plan he has choosen the expiration date is set from the date of acceptance, and a field contract_status is set True. Now, I want to know how I can automatically check that the expiration date of a user has reached and set the contract_status of that user to false and then perhaps do some other stuff. But mainly I want to know how I can check subscription expiration automatically to set the field to False. models.py This is the model that has the fields to store the that date of acceptance, expiration and contract status class Contract(models.Model): user = models.OneToOneField(CustomUser, null= True, on_delete=models.CASCADE) contract_status = models.BooleanField(default=False) date_of_acceptance = models.DateTimeField(null= True) date_of_expiration = models.DateTimeField(null=True, blank=True) views.py This is the view that deals with the above model when the user accpets the agreement if request.method == 'POST': agreement = Contract() if request.user.plan == '7days': agreement.user = request.user agreement.contract_status = True expiry = datetime.now() + … -
Static File On Django 3.2 Not Loading
My Problem is quite simple and yet I'm finding it so hard to solve it. The problem is I am not able to load the CSS File and image which are on the static folder located on the root folder of the project. The static folder is not under the app name. My project name is "ecommerce" and my app name is "store". This is my file hierarchy for my project. This is my settings.py I have added my app too. Yes, the STATICFILES_DIRS too. Tried the other one too. STATICFILES_DIRS = [ BASE_DIR / "static", ] I used temp.html for showing the demo and here is my code. And the CSS file which is named main.css After doing all the things properly, the CSS file and image won't load. Errors That I got in my terminal And in developer mode in Chrome As I know this is quite a rookie mistake and I am a beginner. I can't continue forward till this problem is solved. I'd be grateful if someone could come forward and assist me in resolving the issue. -
please explain me what super().save() is exactly doing here (please dont mark it as duplicate question other answers are hard to understand)
please explain me what super().save() is exactly doing here (please dont mark it as duplicate question other answers are hard to understand). Try to keep it easy to understand. I will be very greatfull. Thanks def save(self, *args, **kwargs): original_slug = slugify(self.title) queryset = BlogPost.objects.all().filter(slug__iexact=original_slug).count() count = 1 slug = original_slug while(queryset): slug = original_slug + '-' + str(count) count += 1 queryset = BlogPost.objects.all().filter(slug__iexactf=slug).count() self.slug = slug if self.featured: try: temp = BlogPost.objects.get(featured=True) if self != temp: temp.featured = False temp.save() except BlogPost.DoesNotExist: pass super(BlogPost, self).save(*args, **kwargs) This is the first time i am trying to learn about super().save() and i am finding it difficut to understand from from other answers on stackoverflow -
django-query: get parent value based on children field
I am sorry if I am not very clear with the query I am trying to build, based on the following models: class BankingDetail(models.Model): sfAttachmentID = models.CharField(max_length=18, unique = True) created = models.DateTimeField(auto_now_add=True) class TransactionBankDetail(models.Model): bankingDetail = models.ForeignKey(BankingDetail, on_delete=models.CASCADE, related_name='BankingDetails') institution = models.TextField(blank=True, unique = False, null=True) I am trying to find which institutions I have and how many are they. However, because 1 BankingDetail can have multiple TransactionBankDetail, I want to count this values only once. In other words, based in my query: #institution_by_attachments = TransactionBankDetail.objects.filter(institution__isnull=False).values('bankingDetail__sfAttachmentID', 'institution').annotate(total=1).order_by('total').reverse() institution_by_attachments = TransactionBankDetail.objects.filter(institution__isnull=False).values('bankingDetail__sfAttachmentID', 'institution') for i in institution_by_attachments: print(i) my result will look like {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0067F0000bCRuSx', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': 'Ost89Porque-111', 'institution': 'Atlantic'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008ieSm', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '0060p000008lpYC', 'institution': 'Africa'} {'bankingDetail__sfAttachmentID': '0060p000008lpYC', 'institution': 'Africa'} {'bankingDetail__sfAttachmentID': '0060p000008lpYC', 'institution': 'Africa'} {'bankingDetail__sfAttachmentID': '12365478987test123', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '12365478987test123', 'institution': 'South Pacific'} {'bankingDetail__sfAttachmentID': '12365478987test123', 'institution': 'South Pacific'} If i use this for my aggregate I will be getting the wrong results: Atlantic 5 South Pacific 8 Africa 3 What I want is: South … -
how to pass the total amount of product to payment gateway
i'm building an ecommerce site with django. once the user press checkout, there is an html billing form which popsup and prompts the user to enter address, email etc. i also passed data like email and it worked fine. but when i try for the amount it doesnt pass how would i pass the amount to the Payment gateway? the Html form <form> <div class="container-fluid"> <div class="row no-gutter"> <div class="col-md-12"> <div class="login d-flex align-items-center py-5"> <div class="container"> <div class="row"> <div id="payment-form" class="col-12 col-lg-6 mx-auto"> <h3 class="mb-3">Billing address</h3> <!-- Error messages in this element --> <div class="row g-3"> <div class="col-sm-7"> <label for="firstName" class="form-label">Full Name</label> <input type="text" class="form-control" id="fullName" placeholder="" required> <div class="invalid-feedback"> Valid first name is required. </div> </div> <div class="col-12"> <label for="email" class="form-label">Email <span class="text-muted">(Optional)</span></label> <input type="email" class="form-control" id="email" placeholder="you@example.com"> <div class="invalid-feedback"> Please enter a valid email address for shipping updates. </div> </div> <div class="col-12"> <label for="address" class="form-label">Address</label> <input type="text" class="form-control" id="custAdd" placeholder="1234 Main St" required> <div class="invalid-feedback"> Please enter your shipping address. </div> </div> <div class="col-12"> <label for="address2" class="form-label">Address 2 <span class="text-muted">(Optional)</span></label> <input type="text" class="form-control" id="custAdd2" placeholder="Apartment or suite"> </div> <div class="col-md-5"> <label for="country" class="form-label">Country</label> <select class="form-select" id="country" required> <option value="">Choose...</option> <option>United States</option> </select> <div class="invalid-feedback"> Please select a … -
Django database access speed depends on host used in request
I am having performance/speed issues in a Python/Django/Postgres application. Specifically, the speed of database queries (via Django's ORM) appears to be related to the hostname used in the request to django. The examples I'm using use either localhost or the VM's hostname (dev.virtual). Using the hostname, performance is good, but using localhost there is a significant slowdown (in the order of tens of times slower). I've created a very basic view to test this: def generate_load_view(request, resource): length = int(request.GET.get("length")) length = 2 ** length iterations = int(request.GET.get("iterations")) iterations = 10 ** iterations if resource == "compute": load_generator = generate_compute_load elif resource == "memory": load_generator = generate_memory_load elif resource == "database": load_generator = generate_database_load else: raise Http404() t_start = time.monotonic() load_generator(length=length, iterations=iterations) t_end = time.monotonic() t_elapsed = t_end - t_start response = {"time": t_elapsed} return Response(response) def generate_database_load(length, iterations): model = django.contrib.contenttypes.models.ContentType pks = model.objects.values_list("pk", flat=True) for _ in range(iterations): random_pk = random.choice(pks) random_obj = model.objects.get(pk=random_pk) I'm using django's ContentType object out of convenience. The database (PostgreSQL) is running in a docker container on the same machine. I've used both django's development server (via manage.py) and a gunicorn server with no appreciable change. To reiterate, if I make a request … -
Ajax URL Not Executing The Correct Function in views.py As Defined in urls.py
I am leveraging Ajax for some pie charts but data-ajax-url is not working as intended (or as I thought). Per urls.py, reptibase:item-update should execute the item_update function in my views.py file. item_update never gets executed though and instead the same function associated with the current pages url is executed again. Currently, am getting a parsing error because HTML is coming back instead of json. json is returned from my item_update function though. item.js window.onload = function () { console.log("Child: ", document.getElementById("piee")) var ctx = document.getElementById("piee").getContext('2d'); var rep_name = $("#pie1").attr("data-rep-name") var ajax_url = $("#pie1").attr('data-ajax-url') var _data = [] var _labels = [] // Using the core $.ajax() method $.ajax({ // The URL for the request url: ajax_url, // The data to send (will be converted to a query string) data: { name: rep_name }, // Whether this is a POST or GET request type: "POST", // The type of data we expect back dataType: "json", headers: {'X-CSRFToken': csrftoken}, context: this }) // Code to run if the request succeeds (is done); // The response is passed to the function .done(function (json) { if (json.success == 'success') { var newMale = json.malePerc var newFemale = json.femalePerc console.log(newMale, newFemale) _labels.push("male", "female") _data.push(parseFloat(newMale), parseFloat(newFemale)) … -
how do I save an image in Django using Cropper.js?
I have a little problem again. I have pictures in my database and it must be possible to crop them at will. I'm trying Cropper.js, but I can't save the image afterwards. What am I doing wrong? I am grateful for all ideas! # index.html {% extends 'base.html' %} {% block content %} <section class="py-5 text-center container"> <div class="row py-lg-5"> <div class="col-lg-6 col-md-8 mx-auto"> <!--<h1 class="fw-light">Album example</h1>--> <form class="bg-light p-4 rounded" method="post"> {% csrf_token %} {{ form }} <button class="btn btn-primary my-2" type="submit"> Получить данные </button> </form> </div> </div> </section> {% for apartment in apartments_list %} <div class="album py-5 bg-light"> <div class="container"> <div class="row row-cols-1 row-cols-sm-6 row-cols-md-2 g-3"> {% for img in apartment.images.all %} <div class="col"> <div class="pop card shadow-sm"> <img src="{{ img.img.url }}" width="100%" height="450" alt="" /> </div> <br /> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <a class="pop btn btn-sm btn-outline-secondary" href="{#% url 'apartments:update-image' img.pk %#}"> Редактировать </a> <a type="button" class="btn btn-sm btn-outline-secondary" href="{% url 'apartments:delete-image' img.pk %}"> Удалить </a> </div> </div> <br /> </div> {% endfor %} </div> <h5 class="card-title">{{ apartment.address }}</h5> <h5 class="card-title">{{ apartment.rooms }}</h5> <h5 class="card-title">{{ apartment.floor }}</h5> <h5 class="card-title">{{ apartment.price }}</h5> <p class="card-text">{{ apartment.desc }}</p> <div class="btn-group"> <a type="button" class="btn btn-sm btn-outline-secondary" href="{% url 'apartments:update' … -
The block in my template gets rendered with an incorrect indentation
I have this problem where my block are correctly indented in the template, but when it gets rendered the indentation fails and all the text of my post get out of place. To clarify I'm using django to create a blog. It's just a personal project, I just stated learning like 4 months ago. Actual Blog This is the source code I get: Source Code As you can see all the code should be to the right side of the red line. I don't know what is happening. I have been trying everything for the last 4 hours and nothing. The thing is, this is my firth project so I made a lot of mistakes. When this problem appeared for the first time I didn't pay much attention to it, I thought it was just a html code problem and easy to solve. Now I'm lost. This is a part of the code of my Base template, where the block is: <!-- Main Content--> <div class="container px-4 px-lg-5"> <div class="row gx-4 gx-lg-5 justify-content-center"> <div class="col-md-10 col-lg-8 col-xl-7"> <!-- Post preview--> <div class="post-preview"> {% block content %} {% endblock %} </div> </div> </div> </div> This is the code of my home: … -
How can I add an extra field in the response to understand which item triggered the search result
I have a simple recipe and ingredient models. class Ingredient(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) class Recipe(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) name = models.CharField(db_column='name', max_length=200, blank=False, null=False, unique=True) ingredients = models.ManyToManyField(Ingredient, related_name='product_ingredients') I have added a filter for recipe search when I can add ingredient ids as parameter. It returns the recipes which have those ingredients. The filter is as follows, class RecipeFilter(django_filters.FilterSet): ingredient_have = django_filters.CharFilter(method='filter_ingredient_have') def filter_ingredient_have(self, queryset, name, value): if value: ids = value.split(',') return queryset.filter(Q(ingredients__id__in=ids)) return queryset class Meta: model = Recipe fields = [] The url is something like this /recipes/?ingredient_have=id1,id2 The response is something like { "items": [ { "id": "13261f0d-408d-4a51-9cc2-cb69ee72fe24", "name": "Curry", "ingredients": [ { "id": "08089ff8-03fb-4946-be61-659d799ca996", "name": "oil" }, { "id": "dc9cb6f2-1810-48eb-b7a7-52a4bd9fdccb", "name": "water" } ] } ] } I would like to add an extra field (in Ingredient) so that I can understand in the frontend which ingredient has triggered the product to be in the search result such as, { "id": "08089ff8-03fb-4946-be61-659d799ca996", "name": "oil", "highlight": false/true } I hope I made the problem clear. Could you please give me some suggestion/solution? Thanks in advance. -
If the value recieved in a Decimal Form is an empty string how can I convert it to a float number?
On my page I ask for various things to the user in the form as it's a calculator that does various things, now you see, the thing is if the user does not have the value for bf I want to give the option to calculate with different values, that is why I required is False, so first what I want to archive is that if the form is empty I want to be passed as a 0 or False, how can I archive this? I have the following form: class CMForm(forms.Form): age = forms.DecimalField(max_digits=2, decimal_places=0, min_value=15, max_value=80) sex = forms.ChoiceField(choices=sex) pregnant = forms.BooleanField(initial=False, required=False) lactating = forms.BooleanField(initial=False, required=False) weight = forms.DecimalField(max_digits=4, decimal_places=1, max_value=635) height = forms.DecimalField(max_digits=4, decimal_places=1, max_value=272) bf = forms.DecimalField(label='Body Fat(not required)', help_text='%', required=False, decimal_places=1, min_value=1, max_value=80) activeness = forms.ChoiceField(choices=activity_level) units = forms.ChoiceField(choices=units) this view: def cmr(request): a = float(request.GET['age']) bf = float(request.GET.get('bf', 0)) s = str(request.GET['sex']) g = 0 if s == 'female': g = 1 w = float(request.GET['weight']) h = float(request.GET['height']) act = str(request.GET['activeness']) u = str(request.GET['units']) p = str(request.GET.get('pregnant', 0)) lac = str(request.GET.get('lactating', 0)) dci = 0 bmrm = 10*w+6.25*h-5*a+5 bmrf = 10*w+6.25*h-5*a-161 bmi = round(w/(h/100)**2, 1) if bf is False: bf = round(-44.988 + …