Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django passing the value of the form in Django-forms
I have 2 models WorkoutCategory and workout with a ForeignKey with workout_Category in catig in my template i have a collapsed div "WorkoutCategory" include a collapse form "to save in workoutmodel the question is how I should pass the catig_id if it's not included in the form below screenshot to simplify my idea collapsed div for woroutcategory and the form models: from django.db import models # Create your models here. class WorkoutCategory(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Workout(models.Model): catig = models.ForeignKey(WorkoutCategory,null=True, on_delete=models.CASCADE) workout_name = models.CharField(max_length=250) video_link = models.CharField(max_length=300) def __str__(self): return self.workout_name the Form: from django.forms import * from .models import * from django import forms class CreateWorkoutForm(ModelForm): class Meta: model = Workout exclude = ['catig'] widgets = { 'workout_name' : forms.TextInput(attrs={'class':'form-control','placeholder':'Workout Name'}), 'video_link' : forms.URLInput(attrs={'class':'form-control','placeholder':'https://www.youtube.com/ ...'}), } the Template: <div class="card-header" data-toggle="collapse" href="#multiCollapseExample{{catg.id}}" role="button" aria-expanded="false" aria-controls="multiCollapseExample{{catg.id}}"> {{catg.name}} </div> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample{{catg.id}}"> <div class="col"> <br> <div class="btn btn-success" data-toggle="collapse" href="#addingworkout{{catg.id}}" role="button" aria-expanded="false" aria-controls="addingworkout{{catg.id}}" style="float: right;">add workout</div> <br> <br> <div class="collapse multi-collapse" id="addingworkout{{catg.id}}" value="{{catg.id}}"> <form id="addingworkout"> <div class="form-row"> <div class="col"> {{workoutForm.workout_name}} </div> <div class="col"> {{workoutForm.video_link}} </div> <button type="submit" class="btn btn-primary">Save</button> </div> </form> </div> </div> I don't want the user it set the catig_id … -
{% block content %} {% endblock content %} mine doesnt load/work can anyone help me out with this problem? #justlearnedcoding
enter image description here {% extend 'base.html' %} {% block content %} NEW SEARCH {% endblock %} those doesnt work as it should -
User Authentication always fails after upgrading to django 2.2.12
I have a website written in Django, and I recently upgraded from Django 1.11.28 to 2.2.12. Since the upgrade, all user authentication fails. There are no error messages displayed in the log; it is as if everyone's passwords have changed. The strange thing is that I can use manage.py to reset my superuser's password, but logging in with the new password still fails. I did note that the Django 2.0 release docs mentions that in djano.contrib.auth: "The default iteration count for the PBKDF2 password hasher is increased from 36,000 to 100,000." I thought I might have to change its setting or ask people to reset their passwords, but after using manage.py to reset the admin password didn't work, I no longer believe that to be the issue. Is there a new setting that I'm missing? You can reproduce the issue here: https://github.com/shadytradesman/the-contract-site/tree/5efa380182222afc65dfa7988996b3b5c48016be The site should be easy to run locally. : ) -
How to implement ClearableFileInput?
I have a model Company with 2 fields: name(Charfield) and logo(FileField) and a ModelForm to render in the template 'form' is included in the context dic of the view. I have in template: {% render_field form.logo %} and It render a normal input file without the checkbox of ClearableFileInput. I was reading the django documentation and they say something about initial data has to be set in order to show the checkbox... I don't know... ¿How can I implement a basic ClearableFileInput? Amazingly i can't find documentation on internet. I'm using Django 2. -
Docker Connects to 'Existing' database, But it Shows Empty
I've found about 15 different way to set up Docker to connect to an existing Postgre database. None of them work for me. It seems that I'm connecting to a database. It appears to be empty. This is the final output from docker-compose up --build: db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2020-05-22 21:32:42.213 UTC [1] LOG: starting PostgreSQL 12.2 (Debian 12.2-2.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db_1 | 2020-05-22 21:32:42.214 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2020-05-22 21:32:42.214 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2020-05-22 21:32:42.216 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2020-05-22 21:32:42.227 UTC [26] LOG: database system was shut down at 2020-05-22 21:32:32 UTC db_1 | 2020-05-22 21:32:42.231 UTC [1] LOG: database system is ready to accept connections web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | web_1 | You have 38 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, … -
Ensuring Users Have Completed Prior Form Before Progressing To The Next Form
Ive got a large questionnaire for users to complete. Because its so big I decided to break it into three separate forms on three consecutive pages. The urls are: questionnaire/section_1, questionnaire/section_2, questionnaire/section_3. After submitting each form, the form data is saved to the database, and after the final (3rd) form, the three forms are saved as a single pdf for that user. Its important that users complete each of the three questionnaires. My problem is that users will be able to use the address bar to type www.website/questionnaire/section_3 and complete just the third section, skipping the first two and submitting an incomplete questionnaire. I cant think of any way to restrict users from accessing later parts of the form until prior parts have been successfully validated and saved. PS - I have thought about setting permission for each of the three forms, adding permissions to the user once they have submitted one form, but I feel this is hacky?? Thank you. -
Django forms: Dynamic choices
I'm developing a project in Django where the user is supposed to register entries filling a form. The forms choices are selected from tables of a database built with AnyTree module. My question is, how can I register the field in models, so the user can navigate through the nodes of the tree? -
Does django pass password form data in clear-text?
I have been making websites in Django for 2 years now. A client gave me an ethical-hack report which mentioned that all passwords in my website are clear-text. I confirmed this by checking the request headers in the 'Network' section in developer console of browsers. I can clearly see my username and password in clear text in the POST queries. This is for all the password fields. Even in django's admin interface login fields. I am using django's built in UserCreationForm and AuthenticationForm with views from django.contrib.auth, since i thought this is the safest practice. So should i be worried? Of course Django's developers surely know what they are doing. But is this really safe? Passing cleartext passwords in POST requests? Should i enable django admin in production environment or not? -
Django NameError: name 'street_address' is not defined
Sorry for the long post as I am new to Django - have looked up other answers for the same error but none of them have been helpful in solving this problem. I am trying to import data from csv files to Django using a python script. Since there are multiple files, the script has options to import those files one by one. The import script shows a menu like below to the user to import data from the said csv files 1: Import FileA 2: Import FileB 3: Import FileC 4: Import FileD All: Import all files Q: Quit/Log Out Now let's say I imported FileA which has the following code run successfully try: addr = Address.objects.create( street_address=row[2], suburb=row[3], pin=row[4], state=state1, country=count, created_by='initial_migration', created_dttm=dt.datetime.now(), updated_by='initial_migration', updated_dttm=dt.datetime.now() ) The main issue I face is that while importing records from FileB, I need to link to the addresses imported from FileA and if there are multiple entries for the same suburb then I need to choose the one which has nothing contained in the street_address field (there will always be one such entry) When I try importing FileB and refer to the same street_address field that has been imported from FileA, … -
django model no column error in a field with foreign key
I have custom user model class User(AbstractUser): model fields and another model which has a field with foreign key relation to User class Comment(models.Model): writer = models.ForeignKey(User,on_delete=models.CASCADE,null=True,related_name='comment_writer') contents = models.TextField(max_length=300,null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) but when I makemigrations and migrate the app and the project, I still get error message at the admin page OperationalError at /admin/User/comment/ no such column: User_comment.writer_id Request Method: GET Request URL: http://localhost:8000/admin/User/comment/ Django Version: 2.2.3 Exception Type: OperationalError Exception Value: no such column: User_comment.writer_id Exception Location: /usr/local/lib/python3.6/dist-packages/django/db/backends/sqlite3/base.py in execute, line 383 Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/potentad/Documents/timesello', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/potentad/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/local/lib/python3.6/dist-packages/onedrived-2.0.0-py3.6.egg', '/usr/local/lib/python3.6/dist-packages/zgitignore-1.0.0-py3.6.egg', '/usr/local/lib/python3.6/dist-packages/tabulate-0.8.7-py3.6.egg', '/usr/local/lib/python3.6/dist-packages/psutil-5.7.0-py3.6-linux-x86_64.egg', '/usr/lib/python3/dist-packages'] Server time: Fri, 22 May 2020 23:20:23 +0000 What's wrong and what should I do ? -
generating random user to in django
i have this piece of code which i want to use to select a random user from db and creates a profile for the user def user_gen(): unique_usernames = set() companies = User.objects.filter(is_company=True) for user in companies: if user not in unique_usernames: unique_usernames.add(user) return user else: unique_usernames.add(user) return user and here is the code to create the profile for the user from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): return super(Command, self).add_arguments(parser) def handle(self, *args, **kwargs): with open('filenames/company_name.txt', 'r') as titles: for company_name in titles: user = user_gen() name = company_name tagline = company_tagline() account_type = generate_account_type() country = generate_countrys() address = addresses() date_added = generate_date_added() company_to_save = company.CompanyProfile.objects.create( user=user, name=name, tagline=tagline, account_type=account_type, country=country, joined_date=date_added, address=address, confirmed=True ) company_to_save.save() self.stdout.write(self.style.SUCCESS('Jobs Generated Successfully...')) i keep getting this error ... File "/home/young/Dev/JobPress/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: UNIQUE constraint failed: company_companyprofile.user_id (venv) young@sysadmin:~/Dev/JobPress$ i know is complaining about unique datas and the error is from the the code how can i fix it pls -
How to find all related items of django foreign key with multi level self relationships?
Given a model: class Example(models.Model): name = models.CharField(max_length=50, blank=True) master= models.ForeignKey('Example', on_delete=models.PROTECT, blank=True, null=True) With this model, it is possible to have an "Example" without any master, or an "Example" can have a master value which is another "Example". Of course, that master "Example" could be foreign-key'ing another "Example". There is no theoretical limit of foreign-key levels. What is the best way to get all related items for an item ("example"), including masters of the "master"? For instance, if one creates a "child" child=Example(name="Child") and a mother mother=Example(name="mother", master=child), and finally a grandmother, grandmother = Example(name="grandmother", master=mother), the command child.example_set.all() only returns the mother. How to get all related items including the grandmother in this example? -
way to solve this problem Bad Request: /login/?
I have this model in django from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token class myUserExtensionManager(BaseUserManager): def create_user(self, username, email, TypeOfUser, password=None): if not username: return ValueError("user must have username") if not email: return ValueError("user must have an email address") if not TypeOfUser: return ValueError("user must have type novice or expert") user = self.model( username=username, email=self.normalize_email(email), TypeOfUser=TypeOfUser, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password, TypeOfUser): user = self.create_user( username=username, email=self.normalize_email(email), password=password, TypeOfUser=TypeOfUser ) user.is_superuser = True user.is_admin = True user.is_staff = True user.save(using=self._db) return user # Create your models here. class UserExtensionApi(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=20, unique=True) email = models.EmailField(verbose_name='email', max_length=60, unique=True) TypeOfUser = models.CharField(max_length=6) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' # for using for login REQUIRED_FIELDS = ['email', 'TypeOfUser'] Manager = myUserExtensionManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): # permation return self.is_admin def has_module_prems(self, app_label): # they permation if they admin return True @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) and as you can see i generate token for each user .. this is … -
VSCODE Start Debugging stops for Django server. How do I get it to not
This is my launch.json { "version": "0.2.0", "configurations": [ { "name": "Python: Django runserver", "type": "python", "request": "launch", // "stopOnEntry": true, "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": ["runserver", "--noreload", "--nothreading"], "django": true } ] } The command generated (env) USER@MacBook-Pro proj-api % cd /Users/USER/Programming/Work/proj/proj-api ; env /Users/USER/Programming/Work/proj/env/bin/python3.7 /Users/USER/.vscode/extensions/ms-python.python-2020.5.80290/pythonFiles/lib/python/debugpy/wheels/debugpy/launcher 53020 -- /Users/USER/Programming/Work/proj/proj-api/manage.py runserver --noreload --nothreading I noticed debugpy wasn't in my env so I tried pip'ing that, but that made no difference. It does start however, it will eventually just run its course. I have tried looking for any logs for the debugger, but was unable to find any. I have gone through the vscode debugger docs for django. I have tried variations of commands in the configuration, but no setting is making any difference. Going through the debugger itself when stopOnEntry is enabled that last file it goes to before stopping is the settings file. -
Pointing Domain to a subdomain [DNS]
I would like to link domain names of each customer to there store in my web application same way as Shopify I'm using Django and Nginx I managed to create a subdomain for each user the current URL of a customer looks something like this user_shop.exemple.com I want from the user to buy a domain and point it to this specific subdomain so that the URL will be user_shop_domain.com and handle all the requests from there any suggestions on how I might achieve this? -
How to manage collectstatic for Django app when deploying to multiple servers
My current setup: Multiple AWS Ec2 instances behind an elastic load balancer Django app source code in Github AWS S3 to host my static files CodeDeploy to clone repository onto new instances I am using Docker to actually build the app on the instance. After the repository is cloned onto the instance, I build the docker image, inside of which I run my gunicorn server, and I forward port 80 requests to the image. My question is regarding "collectstatic". Right now, I include "python manage.py collectstatic" in my Dockerfile as one of the build steps. The problem I am facing is that collectstatic is currently run on each new instance during deployment, thus duplicating the work. It also results in collisions when new static files need to be uploaded to s3, or modified static files need to be updated. One instance will delete the file and begin copying it over, and the second instance will try to perform a read operation on a file that just got deleted, and will crash with botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found How should I be managing updating static files during deployment? I would like to be able … -
How to get a FileField URL witout creating template
I want to download file from my django site, when click on link. If i add file url to link, it downloads it, but i do it manually, i want to do it using link. How to make it, using without creating a template. {{ material.title }} def material(request, pk): material_by_pk = get_object_or_404(Material, pk=pk) return material_by_pk.data.url class Material(models.Model): title = models.CharField(max_length=40) data = models.FileField(upload_to=material_url) Everything stores in media directory. -
I am following a course to have an E-commerce Shop with Django. Problem: Exception Value:__str__ returned non-string (type NoneType)
I am following a course to have an E-commerce Shop with Django. I am having this error when I am trying to see the Order on the Django Admin: Exception Value:str returned non-string (type NoneType) pointing out the line 19 of admin\templates\admin\includes\fieldset.html, error at line 19 {{ field.field }} I know that the problem is with the Customer variable in the Order class, but I do not know how to get the customer from the Customer class to put it on my Order class. This is my code: from django.db import models from django.contrib.auth.models import User from django.shortcuts import reverse class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) name = models.CharField(user, max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name [...] class Order(models.Model): customer = models.ForeignKey(Customer, null=True, blank=True, on_delete=models.SET_NULL) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) -
Django calendar form invalid input
I currently have this class in form.py class DateForm(forms.Form): date = forms.DateTimeField( input_formats=['%m/%d/%Y %H:%M'], widget=forms.DateTimeInput(attrs={ 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1' })) In my views.py I have this snippet of code where it checks if the form was valid checkout = request.POST.get('place_order') if checkout: form = DateForm(request.POST) print(form) if form.is_valid(): pickup_time = form.cleaned_data['date'] However, im getting this error <tr><th><label for="id_date">Date:</label></th><td><ul class="errorlist"><li>Enter a valid date/time.</li></ul><input type="text" name="date" value="04/05/0001 6:07 PM" class="form- control datetimepicker-input" data-target="#datetimepicker1" required id="id_date"></td>. </tr> When I submit the form on the webpage im using this format Since the formats line up, I'm confused on whether it really is an error with the input method or something bigger. -
(inline)modelformset with Many-To-Many and through in Django
I have these models: class Instrument(models.Model): name = models.CharField(max_length=100) family = models.CharField(max_length=20, default='') class Instrumentation(models.Model): players = models.IntegerField(default=1) work = models.ForeignKey(Work, on_delete=models.CASCADE) instrument = models.ForeignKey(Instrument, on_delete=models.CASCADE) class Work(models.Model): instrumentations = models.ManyToManyField(Instrument, through='Instrumentation', blank=True) How can I build a modelformset (better if inline) so that the user can change the instrument and the number of players (i.e. the Instrumentation model)? This is what I've done so far: def work_edit_view(request, id=id): InstrumentFormSet = modelformset_factory(Work.instrumentations.through, extra=0, can_delete=True, fields=('instrument', 'players', 'work')) form_details = InstrumentFormSet(request.POST or None, queryset=Instrumentation.objects.filter(work_id=id), initial=[{'work' : id}], prefix='instruments') When I submit the form the data doesn't get saved at best. Is the above code correct for dealing with through models and modelformset? -
Set Toggle Box Based On Database Value And Save DB Value Based On Toggle Value
I had a normal checkbox for a user to select whether or not they had taken a test. If it was selected, an optional field which was originally display:none was set to display:block and the user could then add an answer to this additional question. When the form was submitted the binary result was saved to the database. Having a single checkbox button for a yes/no question is ugly so I decided to change it to a bootstrap toggle box (https://gitbrent.github.io/bootstrap4-toggle/). My problem is now the toggle box doesnt receive its initial value from the db (its always set to YES on page load), it doesnt update the db on form submission, and my javascript doesnt listen to the button and display the optional fields depending on its value. I have tried many things and butchered my code yet I couldnt get anything to work. Here is my original code before I started trying different things (while this code is missing a lot of things I added later, none of them worked properly and this code is easier to read). fields.py taken_test_before = forms.BooleanField(label='Have you taken the test before', required=False, widget=forms.CheckboxInput()) models.py taken_test_before = models.NullBooleanField() template.html (this is actually a … -
Why's isn't Django updating ModelForm correctly?
I'm working on a project-management website for a client with specific needs. Adding the project to the DB works perfectly fine. When I update the project, the fields get updated with whatever I put in them. But it's not performing the necessary calculations like addProject() does. I can click submit, and the request will go through when updateProject() is called, but it doesn't calculate anything. views.py: def calculate(subtotal, no_of_signs, sign_permit, engineering, other_fees, discount, cash_discount, tax): total = subtotal + (sign_permit * no_of_signs) + engineering + other_fees tax_amount = float(tax) * total total += tax_amount if discount > 0: total -= total * discount elif cash_discount > 0: total -= cash_discount else: return total return total def addProject(request): form = ProjectForm() if request.method == 'POST': # form_copy = request.POST.copy() form_copy = request.POST # get data used to calculate total # ..... mutable = request.POST._mutable request.POST._mutable = True # ...... number_of_signs = int(form_copy['number_of_signs']) sign_permit = float(form_copy['sign_permit']) engineering = float(form_copy['engineering']) other_fees = float(form_copy['other_fees']) # project can have discount OR cash discount discount = (float(form_copy['discount']) * .01) cash_discount = float(form_copy['cash_discount']) # total after discount applied discount_total = float(form_copy['discount_total']) deposit_amount = float(form_copy['deposit_amount']) completion_amount = float(form_copy['completion_amount']) # calculate percentage deposit_percentage = float(form_copy['deposit_percentage']) # form_copy['completion_percentage'] = 100 … -
How to add Boolean Button for a django model BooleanField so that a normal user can set the value as true or false?
I am making a Task Management To Do web app..My code is working upto the level that a user can add task after logging in and the task alongwith the foreign key user gets stores to UserTask Model which contain 4 fields including User(F.K.),Label,Due Date,Status(Boolean). The last three field are entered while adding a task by the user however I need my status field (which gets displayed in the task.html alongwith other fields) such that it can be toggled between true or false (task completed or not) as a checkList preferably. How can i do that in django 3? My models.py,forms.py,views.py and tasks.html are as follows: models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class UserCustom(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) profile_pic=models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username #user os object defined above class UserTask(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) label=models.CharField(max_length=264) date=models.DateField() status=models.BooleanField(default=False) def __str__(self): return str(self.label) forms.py from django import forms from django.forms.fields import DateField from django.contrib.auth.models import User from taskApp.models import UserCustom,UserTask from django.contrib.admin.widgets import AdminDateWidget class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class Meta(): model=User fields=('username','email','password') class UserCustomForm(forms.ModelForm): class Meta(): model=UserCustom fields=('profile_pic',) class UserTaskForm(forms.ModelForm): date=DateField(widget=forms.DateInput(attrs={'placeholder': 'YYYY-MM-DD', 'required': 'required'})) class Meta(): model=UserTask fields=('label','date','status') views.py from django.shortcuts import render from taskApp.forms … -
login potal to view monthly power consumption
Need help in building a web platform to view monthly power consumption,my main concern is how we get the data from the household to the the individual database then to his portal. -
My form keep saying "This(image) field is required!" Django 3.0
I made a project with net-ninja on youtube now I am adding "uploading media" feature in my own project but it is not working although every thing is set just tell me where i m going wrong. My form is keep asking me to upload image file even though i had already done, every time i send a post request it renders the page again with no value in image field. what is wrong here, why it is not taking image input?Don't comment set the required to false that is not the solution i don't know why some people said this to others on stackoverflow when they asked the same question as me. My model class looks like this class Products(models.Model): name = models.CharField(max_length=500, unique=True, ) price = models.IntegerField() stock = models.IntegerField() date_added = models.DateTimeField(verbose_name="date added", auto_now_add=True, ) thumb = models.ImageField(default='default.png', blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None,) def __str__(self): return self.name class Meta(): verbose_name_plural = "Products" My form looks like this class AddProduct(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Product Name', 'required':'True', 'class': 'form-control'})) price = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Set Price', 'required':'True', 'class': 'form-control'})) stock = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Number of items', 'required':'True', 'class': 'form-control'})) thumb = forms.ImageField(required=False, widget=forms.ClearableFileInput(attrs={'placeholder':'Upload Picture', 'enctype' : 'multipart/form-data'})) class Meta(): model = Products fields = …