Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run django-admin
I'm new to django and I would like to follow this tutorial: https://docs.djangoproject.com/en/2.1/intro/tutorial01/ Unfortunately, django-admin is not in my path. When I try to run the django-admin.py script directly, I have the following error: $ /usr/local/lib/python3.7/site-packages/django/bin/django-admin.py Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/bin/django-admin.py", line 2, in <module> from django.core import management ImportError: No module named django.core Here is my configuration: System: macOS 10.13 Python: 3.7.0 (installed via Homebrew Django: 2.1.4 What am I doing wrong? -
Can not save an instance object of a manytomany relationship implemented with inlines
In my app I would like to implement the feature that a user could choose to create a preorder with more than one products. My problem is that despite the fact that I can create the inline form it is not possible to save the instance referring to preorder in my view.py My form appears the Preorder model and my formset appears the Preorder_Has_Products relationshp. Preorder and Product are models with the relationship below: models.py class Preorder(models.Model): client = models.ForeignKey(Client,verbose_name=u'Πελάτης') preorder_date = models.DateField("Ημ/νία Προπαραγγελίας",null=True, blank=True, default=datetime.date.today) notes = models.CharField(max_length=100, null=True, blank=True, verbose_name="Σημειώσεις") preorder_has_products=models.ManyToManyField(Product,blank=True) def get_absolute_url(self): return reverse('preorder_edit', kwargs={'pk': self.pk}) my form.py class PreorderForm(ModelForm): class Meta: model = Preorder fields=('preorder_date','notes',) def __init__(self, *args, **kwargs): super(PreorderForm, self).__init__(*args,**kwargs) self.fields['preorder_date'].widget = MyDateInput(attrs={'class':'date'}) class PreorderHasProductsForm(ModelForm): class Meta: model=Preorder.preorder_has_products.through exclude=('client',) def __init__(self, *args, **kwargs): super(PreorderHasProductsForm, self).__init__(*args, **kwargs) #self.fields['preorder_date'].widget = MyDateInput(attrs={'class':'date'}) self.fields['product'].label = "Ονομα Προϊόντος" PreorderProductFormSet = inlineformset_factory(Preorder,Preorder.preorder_has_products.through, form=PreorderHasProductsForm, extra=1) my view.py class PreorderProductCreateView(LoginRequiredMixin, CreateView): model = Preorder fields=['preorder_date','client',] template_name='test/test.html' def get_success_url(self, **kwargs): return reverse('client_list) def form_valid(self, form): context = self.get_context_data() Preorder_Preorder_Has_ProductsFormset = context['Preorder_Preorder_Has_ProductsFormset'] if Preorder_Preorder_Has_ProductsFormset.is_valid() and form.is_valid(): self.object = form.save() # saves Father and Children #products = Preorder_Preorder_Has_Products_CreateView.save(commit=False) products=Preorder_Preorder_Has_ProductsFormset.save_m2m() print(len(products)) for instance in products: instance.preorder = self.object instance.save() #douleuei, to self.object anaferetai sto preorder #Preorder_Preorder_Has_Products_CreateView.save_m2m() print(instance.id) … -
Cloud system with local printers
I'm developing a new software. Actually i'm using python with django to develop backend and a framework javascript to design frontend. Today I'm using local installation because the software needs to handle some local termal printers. Besides the software I have "mobile app" that is not but a internet page. This mobile app makes a order and it's printed in the printers. In my pilot clients the system are running in a raspberry pi 3 model b+ with fixed IP, S.O raspbian and CUPS managing printers, to use the software it's necessary only open a internet browser and enter the Raspberry IP address. My problem is that I want to have a low cost software to be installed by the customers themselves (they don't have a raspberry pi, they have a machine with windows usually) and in this case, the problem is: How will the software connect to the printers directlly, once the mobile need to send orders without any question about printers as we can see usually on a internet page. -
Save two forms data with OneToOneField in Django
i have two models class Client(models.Model) : Code_Client=models.CharField(max_length=200) ...... and class Adr(models.Model) : client = models.OneToOneField(Client,on_delete=models.CASCADE) I created two forms: one for Client and another for Adr in order to use it in one template I could do that with no problem but when I try to save the data from both form it gives me an error if form.is_valid() and form_Adr.is_valid(): #pdb.set_trace() new_client=form.save() Adr0 = form_Adr.save(commit=False) Adr0.client= new_client Adr0.save() the error is Client: this field is mandatory. -
Django2 queries not written to log
I'm trying to learn Django, but finding it quite hard. Likely because my C++/PHP/Symfony experience is making it difficult to 'think Python'. While most issues tend to be solved in an 'D'oh!' moment after some hours of mumbling profanities, this one is proving to be very resilient. I've got Django2 installed, configured with a MariaDB 10.2 database and the django-debug-toolbar. DEBUG is true and my IP (localhost) is added to INTERNAL_IPS I'd like to see the queries that the Django ORM is producing, but the debug toolbar is only showing me input and output. The actual queries are displayed as 'None' The same thing happens when attempt to log the queries to the console using https://stackoverflow.com/a/20161527/3883632 I'm probably missing something obvious, but can't find it nor any reference to this issue. Relevant version information: Python 3.7.1 Django 2.1.4 Mysqlclient 1.3.14 django-debug-toolbar 1.11 -
Get all urls in django project
I need to make a request to every page of my django project and check its db connections. Is there a way to get list of them? Is this possible to do without using any third-party libraries? -
AttributeError: 'ContactUs' object has no attribute 'model'
can any body help me, i try create contact form on python-django, and when i try make migrations on data base i recieve error "AttributeError: 'ContactUs' object has no attribute 'model'" vievs.py from django.shortcuts import render from .forms import ContactForm, ContactUs from django.core.mail import EmailMessage from django.shortcuts import redirect from django.template.loader import get_template def contact(request): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): first_name = request.POST.get('first_name', '') last_name = request.POST.get('last_name', '') date = request.POST.get('date', '') month = request.POST.get('month', '') year = request.POST.get('year', '') sender = request.POST.get('sender', '') message = request.POST.get('message', '') licence = request.POST.get('licence', '') phoneNumber = request.POST.get('phoneNumber', '') zipCode = request.POST.get('zipCode', '') cdlType = request.POST.get('cdlType', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = { 'first_name': first_name, 'last_name': last_name, 'date': date, 'month': month, 'year': year, 'sender': sender, 'message': message, 'licence': licence, 'phoneNumber': phoneNumber, 'zipCode': zipCode, 'cdlType': cdlType, } content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" + '', ['youremail@gmail.com'], headers={'Reply-To': sender} ) email.send() return redirect('contact') return render(request, 'email.html', { 'form': form_class, }) def contact_us(request): form_class = ContactUs # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): first_name = … -
I do not know how to activate register for foreign key in relationship in the database
I'm Brazilian then in the table Veiculo == vehicle and Pessoa == person and as a person can have several cars plus one car only one person when registering a new monthly check-in in the parking lot, I need to select the person only the cars that he owns appear as an option. I need that when registering a Pessoa and a Veiculo they are realacionamos in a way that when registering using Views Mensalista when I put Pessoa soment the Veiculo that is owned by it appears in a forum gave me the idea to use the code below, but I do not know how to implement it proprietarioId = id queryList = Veiculo.objects.filter(proprietario__id = proprietarioId) Models.py TATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins') ) class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email … -
Django - How to properly stream a matrix in a RESTful API?
After computing some values from on the server side. The result is a matrix (i.e a pandas.DataFrame) with the following format: 0 1 2 3 4 5 6 0 1 0 0 0 2 0 6 100 0 0 0 0 0 0 0 200 0 0 0 0 0 0 0 300 0 0 0 0 0 0 0 Where first row/column represents row/column indexes, and (just in this case) some of the values are zero. What would be a popper JSON format to stream this matrix? Is there any standard way to do it? -
django email attachment of an uploaded file using modelname.filevariable.url
I have a Django library application, wherein from a list of books, the customer can email a particular book's pdf file link that was originally uploaded using FileField by the admin. Now, the email is being sent/received successfully, however the pdf file is not getting attached. I have also looked into other stackoverflow references for the same, but I am unable to interpret the correct solution: Django email attachment of file upload On clicking the email button, the form is submitted as follows: Three hidden values are also being submitted on submitting the form. , one of which is the book.file.url <form method="POST" action ="{% url 'email_book' %}" enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="book_title" value="{{ book.title }}"> <input type="hidden" name="book_author" value="{{ book.author }}"> <input type="hidden" name="book_pdf" value="{{ book.file.url }}"> <button type="submit" class="btn btn-info"><span class="glyphicon glyphicon-envelope"></span>&nbsp;&nbsp;Email</button> </form> The urls.py urlpatters=[....path('email_book/', views.send_email, name='email_book'),...] In views.py, I have used Django's EmailMessage class as follows: def send_email(request): book_title = request.POST.get('book_title') book_author = request.POST.get('book_author') book_pdf = request.POST.get('book_pdf') # i.e book.file.url email_body = "PDF attachment below \n Book: "+book_title+"\n Book Author: "+book_author try: email = EmailMessage( 'Book request', email_body, 'sender smtp gmail' + '<dolphin2016water@gmail.com>', ['madhok.simran8@gmail.com'], ) # this is the where the error occurs email.attach_file(book_pdf) … -
Find the model name from a Django Rest framework Serializer
I have a serializer from which I need to find the associated model name.This is how i did it: In [30]: from my_app.serializers.PolicySerializer import PolicyCreateSerializer In [31]: model_name = PolicyCreateSerializer.Meta.model In[32]: model_name Out[32]: my_app.models.Policy.Policy What i need is the last part of that value separated by dots(Policy).However, the type of model_name is not a string and converting it to a string gives a weird string as follows: In [33]: type(model_name) Out[33]: django.db.models.base.ModelBase In [34]: str(model_name) Out[34]: "<class 'my_app.models.Policy.Policy'>" Is there an easier way to avoid this gnarly string and this get the Model name ? -
Generic Views for passing multiple data to template
Field values are not shown in template only extrainfo is displayed. I want to display both (fields) and (extrainfo) values class CompanyUpdateView(UpdateView): model = Company fields = ['company_name', 'company_description','company_email', 'company_phone', 'company_address', 'company_website' , 'company_status', 'company_monthly_payment'] def get_context_data(self, **context): context[self.context_object_name] = self.object context["extrainfo"] = "Processador123123" return context -
Update method on Django Rest framework nested serializer for M2M fields
I have three models in my models.py as follows: class Service(models.Model): name = models.CharField(max_length=50, unique=True) port = models.PositiveSmallIntegerField() protocol = models.CharField(max_length=50) class ServiceGroup(models.Model): name = models.CharField(max_length=50, unique=True) services = models.ManyToManyField(Service, through=ServiceToServiceGroup) class ServiceToServiceGroup(models.Model): service = models.ForeignKey(Service) service_group = models.ForeignKey(ServiceGroup) My JSON payload to create a new service group is as follows: { "name": "test_service_group1", "services":["service_1", "service_2"], } Since I have a M2M through table, my strategy to create a new ServiceGroup is to first pop out the services list, create the ServiceGroup with the name and then create the M2M realtionships. My serializer to create a new ServiceGroup is as follows: class ServiceGroupCreateUpdateSerializer(serializers.ModelSerializer): services = serializers.SlugRelatedField(queryset=Service.objects.all(), slug_field='name', many=True) class Meta: model = ServiceGroup fields = ['id', 'name', 'services'] def create(self, validated_data): # Pop the services list out services = validated_data.pop('services', None) # Create the ServiceGroup with the name service_group = ServiceGroup.objects.create(name=validated_data['name']) #Create M2M associations for service in services: service_id = Service.objects.get(name=service) ServiceToServiceGroup.objects.create(service_id=service_id, service_group_id= service_group.id) My question is how do I now write the update method ? My JSON payload remains the same, the only difference being that I pass the instance id in the URL.The pseudo code is as follows: Pop the services list. Save the name to the instance … -
Integrate Django blog project in HTML website
I have a regular website where HTML5, CSS3, JQUERY and static images have been used. I also have a Blog written in Django and I would like to integrate it in the website. I am really new to Django so I was wondering which is the best approach to use. Should I integrate the website code as part of the Django project or there are some other solutions? thanks! -
New to Python - Django, Need To Read Log
I have been handed over an application which is built in Python - Django. I need to support it. There was no handover or anything like that. Pitty Me! I am new to this language and framework. When I try to run the server with python manage.py runserver I get following errors: Unhandled exception in thread started by .wrapper at 0x108f48e18> Traceback (most recent call last): File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/contrib/admin/init.py", line 4, in from django.contrib.admin.filters import ( File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/contrib/admin/filters.py", line 10, in from django.contrib.admin.options import IncorrectLookupParameters File "/Users/atariq/Sites/Python_Stuff/123/venv/lib/python3.7/site-packages/django/contrib/admin/options.py", line 12, in from django.contrib.admin … -
Django loaddata ignore existing objects
I have a fixture with list of entries. eg: [ { "fields": { "currency": 1, "price": "99.99", "product_variant": 1 }, "model": "products.productprice", "pk": 1 }, { "fields": { "currency": 2, "price": "139.99", "product_variant": 1 }, "model": "products.productprice", "pk": 2 } ] This is only initial data for each entry (The price might change). I would like to be able to add another entry to that fixture and load it with loaddata but without updating entries that already exist in the database. Is there any way to do that? Something like --ignorenonexistent but for existing entries. -
Serialize model fields related through another model
I have three models linked like so: class A: some fields class B: ForeignKey('A') class C: ForeignKey('B') Now, when I serialize C, I want to serialize model fields from A. Of course, this can be done using nested serializers like so: class ASerializer: class Meta: model = A fields = ('id', some fields) class BSerializer: a_s = ASerializer(read_only=True) class Meta: model = B fields('id', 'a_s') class CSerializer: b_s = BSerializer(read_only=True) class Meta: model = C fields('id', 'b_s') However, I want to only display the fields of related A objects when serializing C (without using BSerializer). How do I do this? -
Django Manytomanyfield in Ajax CRUD
I implemented an Ajax CRUD. My Model has one ManyToMany field. If i choose only one item for this field everything will be good, but if choose multi items it shows form invalid error. Please tell me what should I do. model.py: class BusienssCategory(models.Model): title = models.CharField(max_length=20, unique=True) slug = models.SlugField(unique=True) description = models.CharField(max_length=45) def __str__(self): return self.title class BusienssProfile(models.Model): title = models.CharField(max_length=20) shortDescription = models.CharField(max_length=40) category = select2.fields.ManyToManyField(BusienssCategory) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) def __str__(self): return self.title form.py: class BusinessForm(forms.ModelForm): class Meta: model = BusienssProfile fields = ('title', 'category', 'shortDescription') view.py: def save_business_form(request, form, template_name): data = dict() form = BusinessForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True businesses = BusienssProfile.objects.all() data['html_business_list'] = render_to_string('business/business_profile/partial_business_list.html', { 'businesses': businesses }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) ajax.js: var saveForm = function() { var form = $(this); var data = new FormData($('form').get(0)); var categories = $("#id_category").val(); alert(categories) var featured = $('#id_featured').prop('checked'); var active = $('#id_active').prop('checked'); data.append("image", $("#id_image")[0].files[0]); data.append("title",$("#id_title").val()); data.append("category", categories); data.append("description",$("#id_Description").val()); $.ajax({ url: form.attr("action"), data: data, processData: false, contentType: false, type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { Command: toastr["success"]("The profile has been deleted.", "Success"); } … -
Nginx bad gateway error on some methods while other works
I am running Django on nginix but one of my functions is returning this error: upstream prematurely closed connection while reading response header from upstream While other methods are working fine. I have traied increasing server timeout in nginx.conf file but still it gives me the same error. This methods runs fine whe i run my django independently with python manage.py runserver 0.0.0.0:8000 Can someone help me to resolve it? -
I can't create custom reset pass view - django - logic error
thank you for helping But I'm trying to create reset password view, without using the default Django reset password to view. by following this tutorial: https://wsvincent.com/django-user-authentication-tutorial-password-reset/ and a second tutorial https://simpleisbetterthancomplex.com/tutorial/2016/09/19/how-to-create-password-reset-view.html my code is the same as the code for the tutorial but for better, understanding I posted a picture of the Django Project URL here:my codes structure of password reset -
Django query, return only if all children's column value is zero
is there any easy way to do a query where it only returns the parent object (trade) if all of its children's(tradeleg) quantity column has zero value? e.g. return trade_1 if trade_1 has five children and all of its children has "0" value on their quantity field. e.g. do not return trade_2 if trade_2 has two children and one of its children has value of "1" on its quantity field. I have this model: class Trade: name = models.CharField( default='', max_length=50, blank=True, null=True ) date = models.DateField( default=None, blank=True, null=True ) class TradeLeg(models.Model): trade = models.ForeignKey( Trade, on_delete=models.CASCADE ) quantity = models.IntegerField( default=0 ) my current query: trade = Trade.objects.filter(tradeleg__quantity = 0) -
django: messages.add_message not displaying in html page
I have a Django library application, wherein I have a book_detail page in which the user can download/email the book's pdf link to himself. On sending such an email(which is working perfectly, the email is being received), I want to display a pop-up or an alert message on that same html page instead of redirecting to some other page. Here is the views.py code: def send_email(request): try: send_mail('Book request', 'email body', settings.EMAIL_HOST_USER, ['xyz@gmail.com'], fail_silently=False) #this message is not getting displayed in the same html page messages.add_message(request, messages.SUCCESS, 'Email sent successfully.') except EmailMessage: messages.add_message(request, messages.SUCCESS, 'Error has occurred') HTML page book_detail.html code: ...... rest of the code.... {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endblock %} The error occuring: Please suggest what should be done, is there any other solution I can try for displaying an alert box/message on that same html page, without redirecting it to any other page. Thanks! -
authenticate function not working for ldap authentication with ldap3
I am trying to configure my app with ldap. I am using ldap3. I am getting this error : Non-ASCII character '\xe2' in file C:\Users\dm050767\Documents\UserProfile\auth\auth_backend.py Following are the files: settings.py AUTHENTICATION_BACKENDS = [ 'auth.auth_backend.UserAuthentication', ] views.py def login_user(request): username = request.POST['username'] password = request.POST['password'] print(username,password) user = authenticate(request, username=username, password=password) print(user) if user is not None: print('User not none') login(request, user) print('Login successful') return redirect(request.POST['next'] or '/') else: print('Login failed') return redirect('/login?error=auth') def login_view(request): if request.method == "POST": return login_user(request) else: return render(request, 'Profile/login.html') auth/auth_backend.py class UserAuthentication: def authenticate(self, request, username=None, password=None, domain="domain"): # TODO add error handling when uid and or pwd is not passed # Check the username/password and return a user. If not valid, it should return None. user = domain + username server = Server('server', get_info=ALL) conn = Connection(server, user=user, password=password, authentication=NTLM) valid_user = conn.bind() if valid_user: try: user = User.objects.get(username=username) if settings.DEBUG: print("YouRockAuth.authenticate: found user %s" % user.username) except User.DoesNotExist: pass else: user = None return user def get_user(self, user_id): try: user = User.objects.get(pk=user_id) return user except User.DoesNotExist: return None -
custom email authentication backend not working in django 2.1.4
I am having trouble in integrating custom authentication backend in django 2.1.4 . Following is my code : my FMS.authBackend module : from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class authEmailBackend(ModelBackend): def authenticate(self, username=None, password=None, **kwargs): print("aaaaaaa") UserModel = get_user_model() try: user = UserModel.objects.get(email=username) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user return None my settings.py : AUTHENTICATION_BACKENDS = ( 'FMS.authBackend.authEmailBackend', 'django.contrib.auth.backends.ModelBackend', ) my urls.py : from django.contrib.auth import views as auth_views urlpatterns = [ path('login', my_decos.logout_required(auth_views.LoginView.as_view(template_name = 'register/login.html')),name = 'login') ] The above code is not working in my case. Function authenticate in authEmailBackend is never called as nothing printed in console but I print statement in authenticate function. although the same code was working for django 2.0.8, the only difference then was that the urls.py was : from django.contrib.auth import views as auth_views urlpatterns = [ path('login', my_decos.logout_required(auth_views.login(template_name = 'register/login.html')),name = 'login') ] but in the newer django the django.contrib.auth.views.login doesn't support any more and we need to use django.contrib.auth.views.LoginView. I read somewhere that to use custom AUTHENTICATION_BACKEND our url must point to django.contrib.auth.views.login but which is not possible here. So can you please help me to overcome the problem. -
How to pass data to template from class based generic form view
views.py class CompanyUpdateView(UpdateView): model = Company fields = ['company_name', 'company_description','company_email', 'company_phone', 'company_address', 'company_website' , 'company_status', 'company_monthly_payment'] company_form.html {% extends "super_admin/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> {{ object.update }} <form action="" method="POST"> {% csrf_token %} <fieldset class="from-group"> <legend class="border-bottom mb-4">Enter New Company</legend> {{ form | crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% endblock content %} I am getting the form values in company_form.html but i want static value which will be stored in CompanyUpdateView and will be display in company_form.html template. The reason i am doing this because i am using same template for update delete and create company where when i click on edit button it will show delete button instead of save button {% extends "super_admin/base.html" %} {% block content %} <a class="btn btn-primary" href="{% url 'super-company-create' %}" role="button">Add a Company</a> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Company Name</th> <th scope="col">Company Email</th> <th scope="col">Company Website</th> <th scope="col">Company Status</th> <th scope="col">Company Monthly Payment</th> <th scope="col">Edit</th> </tr> </thead> <tbody> {% for company in companies %} <tr> <th scope="row">{{ company.id }}</th> <td>{{ company.company_name }}</td> <td>{{ company.company_email }}</td> <td>{{ company.company_website }}</td> <td>{{ company.company_status }}</td> <td>{{ company.company_monthly_payment }}</td> <td><a href="{{ company.id …