Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Configure VSCODE to step into Django Model
How to configure vscode to be able to step into Django Model? I use pipenv, django & vscod. The python path is setup correctly but it just cannot understand the methods within the django model. Here is a picture as a reference. Thank you! Note pm comes from People.objects.get... -
ERROR while ingegrating MongoDB with Django on windows
I am trying to integrate MongoDB and Django. but when i run the code python manage.py runmigrations app_name i am getting the error: File "C:\Users\Gourav\Envs\test\lib\site-packages\django\db\utils.py", line 126, in load_backend raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' and utils.py line 119 to 136 code looks like; builtin_backends = [ name for _, name, ispkg in pkgutil.iter_modules(django.db.backends.__path__) if ispkg and name not in {"base", "dummy"} ] if backend_name not in ["django.db.backends.%s" % b for b in builtin_backends]: backend_reprs = map(repr, sorted(builtin_backends)) raise ImproperlyConfigured( "%r isn't an available database backend or couldn't be " "imported. Check the above exception. To use one of the " "built-in backends, use 'django.db.backends.XXX', where XXX " "is one of:\n" " %s" % (backend_name, ", ".join(backend_reprs)) ) from e_user else: # If there's some other error, this must be an error in Django raise every required directories is already installed in my virtual environment. pip list gives following result; asgiref 3.5.2 Django 4.0.5 django-mongoengine 0.5.4 djongo 1.3.6 dnspython 2.2.1 mongoengine 0.24.1 Pillow 9.1.1 pip 22.1.2 psycopg2 2.9.3 pymongo 4.1.1 python-snappy … -
Django Class Based View - How to access POST data outside of post() method
I have a CBV based on a TemplateView It has a post(self) method to access user input. Also, it has a template_name property which should be populated with data from post(). No Django models or forms are used here. Attempt to extract data within post method: # views.py class ReturnCustomTemplateView(TemplateView): def post(self, *args, **kwargs): chosen_tmplt_nm = self.request.POST.get('tmplt_name') print(chosen_tmplt_nm) # correct value. # how do I use it outside this method? (like bellow) template_name = chosen_tmplt_nm ... or is there any other way I can get the data from request.POST without def post()? Thanks in advance! -
Can django AutoField be used for custom increment logic in addition to the separate automatic ID AutoField?
I have the following model: class Lot(models.Model): parent_lot_number = models.IntegerField(default=0) child_lot_number = models.IntegerField(null=True, blank=True) I want the following behavior: parent lot number should increment only when the user enters data in a specific form that is creating a new parent child lot number should increment all the time, within each parent For example, the following should be valid data for Lot records: parent_lot_number: 1, child_lot_number: null parent_lot_number: 1, child_lot_number: 1 parent_lot_number: 1, child_lot_number: 2 parent_lot_number: 2, child_lot_number: null parent_lot_number: 2, child_lot_number: 1 parent_lot_number: 1, child_lot_number: 3 parent_lot_number: 3, child_lot_number: null Right now, I have working business logic to do this in my views/forms by getting the max of child_lot_number and parent_lot_number, then assigning the value after the record is created. Instead, can I accomplish this by removing the default=0 on parent_lot_number and using AutoField? When I set parent_lot_number = models.AutoField() I receive errors that "NOT NULL constraint failed: main_lot.parent_lot_number" or "ValueError: Model main.Lot can't have more than one auto-generated field." because of django's hidden ID column. This is a column I cannot drop. -
Can I access same django website on another computer connected with LAN with my computer?
Hey I am trying to access my django webapp on an external machine within my local network. but I am having issues. Below you are the things I have done. But no success. DEBUG = True ALLOWED_HOSTS = ['*'] at this point i've already added port 9595 as an inbound rule within windows firewall. Inbound rules were added on the machine running : python manage.py runserver 0.0.0.0:9595 second machine on network: second-machines-ip-address:9595 first-machines-ip-address:9595 result: empty page/no success. would you have any ideas as to why this is happening? -
How to create a query that shows cases for all status?
I have a problem in my Django project. I have some cases like; Case Type Status Sub Case Stage Volleyball 2020 finished win Basketball 2022 pending none Basketball 2021 finished loss Volleyball 2020 finished win I want to create a query for example are there how many cases is volleyball - 2020 - finished - win or are there how many cases is basketball - 2021 - finished - loss There are a lot of cases with different attributes, I have to count them with a dynamical query. Maybe pandas can help me with that but I don't know. Any idea can help me. -
What's the best way to load a ML model with Django
I'm deploying a Machine Learning model (Named Entity Recognition) with Django. In short, the user chooses a field (Politics or Science for example) and writes a text in a search area. Then the model identifies the named entities in the text. My problem is that the ML model (encoder) is loaded each time the view is triggered, which slows down the process. Any idea how to optimize this and load it only once ? My views.py : def search_view(request): if request.POST: field = request.POST['field'] query = request.POST['query'] encoder = load_encoder(field) results = Ner_model(query,encoder) context['result'] = results return render(request,'ner/results.html', context) Thanks! -
how to send flutter firebase notification using dcm-django
I am trying to send notification to flutter app from firebase. It sends notification well while sending from: https://console.firebase.google.com/project/nadir-d4ec4/notification/compose but I want to connect/control firebase with django. so, django will call firebase api asking it to send notification to flutter app. django package used: fcm-django settings.py is only file i have edited for that and settings.py contains: INSTALLED_APPS = [ # other apps "fcm_django" ] FIREBASE_APP = initialize_app() FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "87-digit string copied from:`project settings/cloud messenging` of firebase app", "APP_VERBOSE_NAME": "[string for AppConfig's verbose_name]", "ONE_DEVICE_PER_USER": False, "DELETE_INACTIVE_DEVICES": False, # True/False } I could not find what APP_VERBOSE_NAME is supposed to be so left as it is. and I want to send notification using: python3 manage.py runserver from fcm_django.models import FCMDevice device = FCMDevice.objects.all().first() device.send_message("Title", "Message") device.send_message(data={"test": "test"}) device.send_message(title="Title", body="Message", icon=..., data={"test": "test"}) but # FCMDevice.objects.all() is giving empty list instead of users so no user to send notifications. I want list of user to send notifications to. code: django: https://github.com/Aananda-giri/uzme_backend/ flutter: https://github.com/Yogeshpanta/nadir -
How to update nested serializer field with many=True
I'm having trouble in updating the serializer data that have nested serializer field, please if someone have any idea to it with best practice i will appreciate your answer! class SerializerA(serializers.ModelSerializer): anyfielda = serializers.CharField() class SerializerB(serializers.ModelSerializer): anyfieldb = serializers.CharField() nested_field = SerializerA(required=True, many=True) How to implement the update method please guide! I'm able to do create but update does not allowed as it is asking for ListSerializer must, I want to know if there is any other way! -
Apache2 does not find python3.8 based virtual env and load python3.6 based env
i have an issue with a django based application deployment with apache2 on ubuntu18.04 with python3.8. I installed the mod_wsgi and apache2 as: sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi-py3 I setup venv folder in the project folder. I get error logs as: Error Log 1 [Tue Jun 21 08:34:13.966782 2022] [mpm_event:notice] [pid 660:tid 140673610189760] AH00491: caught SIGTERM, shutting down [Tue Jun 21 20:11:41.285936 2022] [mpm_event:notice] [pid 32599:tid 139678582156224] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Tue Jun 21 20:11:41.287426 2022] [core:notice] [pid 32599:tid 139678582156224] AH00094: Command line: '/usr/sbin/apache2' Error Log 2 [Tue Jun 21 20:11:44.374973 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] mod_wsgi (pid=32600): Target WSGI script '/home/$USER/{{project_name}}/{{project_name}}/wsgi.py' cannot be loaded as Python module. [Tue Jun 21 20:11:44.375046 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] mod_wsgi (pid=32600): Exception occurred processing WSGI script '/home/$USER/{{project_name}}/{{project_name}}/wsgi.py'. [Tue Jun 21 20:11:44.375175 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] Traceback (most recent call last): [Tue Jun 21 20:11:44.375230 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] File "/home/$USER/{{project_name}}/{{project_name}}/wsgi.py", line 12, in <module> [Tue Jun 21 20:11:44.375244 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] from django.core.wsgi import get_wsgi_application [Tue Jun 21 20:11:44.375272 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] ModuleNotFoundError: No module … -
How to render non-model objects in django admin?
I have the following model listed in Django admin already with the following view: class BookTabularInline(admin.TabularInline): model = Book @register(Bookcase) class BookcaseAdmin(admin.ModelAdmin): inlines = [BookTabularInline] The changes I want to make is: Instead of returning all the Books associated with Bookcase, I only want to return specific ones via queryset for example: Books.objects.filter(isAvailable=True, bookcase=bookcase).order_by("name"). How can I accomplish this? Instead of returning the model (Book) from this queryset, I want to return a BookPublicObject with different attributes inline, but BookPublicObject is a dataclass and not a Django model. Is this possible? -
Getting 500 error with Django via Ajax request, even though Django receives the request and is returning data
I have a click function that calls the Ajax request as shown to a url defined in urls.py. I can see that django is getting the data because I have print statements in views.py which print the data that will be passed back to frontend, but I end up getting this error: "GET /comment-data/?asset=total&timestamp=1654957681 HTTP/1.1" 500 145. If anyone's run into this before, much help is appreciated! Ajax call urls.py views.py (yes I know I have a bunch of unused variables) -
Unable to log in with provided credentials in DRF
I get the error { "non_field_errors": [ "Unable to log in with provided credentials." ] } whenever I do http://127.0.0.1:8000/api-token-auth/ and pass in my username and password. what's confusing is that when i run the post with my superuser account it works (i get my account token) though i noticed that my superuser's password is hashed but my normal account password isn't models.py def create_user(self, email, password, **other_fields ): if not email: raise ValueError("you must add an email") email = self.normalize_email(email) user = self.model(email =email, password = password, **other_fields) user.set_password(password) user.save(using=self._db) return user.email def create_candidate(self, email, password, **other_fields ): user = self.create_user(email, password, **other_fields) user.is_candidate = True user.save(using=self._db) return user.email def create_superuser(self, email, password, **other_fields ): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_candidate', False) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be assigned is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be assigned is_superuser=True') return self.create_user(email, password, **other_fields) -
Bootstrap 5 - Navbar - Logo/Brand Text Left - Menu Center - Search Right
I am trying to make a Navbar in Bootstrap 5. I would like to have the Logo (In my case this is just some fancy text) on the left. I would then like the menu centered and my search field on the right. The issue I seem to be having is when I have managed to get them lined up like this, the menu is going in the center of the search and logo divs, which due to logo size etc hasn't necessarily been the middle of my screen like I want. I have been at it for days trying different things on her but just can't seem to get it right. I also want the mobile menu to collapse and include the search. The mobile menu should then have the logo aligned in the center and the collapse button just below it also centered. The latest code I have tried is this: index.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}{% endblock %}Life With Vicky</title> <meta name="description" content="{% block meta_description %}{%endblock %}"> {% block canonical %}{%endblock %} {% block opengraph %}{%endblock %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <link … -
How to manage session with 3rd party API in Django?
Context: I have a Django based application. This application has various REST API endpoints where users can gather data. Some of this data needs to be pulled from a third-party API. This external API uses basic authentication. In order to fetch this data, I have the following code implemented in my endpoint logic. def metadata(jira_key: str, format=None): username = "example" password = "example" try: print(f"fetching {jira_key} with '{username}' credentials") url = f"https://external.api.com/issue/{jira_key}" session = requests.Session() session.auth = username, password headers = {'Content-Type': 'application/json'} response = session.get( url, headers=headers) print(f"response: {response.status_code}") return response except Exception as e: message = {"error": "Uncaught error", "message": str(e)} return message Long story short; it works! This endpoint is essentially just a proxy for another API. This is done for security purposes. However, I have been experiencing lock-outs where permission for the service account needs to be reinstated periodically... I suspect the session is being generated every time the endpoint is hit. So my question is this: How can I implement a persisted request.Session() with basic auth that is established at build time, and reused for each requests? Thanks for your help in advance! :) -
Timeout error in django send_mail program
I am doing a send_mail function in django and connected mysql database with it to store the name and subject values. I am using the smtp backend server to connect the mail and django. The port used is 587. This is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mail_test', 'USER': 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306', 'OPTIONS':{ 'init_command':"SET sql_mode='STRICT_TRANS_TABLES'" } } } ---- DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'swarai.bot@gmail.com' EMAIL_HOST_PASSWORD = 'pfxbswfjgligavgb' ** This is my views.py** from django.views.generic import FormView, TemplateView from .forms import EmailForm from django.urls import reverse_lazy from mailapp.models import Email from django.shortcuts import render class MailView(FormView): template_name = 'index.html' form_class = EmailForm success_url = reverse_lazy('mailapp:success') def form_valid(self, form): # Calls the custom send method form.send() return super().form_valid(form) def registered(request): name = request.POST['name'] email = request.POST['email'] inquiry = request.POST['inquiry'] message = request.POST['message'] person = Email(name=name, email=email, inquiry=inquiry, message=message) person.save() return render(request, 'success.html') class MailSuccessView(TemplateView): template_name = 'success.html' I am getting timeout error whenever I submit the page. I tried to add the port 587 using control panel. But then also, I am getting the same error. I don't know whether this error is … -
django post request: Forbidden (CSRF token missing.): /categories
In my file view.py I want to write a class based on View with get and post methods for API. Get is already written, it works. There was a problem with the post: Code of this class: class CategoryListView(View): def get(self, request): if not check_correct_api_secret(request): return HttpResponseForbidden('Unknown API key') query_set = Category.objects.all() query_params = request.GET query_set = paginate(query_params, query_set) items_data = serialize_category_list(request, query_set) return JsonResponse(items_data, safe=False) # Method code is written for example, just to see some kind of reaction to the post request def post(self, request): query_params = request.POST name = query_params.get('name') Category.objects.create(name=name) return HttpResponse(201) I try send post request: /categories?name=Category6 (For example) And I get error: Forbidden (CSRF token missing.): /categories [21/Jun/2022 16:21:26] "POST /categories?name=Category777 HTTP/1.1" 403 2506 My urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('categories', CategoryListView.as_view()), ] -
“non_field_errors”: [ “Invalid data. Expected a dictionary, but got QuerySet.” ] problem with serializer or model from djongo
I've recently started to learn django. And at this time i'm working on integrating mongoDB with Django using djongo driver. I've created a model for saving and mapping my data objects to mongoDB but i'm lacking knowledge about implementing serializers and at this stage i'm encountering one situation which i've been unable to resolve since 2 days so please throw some light and help me implement it. the error message from django REST framework api models.py from djongo import models # Create your models here. class OrderItem(models.Model): itemDescription = models.TextField(name = "itemDescription") itemQuantity = models.FloatField(name = "itemQuantity") itemPrice = models.FloatField(name = "itemPrice") class Meta: abstract = True class Order(models.Model): email = models.EmailField(primary_key = True, name = "email") customerName = models.CharField(max_length=30, help_text="Enter Customer Name", name = "customerName") customerAddress = models.TextField(help_text="Enter customer's Address", name = "customerAddress") orderItems = models.ArrayField( model_container = OrderItem, ) objects = models.DjongoManager() serializers.py from .models import Order, OrderItem from rest_framework.serializers import ModelSerializer class OrderItemsSerializer(ModelSerializer): class Meta: model = OrderItem fields = '__all__' class OrderSerializer(ModelSerializer): orderItems = OrderItemsSerializer(many=True) class Meta: model = Order fields = "__all__" views.py @api_view(['GET']) def getOrders(request): orders = Order.objects.values() serializer = OrderSerializer(data = orders) if serializer.is_valid(): print("Valid") return Response(data = serializer.data) else: print("invalid") print(serializer.errors) return … -
Nested Serializers with different queryset
How to create a nested serializer with it's own queryset? In the following example I would like to replace an '@api_view' function with a class based view with serializers. Simplified, I have the following code: models.py class Klass(models.Model): name = models.TextField() class Pupils(models.Model): name = models.TextField() klass = models.ForeignKey(Klass) class Chapter(models.Model): """A Chapter in a school book.""" name = models.TextField() class TestResult(models.Model): """TestResults for a Chapter.""" pupil = models.ForeignKey(Pupil) chapter = models.ForeignKey(Chapter) score = models.IntegerField() view.py @api_view def testresults(request, klass_id, chapter_id): pupils = Pupils.objects.filter(klas__id=klass_id) tests = Tests.objects.filter(chapter__id=chapter_id) ret_val = [] for pupil in pupils: pu = { "name": pupil.name, "tests": [{"score": test.score, "chapter": test.chapter.name} for test in tests.filter(pupil=pupil)] } ret_val.append(pu) return Response({"pupils": ret_val}) url /api/testresult/<klass_id>/<chapter_id>/ -
IIS can not access newly added files in a django project
In a django project that is served by IIS (windows), i added a local file, test.py. The project ran perfectly before and still runs perfect on localhost, however IIS appears to not recognize the new test.py file. It appears IIS access to this file fails, even if the users IUSR and IIS_USRS have full access (same as for all other files in the folder). I get below error message, and somethimes also the same but "No module named 'app.test'. Removing the "import app.test as test" in views.py solves the issue. Suprisingly the "import app.oldFile as oldFile" works without issue. In my views.py, i import the python scripts like this import app.oldFile as oldFile import app.test as test My django project has the structure: djangoRest -app --__init__.py --views.py --oldFile.py --test.py -djangoRest --__init__.py --settings.py --urls.py --wsgi.py -
How to know if which selected in django template select?
In my django templates how can I know which select option is selected? <select id="platformid" name="platform"> {% for x in list %} <option value="{{x.company}}">{{x.company}}</option> {% endfor %} </select> -
Django POST request returns NONE
so ive been serching for a solution for about a week now I just need the data from a hidden label within a form witch should be no problem but instead of the data from the label i just get 'NONE' Template (form): {% for Gerecht in Gerechten %} <form method="POST"> {% csrf_token %} </section> <section class="u-clearfix u-custom-color-2 u-valign-middle u-section-2" id="sec-a9e5"> <div class="u-clearfix u-gutter-0 u-layout-wrap u-layout-wrap-1"> <div class="u-layout" style=""> <div class="u-layout-row" style=""> <div class="u-align-left u-container-style u-image u-layout-cell u-left-cell u-shading u-size-30 u-size-xs-60 u-image-1" src="" data-image-width="4880" data-image-height="3253" style=" background-image: linear-gradient(0deg, rgba(0,0,0,0.25), rgba(0,0,0,0.25)), url('{% static '/img/{{ Gerecht.afbeelding }}' %}')"> <div class="u-container-layout u-container-layout-1" src=""></div> </div> <div class="u-align-left u-container-style u-custom-color-1 u-layout-cell u-right-cell u-size-30 u-size-xs-60 u-layout-cell-2"> <div class="u-container-layout u-container-layout-2"> <h2 class="u-text u-text-default u-text-white u-text-1"> {{ Gerecht.naam }}</h2> <p class="u-text u-text-default u-text-white u-text-2">Duur: {{ Gerecht.duur }} u </p> <input type="submit" value="ga naar gerecht" class="u-active-custom-color-3 u-align-left u-border-1 u-border-active-custom-color-3 u-border-hover-custom-color-3 u-border-white u-btn u-btn-round u-button-style u-hover-custom-color-3 u-none u-radius-12 u-text-active-white u-text-hover-white u-btn-2" name="btnZieRecept"> <label name="id" style="display: none;" value="{{ Gerecht.id }}">{{ Gerecht.id }}</label> </div> </div> </div> </div> </div> </section> </form> {% endfor %} My views.py: if request.POST.get('btnZieRecept'): PK = request.POST.get('id') logging.basicConfig(level=logging.NOTSET) logging.debug(request.POST.get('id')) return redirect('GerechtPreview', PK=PK) So here PK=None and i dont know why def GerechtPreview(request, PK): obj = Gerecht.objects.get(pk=PK) ingList=[] for f … -
Django: How to change the value on a model's field within a property on the model
I would like to change the value of a model field within a property set on the model. Let's say we have the model and the following properties: class Rider(models.Model): booking = models.BooleanField(default=True) cancel = models.BooleanField(default_True) _disabled_notifications = JSONField() @property def disabled_notification(self): return json.loads(self._disabled_notifications @disabled_notifications.setter def disabled_notifications(self, value) try: field = self._meta.get_field(value) except FieldDoesNotExist as e: raise e In this case, field would return an Options object. How do I use this to change the value on the field? -
How to test Stripe `SignatureVerificationError` in Python
For python, the standard stripe webhook code example includes: event = None try: event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret) except ValueError as e: logger.error(f"*** Stripe invalid payload: {e = }") return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: logger.error(f"*** Stripe invalid signature: {e = }") return HttpResponse(status=400) I've tried to test this with the following test that inherits from Django testcase: class TestStripeWebhookView(TestCase): @mock.patch("logging.Logger.error") @mock.patch("lettergun.apps.payments.views.create_order") @mock.patch("lettergun.apps.payments.views.stripe") def test_signature_verification_error(self, stripe, create_order, error): stripe.Webhook.construct_event.side_effect = SignatureVerificationError data = { "type": "placeholder", } response = self.client.get( reverse("payments:stripe_webhook"), data, HTTP_ACCEPT="application/json", HTTP_STRIPE_SIGNATURE='placeholder_signature"}', ) error.assert_called_with(f"*** Stripe invalid signature: e = an error message") assert not create_order.called assert response.status_code == 400 This produces the following error which I dont understand: > except stripe.error.SignatureVerificationError as e: E TypeError: catching classes that do not inherit from BaseException is not allowed How can I test that the signature verification error will have the expected effects? -
Change model rendered form select/option element into multi-select checkboxes with Django
I need to change two form fields (now select/option) into multi-choice checkboxes in a form that is rendered from the model. Despite carefully reading the Django docs I don't get it displayed, i.e nothing happens. What do I need to do in models.py to render the checkboxes? (For simplicity, I only display the code for one field) So far in form.py: class CreateVariantForm(ModelForm): class Meta: model = VariantView fields = '__all__' suitable_for = forms.MultipleChoiceField(choices=VariantView.SuitableForProduct.choices, widget=forms.CheckboxSelectMultiple) In models.py: class VariantView(models.Model): class SuitableForProduct(models.TextChoices): JEWELLERY = "Jewellery", _("Jewellery") ACCESSORIES = "Accessories", _("Accessories") COSMETICSHYGIENE = "Cosmetics & Hygiene", _("Cosmetics & Hygiene") ELECTRONICSGADGETS = "Electronics & Gadgets", _("Electronics & Gadgets") suitable_for_product = models.CharField(max_length=255, choices=SuitableForProduct.choices, null=True, blank=True ) class Meta: managed = False db_table = "variant_view" In views.py: class ProductUpdate(LoginRequiredMixin, UpdateView): login_url = "/" model = VariantView template_name = "searchapp/product_update_form.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["suitable_for_product"] = SuitableForProduct.objects.values_list( "suitable_for", flat=True ) return context def get_success_url(self): return reverse_lazy("listvariants", args=[self.object.product_group_id])`` ```