Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Specifying Django widget attribute in ModelForm rather than as HTML <style>
I have a Django input slider defined as follows: #widgets.py from django.forms.widgets import NumberInput class RangeInput(NumberInput): input_type = 'range' #forms.py from polls.widgets import RangeInput class VoteForm(forms.ModelForm): class Meta: #model = CC_Responses model = CC_Resp_NoFK fields = ['Person_ID', 'Test_date', 'Response_value'] # following added from SliderModelForm widgets ={ 'Response_value':RangeInput } which is “processed” by the view def p2vote(request,q_id): CC_question = get_object_or_404(CC_Questions, pk=q_id) # if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): item = form.save(commit=False) item.Q_ID = q_id item.save() return redirect('/polls/p2') else: formV = VoteForm() return render(request, 'pollapp2/vote.html', {'var_name':CC_question,'form' : VoteForm()}) and in the template I have the inline CSS <style> /* Following CSS is used by the input slider (range) since Django assigns id value of id_Response_value */ /*See: https://stackoverflow.com/questions/110378/change-the-width-of-form-elements-created-with-modelform-in-django */ #id_Response_value{width:300px;} </style> which is associated with the slider/range <label for="Response_value">Response value</label> {% render_field form.Response_value rows="1" class="form-control" %} I obtained id_Response_value by looking at the source of the rendered HTML in the browser – I guess I could explicitly set an ID. All the above works exactly as I want. I can control the width of the range slider using CSS. Now, I believe, inline CSS is a “bad thing”, so as a step to improve my code I’m trying to … -
I want to display the images and user can select one of them
I am new at Django I want some helps. Basically,I want from users that they can select multiple images and save it, but I got like this and I don't know how to do it. I want to display the images and user can select one of them. please help. models.py class Images(models.Model): product_image=models.ImageField(upload_to='media',null=True, blank=True) def __str__(self): return "{}".format (self.product_image) class user_select(models.Model): name = models.CharField(max_length=200, null=True, blank=True) product_image=models.ForeignKey(Images, on_delete=models.CASCADE) def __str__(self): return "{}".format (self.name) forms.py class UserForm(forms.ModelForm): class Meta: model = user_select fields = '__all__' views.py def home(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'home.html', {'form':form}) home.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container mt-5"> <div class="row mt-5 mr-5"> <div class="col-md-8 mt-5"> <div class="card border border-secondary mt-5"> <div class="col-md-8 mt-5" align='center'> <form method="POST" action="" > {% csrf_token %} <div class="col-md-8"> {{ form|crispy }} </div> </form> <button type="submit" class="btn btn-success mt-5 mb-5">Place Order</button> </div> </div> </div> </div> </div> {% endblock %} enter image description here -
Dehydrate the same field django
I have a model Student: class Student(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, verbose_name='Name') lastname = models.CharField(max_length=100, verbose_name='Lastname') history = HistoricalRecords() Also I have a model: class Class(models.Model): id = models.AutoField(primary_key=True) student = models.models.ForeignKey(Student,on_delete = models.CASCADE, related_name='+') my admin.py class ClassResource(resources.ModelResource): class Meta: model = Class fields = ('student',) def dehydrate_student(self, Class): student= getattr(Class.student, "name") return '%s' % (student) class ClassExportAdmin(ImportExportModelAdmin, ClassAdmin): resource_class = ClassResource admin.site.register(Class, ClassExportAdmin) Now I am executing only name, is that possible to dehydrate the same field student one more time. I need past into my 2 column the surname of the student. -
Django : Rename a file with the username and the the timestamp before uploading
I am newbee in Django. I have an app where I can upload multiple files. I would like to rename the file by including the username that is authenticated and the timestamp : "bild.png" should become "bild_John_Bown_202204055.png" I use the Microsoft Graph tutorial on Django to the authentication process (https://docs.microsoft.com/en-us/graph/tutorials/python). Anyone can help me to include that in my code. Thank you models.py from django.db import models class UploadFiles(models.Model): documents = models.FileField(upload_to='document/', blank=True, null=True) uploaded_at = models.DateTimeField(auto_now_add=True) forms.py from django import forms from django.forms import ClearableFileInput from .models import UploadFiles class FilesForm(forms.ModelForm): class Meta: model = UploadFiles fields = ['documents'] widgets = {'documents': ClearableFileInput(attrs={'multiple': True}),} views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from base.auth_helper import get_sign_in_flow, get_token_from_code, store_user, remove_user_and_token, get_token from base.login_helper import * from django.core.files.storage import FileSystemStorage from os import listdir from os.path import isfile, join, getmtime from django.conf import settings from base.forms import FilesForm from base.models import UploadFiles def home(request): context = initialize_context(request) return render(request, 'home.html', context) def initialize_context(request): context = {} # Check for any errors in the session error = request.session.pop('flash_error', None) if error != None: context['errors'] = [] context['errors'].append(error) # Check for user in the session context['user'] = … -
how to delete an specific item from a foreign key within .views? Django
Im working on a Django app where you can join events only under the approval of the owner of the event. By now, I have the function that adds the current user to the event for approval. .views @login_required def request_event(request, pk): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) Attending.objects.create(post=post, attendant=request.user) messages.success(request, f'Request sent!') return redirect(previous) except post.DoesNotExist: return redirect('/') and here is the function that deletes de user request (By now is deleting the request of the current logged user) @login_required def remove_attendant(request, pk): previous = request.META.get('HTTP_REFERER') try: post = Post.objects.get(pk=pk) #attendant = #post.attending_set.all Attending.objects.filter(post=post, attendant=request.user).delete() messages.success(request, f'User removed!') return redirect(previous) except post.DoesNotExist: return redirect('/') My situation here is that I'm a having problem to get the attendants of the event (all the users who where added as atendant), so that the owner can reject which ever request he want. How can I change this so that the function is going to delete a specific user of the event? Thanks!! Additional: models.py class Attending(models.Model): is_approved = models.BooleanField(default=False) attendant = models.ForeignKey(User, related_name='events_attending', on_delete=models.CASCADE, null=True) post = models.ForeignKey('Post', on_delete=models.CASCADE, null=True) class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) urls.py path('post/<int:pk>/remove_attendant/', views.remove_attendant, name='remove-attendant'), -
Django - how to create a form field containing checkboxes WITH an 'Other' text input field
I'm creating a form in Django, and would like to give users a list of checkboxes with the option of having an Other _____ text input as one of the choices. Here's my code using MultipleChoiceField and CheckboxSelectMultiple: class IntakeFormSimple(Form): def __init__(self, *args, **kwargs): super(IntakeFormSimple, self).__init__(*args, **kwargs) preferred_pronouns = forms.MultipleChoiceField( choices=(("she/her", "she/her"), ("he/him", "he/him"), ("they/them", "they/them")), # <--- add "Other" here label="What are your preferred pronoun(s)?", widget=forms.CheckboxSelectMultiple, ) -
How to implement a low cost (semi) chat in django/mobile app
I want to implement a semi (realtime) web chat. The project has 2 user groups, Managers and Users. The manager is in a group chat with his users. There are a couple of demands/problems: Now the thing is django is hosted on pythonanywhere, they dont support websocket. The cost of the project has to be low so streamer is not an option for now. I can do it over rest api but there will be a lot of requests on the server side, i dont know if this is a problem over time. Anyone done a project like this ? please advise. -
How to use Django's hidden `through` models in a `Q` expression
I learned yesterday that you can use a through expression in a key path that's in a Q expression. And I learned that when filtering using fields in M:M related tables, the resulting queryset is more like a true join (where the root table record is duplicated and combined with multiple related table records). I learned that I could accomplish this using ModelA.mmrelatedModelB.through.filter() in the shell. For example, I have 106 PeakGroup records, and every PeakGroup for compound "citrate" also links to compound "isocitrate", so if I query for 1, I get back 106 records. And if I query for either, I get back 212: In [16]: PeakGroup.compounds.through.objects.filter(Q(compound__name__exact="citrate")).count() Out[16]: 106 In [17]: PeakGroup.compounds.through.objects.filter(Q(compound__name__exact="citrate") | Q(compound__name__exact="isocitrate")).count() Out[17]: 212 However, I learned in the comments under this stack answer, that I should be able to accomplish the same thing in the Q expression only, without referencing PeakGroup.compounds.through. I imagined the expression might look something like this: PeakGroup.objects.filter(Q(through_peakgroup_compound__compound__name__exact="citrate") | Q(through_peakgroup_compound__compound__name__exact="isocitrate")).count() but I have been unable to figure out how to construct the "path" that includes the through model... Every attempt results in an error something like: FieldError: Cannot resolve keyword 'through_peakgroup_compound' into field. Perhaps in the comments of that linked stack answer, there … -
what's gettext_lazy on django is for?
maybe is a dummy question but i have read on the documentation of Django about the "gettext_lazy", but there is no clear definition for me about this exact function and i want to remove it and i found this implementation from django.utils.translation import gettext_lazy as _ and is used on a django model field in this way email = models.EmailField(_('email address'), unique=True) what's is for? what's happen if i remove it? -
how do I request a user and save the user in a Foreignkey field of a model
I've been at it for some time but can't find a way to set the 'customer' to the 'ShippingAddress' model's customer foreignkey field, how do I query the customer field so that along with the shipping data through the form, the customer gets saved in the foreignkey field as well. thx in advance! **models.py** class Customer(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=150) class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) address_two = models.CharField(max_length=200) ... **views.py** def checkout(request): if request.method == 'POST': form = ShippingForm(request.POST) customer = request.user.customer if form.is_valid(): # how to get the customer and send it back to the shippingmodel form user = ShippingAddress.objects.get(customer=customer) form.save() return redirect('store:checkout_shipping') else: form = ShippingForm() else: form = ShippingForm() context = {"form": form} return render(request, 'store/checkout.html', context) -
Configuring multiple databases in Django
Introduction I have read Django docs: Multiple databases, but it doesn't seem to work for me after upgrading from 3.2 to 4.0. Other changes have been made, but since I'm working in a development environment, I chose to remove all previous migrations and run ./manage.py makemigrations again, but it did not help to solve the issue. Router Definition First, here's how I define the router. You'll notice it's nearly identical to the example, but I include mostly everything in the admin_db database (with two exceptions: custom apps api.dictionary and api.pdf). /api/authentication/routers.py class AdminDBRouter: """ A router to control all database operations on models in the authentication application, all and any dependent applications, and Django administrative applications. """ route_app_labels = { 'admin', 'auth', 'authentication', 'contenttypes', 'sessions', 'sites', 'token_blacklist', } def db_for_read(self, model, **hints): """ Attempts to read models defined in any app in 'self.route_app_labels' go to 'admin_db'. """ if model._meta.app_label in self.route_app_labels: return 'admin_db' return None def db_for_write(self, model, **hints): """ Attempts to write models defined in any app in 'self.route_app_labels' go to 'admin_db'. """ if model._meta.app_label in self.route_app_labels: return 'admin_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in any app defined in 'self.route_app_labels' is … -
Migrating my Django project on Heroku is showing django.db.utils.ProgrammingError: relation "users_customuser" does not exist
Migrating my Django project on Heroku is showing django.db.utils.ProgrammingError: relation "users_customuser" does not exist. But this is working completely fine on my local. Running migrations: Applying account.0001_initial...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "users_customuser" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 230, in apply_migration migration_recorded = True File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 118, in __exit__ self.execute(sql) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 145, in execute cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, … -
Problems with JSON data can't get it rendered on template
I have the models.py with employee and all the info. With one click i want to render all the info of my employee. the thing is, I have 2 columns one for names and one for information. when i click a name the right column has to come up with the array with name last name..... i can see it on the console but i can't get it rendered. Think i have problems with the key but i dont know. here is the code.. views.py in this function i want to get the id of the name by jsonloads by clicking the name and filter the employe with it.(this works) def check(request): if request: if request.method == 'POST': data = json.loads(request.body) employeId = data['id_s'] empinfo = Employe.objects.filter(id=employeId) print(empinfo) print(data) return JsonResponse({'data': list(empinfo.values())}, safe=False, status=200) return HttpResponse() js code is here. in these code i want to get the data by fetch url. i can see it on the console log that the data is recieved(these function works good aswel) function checkEmp(id_s, action){ var url = '/checks/' fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'id_s': id_s, 'action': action}) }) .then((response)=>{ return response.json() }) .then((data)=>{ console.log(data); }) } index.html i … -
how do i remember the radio button selection in django
i'm trying to make sure that even if the user refresh the page or goes back and comes back to that page, the radio button is still the same as what the user selects. N.B: the value of the radio button is saved in sessions <div class="col-md-1 ps-md-1"> <input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}" value="{{option.id}}"> </div> my ajax $('input[type=radio][name=deliveryOption]').on('change', function(e) { e.preventDefault(); $.ajax({ type: "POST", url: '{% url "checkout:cart_update_delivery" %}', data: { deliveryoption: $(this).val(), csrfmiddlewaretoken: "{{csrf_token}}", action: "post", }, success: function (json) { document.getElementById("total").innerHTML = json.total; document.getElementById("delivery_price").innerHTML = json.delivery_price; }, error: function (xhr, errmsg, err) {}, }); }); </script> my view def cart_update_delivery(request): cart = Cart(request) if request.POST.get("action") == "post": delivery_option = int(request.POST.get("deliveryoption")) delivery_type = DeliveryOptions.objects.get(id=delivery_option) updated_total_price = cart.cart_update_delivery(delivery_type.delivery_price) session = request.session if "purchase" not in request.session: session["purchase"] = { "delivery_id": delivery_type.id, } else: session["purchase"]["delivery_id"] = delivery_type.id session.modified = True response = JsonResponse({"total": updated_total_price, "delivery_price": delivery_type.delivery_price}) return response -
Django annotate count of disctinct values of the running quesyset in its children
I was tracing this bug for a while until I found the source I believe it's coming from, and I have been stuck here now. I have the following models below: class ShopItem(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) store = models.ForeignKey(to=Store, on_delete=models.CASCADE) name = models.CharField(max_length=250) class SelectedProduct(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="products", null=True, blank=True) product = models.ForeignKey(ShopItem, null=True, blank=True, on_delete=models.SET_NULL) class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) store = models.ForeignKey(Store, on_delete=models.CASCADE, related_name="orders") status = models.PositiveIntegerField(choices=OrderStatus.choices, default=OrderStatus.CART) number = models.CharField(max_length=36, blank=True, null=True) Lets say for example an order has 5 products, 3 of these products are of the same type (p1, p2, p3) as they reference same shop item; where are the other two products (p4, p5) are different since they reference different shop items. I am trying to annotate how many same products exist on this order as in the following products = order.products.all().annotate(quantity=Count("product")) Attempting to get a queryset of these products with quantity annotated, only thing, I get quantity of 1 for all products, where I am trying to get: p1.quanity > 3 p2.quanity > 3 p3.quanity > 3 p4.quanity > 1 p5.quanity > 1 is there anyway I could … -
How to delete localstorage item from AJAX DOM?
I have localstorage itemcheck on following format: {"images":["png1"],"itemIds":["1","3","4"]}' On Ajax success, DOM is passed on following way: success: function (data) { console.log(data) $.each(data, function (key, value) { if ($.trim(key) == "products") { for (var i = 0; i < data[key].length; i++) { var wishlistUrl = "{% url ecommerce:add_to_wishlist %}"; var featured_image = data[key][i]['featured-images'][0]['image'] var div = '<a href="#" class="btn remove-product"><i class="w-icon-times-solid" id="remove_compare" attr="' + data[key][i].id + '"></i></a>'; $("#items").append(div); On #remove_compare button click, I want to remove item from localstorage having itemIds equal to attr value inside ajax DOM. How can I do this? -
registering user in django des not work and it does not gievs me any error
I was working on a simple register veiw that sends activation code too in django . And the problem is that it does not gives me any error and It does not register any user and I dont know why? Here is my code : veiws.py : def register_page(request): if request.method == 'POST' : form = forms.UserRegister(request.POST) if form.is_valid(): data = form.cleaned_data if data['password_1'] != data['password_2'] and '@' in data['email'] and data['username'] != data['email'] and not User.objects.filter(username = data['username']).exists(): user = User.objects.create_user(username=data["username"] , email = data['email'] , password = data['password1'] , is_active = False) user.save() v = randint(1000 , 5000) subject = 'sample subject' message = f'your code : {v}' email_from = settings.EMAIL_HOST_USER recipient_list = [data['email'] , ] send_mail( subject, message, email_from, recipient_list ) active_code.objects.create(code = v , email = data['email']).save() return redirect('home:activeveiw') else: if data['username'] == data['email']: messages.error(request ,'error 506') if User.objects.filter(username = data['username']).exists(): messages.error(request ,'error 789') if data['password_1'] != data['password_2'] : messages.error(request , 'error 899') else : form = forms.UserRegister() con = {"form" : form } return render (request , 'home/register.html' , con) template : <form action="" method="post"> {% csrf_token %} <input type="text" name="username"> <input type="text" name="email"> <input type="text" name="password_1"> <input type="text" name="password_2"> <button type="submit">send</button> </form> {% if … -
How to show the saved data of 3 forms in my template in Django?
let's say I have a form_1, a form_2 and a form_3, all three forms store information and they are in different html pages. I would like to have a view that presents the information saved in forms 1, 2 and 3 in the same template. How can I do that? -
Can I integrate a django project to an android app?
I am a beginner (about 1 year since i started learning python on web) I was working on a project (for online video conferencing) you can check the developement here (JUST CLICK THE MAKE A MEETING BUTTON) https://pranaam.web.app but now i am in a doubt that i know basic JS (not node) HTML/CSS and python and if i am working on my project then i want to launch it on android platform like in ZOOM meetings we can both join from browser and the exe/apk is there a way to integrate my online functioning website to a mobile app (using python as i dont know any other languages) and also Organise all the buttons and functions in mannered way (not a messed up web view) -
How to abort model instance deletion from django model admin interface based on some condition
I want to abort model deletion from django admin based on some condition. I tried overriding delete_queryset(self, request, queryset) method. def delete_queryset(self, request, queryset): if (<my condition>): message = "Error message" raise ValidationError(message) super().delete_queryset(request, queryset) This doesn't work since django does not handles exception at this stage. -
How can access input value in django view through AJAX without form submission
I am beginner in django.I am working on a single text box in a django form which have number of fields.I wrote AJAX code for passing each value(entered from keyboard). How can i access this value in django class based view code. I want to save this value into a variable. Here i am trying to check given text is already existing or not. checking is done for each keyboardinput. $(document).ready(function () { $('#s_id > input').on('input',function(e){ console.log(e); s_text = e.target.value; $.ajax({ type: 'POST', url: "{% url 'create-studentpage' %}", data: s_text, success: function (response) { console.log("response", response); }, error: function (response) { console.log("error", response.responseJSON.error); } }) }); -
django - model foreign key as logged user
I've got model code as follows: from django.db import models from django.core.validators import MinLengthValidator from django.urls import reverse from django.conf import settings class Doc(models.Model): ... added_by = models.CharField(blank=False,null=True,max_length=100,validators=[MinLengthValidator(10)]) added_by_2 = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... I can migrate this without any problems, but every when I run server and in admin site try to view all records I get: Exception Type: OperationalError Exception Value: no such column: added_by_2_id What is the cause of this error? How to resolve it? -
Foreign key of foreign key in django-polymorphic
I have the following (simplified) django and django-polymorphic models: class GenericOffer(PolymorphicModel): pass class OfferA(GenericOffer): special = models.IntegerField() class OfferB(GenericOffer): pass class GenericProduct(PolymorphicModel): offer = models.ForeignKey(to=GenericOffer) class ProductA(GenericProduct): pass class ProductB(GenericProduct): pass class Gizmo(models.Model): product = models.ForeignKey(to=GenericProduct) from which I can create the following instances: offer_a = OfferA() product_a = ProductA(offer=offer_a) gizmo_a = Gizmo(product=product_a) Now, I have: assert product_a.offer == offer_a assert gizmo_a.product == product_a But: assert gizmo_a.product_a.offer != offer_a assert gizmo_a.product_a.offer.get_real_instance() == offer_a That is, the foreign key linked to a foreign key of my Gizmo is not automatically cast to its proper type. Is it the expected behavior? Should I use a GenericRelation instead of a ForeignKey in my Gizmo ? Thanks for any advice -
Django view testing (sessions , ajax )
In django e-commerce project, i have view which adds a product in basket via sessions, also this view getting POST request from ajax. I can't find how to test this code. basket/views.py def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) basket.add(product=product, qty=product_qty) basketqty = basket.__len__() response = JsonResponse({'qty': basketqty}) return response basket/basket.py class Basket(): """ A base Basket class, providing some default behaviors that can be inherited or overrided, as necessary. """ def __init__(self,request): self.session = request.session basket = self.session.get(settings.BASKET_SESSION_ID) if settings.BASKET_SESSION_ID not in request.session: basket = self.session[settings.BASKET_SESSION_ID] = {} self.basket = basket def add(self,product,qty): """Adding and updating the users basket session data """ product_id = str(product.id) if product_id in self.basket: self.basket[product_id]['qty'] = qty else: self.basket[product_id] = {'price': str(product.regular_price),'qty':int(qty)} self.save() how to catch this piece of code in testing? <button type="button" id="add-button" value="{{product.id}}" class="btn btn-success fw500">Add to basket</button> <script> $(document).on('click', '#add-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "basket:basket_add" %}', data: { productid: $('#add-button').val(), productqty: $('#select option:selected').text(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { document.getElementById('basket-qty').innerHTML = json.qty }, error: function (xhr, errmsg, err) {} }); }) </script> -
Correct way to define list parameter in django-rest-framework and swagger
Background I have the following view and the accompanying swagger UI is generated by django-spectacular: class AllowedNameType(Enum): BRAND = "BRAND" .... @classmethod def list(cls): return list(map(lambda c: c.value, cls)) class GenerateCompanyNamesViewSet(viewsets.ViewSet): http_method_names = ["get"] def list(self, request: Request, *args, **kwargs) -> Response: """Generate suggested company names""" # query_params: dict = {} allowed_name_types: list[AllowedNameType] = query_params.get("allowed_name_types") suggestions: list[Suggestion] = ... return Response(serializers.SuggestionSerializer(suggestions).data) I want to achieve the following: The swagger UI should have a parameter allowed_name_types which is a list of AllowedNameType values The input should be validated as per the serializer definition Type checking should be enforced on query_params to make sure the allowed_name_types is of type list[AllowedNameType] (ideally, allowed_name_types would actually be a named parameter in (eg list(..., allowed_name_types: list[AllowedNameType]) Attempted Solution class AllowedNameTypesParamSerializer(rest_framework_serializers.Serializer): allowed_name_types = rest_framework_serializers.ListField( child=rest_framework_serializers.ChoiceField(choices=models.AllowedNameType.list()), required=False, allow_empty=True, ) and added the following decorator to the list method: @extend_schema( parameters=[ OpenApiParameter(name="allowed_name_types", required=True, type=AllowedNameTypesParamSerializer), ], responses=serializers.FoodSearchAutoCompleteSerializer, ) def list(....) This leads to the following interface: Unfortunately: The swagger component expects a dictionary of {"allowed_name_types:...} instead of a list the allowed_name_types validation of list elements does not work (i.e I can put a value in the list that is not from AllowedNameType) Strangely, calling request.query_params.get('allowed_name_types') only returns the last …