Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i pass get values to specific models fields in views.py
How to pass request.GET.get value to another form in django. def bacadmininvitoBid_views(request): project_list = ProjectNameInviToBid.objects.all() query = request.GET.get('query') if query: project_list = project_list.filter(ProjectName__icontains=query) if request.method == 'POST': form = invitoBidForm(request.POST, request.FILES) if form.is_valid(): form.ProjectName = project_list form.save() messages.success(request, 'File has been Uploaded') else: form = invitoBidForm() args = { 'form': form, 'project_list': project_list } return render(request, 'content/invitoBid/bacadmininvitoBid.html', args) i want to pass it to ProjectName field -
unable display profile details through signup only admin login profile displaying?
I'm new to django i created signup form when i enter the data it will saved to database login also fine but only saving admin user details not saved our table details in admin thats the resion try to display profile details only user details displaying suppose i enter data through admin all details will displaying in profile views.py -------- from django.shortcuts import render,redirect from django.contrib.auth.decorators import login_required from django.http import HttpResponse,HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from testapp.forms import signupform from django.contrib.auth.hashers import check_password from testapp.models import Userprofile def homeview(request): return render(request,'testApp/home.html') @login_required def feedbackview(request): return render(request,'testApp/feedback.html') def logoutview(request): return render(request,'testApp/logout.html') def akhilview(request): return render(request,'testApp/akhil.html') def siriview(request): return render(request,'testApp/siri.html') def depview(request): return render(request,'testApp/dep.html') def subview(request): return render(request,'testApp/sub.html') @login_required def view_profile(request, pk=None): if pk: user = Userprofile.objects.get(pk=pk) else: user = request.user args = {'user': user} return render(request, 'testApp/profile.html', args) def register(request): form=signupform() if request.method=='POST': form=signupform(request.POST) if form.is_valid(): user=form.save() user.set_password(user.password) user.save() return redirect("/accounts/login") else: print(form.errors) else: form=signupform() # return HttpResponseRedirect('/accounts/login') return render(request,'testapp/singup.html',{'form':form}) forms.py ------- from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core import validators class signupform(forms.ModelForm): name=forms.CharField(max_length=25) password = forms.CharField(max_length=32, widget=forms.PasswordInput) phone = forms.IntegerField() date_of_birth=forms.DateTimeField(help_text='DD/MM/YYYY H:M',input_formats=['%d/%m/%Y %H:%M']) gender = forms.CharField(max_length=10, required=True) age = forms.IntegerField() … -
Not able to created nested comment functionality using django rest framework
I am trying to make a nested comment functionality using django rest framework. I am using Django 2.2 and rest framework version 3.10.2 but here i am following a video in youtube that uses Django 1.9. No matter what value i passed in URL, it always return a validation error stating that model_qs is empty. I am not able to solve this issue. Can someone please look into it and let me point out what i am doing wrong here. from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType urls.py urlpatterns = [ path('create/', CommentCreateAPIView.as_view(), name='create'), ] model.py class CommentManager(models.Manager): def all(self): qs = super(CommentManager, self).filter(parent=None) return qs def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id).filter(parent=None) return qs def create_by_model_type(self, model_type, slug, content, user, parent_obj=None): model_qs = ContentType.objects.filter(model=model_type) if model_qs.exists(): some_model = model_qs.first().model_class() obj_qs = some_model.objects.filter(slug=slug) if obj_qs.exists() and obj_qs.count() == 1: instance = self.model() instance.content = content instance.user = user instance.content_type = model_qs.first() instance.object_id = obj_qs.first().id if parent_obj: instance.parent = parent_obj instance.save() return instance return None class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) … -
Form after registration is not submitting Django
To complete registration, I want users to complete secondary form. However secondary form is not submitting. I think user is not getting authenticated in the registration and then the secondary form is not submitting. The login() seems to not work. # the form in this view that's not submitting def agreements(request): if request.method == "POST": form = AgreementsForm(request.POST) if form.is_valid(): user = request.user agree = form.save(commit=False) agree.save() else: raise ValidationError("Form is not valid. Try Again.") else: form = AgreementsForm() return render(request, 'agree.html', {'form': form}) Here is the forms.py for the agreements: class AgreementsForm(forms.ModelForm): non_ent=forms.BooleanField(label='kdmkl kdldsk') agreement1=forms.BooleanField(label='dmklsd. lkdfmld') class Meta: model = Agreements fields = ('non_ent', 'agreement1') def save(self, commit=True): agree = super(AgreementsForm, self).save(commit=False) agree.non_ent = self.cleaned_data['non_ent'] agree.agreement1 = self.cleaned_data['agreement1'] if commit: agree.save() return agree Here is the initial registration view: # register view which submits, but I think it's not authenticating the user def registration(request): if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = True user.save() login(request, user, backend='django.contrib.auth.backends.ModelBackend') return redirect('agreements_page') else: raise ValidationError("Form is not valid. Try Again.") else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}) -
have different base image for an application in docker
I am new in docker world.I am trying to understand Docker concepts about parent images. Assume that I want to run my django application on docker. I want to use ubuntu and python, I want to have postgresql as my database backend, and I want to run my django application on gunicorn web server. Can I have different base image for ubuntu, python, postgres and gunicorn and create my django container like this: FROM ubuntu FROM python:3.6.3 FROM postgres FROM gunicor ... I am thinking about having different base image because if someday I want to update one of these image, I only have to update base image and not to go into ubuntu and update them. -
Django dynamic filter the data base on dropdown select
Having trouble selecting data based on the dynamic dropdown list. Save the user data and being populated as a list. Couple questions: how to bring data from the AddData into SiteData Also when user select the dropdown code from the SiteData, How to associate or populate data only for that SiteData how to map the data code with site_ip, site_prefix, site_data1,site_data2 Also noticed, when selecting dropdown, I get the value as number not the text name.. for example: site 68 site_ip 1 MODEL class Code (models.Model): name = models.CharField(max_length=4, default=None, blank=True, unique=True, error_messages={'unique':"Already in Used"}) def __str__(self): return self.name class AddData (models.Model): code = models.ForeignKey(Code, on_delete=models.CASCADE, null=True) data1_ip = models.GenericIPAddressField(protocol='IPv4', unique=True, error_messages={'unique':"Already in Used"}) data2_prefix = models.CharField(max_length=2, default='22') def __str__(self): return self.data1_ip class SiteData (models.Model): site = models.ForeignKey(Code, on_delete=models.CASCADE, null=True) site_ip = models.ForeignKey(AddData, on_delete=models.CASCADE, null=True) site_prefix = models.ForeignKey(AddData, on_delete=models.CASCADE, null=True) site_data1 = models.CharField(max_length=3, default='120') site_data2 = models.CharField(max_length=1, default='1') FORM class CODE_Form(forms.ModelForm): class Meta: model = Code fields = ('name',) class AddData_Form(forms.ModelForm): class Meta: model = MIDTIER_Add_Site fields = ('code', 'data1_ip', 'data2_prefix',) class SiteData_Form(forms.ModelForm): def __init__(self, *args, **kwargs): super(SiteData_Form, self).__init__(*args, **kwargs) if 'site' in self.data: c = self.data.get('site') c_ip = self.data.get('site_ip') self.fields['site'] = forms.ModelChoiceField(queryset=CODE.objects.filter(name=c)) self.fields['site_ip'] = forms.ModelChoiceField(queryset=CODE.objects.filter(name=c_ip)) class Meta: model = … -
Permission Denied when attempting to start Daphne systemctl process
I'm deploying a website using Django and Django-Channels, with Channel's daphne ASGI server substituting for the typical Gunicorn WSGI setup. Using this Gunicorn WSGI tutorial as a jumping off guide, I attempted to write a systemctl service for my daphne server, when I hit the below error: CRITICAL Listen failure: [Errno 13] Permission denied: '27646' -> b'/run/daphne.sock.lock' I was unfortunately unable to find any answers to why permissions would be denied to the .sock file, (in context to Daphne) so I was hoping I could get some hints on where to begin debugging this problem. Below are my daphne.socket and my daphne.service files. daphne.service [Unit] Description=daphne daemon Requires=daphne.socket After=network.target [Service] User=brianl Group=www-data WorkingDirectory=/home/brianl/autoXMD ExecStart=/home/brianl/autoXMD/env/bin/daphne -u /run/daphne.sock -b 0.0.0.0 -p 8000 autoXMD.asgi:application [Install] WantedBy=multi-user.target daphne.socket [Unit] Description=daphne socket [Socket] ListenStream=/run/daphne.sock [Install] WantedBy=sockets.target Based off the linked DigitalOcean tutorial, I start my service with sudo systemctl start daphne.socket. My guess is that there's some kind of discrepancy between setting up systemctl services for Gunicorn and Daphne that I missed, but I don't know for sure. (If it helps, I'm planning on using Nginx as the main server, but I haven't reached that point yet) -
How create model objects when one of field foreign key without value
I have a model Ligue class League(models.Model): league_id = models.IntegerField(primary_key=True) league_name = models.CharField(max_length=200) country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL) season = models.ForeignKey('Season',null=True, on_delete=models.SET_NULL) season_start = models.DateField(null = True) season_end = models.DateField(null = True) league_logo = models.URLField(null = True) league_flag = models.URLField(null = True) standings = models.IntegerField(null=True) One of the fields country_code related with foreign key to another field which at time of creating object from model league will be without any value without data. What is right way of creating objects from models when foreign keys of this model reference to tables without data -
Django Admin Detail Page Link to an External URL
I am trying to link to a page OUTSIDE of my django admin side with the following code for a function that is added as as read_only field of my admin interface. def website(self, preset): if preset.he_school.profile.admissions_url: return format_html( f"<a href='{preset.he_school.profile.url}'>Link</a>" ) The problem is I always get URLs of the resulting link with the path to this page prepended to the URL I actually want to send people to: 386/change/www.sc.edu/admissions instead, I just want to send people to www.sc.edu/admissions How can I prevent this from happening? -
How to deal with inconsistent dates in Django?
I am trying to show the birth and death dates for artists. Some artists have incomplete dates. For example: Johannes Vermeer is "Delft, October, 1632 - Delft, 15 December, 1675". How can one deal with this in Django model.Datefield()? Should I save the year, month and day separately? -
Generic Relation not reflecting in migrations in django?
I'm trying to add a GenericRelation field to the Notification model to my "Bond" model. The issue is that whenever I run makemigrations, this field does not get acknowledged. What could be the issue? Error: django.core.exceptions.FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. class Bond(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") bond_created = models.DateTimeField(default=now) notifications = GenericRelation(Notification) class Notification(models.Model): #337, 777, 765, 843, 124 notification_type = models.PositiveIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') -
How to set default as request.user in a model
I have a ForeignKey in a model, and a class based view: models.py class Book(models.Model): author = models.ForeignKey(get_user_model()) views.py class BookCreate(CreateView): model = Book ... How can I set a default value for the author to be the logged in user. E.g. something like author = models.ForeignKey(get_user_model(), default=request.user), although this obviously doesn't work. -
Building a poll application with Django
Okay guys so I'm building a financial planner application. The beauty of this application is that when a user inputs certain variables such as: salary, cost of asset and monthly saving goal a formula will work out how much is needed to save over x amount of time. So for example a formula I wrote up earlier: b = monthly saving/700 y = salary/40,000 x / (12b + y) = x x = amount needed to save Based on the user input the desired outcome would return the length and amount of time it will take to achieve z. I plan to create this project using Django but would really appreciate some recommended material or similar apps that you guys may have seen that I can learn from. -
How to stop my repo from cloning into new folder and clone into direct folder instead
I have a template I created but when cloning into the Django project folder it creates a subproject folder. I want it to just clone the subfolders and files when cloning the repo. Is there a way to do this? -
How to update a form and update table cell in Django
I am very new Django and python, trying to learn and build a webapp. I want to show some data to user in a table format. The user should be able to add, delete and update records in the table view. I am able to achieve the add, delete part but, cannot get my head around updating the existing records. Ideally, i want the row data to be populated in a modal view as a django form when clicked on "edit" button of a particular row. But unable to even get the basic update from a editable table row. Here is my sample code.. I tried this at below link but, did not help .. or may be i did not understand. Django: updating database row via table cell models.py # Create your models here. class customerDataModel(models.Model): customerName = models.CharField(max_length=200) custormerLocation = models.CharField(max_length=200) custormerAge = models.CharField(max_length=200) custormerLanguage = models.CharField(max_length=200) def __str__(self): return self.customerName forms.py from django import forms from . models import customerDataModel class addCustomerForm(forms.ModelForm): class Meta: model = customerDataModel fields = ('customerName', 'custormerLocation', 'custormerAge', 'custormerLanguage') widgets = { 'customerName': forms.TextInput( attrs={ 'class': 'form-control' } ), 'custormerLocation': forms.TextInput( attrs={ 'class': 'form-control' } ), 'custormerAge': forms.TextInput( attrs={ 'class': 'form-control' } ), … -
How to serialize multiple images(as in url) of an object in DRF?
I have a Image model related to Item model via ForeignKey, but the API endpoint of this resource only shows the images's name instead of image's url. (I have a single imagefiled in Item model, which can be shown as url/uri). So, how to serialize the data in order to get all the media urls for the images. Models : class Item(models.Model): title = models.CharField(max_length=200) ... img = models.ImageField() class ItemDetailImg(models.Model): item = models.ForeignKey( Item, on_delete=models.CASCADE, related_name='images') image = models.ImageField() Serializers: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ("id", "title", ... "images" ) one API response: { "id": 16, "title": "Venice", ... "img": "http://127.0.0.1:8000/media/roman-kraft-g_gwdpsCVAY-unsplash.jpg", "images": [ 7, 8 ] } I expect this kind of api response { "id": 16, "title": "Venice", ... "img": "http://127.0.0.1:8000/media/roman-kraft-g_gwdpsCVAY-unsplash.jpg", "images": [ "http://127.0.0.1:8000/media/image1.jpg", "http://127.0.0.1:8000/media/image2.jpg" ] } Thank you, any help would be appreciated! -
is possible to use django rest framework for a build APK?
I am working whit django rest framework my link is this: http://hernancapcha.webfactional.com/licencias/ and for angular and IONIC local works Ok but when I build my APK a got one error "http failure response for 0 unknown error" I undestand that is becouse the headers in django, but is there a way to comunicate both? this is my Service: getOneLicencia(pet):Observable<any>{ return this.http.get(this.baseUrl+'/milistac/lice/?q=' +pet+ '', {headers:this.httpHeaders}); } -
What will happen if i create a group and didn't add a specific permissions to it?
I have two groups 'user' and 'moderator' with no specific permissions added (Chosen permissions empty). I have also three views to add/edit/delete objects, user can only add whereas moderator can edit/delete views.py class AddView(GroupRequiredMixin, CreateView): model = Post form_class = UpdateForm template_name = 'post_add.html' group_required = u"user" class UpdateView(GroupRequiredMixin, UpdateView): model = Post form_class = UpdateForm template_name = 'post_update.html' group_required = u"moderator" class DeleteView(GroupRequiredMixin, DeleteView): model = Post template_name = 'post_delete.html' group_required = u"moderator" The question is do i need to add permissions to the groups? for exmple add a permission to group 'user' that he can only add objects to model post ? or it is not needed ? thanks -
How to pass a custom tag parameter from a form field?
In order, i need to extend a model DetailView page with a specific custom function. That function need to be called from DetailView page and return some data, depending on the parameter entered by user into custom form on DetailView. That data, responded by custom function, i need to display on the same DetailView page, without database record, when user enter a form field value and press 'submit'. I think to implement that function by custom tag, which is located in /app/templatetags/func.py #/app/templatetags/func.py from django import template register = template.Library() def get_data(current_version, previous_version, some_data): return current_version+' works!' and call it in template, something like that: <!--templates/detail/article_detail.html--> {% load func %} ... {% get_data article_object.value %} <form action="" method="get"> {{ form }} <input type="submit" value="Compare"> </form> ... it works then i trying to specify an argument here in template. But i cannot understand how to take it from the form. Here is views.py: class ArticleDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Version context_object_name = 'article_object' template_name = 'detail/article_detail.html' login_url = 'login' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = GetChangelog() return context forms.py class GetChangelog(forms.Form): diff_version = forms.CharField(label='difference',max_length=10) Looks like it's impossible to pass a parameter through the url, because of that: -
Appropriate schema to design a notification system in django?
I am trying to create a notification system in Django. Is it better to have a notification_type field, user_id and a foreign key to different tables (like, comment, relationship tables)? Or should they all have a separate table for each type of notification like "LikeNotification", "CommentNotification", etc in addition to all of them having a user_id field? Design 1: class LikeNotification(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class CommentNotification(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class PostNotification(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class BondNotification(models.Model): bond = models.ForeignKey(Bond, on_delete=models.CASCADE,) user = models.ForeignKey(User, on_delete=models.CASCADE) Design 2: class Notification(models.Model): notification_type = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) like = models.ForeignKey(Like, on_delete=models.CASCADE) comment = models.ForeignKey(Comment, on_delete=models.CASCADE) bond = models.ForeignKey(Bond, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) -
Correctly parsing XML in python
How do I pass my XML data into my view correctly? The workstation element should have multiple fields, and I only want a few. How do I tie those fields together and pass them correctly? Right now my code is only showing the last child in the first element called 'last_scan_time' so how can I pick apart other aspects that I may want. And how can I pass those to the view? like wanting to show the two workstations into a table? I imagine it'll be like a for each statement, but i'm stuck. Thanks! I'm using the latest version of Django. I know that my code is incomplete, I just need to know what I should be asking for during my request! for child in root for elements in child: print(elements.tag, elements.text) context = {'Name': child.tag, 'description': child.text} return render(request, 'pages/dashboard.html', context) Sample Response <?xml version="1.0" encoding="ISO-8859-1"?> <result created="2019-09-02T14:10:38-05:00" host="www.systemmonitor.us" status="OK"> <items> <workstation> <guid> <![CDATA[96d1fc87beb50e78b693ef4f73ce9056]]> </guid> <name> <![CDATA[DESKTOP-IV3PGUT]]> </name> <description> <![CDATA[Andy]]> </description> <install_date>2018-03-02</install_date> <last_boot_time>1565914977</last_boot_time> <dsc_active>1</dsc_active> <atz_dst_date>0000-03-02:00T02:00:00</atz_dst_date> <utc_apt>2019-09-02 17:34:46</utc_apt> <utc_offset>14400</utc_offset> <user> <![CDATA[DESKTOP-IV3PGUT\Andy]]> </user> <domain> <![CDATA[WORKGROUP]]> </domain> <manufacturer> <![CDATA[Gateway]]> </manufacturer> <model> <![CDATA[DX4850]]> </model> <ip> <![CDATA[192.168.0.3]]> </ip> <external_ip> <![CDATA[]]> </external_ip> <mac1> <![CDATA[]]> </mac1> <mac2> <![CDATA[]]> </mac2> <mac3> <![CDATA[]]> </mac3> <os> <![CDATA[Microsoft Windows … -
Nodemcu POST response -1
Nodemcu device is returning -1 http response for a POST request on django rest api. I tried the same http request to Postman, and it works perfectly fine. if(WiFi.status() == WL_CONNECTED) { HTTPClient http; http.begin(host_url); http.addHeader("Content-Type", "application/x-www-form-urlencoded"); httpCode = http.POST(postData); payload = http.getString(); http.end(); } The expected result is 200, whereas I get -1. Can someone please explain? -
how to pass a function loggin from an app to other
thanks for your time. i'm having some trouble to setup my loggin system, besides having a "login.html" i'd like to let displayed the loggin system on the navbar on my "base.html" and after the user login let displayed the user logged in. i don't know hot to call the login_view on other apps from the same project. i've succeded to let displayed the username and the form before the login. although i've created an app just for the accounts and its displaying the form just in the 'accounts/login' (not shure if creatting an app just for this is the best way). login_view.accounts.views.py def login_view(request): next = request.GET.get('next') form = LoginForm(request.POST or None) # se estiver escrito certo# if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') # autenticando o usuario# user = authenticate(username=username, password=password) # se estiver tudo certo (autendicado) chamar a função login# login(request, user) if next: return redirect(next) return redirect('/c2vconfig/MP4') context = { 'form2': form, } return render(request, "base.html", context) the login section on navbar on base.html: <li class="nav-item"> <a class="nav-link">{{request.user.username}}</a> </li> </ul> <form class="form-inline my-2 my-lg-0" action="{% url 'login' %}"> {{form2}} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">login</button> accounts.urls.py: urlpatterns = [ path('login', views.login_view, name='login'), path('register', views.register_view, name='register'), path('logout', … -
Django Templates List of Checkboxes
I Want a list of checkboxes. When I tap them I want my model Checker.checked == True or False. My problem now when I tap one all of them are connected so only the first one changes value when I click number 2 or 3. And right now its not connected to the database. And I want it to be connected. class Checker(models.Model): name = models.CharField(max_length=100) checked = models.BooleanField(default=False) sender = models.ForeignKey(UserProfile, blank=True, on_delete=models.CASCADE, related_name="person_who_checks_checker"), canview = models.ManyToManyField(UserProfile, blank=True, related_name="can_view_checker") @login_required def detailTaskPage(request,pk): username = request.user checkers = Checker.objects.filter(task__id=pk) tasks = get_object_or_404(Task,pk=pk) return render(request, 'nav-side-task.html', {'task': tasks, 'MyName': username, 'Checkers': chrs}) {% for checker in Checkers %} <div class="row"> <div class="form-group col"> <span class="checklist-reorder"> <i class="material-icons">reorder</i> </span> <div class="custom-control custom-checkbox col"> <input type="checkbox" class="custom-control-input" id="checklist-item"> <label class="custom-control-label" for="checklist-item"></label> <div> <input type="text" placeholder="Checklist item" value="{{ checker.name }}" data-filter-by="value" /> <div class="checklist-strikethrough"></div> </div> </div> </div> <!--end of form group--> </div> {% endfor %} -
how to get element by ID on django modelform
** i'm setting up a django modelform that has a addmore button using js i want to be able to get the id of the button to be part of the the modelform since it has an html type.text..so i can see the value in the model admin th form.py from django import forms from django.contrib import admin from .models import FandB from Guest.models import Guest_Profile from .choice import * class FandBForm(forms.ModelForm): food_Items = forms.ChoiceField(choices = FOOD, label="Food", initial='select food', widget=forms.Select(), required=True) drinks_Items = forms.ChoiceField(choices = DRINKS, label="Drinks", initial='', widget=forms.Select(), required=True) payment_type = forms.ChoiceField(choices = PAYMENT_TYPE, label="Payment", initial='', widget=forms.Select(), required=True) amount = forms.DecimalField(max_digits=10, decimal_places=2) class Meta: model = FandB fields = ('guest',) def str(self): return self.food_Items views.py from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from django.template.loader import render_to_string from Home . utils import render_to_pdf from datetime import datetime from django.http import HttpResponse from django.views.generic import View from Home. utils import * from .models import FandB from Guest.models import Guest_Profile from .forms import FandBForm def order_list(request): orders= FandB.objects.all() context ={ 'orders':orders } return render(request, 'FB/order_list.html', context) def save_order_form(request, form, template_name,*args,**kwargs): data = dict() if request.method == 'POST': form = FandBForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True orders = FandB.objects.all() …