Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: ModelForm registration overwrites prevoius object
I have been trying to make my own project based on a project from Codecademy Django path. Where a vetoffice is used as an example. I'm currently working on building upon the base code provided, and added Forms. I'm currently trying to use ModelForms to register a new owner, and then display a list of all registered owners at the vetoffice. But when I register a new owner, the previous owner is seemingly overwritten, and only the new one is displayed. I'm quite new to writing Django, so my code will not be perfect. The owner model: class Owner(models.Model): #The Owner table, with OwnerID as primary key #Owner can own several pets """Create the Owner SQLite Table. Primary Key: OwnerID, used as Foreign Key for paitient Fields: first_name(String), last_name(string), phone(string(of numbers)) __str__ for easy coupling first and last name of owner. Function: has_multiple_pets reurns boolean True if owner have several pets registered with the Vet Office. """ ownerID = models.BigAutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=30) def __str__(self): #Returns the first and last name of owner with whitespace between return self.first_name + " " + self.last_name def has_multiple_pets(self): '''Do Owner have multiple pets. Checks if a owner … -
image not getting displayed in django
I have a simple snippet that is trying to show the image frame that I saved in DB but the page is me nothing, images are not getting displayed at all <div class="row"> <h3>Captured images </h3> {% for image in images_frames %} <div class="col-md-4"> <h3> {{image.time_stamp}} </h3> <img src="{{ image.image_frame.url }}" class="image_frames" alt=""> </div> {% endfor %} </div> Model class ImageFrames(models.Model): time_stamp = models.DateTimeField(auto_now_add=True) image_frame = models.FileField(upload_to = 'camera_frames',null=True,blank=True,max_length=500) -
what is this error after 'python manage.py migrate' i don't understend?
models.py this is my model.py file i don't 'python manage.py migrat' understend what is this problem.... plz anyone answer if you need another file plz aksed me !!!!! class Myclabusers(models.Model): first_name = models.CharField('first_name', max_length=100 ,default='') last_name = models.CharField('last_name', max_length=100, default='') email = models.EmailField('user email',default='') def __str__(self): return self.first_name +' '+self.last_name class Venue(models.Model): name = models.CharField('venue name' , max_length=100) address = models.CharField('address' , max_length=500) zip_code = models.CharField('zip code' , max_length=20) phone = models.CharField('phone no.' , max_length=15) wab = models.URLField('url' , max_length=100,default='http://') email = models.EmailField('email' , max_length=30) venue_owner = models.IntegerField('venue_owner' , blank=False, default=1) def __str__(self): return self.name class Event(models.Model): event_name = models.CharField('event name' , max_length=100) event_date = models.DateField('event time' ) venue = models.ForeignKey(Venue, blank=True, null=True,on_delete=models.CASCADE) manager = models.ForeignKey(User,default=User, on_delete=models.SET_NULL,null=True) description = models.TextField(blank=True) attendens = models.ManyToManyField(Myclabusers, blank=True ) def __str__(self): return self.event_name + ' at '+ self.venue.name enter image see error description here -
graphene-django v2.0 depth validation
Is there any way I can validate the query depth with graphene-django 2.0? I've tried to use this suggested backend: from graphql.backend.core import GraphQLCoreBackend def measure_depth(selection_set, level=1): max_depth = level for field in selection_set.selections: if field.selection_set: new_depth = measure_depth(field.selection_set, level=level + 1) if new_depth > max_depth: max_depth = new_depth return max_depth class DepthAnalysisBackend(GraphQLCoreBackend): def document_from_string(self, schema, document_string): document = super().document_from_string(schema, document_string) ast = document.document_ast for definition in ast.definitions: # We are only interested in queries if definition.operation != 'query': continue depth = measure_depth(definition.selection_set) if depth > 3: # set your depth max here raise Exception('Query is too complex') return document url(r'^api', csrf_exempt(FileUploadGraphQLView.as_view( schema=schema, middleware=(middleware), backend=DepthAnalysisBackend()))), but it returns the error FileUploadGraphQLView() received an invalid keyword 'backend'. as_view only accepts arguments that are already attributes of the class. -
Django REST - send multiple querysets in one GET-Response
My view currently accepts a username and if the user exists it sends back a queryset of all entries in a Model, where the corresponding userid fits. The Model UserProject consists of a UserID and a ProjectID, both are references to their own tables. I would like to add the Project Model to the queryset. my view: class GetUserDataByNameView( APIView, ): def get(self, request, username): if User.objects.filter(username = username).exists(): uid = User.objects.get(username = username).id queryset = Userproject.objects.filter(user_id = uid) readSerializer = UserprojectSerializer(queryset, many = True) return Response(readSerializer.data) else: return Response({"status": "error", "data":"no user with this username"}, status = 200) the Response currently looks like this: [ { "id": 16, "created_at": "2021-10-20T16:05:03.757807Z", "updated_at": "2021-10-20T16:05:03.762307Z", "user": 3, "project": 50 }, { "id": 17, "created_at": "2021-10-20T16:27:59.938422Z", "updated_at": "2021-10-20T16:27:59.945439Z", "user": 3, "project": 51 #"projectname": (from ProjectID 51) #"projectDescriptor": #" other stuff from ProjectModel": } ] So how would I insert the fields for the current Project ? If I did some useless stuff in the code, please tell me. Newbie in Django -
How can I send user registration details from Django to a postgresql table
I've successfully migrated my database to postgresql, but the issue is I don't know how to send user registration/login details to my postgresql table, please any help is appreciated. -
Django MultiValueDictKeyError when updating a models field
In my models i have two imageFields. When i try to update only one of them, or just change another field in my models thru my 'Edit view' it throws the error MultiValueDictKeyError. Due to errors i had with the updating i opted to doing the saving manually in the Views. Wondering if that is what is causing the error. I can't see any errors in the logic or with the code itself. My Views: def editTrucks(request, pk): item = get_object_or_404(trucks, pk=pk) if request.method == "POST": form = trucksForms(request.POST or None, request.FILES or None, instance=item) data = request.POST if form.is_valid(): try: truck = trucks.objects.get(vin=data['vin']) truck.nickname = data['nickname'] truck.make = data['make'] truck.model = data['model'] truck.type = data['type'] truck.plate = data['plate'] truck.ezPass = data['ezPass'] truck.mileage = data['mileage'] truck.reportedProblem = data['reportedProblem'] truck.inspection = convert_date(data['inspection']) truck.registration = convert_date(data['registration']) truck.oilChange = data['oilChange'] truck.isMonitored = data['isMonitored'] truck.status = data['status'] truck.title = request.FILES['title'] truck.insurance_card = request.FILES['insurance_card'] truck.save() except FileNotFoundError: truck_info = trucks( nickname=data['nickname'], make=data['make'], model=data['model'], type=data['type'], plate=data['plate'], vin=data['vin'], ezPass=data['ezPass'], mileage=data['mileage'], reportedProblem=data['reportedProblem'], inspection=convert_date(data['inspection']), registration=convert_date(data['registration']), oilChange=data['oilChange'], isMonitored=data['isMonitored'], status=data['status'], title=request.FILES['title'], insurance_card=request.FILES['insurance_card'] ) truck_info.save() return redirect('index') else: form = trucksForms(instance=item) return render(request, 'Inventory/edit_items.html', {'form': form}) My Model: class trucks(models.Model): TYPE_CHOICES = (('Sedan', 'Sedan'), ('Pickup', 'Pickup'), ('SUV', 'SUV'), ('Flatbed', 'Flatbed')) MON_CHOICES = … -
Get all objects with today date, django
I have a model like this class Maca(models.Model): created_at = models.DateTimeField( auto_now_add=True ) Now I want in the views.py file to get all the entries that have created today I'm trying this Maca.objects.filter(created_at=datetime.today().date()) But this looks for the clock that object is created too. Can someone help me to select all entries that have been created today? Thanks in advance -
How to add a distinct() to an annotation filter on Django queryset?
roi_values_to_sum = (Q(trades__created_at__date__lt=one_year_back) & ~Q(trades__roi_plus_year=None)) roi_sum_field = f('roi_plus_year') users = ( User.objects .annotate( roi_sum = Sum(roi_sum_field, filter = roi_values_to_sum), .exclude(roi_sum=None) .order_by("-roi_sum") In the query above, I want to annotate roi_sum to the users I am getting, however I only want to sum distinct trade objects because the same trade object appears multiple times. How can I pass a distinct() to the filter= field so the roi_sum only adds up distinct objects? In the above example, trades are attached to users, and they have created_at dates. -
I am trying to create user in auth_user in Django but I am getting this error TypeError at /register/ set_password() missing 1 required
Hello I am trying to create user in auth_user in database but it is showing me a error The method I am using from django.contrib.auth.models import User user = Users.objects.get(username='myuser') user.set_password('mypassword') user.save() My views.py def registerpage(request): if request.method == 'POST': myusername = request.POST['name'] email = request.POST['email'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] myuser = User.objects.get(username=myusername) User.set_password('pass1') myuser.name = myusername myuser.email = email myuser.password = pass1 myuser.save() return redirect('testlogin') The error that I am getting TypeError at /register/ set_password() missing 1 required positional argument: 'raw_password' I need help ! -
django models cyclic import
I have read some relevant posts on the issue on mutual imports (circular). I am working on a django app, here's how I run to an issue: I have two apps, first one articles, second one tags my article model have a many to many field, to indicate relevant tags: articles/models.py from django.db import models from tags.models import Tag class Article(models.Model): tags = models.ManyToManyField(Tag) however, in my tags app, I also need to import Article model to achieve the methods: tags/models.py from django.db import models from articles.models import Article # Create your models here. class Tag(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=255) def getAritcleLength(): pass def getQuestionLength(): pass I usually use a module to combine those class definitions, normally won't run into issue according to method resolution order. However, in django the workflow we need to put classes into separated folders, I will be so glad for any suggestion. -
Access and modify Django DB without login in as superuser
I have a newbie question here. I'm currently working on a site where the user can add items to a model I created. The thing works fine if I'm logged in as super admin in the Django admin panel, but if I'm not, the CSRF verification doesn't work and I can't operate. Is this a "Debug: True" thing? Once I'm ready to production and turn debug off, will it work without login? Thanks! -
How to execute django runserver and python script at the same time (on one line in cmd)
I have wrote a python script which automatically uploads files from a given folder to a django modell. I want this script running while django server is running. My script runs perfectly when I run it in pycharm console. I have tried a few command to achieve this: python manage.py runserver & python manage.py shell < myscript.py python manage.py runserver & python manage.py runscript -v3 myscript In the first case nothing happens until I press ctrl+c, then it display errors "unexpected indent" for every single row of my code. In the second case my script starts to run only when I press ctrl+c (so my django server is shut down and my script is executed). I am using windows so celery is not a good alternative for me (and celery is overkill for such a simple task like that). -
when i use "recognizer = cv2.face.LBPHFaceRecognizer_create()" in normal program it run but when i used it in Django it gives me mudule error
I am doing my acdemic project i am using face recogangnation in python using opencv LBPH algorithm. It works fine when i used in normal program. But when i use that same function in django it gives me module not found error. this function work finr with noraml execution ''' def result(): video = cv2.VideoCapture(0) correct_result = [] BASE_DIR = Path(__file__).resolve().parent # Give The base path = D:\BE\Final Project\Hostel_Automation\Face model_path = (str(BASE_DIR)+ "/static/models/trained_model2.yml").replace(os.sep,'/') # Give the path of model = D:/BE/Final Project/Hostel_Automation/Face/static/models/trained_model2.yml recognizer = cv2.face.LBPHFaceRecognizer_create() # creates an instance for 'LBPHFaceRecognize' Recognizer recognizer.read(model_path) count = 0 # video = cv2.VideoCapture(0) # 0 means system camera for other external camera use 1 while 1: check, frame = video.read() # check parameter gives true value if camera is is correctly configure if check: gray_img = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) face = face_classifire.detectMultiScale(gray_img, scaleFactor=1.2, minNeighbors=5) if face is (): print("face not found") else: count += 1 for(x,y,w,h) in face: ID , conf = recognizer.predict(gray_img[y:y+h,x:x+w]) confidence = int(100*(1-(conf)/300)) if confidence >75: print("founded" , ID) correct_result.append(ID) cv2.putText(frame , "Founded " + str(confidence), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0),2) else: print("not founded") cv2.putText(frame, "Unknown" + str(confidence), (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 128, 0),2) cv2.imshow('im', frame) cv2.waitKey(2) else: print("please … -
Filtering Model Fields with button in Django
i'll include my code first Models: Base.html: (for the navbar button) views.py: and this is the page: So what i want to do is if the user click the button, the page is filtering and just return the book with requested genre. Is it possible if not using jquery,ajax, etc?, if not it's ok but give me an explanation. -
How can I display different fields for staff and superuser in django admin page
I am developing a django website where I want to super user to be able to create posts with the name of other users but don't want the staff members to be able to do it. so I want the field user to be displayed only to the super user and not to the staff. -
I need a django way of query for my need. Help me with it. I am new to Django
I need a Django way of query. Now I am using raw query. Which is not very useful. SELECT parent.id CASE WHEN child.subject is NULL THEN parent.subject ELSE child.subject END as subject FROM parent LEFT JOIN child on parent.id=child.id Please help me with it. -
problems dropdown filter saving data in the database
I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data. This is the error: select a valid choise. That choice is not one of the available choices. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. my models class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = True, null = True ) dati_esercizio = models.ForeignKey( Esercizi, on_delete = models.CASCADE, related_name = 'dati_esercizio' ) … -
Django create spesific Queryset
I want to find the ones whose price is 100 dollars in CompanyProduct and get their Product queries.(queryset format) Product Model: product_name = models.CharField(max_length=300, verbose_name="Product Name") slug = models.SlugField(unique=True, editable=False, max_length=300) category = models.ForeignKey('ProductCategory', null=False, on_delete=models.CASCADE, max_length=100, verbose_name="Category") brand = models.ManyToManyField('Brand', null=True, max_length=100, verbose_name="Brand") CompanyProduct Model: product = models.ForeignKey('product.Product', on_delete=models.CASCADE, verbose_name="Product") company = models.ForeignKey('company.Company', on_delete=models.CASCADE, verbose_name="Company") price = models.IntegerField(blank=True, null=True, verbose_name="Price") -
How can I edit or customize the required characters of a username field?
I'm making a blog type website, and it's pretty much done but earlier today I realized a major flaw in it. When creating creating a username (when registering or editing one's profile) it asks for certain characters, but it won't allow me to have spaces in my name. For example if I wanted my username to be "Winston Pichardo", it won't be possible because that will trigger the error that says "only letters and digits as @/./+/-/_ are allowed". So how can I edit these 'requirements' to allow spaces in the username? I'm using the default django forms and combining those with Crispy Forms to make it all work. these are some examples of my code: forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField( label= 'Correo Electrónico', required=True, ) username = forms.CharField( label = 'Nombre de Usuario', required=True, ) password1 = forms.CharField( label = "Contraseña", required=True ) password2 = forms.CharField( label = "Confirmar Contraseña", required=True ) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField( label='Correo Electrónico', required=True ) username = forms.CharField( required=True, label='Nombre de Usuario' ) class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): image = forms.ImageField( label = 'Foto de … -
Is there a built-in way to set a maximum relations size for ManyToManyField?
Initially I had an ArrayField that could have a maximum of 3 enums inside it. But with my project getting more complex, I had to change this field to a separate model, which has other fields along (but the enum still the same). The target model, which previously contained the ArrayField would then need a ManyToMany in order to correctly reference these multiple instances, with a limit of 3 instances max. I know I could override the save method in order to check this before saving, but I was curious if there's a built-in way in the MTM field to do this kind of check -
Unable to integrate a database (with images) into a Django project
I am trying integrate a database full of questions (with images) into a sqlite3 database in Django. After running 'inspectdb', I pushed the model at the appropriate place. My model looks like this: class Questions(models.Model): main_ques = models.IntegerField(db_column='Main_ques', blank=True, null=True) sub_ques = models.TextField(db_column='Sub_ques', blank=True, null=True) page_num = models.IntegerField(db_column='Page_num', blank=True, null=True) marks = models.IntegerField(blank=True, null=True) topic = models.TextField(db_column='Topic', blank=True, null=True) subques_images = models.ImageField(db_column='Subques_images', blank=True, null=True) mainques_image = models.ImageField(blank=True, null=True) class Meta: managed = True db_table = 'questions' And my 0001_initial.py looks like this: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Questions', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('main_ques', models.IntegerField(blank=True, db_column='Main_ques', null=True)), ('sub_ques', models.TextField(blank=True, db_column='Sub_ques', null=True)), ('page_num', models.IntegerField(blank=True, db_column='Page_num', null=True)), ('marks', models.IntegerField(blank=True, null=True)), ('topic', models.TextField(blank=True, db_column='Topic', null=True)), ('subques_images', models.ImageField(blank=True, db_column='Subques_images', null=True, upload_to='')), ('mainques_image', models.ImageField(blank=True, null=True, upload_to='')), ], options={ 'db_table': 'questions', 'managed': True, }, ), ] The admin page looks like this.. But after that it says, this Error message I get I am pasting the error message below: OperationalError at /admin/sql_inte/questions/ no such column: questions.id Request Method: GET Request URL: http://127.0.0.1:8000/admin/sql_inte/questions/ Django Version: 3.2.8 Exception Type: OperationalError Exception Value: no such column: questions.id Exception Location: /Users/BivashChakraborty/PycharmProjects/database/venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /Users/BivashChakraborty/PycharmProjects/database/venv/bin/python Python Version: 3.7.0 … -
ModuleNotFoundError: No module named 'backend'
Running "python manage.py collectstatic" for a Django app I hope to host on Heroku results in this error: Traceback (most recent call last): File "C:\Code\Django\store\manage.py", line 22, in <module> main() File "C:\Code\Django\store\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 161, in handle if self.is_local_storage() and self.storage.location: File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 215, in is_local_storage return isinstance(self.storage, FileSystemStorage) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 246, in inner self._setup() File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\storage.py", line 438, in _setup self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\files\storage.py", line 366, in get_storage_class return import_string(import_path or settings.DEFAULT_FILE_STORAGE) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'backend' I tried following that path and saw that there was no python file … -
Django ORM: group query results by day
I has next Model: class Invoice(AbstractOrder): order = models.ForeignKey(Order, related_name="invoices",...) is_paid = models.BooleanField() paid = models.DecimalField() paid_at = models.DateField() tax = models.IntegerField() total = models.IntegerField() date = models.DateField() number = models.CharField() client_accepted_at = models.DateTimeField() issued_at = models.DateTimeField() prepared_at = models.DateTimeField() Based on this model I render PDF`s with query, filtered by 'from_date' and 'to_date'. Query looks like this: invoices = Invoice.objects.filter(date__gte=date_gte, date__lte=date_lte) This query return me list of Invoices like But I need to group this resulpt by each date like next and count invoices per day, all items in all invoices at this day, same as taxs, totals, etc: -
Django How to get the value from many to many relationship
I have a product update form where I want to update the sizes of a product, with a many-to-many column relation. I am able to get the saved values but I can't get item ID or size. {{item.id}} shows empty value. {% for item in form.size.value %} <span> <input type="checkbox" name="size" id="{{ item.id }}" value="{{ item.id }}"> <label for="{{ item.id }}">{{ item }}</label> </span> {% endfor %} SIZE MODEL class Size(models.Model): identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) size = models.CharField(max_length=200, unique=True, null=False, blank=False) active = models.BooleanField(default=True) date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True) date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True) PRODUCT MODEL class Product(models.Model): identifier = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=200, null=False, blank=False) slug = models.SlugField(max_length=30, unique=True) showcased = models.BooleanField(default=False) recommended = models.BooleanField(default=False) active = models.BooleanField(default=True) price = models.DecimalField(max_digits = 5, decimal_places = 2, null=True, blank=True) pagetitle = models.CharField(max_length=200, null=True, blank=True) shortDescription = models.CharField(max_length=200, null=True, blank=True) longDescription = HTMLField(null=True, blank=True) specifications = models.TextField(null=True, blank=True) features = models.TextField(null=True, blank=True) care = models.TextField(null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) subCategory = models.ForeignKey(SubCategory, null=True, blank=True, on_delete=models.PROTECT) image = models.ManyToManyField(Image, blank=True) size = models.ManyToManyField(Size, blank=True) tag = models.ManyToManyField(Tag, blank=True) date_created = models.TimeField(verbose_name='Date Created', auto_now_add=True) date_updated = models.DateTimeField(verbose_name='Last Updated', auto_now=True) I have tried different ways but not had success in …