Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UpdateView creates duplicated formsets
I'm having problems when updating the entries of my products, discounts and inventory in the database, the inventories and discounts have the product id as a foreign key and I have defined two inline formsets to enter all the data in one single form ProductMeta=forms.inlineformset_factory(Product,Inventory,InventoryForm,extra=0,can_delete=False) DiscountMeta=forms.inlineformset_factory(Product,ProductDiscount,DiscountForm,extra=0,can_delete=False) Something strange happens, both formsets work normally when creating using extra=1 in the formsets, but in the UpdateView I must use extra=0, otherwise the inventory and discount forms get duplicated, and both forms disappear from the creation view views.py class UpdateProduct(UpdateView): model=Product form_class =ProductForm template_name = 'new_product.html' title = "UPDATE PRODUCT" def get_context_data(self, **kwargs): context = super(UpdateProduct, self).get_context_data(**kwargs) if self.request.method == 'POST': context['product_meta_formset'] = ProductMeta(self.request.POST,instance=self.object) context['discount_meta_formset'] = DiscountMeta(self.request.POST,instance=self.object) else: context['product_meta_formset'] = ProductMeta(instance=self.object) context['discount_meta_formset'] = DiscountMeta(instance=self.object) return context def form_valid(self, form): context=self.get_context_data() productMeta=context['product_meta_formset'] discountMeta=context['discount_meta_formset'] if productMeta.is_valid() and discountMeta.is_valid(): self.object=form.save() productMeta.instance=self.object productMeta.save() discountMeta.instance=self.object discountMeta.save() if not productMeta.is_valid(): print("productMeta invalid") if not discountMeta.is_valid() : print("discountMeta invalid") return redirect(reverse("products:listProducts")) For some reason Django considers that my productMeta and discountMeta are invalid since both prints are executed and obviously the changes are not saved in the database, for now I fix the inlineformset extra=0 problem using other inlineformsets, but I would like to know how to solve the invalid … -
(Hidden field id) Select a valid choice. That choice is not one of the available choices. (Django)
I'm receiving this error when I try to submit two formsets. After I fill the form and click the save button, it gives the error: (Hidden field id) Select a valid choice. That choice is not one of the available choices. I'm trying to create dynamic form so that the user can add new sections and also new lectures inside the section when they click "Add" button. The adding new form function works well, I just have problem saving it to the database. Views.py def addMaterials(request, pk): course = Course.objects.get(id=pk) sections = CourseSection.objects.filter(course_id=pk) materials = CourseMaterial.objects.filter(section__in=sections) SectionFormSet = modelformset_factory(CourseSection, form=SectionForm, extra=0) sectionformset = SectionFormSet(request.POST or None, queryset=sections) MaterialFormSet = modelformset_factory(CourseMaterial, form=MaterialForm, extra=0) materialformset = MaterialFormSet(request.POST or None, queryset=materials) context = { 'course': course, 'sectionformset': sectionformset, 'materialformset': materialformset, } if request.method == "POST": if all([sectionformset.is_valid() and materialformset.is_valid()]): for sectionform in sectionformset: section = sectionform.save(commit=False) section.course_id = course.id section.save() for materialform in materialformset: material = materialform.save(commit=False) print(material) material.section_id = section #section.id or section.pk also doesn't work material.save() return('success') return render(request, 'courses/add_materials.html', context) Forms.py class SectionForm(forms.ModelForm): class Meta: model = CourseSection fields = ['section_name', ] exclude = ('course_id', ) class MaterialForm(forms.ModelForm): class Meta: model = CourseMaterial fields = ['lecture_name', 'contents'] The second formset … -
Rebuilding a PyQt5 Desktop App for the web? with Python/Django
I have created a PyQt5 Desktop App but I've decided I want it as a webpage instead. So, to do this I think I'm going to completely remake the app using Django/python. My app is essentially 1 page of around 100 buttons that output midi notes when clicked. I would like to see exactly the same layout of buttons and CSS on a webpage as I currently do on my Desktop App and need to have the buttons call functions, just as they do on the desktop app. Essentially I need to translate my PyQt5 Desktop app to a Webpage and need help understanding how to start, thanks. -
aws codestar deploy daphne django
I need deploy my proyect with dpahne in aws codestar but, i can't do it, i do this in file install_dependencies # Set up a virtual environment python3.8 -m venv environment source environment/bin/activate # Install awscli and python dev libraries python3.8 -m pip install -r requirements.txt daphne -u /tmp/daphne.sock my_project.asgi:application but not works, do this in supervisor.conf environment/bin/daphne my_project.asgi:application --port 8000 --websocket_timeout -1 --bind 0.0.0.0 -v2 codestar use ami aws linux and i can't install like apt because yum is so restricted and somone know if i'm bad o know how do it, thanks. -
ORM vs Raw Queries (For big project)
I am working on a project which I want to eventually launch to the public. In past, I have Used Django which uses ORM to use databases as python models. But I also know that they add extra overhead in terms of latency and query optimization. But now I am using FastAPI as my restapi server, PSQL as DB and I have to use 3rd party ORM such as SqlAlchemy (which is really complex). I am thinking of two choices Start with ORM initially, and later move to raw queries if there is a performance issue or high demand of users. Start with raw SQL initially using psycopg2 library. If I go with this, I have to manage everything such as connection pooling, queries, and if conn breaks reconnect it etc. Is there any python famous lib that can do that on top of psyopg2. I wanted to know if there is increase in app consumers how to tackle database queries. How do the big companies like facebook, amazon, Instagram do this? I am sure they are not using ORMs. -
django Model object.all() for ModelChoiceField and ModelMultipleChoiceField
I have a TransactionCategory model and I want to use it to display both ModelMultipleChoiceField and ModelChoiceField in django form. model.py class TransactionCategory(models.Model): """ Transaction Category database model """ txn_category = models.CharField("Transaction Category", max_length=50, null=True, default=None, blank=True) def __str__(self): """ Transaction Category Returns: transaction category : str """ return f"{self.pk} ({self.txn_category})" class Meta: verbose_name = "Transaction Category" db_table = "txn_category" forms.py queryset fills the MultipleChoiceField control using "id" as value and "txn_category" as text perfectly. class TxnCategoryDetailModelForm(forms.ModelForm): txn_description = forms.ModelMultipleChoiceField(label="Transaction Description", queryset=CreditCardTxnDescription.objects.all().order_by("description"), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = TransactionCategory fields = ["txn_category"] Doesn't work well with ModelChoiceField (dropdown), the queryset populates the id correctly but text shows "id (txn_category)" e.g. "1 (food)" class TxnDescriptionTagsModelForm(forms.ModelForm): description = forms.CharField(widget=forms.TextInput(attrs={"autofocus": "autofocus"}), strip=False) txn_category = forms.ModelChoiceField(queryset=TransactionCategory.objects.all().order_by('txn_category')) tags = TagWidget() class Meta: model = CreditCardTxnDescription fields = ["description", "description_comment", "txn_category", "tags"] How can I use TransactionCategory model for both ModelMultipleChoiceField and ModelChoiceField and have them displayed properly? -
The best way for calculated fields in Django
I'm starting to create my first web application in Django. I'm dealing with backEnd part first. In my data structure I need to calculate some fields like average rating of employee's salary for each model object (company, department ..). I found some ways to calculate and display calculated field in API. Add a property into model and override querySet for better performance. Calculate and add extra field in serializers and display it for API. Use build-in computedfields.models I can not decide which way is best for calculating fields, what are pros and cons of each way. Thanks for some advice. -
Best way to create an 'online virtual piano' webpage?
I want to create a basic online midi piano webpage. I know Python very well but not JavaScript yet. What is the best way to do this? Is Django or Flask relevant here? Essentially I just want a super basic midi piano on a webpage and am just looking for a point in the right direction, thanks. Context: I have made a PyQT5 Desktop App but have now decided I want it as a webpage so I need to completely remake it. I've never done any web development. I need Midi and not audio files. -
json.dumps serialized query set into unusable format in Django with WebSockets (Channels)
I read everything I could found about serializing QuerySets in Django but still can not find any working solution for transferring the existing WSGI function into a ASGI WebSocket Consumer. My view function looked like this: ... context = { "registered": user_is_player, "object": game, "player": player, "players": game.player_set.all(), "players_cards": players_cards, "card_deck": game.globalcarddeck_set.all(), "prio_deck": game.prioritydeck_set.all(), "table": game.table_set.all(), "cards": game.card_set.all(), } return render(request=request, template_name=template_name, context=context) and was working fine, but the query results sadly seam not to be transferable via synchronous web socket. Within my class GameConsumer(WebsocketConsumer) I figured that I can transfer a single result with with model_to_dict (after sadly loosing a few fields) but same does not apply to QuerySets. Those can be only serialized with the serialize function like: serialize("json", game_instance.player_set.all()). ... game_instance = Game.objects.get(slug=self.game_name) game_json = model_to_dict( game_instance, fields=["name", "slug", "round_number", "active", "started"] ) context = { "registered": user_is_player, "game": game_json, "player": player, "message": message, "players": serialize("json", game_instance.player_set.all()), "players_cards": serialize("json", players_cards), "card_deck": serialize("json", game_instance.globalcarddeck_set.all()), "prio_deck": serialize("json", game_instance.prioritydeck_set.all()), "table": serialize("json", game_instance.table_set.all()), "cards": serialize("json", game_instance.card_set.all()), } self.send(text_data=json.dumps({"context": context})) At the end everything needs to be dumped with json.dumps, otherwise one would end up with the exception: self.sendMessage(content.encode("utf8"), binary) AttributeError: 'dict' object has no attribute 'encode' This seam to be the … -
Cannot Containerise (Docker) Django App - Pillow Install Error in Container but works OK in localhost
I have a Django App built on my localhost with postgreSQL DB backend. I want now to containerise this App. In my local app, I'm using Django, Pillow and Psycopg2. Here is my Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD python3 manage.py runserver 0.0.0.0:80 Here is an extract of my requirements.txt file: Django==4.0.3 psycopg2-binary==2.9.3 Pillow==8.4.0 The above versions (in the requirements.txt file) are taken from the versions I'm already using and the app is working flawlessly on my localhost:8000 But when I build the dockerfile, here's the error: [+] Building 20.4s (8/9) => [internal] load build definition from Dockerfile 0.1s => => transferring dockerfile: 37B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => [internal] load metadata for docker.io/library/python:3.9-alpine 1.5s => [internal] load build context 2.0s => => transferring context: 902.95kB 1.8s => [1/5] FROM docker.io/library/python:3.9-alpine@sha256:2b876321cf313033a9cd2c70f9e7ca99d627c3b74e4850349a0793676947a8cf 0.0s => CACHED [2/5] WORKDIR /app 0.0s => CACHED [3/5] COPY requirements.txt . 0.0s => ERROR [4/5] RUN pip install -r requirements.txt 16.8s ------ > [4/5] RUN pip install -r requirements.txt: #8 6.241 Collecting Django==4.0.3 #8 6.360 Downloading Django-4.0.3-py3-none-any.whl (8.0 MB) #8 7.261 Collecting psycopg2-binary==2.9.3 #8 7.281 … -
Error installing Python Plugin: ModuleNotFoundError: No module named <module>
I'm trying to build a Python Plugin for Saleor using Poetry and I'm having issues installing the plugin on Saleor. I run poetry add ../social_auth to install the plugin on saleor and it succeeds but when I try to run Saleor I get this Error: No module named 'social_auth' File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/ton/.cache/pypoetry/virtualenvs/saleor-nXZtbKPR-py3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/usr/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 930, in _bootstrap self._bootstrap_inner() But I checked, the module is in settings.INSTALLED_APPS, settings.PLUGINS and listed on pip list... Here's the plugin structure: ├── __init__.py ├── poetry.lock ├── pyproject.toml └── social_auth ├── __init__.py └── plugin.py 1 directory, 5 files the pyproject.toml file: [tool.poetry] name = "social-auth" version = "0.1.0" description = "Social auth for saleor" authors = ["Wellington Zenon <wellington.zenon@gmail.com>"] packages = [ … -
use two models in a single view that you can save and edit in django
lovers of zero and one. How can I make a view have two forms with two different models but saving one form doesn't affect the other? try to use a modelform use it in a single view. but I would like to know how to solve it or the best practice for these cases. -
Django App works on PyCharm by not VS-code (File manage.py line 17 error)
I have a Django App that works well in PyCharm. All modules etc work. I need, however, to open the code in Visual Studio Code. However, when I execute a: python manage.py runserver command in visual studio code, I get the following error: File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax I've scoured the resources - but I can't find any solution. I've re-installed python Django using PIP.. - still no luck. Yes, I've reactivated the VENV - it just so happens it is stuck in activated state - but im ok with that. Any ideas ? Thanks -
More than two custom params to generate Token in Django RF
I'm a frontend mobile developer, i have a Flutter project 100% white labeled, now i'm studying the backend and developing it with Django RF. I'll use the same database for all generated builds of my app, so to prevent the user to login with the same account in two differents builds, i need to generate a Token with more than 2 parameters (email/password + a third one). What's the best practice in this case? I'm using the 'rest_framework.authentication.TokenAuthentication'. -
How to call field from Serializers.py to views.py
I am learning it. So there is a field called password in serializers.py I want to call that field in views.py. The password field is randomly generated. I want to get this field. How do I achieve this? -
mobile app from website is a good option?
I am developing a website and I have plans to convert to a mobile app. The technologies used to build the website are: Frontend: HTML, CSS, JavaScript Backend: Python (Django) DataBase: SQLite I wonder if converting from site to mobile app is a good option? -
How do I run a function in the background so that it doesnt stop the other pages django
I have a script which is starting a download of a sound file when the user clicks a button on the website, but when one user starts the download the whole backend stops and waits for it to finish before any other user can use the website. songList = await self.getSongs() await self.downloadSongs(songList) async def downloadSongs(self, songList): dirList = os.listdir("Directory") await self.channel_layer.group_send( self.room_group_name, { 'type': 'loadingGameGroup', }) downloadThread = threading.Thread(target=self.download, args=(songList, dirList)) downloadThread.start() downloadThread.join() def download(self, songList, dirList): for song in songList: try: self.downloadSong(song, dirList) except: self.downloaded = False return def downloadSong(self, song, dirList): songId = song["song_id"] if songId + ".mp3" in dirList: return video_url = "https://www.youtube.com/watch?v="+ songId video_info = youtube_dl.YoutubeDL().extract_info( url = video_url,download=False ) filename = "Directory" + songId + ".mp3" options={ 'format':'bestaudio/best', 'keepvideo':False, 'outtmpl':filename, } with youtube_dl.YoutubeDL(options) as ydl: ydl.download([video_info['webpage_url']]) How do I make it so it downloads the songs, waits for one group of songs to finish so I then can send a websocket message back to the client so that one can proceed. While the other groups doesnt have to wait for it to finish to do something -
Django {{data|escapejs}} from a js static file
I use {{data|escapejs}} django banner to import some data in my the javascript of my page. Simple example : <script> console.log({{data|escapejs}}) </script> But it doesn't work if I place this line in a .js static file <script src = "{% static 'mycode.js' %}> In mycode.js : console.log({{data|escapejs}}) How to make it work ? -
Cant include navbar.html in other modules
I'm quite a beginner in web development I've encountered some problems using Django this is my projects modules code. {% include 'navbar.html' %} <h1>projects template</h1> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> {% endblock content %} and this is my navbar.html: <h1>Logo</h1> <hr> when I run this, it is expected to return something like this: enter image description here but it instead outputs this: enter image description here as you can see it doesn't wrap the navbar text correctly. I would really appreciate it if someone helps me with this issue. -
Always get None from Django api request as result
I am going to get whitebg_url result from sqlite database according to matched items and made the api request using django like this. @api_view(['POST']) def getUrlFromAttributes(request): try: print('>>>>>>>>>>>>>>>>>>>>>', request) hairstyle = request.data.get("hairstyle") haircolor = request.data.get("haircolor") skincolor = request.data.get("skincolor") print("error>>1", str(hairstyle), str(haircolor), str(skincolor)) basic_query = BasicSetup.objects.all().filter(skin_color=skincolor, hair_color=haircolor, hair_style=hairstyle, isDeleted= 0) print('returned basic queyr : ', basic_query) lists_basicSetup = list(basic_query.values( 'whitebg_url')) print('returned lists_basicSetup : ', lists_basicSetup) return JsonResponse({'result': lists_basicSetup}) except Exception as error: print("error", str(error)) return JsonResponse({'result': str(error)}) But as you can see the result at the below image, response is always None. I tried to find the solution from google, but can't do it. I already add rest_framework at INSTALLED_APPS in settings.py file. and path is like defined. path('getUrlFromAttributes', views.getUrlFromAttributes, name='getUrlFromAttributes'), I tried to do this using Postman, but the result was same. Anyone knows why I was getting None as result? -
Temporary data storage in django which is persistent across browser
I'm building a Django where the admin will create a user and then one mail will be sent to the user. In the mail, I'm also sending one token with the URL on clicking which the user will get verified by checking the correctness of the token. But the problem is I'm storing the token in Django session and when I open the link on the same browser it works but on a different machine user is not getting verified as session data becomes unavailable. Someone suggest me the best way to store the token. I didn't want to use the database as it doesn't make sense. -
How to solve urls not found issue in django
I am building an app using django and notice that some new urls that i have created, the list is provided below are not being found. I read somewhere that the slug might be the reason django cannot found the urls but i am not sure main urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path(config("ADMIN_URL"), admin.site.urls), path("", include("core.urls", namespace="core")), ] application urls.py from django.contrib import admin from django.urls import path, include from . import views app_name = 'core' urlpatterns = [ path('index/', views.index, name='index'), path('home/', views.home, name='home'), path('home/<str:slug>/', views.user_lessons_details, name='user-lessons-details'), path('home/join-transaction/', views.user_lessons_join_transaction, name='user-lessons-join-transaction'), path('home/start-transaction/', views.new_test_epoint, name='new-test-epoint'), path('home/draft/<str:slug>/', views.user_lessons_core_action, name='user-lessons-draft'), path('teachers/lessons/create/', views.merchant_lessons_create, name='teachers-lessons-create'), path('teachers/lessons/list/', views.teachers_lessons_list, name='teachers-lessons-list'), path('teachers/lessons/<str:slug>/', views.teachers_lessons_details, name='teachers-lessons-details'), path('teachers/lessons/<str:slug>/update/', views.teachers_lessons_update, name='teachers-lessons-update'), path('teachers/lessons/<str:slug>/delete/', views.teachers_lessons_delete, name='teachers-lessons-delete'), path('teachers/drafts/create/', views.teachers_core_actions_create, name='teachers-drafts-create'), path('teachers/drafts/list/', views.teachers_core_actions_list, name='teachers-drafts-list'), path('teachers/drafts/<str:slug>/', views.teachers_core_actions_details, name='teachers-drafts-details'), path('teachers/drafts/<str:slug>/update/', views.teachers_core_actions_update, name='teachers-drafts-update'), path('teachers/drafts/<str:slug>/delete/', views.teachers_core_actions_delete, name='teachers-drafts-delete'), path('teachers/home/list/', views.teachers_home_list, name='teachers-home-list'), path('teachers/home/<str:slug>/', views.teachers_home_details, name='teachers-home-details'), path('teachers/home/create/course/', views.teachers_home_transaction_quote, name='teachers-home-create-course'), path('teachers/home/create/something/', views.teachers_home_create_transaction, name='teachers-home-create-something'), path('teachers/home/create/fields-selection/', views.teachers_home_fields_selection, name='teachers-home-fields-selection'), # ALL THE NEW URLS BELOW return NOT FOUND in django no matter what i do path('teachers/home/account/settings/', views.teachers_settings, name='teachers-settings'), path('teachers/account/settings/update-password/', views.teachers_settings_update_password, name='teachers-settings-update-password'), path('teachers/account/payments/', views.teachers_payments, name='teachers-payments'), path('teachers/account/payments/update/', views.teachers_payments_update, name='teachers-payments-update'), path('teachers/account/analytics', views.teachers_analytics_stuff, name='teachers-analytics-stuff') ] How can i possibly solve this urls not found issue in django? -
Should i use django or no?
I should implement a deep learning face recognition model that should use photos from a database should i build the model using tensorflow and python first then deploy it on a backend done with nodejs or I should start the project with using tool like django? -
Django Media Files Not Showing
My Django files are loading after upload and are shown in the media folder, however I cannot access them at localhost:<PORT>/media/<FILENAME._EXT>. I've looked at several other answers on stackoverflow and they haven't worked. For example adding the urlpatterns += static(...), having DEBUG=True in settings.py. When accessing: http://localhost:8000/media/controller.gif: Error: lightchan-backend-1 | Not Found: /media/controller.gif lightchan-backend-1 | 2022-03-06 16:37:34,875 WARNING Not Found: /media/controller.gif In settings.py: DEBUG = True MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') In my urls.py: from django.urls import path from django.conf.urls.static import static from django.conf import settings from . import views urlpatterns = [ path('', views.index, name='index'), path('comment/<int:comment_id>/', views.comment, name='comment'), path('comments/', views.comments, name='comments'), path('reply/<int:incoming_id>/', views.reply, name='reply') ] # if settings.DEBUG is True: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Why ModelForm in my forms.py showing error?
I have made the simple form using django, i am new to django,yesterday, i have wrote some code to practice,from today it is not working,but it is working yesterday. template file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="POST" novalidate> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> </body> </html> from django.http import HttpResponse from django.shortcuts import render from .forms import FeedBackFormCustom from .models import FeedBack # Create your views here. def home(req): if req.method == "POST": form = FeedBackFormCustom(req.POST) if form.is_valid(): nm = form.cleaned_data['name'] ag = form.cleaned_data['age'] em = form.cleaned_data['email'] st = form.cleaned_data['state'] inst = FeedBack(name=nm, age=ag, email=em, state=st) inst.save() return HttpResponse('<h2>Form successfully submitted.</h2>') else: form = FeedBackFormCustom() context = {'form': form} return render(req, 'home/index.html', context) Models.py from pyexpat import model from django.db import models # Create your models here. class FeedBack(models.Model): STATES_AVAILABLE = ( ('ap', 'Andhra Pradesh'), ('mp', 'Madhya Pradesh'), ('kn', 'kutub nagar'), ('mu', 'Mumbai'), ('de', 'Delhi'), ('ch', 'Chennai'), ) name = models.CharField(max_length=30) age = models.PositiveIntegerField() email = models.EmailField(max_length=200) state = models.CharField(max_length=3, choices=STATES_AVAILABLE) def __str__(self): return self.name ModelForm.py from django import forms from .models import FeedBack from django.contrib.auth.forms import UserChangeForm, UserCreationForm, PasswordChangeForm, SetPasswordForm class FeedBackFormCustom(forms.ModelForm): class Meta: …