Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix Form validation 'unknow' in django
When I use single form there is no problem but when I used multi-forms in a class based view it's getting validation failed with image field. I tried to fix with previous solution provided in stack overflow but couldn't able to solve it. views.py codes in views class ProfileEditView(View): profile_class = ProfileForm profile_image_class = ProfileImageForm template_name = 'user/profile_edit.html' def get(self,request,pk): if pk: user = User.objects.get(pk=pk) profile = Profile.objects.get(user = user) profile_image = ProfileImage.objects.get(user = user) profile_form = self.profile_class(instance = profile) profile_image_form = self.profile_image_class(instance = profile_image) context = { 'profile_form':profile_form, 'profile_image_form':profile_image_form } return render(request, self.template_name, context) else: profile_form = self.profile_class(None) profile_image_form = self.profile_image_class(None) context = { 'profile_form':profile_form, 'profile_image_form':profile_image_form } return render(request, self.template_name, context) def post(self,request,pk=None, **kwargs): profile_form = self.profile_class(request.POST,instance=Profile()) profile_image_form = self.profile_image_class(request.POST,instance=ProfileImage()) if profile_image_form.is_valid(): #and profile_image_form.is_valid(): profile = profile_form.save(commit=False) profile_image = profile_image_form.save(commit=False) profile.user = self.request.user profile_image.user = self.request.user profile.save() profile_image.save() return redirect('music:album_list') context = { 'profile_form':profile_form, 'profile_image_form':profile_image_form, 'error_message':'Something went wrong', } return render(request, self.template_name, context) models.py codes in model def get_profile_upload_to(instance,filename): new_filename = '{}.{}'.format(uuid4,filename.split('.')[-1]) return "profile/{}/{}".format(instance.user.id, new_filename) class ProfileImage(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(upload_to=get_profile_upload_to) uploaded = models.DateTimeField(auto_now=True) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.TextField(max_length=500,null=True, blank=True) location = models.CharField(max_length=50,null=True, blank=True) birth_date = models.DateField(null=True, blank=True) email_confirmed = models.BooleanField(default=False) form.py codes in … -
i didn't understand about an error saying Runtime error:Model class travello.models.Destination doesn't declare an explicit app_label
INSTALLED_APPS = [ 'travello.apps.TravelloConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] i am getting, RuntimeError:Model class travello.models.Destination doesn't declare an explicit app_label and isn't in an Installed_Apps the python is screenshooted in below -
How to write a query for retrieving matching book-instances?
I need to make a filter to show BookInstances with following conditions: BookInstance.public = True BookInstance.owner != current logged in user BookInstance.book.title like %some text% BookInstance.book.description like %some text% BookInstance.book.authors(id_in=some list of ids) BookInstance.book.categories(id_in=some list of ids) The conditions will be combined as: 1 AND 2 AND ( ( 3 OR 4 ) OR 5 OR 6 ) 3 & 4 use same text for search. current scaffolding in view: searchedObjects = BookInstance.objects; filterObj = dict(request.POST) for key in filterObj: if key == 'bookTitleOrDescription': #condition 3 and 4 bookTitleOrDescription = filterObj[key][0] elif key == 'author[]': # condition 5 authorList = filterObj[key] elif key == 'category[]': # condition 6 categoryList = filterObj[key] searchedObjects will have the query result. models: class Author(SafeDeleteModel): name = models.CharField(max_length=255) class Category(SafeDeleteModel): title = models.CharField(max_length=255) class Book(SafeDeleteModel): title = models.CharField(max_length=255) description = models.CharField(max_length=255) authors = models.ManyToManyField(Author) categories = models.ManyToManyField(Category) class BookInstance(SafeDeleteModel): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) book = models.ForeignKey(Book, on_delete=models.CASCADE) public = models.BooleanField(verbose_name='Will show in search ?') lendable = models.BooleanField(verbose_name='In good condition ?') -
How to get average from each hour in one week in django?
I have a task to get the average some data in each hour inside a week. {'hour': 0, 'count': 70} {'hour': 1, 'count': 92} {'hour': 2, 'count': 94} {'hour': 3, 'count': 88} {'hour': 4, 'count': 68} {'hour': 5, 'count': 69} {'hour': 6, 'count': 70} {'hour': 7, 'count': 82} {'hour': 8, 'count': 91} {'hour': 9, 'count': 67} {'hour': 10, 'count': 92} {'hour': 11, 'count': 100} {'hour': 12, 'count': 92} {'hour': 13, 'count': 55} {'hour': 14, 'count': 61} {'hour': 15, 'count': 47} {'hour': 16, 'count': 36} {'hour': 17, 'count': 19} {'hour': 18, 'count': 11} {'hour': 19, 'count': 6} {'hour': 20, 'count': 3} {'hour': 21, 'count': 9} {'hour': 22, 'count': 27} {'hour': 23, 'count': 47} The data above is the result of this query result = Device.objects.filter(station__in=stations, created_at__range=(start_date, end_date)) \ .extra({'hour': 'hour(created_at)'}) \ .values('hour').annotate(count=Count('id')).order_by('hour') the result is queryed by 7 days range, what I want to do is get the average for each hour in 7 days, exampe the total of count in hour 0 is 70 then i need to average it from 7 days. Any suggestion? -
'RelatedManager' object is not subscriptable
thanks for your time. i'm trying to get the first images of a foreignKey image model and display with the other fields i've read some questions and docs about related models and the best i got was to create a function on my models to call it after just to get the first image. models.py: class Veiculos (models.Model): YEAR_CHOICES = [] for r in range(1960, (datetime.now().year+1)): YEAR_CHOICES.append((r, r)) modelo = models.CharField(max_length=100) potencia = models.CharField(max_length=40) cor = models.CharField(max_length=30) preco = models.DecimalField(max_digits=8, decimal_places=2) ano = models.IntegerField(('ano'), choices=YEAR_CHOICES, default=datetime.now().year) category = models.ManyToManyField('Categorias') created_time = models.DateTimeField(auto_now=True) updated_time = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s %s' % (self.modelo, self.preco) def get_absolute_url(self): return reverse('category2') def first_image(self): return self.images[0] def get_image_filename(instance, filename): modelo = instance.veicle.modelo slug = slugify(modelo) return "veiculos_imagens/%s-%s" % (slug, filename) class Imagens (models.Model): veicle = models.ForeignKey(Veiculos, default=None, on_delete=models.CASCADE, related_name='images') imagem = models.ImageField(upload_to=get_image_filename) views.py: def amp_category(request): queryset = Veiculos.objects.all() return render(request, 'amp/category.amp.html', {'veiculos': queryset}) category.amp.html: {% extends "amp/base.amp.html" %} {% block tittle %} <title>ok</title>{% endblock tittle %} {% block content %} <body> <h1>ok</h1> {% for veiculo in veiculos %} <h2>{{veiculo.modelo}}</h2> <amp-img src="{{ veiculo.first_image.src }}" alt="" width="300" height="340"></amp-img> {% endfor %} </body> {% endblock %} </html> thats the error that i'm getting: hava i set related_name wrong … -
registration form with profilepicture by using django
registration form with userid,username,useremail,userlocation,profilepicture,password1'password2 and login page with userid,password after login it will show total registration mumbers with photo and name.by using django -
How to add new fields to users according to its group (role) in Django
I'm trying to do a logistics web application in Django and I need to assign different roles to the users. I have normal users (clients), employees (office employees, delivery man, truck drivers...) and supervisors. I need to do the following: Office employees and delivery man users: need to have an office assigned Truck drivers users: need to have an assigned route I've made 2 models (Offices and Routes) but I don't know how to relate the users with these models. I've read websites that create custom classes inherited from AbstractBaseUser or AbstractUser, but I don't know how to do it with this special case. I hope to hear the right answer here. Thanks in advance! -
I created a form in Django from the model attributes ! but I did not find anything to customize this form ! I have to change it's design
I created a form from the model attributes ! but I did not find anything to customize this form ! I have to change it's design ! This is my form -
Heroku build error - ERROR in Entry module not found
I'm deploying my Django react app to Heroku, but Terminal Error Server Error package.json & webpack.config.js -
Download (powerpoint) - file with django REST framework
I am running a django app and I want to be able to download a powerpoint file with an API call using django REST framework and the library requests. My model is very simple: class FileCollection(models.Model): name = models.CharField(max_length=120, null=True, blank=True) store_file = models.FileField(upload_to='file_storage_api/', null=True, blank=True) creation_date = models.DateTimeField(null=True, blank=True) Then in my view I want to query different instances of the FileCollection model which I then want to download. First I tried just calling the link but my upload files should be private that's why I would like to use token authentication that I already have implemented. I also tried following this answer but https://stackoverflow.com/questions/38697529/ but can't get it to work. I also read the REST doc on Renderers but I don't really get how to implement them. Is there any (easy) way of a downloading a powerpoint file with REST and requests? Any help is very much appreciated, thanks very much in advance! -
when I click on next on pagination all previous query parameter are lost in django
I have a list page for ads. There are two search forms with multiples parameters as well as pagination. When I click on next on the pagination bar, the following error shows up: UnboundLocalError at /towns/results/ local variable 'post_city' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/towns/results/?page=2& Django Version: 1.11.4 Exception Type: UnboundLocalError Exception Value: local variable 'post_city' referenced before assignment Exception Location: /Users/engsalehalomari/Desktop/try/try/try/salehslist/towns/views.py in search, line 615 Python Executable: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Python Version: 3.6.5 I have two functions one to view the listing page and the other one to conduct the search. There are three parameters passed to listing page "post city, category, and subcategory". These parameters are also passed with other search parameter. When I load the page, everything works fine, the only problem is when I click on icon " link" next on pagination bar. It gives the previous error. It seems to me that the search parameters from the search result is lost. Please help me to resolve this issue. the two views functions are: def list_page(request, post_city, category_name, sub_category_name): template = 'towns/salehslist/list_page.html' query_fc = post_city query_fcc = category_name query_fsc = sub_category_name all_p_cities = City.objects.filter(province_name__country_id__country_name__iexact='united states') all_p_categories = Post_Category.objects.all() all_p_sub_category = Post_Sub_Category.objects.all() context = { "post_city":post_city, … -
How to create a form and view consist of nested formset
I'm creating a form to add a company consist of many formsets such as phone, mobile, whatsapp and employeee. The employee formset is nested. it has some formsets too such as phone, mobile, whatsapp, and ... . I need some help to create this form, view and template. Is it possible to use Django formsets or I should try another way -
Unable to access / var / tmp in Subprocess via Django
I created a script that outputs the execution result of a shell script to a Web screen using Django and subprocess of python. Specifically, the following two scripts were created. test.py #!/usr/bin/python import sys,os import subprocess import syslog command_list = ['/bin/sh', '/var/tmp/test.sh'] proc = subprocess.Popen(args=command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(command_list[0]), shell=False) result = proc.communicate(input=None) print str( result ) test.sh #!/bin/bash echo "begin" cat /var/tmp/data.txt data.txt data1 data2 Unit tests were performed on the two scripts, and they were confirmed to work properly. However, when I used test.py via Django, test.sh's "cat" command and data.txt existed, “Cat: /var/tmp/data.txt: No such file or directory” is displayed. What is the cause? version python 2.7.13 Django 1.11.20 -
Why do I get 'detail: not found' for primary key formatted as '12-345.78'?
When I try to display detail info calling e.g. /api/products/12-345.67/, I get detail: Not found. as a response. As you can see, product IDs are formatted as 12-345.67. My first suspect was the RegEx validator (listed below), but it works the same way with or without it. Model, serializers, viewsets and URLs are defined this way: # models.py: class Product(models.Model): product_id = models.CharField(max_length=9, primary_key=True) name = models.CharField(max_length=40) is_active = models.BooleanField(default=True) def __str__(self): return self.product_id # serializers.py: class ProductSerializer(serializers.ModelSerializer): product_id = serializers.RegexField(regex='^\d{2}-\d{3}\.\d{2}$', max_length=9, min_length=9, allow_blank=False) name = serializers.CharField(min_length=6, max_length=50, allow_blank=False) class Meta: model = Product fields = '__all__' class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'product_id' # urls.py: router = routers.DefaultRouter() router.register(r'products', ProductViewSet, basename='products') (...) urlpatterns = [ path('api/', include(router.urls)), (...) -
angular or python django which is best for developing web application?
angular or python Django which is best for developing web applications? what is the difference is there for both? The advantages and disadvantages of both? which is fast? -
Return the progress to the template each value change in Django
I want to show the progress of the task going in the back-end in order let the user know that the work is still in progress. I have ajax call to a function to get the final value. In back end it will take lot of time to complete the job, but each time i have the progress of the job in one variable i want to show the values of this variable in the front end. For example my ajax function is def ajax_call(request): j = 0 for i in range(1,10000): j += i res = {'data': j} return JsonResponse(res, safe=False) As we know it will return the final value of j. But i want to show the value of j in the front end in each change. Is there any simple way to do this using celery or something -
How to send mail to selected users
Here i have a view which will either sends email to selected users or delete the selected users.The deleting the selected users is working fine but sending email to selected to users is not working. I tried these ways for sending email to selected email. with first approach Exception Type: AttributeError Exception Value: 'str' object has no attribute 'email' and also i want to remove the selected users from session if email sends to the users and restart the session again which is not happening here with this code With second approach it says invalid email address. First Approach def selected_users(request): selected_users = get_user_model().objects.filter(id__in=request.POST.getlist('users')) #tring to store selected users in session initial = {'users':[]} session = request.session.get('users',initial) if selected_users: for user in selected_users: session['users'].append(user.email) request.session['users'] = session print('hello',request.session['users']) # here i want to restart session either email sends or not to the user if selected_users and request.method == 'POST' and 'delete_selected' in request.POST: selected_users.delete() messages.success(request, 'deleted') return redirect('view_users') elif request.method == 'POST' and 'mail_selected' in request.POST: form = SendMailForm(request.POST or None) config = EmailConfiguration.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) if form.is_valid(): sub = form.cleaned_data['sub'] msg = form.cleaned_data['msg'] for user in request.session['users']: email = EmailMessage(subject=sub, body=msg, from_email=config.email_host_user, to=[user.email], connection=backend) … -
Is there any way to get the step-by-step solution in SymPy on my project?
Is there any function or code that can be implemented in my project to run the step by step solution work like sympy gamma [ referce:- see-steps button in sympy gamma]. -
How can I use '{{' , '}}' letter for plain text on template?
The problem was shown when I wanted to explain syntaxes of Django templates on my html document. However, {{ or {% letters are recognized and by the template engine, so I couldn't use them for just plain string. How can I make Django template engine to bypass that letters? I have already tried to use some letters, like backslash \ or Django template's comment function {# #}. First, backslash was not worth at all. Second, comment function makes bypassing everything inside the function. It is an example of my situation: <p>A variable outputs a value from the context, which is a dict-like object mapping keys to values. Variables are surrounded by {{ and }} like this:</p> <p>My first name is {{ first_name }}. My last name is {{ last_name }}.</p> I expected the output have to be like: A variable outputs a value from the context, which is a dict-like object mapping keys to values. Variables are surrounded by {{ and }} like this: My first name is {{ first_name }}. My last name is {{ last_name }}. But actually, it was like: A variable outputs a value from the context, which is a dict-like object mapping keys to values. … -
Django - Increasing the quantity of each products in cart
I added two products with variations in a cart i could not be able to increase the quantity of the second product. When i click on the quantity '+' sign of the second product it automatically increases the first product quantity. I have been stocked for days trying to fixed this problem but i failed. Someone help me! (sorry for the punch of codes). MODEL: class Item(models.Model): title = models.CharField(max_length=250) price = models.IntegerField() discount_price = models.IntegerField(null=True, blank=True) description = HTMLField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField(unique=True,max_length=250) def __str__(self): return self.title def get_absolute_url(self): return reverse("product-detail", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'slug': self.slug }) class VariationManager(models.Manager): def all(self): return super(VariationManager, self).filter(active=True) def sizes(self): return self.all().filter(category='size') def colors(self): return self.all().filter(category='color') VAR_CATEGORIES = ( ('size', 'size'), ('color', 'color'), ('package', 'package'), ) class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) category = models.CharField(max_length=120, choices=VAR_CATEGORIES, default='size') title = models.CharField(max_length=120) active = models.BooleanField(default=True) objects = VariationManager() def __str__(self): return self.title def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("remove-from-cart", kwargs={ 'slug': self.slug }) class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) … -
Celery tasks don't send email to admins on logger critical messages
My celery tasks don't send an email to application admins each time I call logger.critical. I'm building a Django application The current configuration of my project, allows the admins of the application to receive an email each time a logger.critical message is created. This was pretty straight forward to set up. For some reason, which I'm not figuring out, the code that runs inside a celery task, does not have the same behavior. Does celery actually event allow this to be done? Am I missing some configuration? Does anyone got this problem and was able to solve it? Using: Django 1.11 Celery 4.3 Thanks for any help. -
Bitnami Django - No 'Access-Control-Allow-Origin' header is present on the requested resource
I have installed django(shopify app) on aws using bitnami. Everything is working fine but when i send xmlhttp request from shopify store to django i get CORS error- Access to XMLHttpRequest at 'https://django-app-url' from origin 'https://store_url' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have enabled cors on django- as earlier i was using openlite on aws and it was working. After moving to bitnami i started getting error- cors headers installed- pip3 install django-cors-headers and cors headers added in settings.py in middleware and installed apps Also added in /opt/bitnami/apps/django/django_projects/Project/conf httpd.conf Header set Access-Control-Allow-Origin "*" -
How to create Interactive charts in python
Could someone recommend a way to generate interactive charts using python library? Also if there is any existing library or any other way for features like, fetching/displaying the data in a table format when the chart is clicked I've tried using Bokeh, however it doesn't fulfill the complete requirement i.e. displaying the data in a table format when the chart is clicked ## Sample code from bokeh.core.properties import value from bokeh.io import show, output_file from bokeh.plotting import figure output_file("bar_stacked.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ["2015", "2016", "2017"] colors = ["#c9d9d3", "#718dbf", "#e84d60"] data = {'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 4, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]} p = figure(x_range=fruits, plot_height=250, title="Fruit Counts by Year", toolbar_location=None, tools="hover", tooltips="$name @fruits: @$name") p.vbar_stack(years, x='fruits', width=0.9, color=colors, source=data, legend=[value(x) for x in years]) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p) -
How to solve Read-only file system problem?
I've upgraded to the last OS on MAC (Catalina), but now I have problem with virtualenv, python and django. When I do source ve37/bin/activate it's fine, but when I then do python manage.py runserver I get error as follow OSError: [Errno 30] Read-only file system: '/data' The full error is as follows: Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/core/management/__init__.py", line 325, in execute settings.INSTALLED_APPS File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/conf/__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/site-packages/django/conf/__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/my_name/Projects/my_project/ve37/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/my_name/Projects/my_project/Autralis/Autralis/__init__.py", line 2, in <module> from .celery import app as celery_app File "/Users/my_name/Projects/my_project/Autralis/Autralis/celery.py", line 4, in … -
Many-to-many field value show as user specific in django template and i am using update(Generic view)
I have create model used many to many field and other one is user as foreign key so i wanna to show on many to many field as per user. I have create model: class Deal(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='userdeal', on_delete=models.SET_NULL) name = models.CharField(max_length=256, null=True, blank=True) image = models.ImageField(upload_to='images/',blank=True, null=True,) product = models.ManyToManyField(Product,blank=True,) store = models.ManyToManyField(Store,blank=True, ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) discount = models.IntegerField(blank=True, null=True,) location = models.CharField(max_length=200,blank=True, null=True,) is_active = models.BooleanField(default=True) toDate = models.DateTimeField(blank=True, null=True,) fromDate = models.DateTimeField(blank=True, null=True,) description = models.TextField(blank=True, null=True,) price = models.IntegerField(blank=True, null=True,) conditioned = models.TextField(blank=True, null=True,) def __str__(self): return self.name def get_absolute_url(self): return reverse('Deallist', kwargs={'pk': self.pk}) view: class DealUpdate(SuccessMessageMixin, UpdateView): model = Deal template_name = 'company/create_deal.html' form_class = DealForm success_url = reverse_lazy('Deallist') success_message = "%(name)s was updated successfully" def get_success_message(self, cleaned_data): return self.success_message % dict( cleaned_data, name=self.object.name, ) def form_valid(self, form): form.instance.user = self.request.user return super(DealUpdate, self).form_valid(form) forms.py: class DealForm(forms.ModelForm): class Meta: model = Deal widgets = { 'name': forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Name'}), 'description': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Description'}), 'price': forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Enter Price'}), 'discount':forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Enter Price'}), 'conditioned': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter term and condition'}), 'toDate':forms.TextInput(attrs={'class': 'form-control datepicker','id':"date_timepicker_end", 'placeholder': 'Enter expire date and time'}), 'fromDate': forms.TextInput(attrs={'class': 'form-control datepicker', 'id': "date_timepicker_start",'placeholder': 'Enter …