Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change is query in ListModelMixin after Django upgrade
I have upgraded my existing project from Django 2.2.26 to 3.2.11 and updated all its dependencies. Using the list method in ListModelMixin after the upgrade yields a different query. My approach has been to check Django changelogs which has not provided me with an answer yet. Is there any other possible reason for this to happen? -
Is it possible to display objects in Django with customized sorting according to categories, just like Pandas dataframes?
Thank you for reading. A large amount of data has been saved through Django objects.save(). In that data, I want to reorder rows with a specific value in a specific column first, and then just float the rest in order. Data objects data category 1 A 2 B 3 C 4 C For example, I want to show category B first, i want to reorder like below. data category 2 B 1 A 3 C 4 C In a pandas dataframe, I can use the sort function after creating a category like below. df['category'] = pd.Categorical(df['category'], ["cate3", "cate4", "cate1","cate2"]) df.sort_values(['category']) But what if I have already saved it as a django object? Django object.save takes a lot of time, so I can't save it after sorting the dataframe. I saved django objects with below codes. ca=pd.read_csv('data.csv') for i in range(0,1000): Product(data=ca.iloc[i].data.astype('float'),category=ca.iloc[i].category).save() Thank you. -
Django tables2 TypeError: Object of type Client is not JSON serializable
I'm trying to implement a big data on django-tables2, but with bootstrap table fitches (sort, filter, export, click to select, etc). Found a solution but it works with only simple fields, in my project, some fields in the model are linked to another model: class Cars(models.Model): dealer = models.ForeignKey(Dealer, blank=True, null=True, on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True) VIN = models.CharField(max_length=19, blank=True, null=True) model = models.CharField(max_length=50) # Car_model, on_delete=models.CASCADE client = models.ForeignKey(Client, blank=True, null=True, on_delete=models.CASCADE) manager = models.ForeignKey(Manager, blank=True, null=True, on_delete=models.CASCADE) This is my code in views.py: class TableViewMixin(SingleTableMixin): # disable pagination to retrieve all data table_pagination = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # build list of columns and convert it to an # ordered dict to retain ordering of columns # the dict maps from column name to its header (verbose name) table: Table = self.get_table() table_columns: List[Column] = [ column for column in table.columns ] # retain ordering of columns columns_tuples = [(column.name, column.header) for column in table_columns] columns: OrderedDict[str, str] = OrderedDict(columns_tuples) context['columns'] = columns return context def get(self, request, *args, **kwargs): # trigger filtering to update the resulting queryset # needed in case of additional filtering being done response = super().get(self, request, *args, **kwargs) if 'json' … -
'QueryDict' object has no attribute 'method'
**question ** i have error in this code, the error is written below :- 'QueryDict' object has no attribute 'method' code def contect(request): if request.method == 'POST': fmo=contect(request.POST) if fmo.is_valid(): nm = fmo.cleaned_data['name'] em = fmo.cleaned_data['email'] sj = fmo.cleaned_data['subject'] ms = fmo.cleaned_data['message'] reg1 = User1(name=nm, email=em, subject=sj, massage=ms) reg1.save() else: fmo = Contect() return render(request, 'index4.html', {'info': fmo}) -
Datas are not displaying After pagination implement on Settings.py on Django Rest Framework
class ApiBlogListView(ListAPIView): queryset = Meeting.objects.all() serializer_class = MeetingSerializer Permission_Classes = [ permissions.IsAuthenticatedOrReadOnly] filter_backends = (SearchFilter, OrderingFilter) search_fields = ('name', 'id') pagination_class = SmallPagination context = queryset def MeetingViewSearch(request): meeting = "http://127.0.0.1:8000/details/?page=1" read_meeting = requests.get(meeting).json() context = {'details': read_meeting} return render(request, 'index.html', context) It works without pagination but when I implemented default pagination to setting , It stops to displaying datas. -
How to use a 'dependent_fields' with django easy-select2
I use easy-select2 to set up some dropdown menus. I would like to set up dropdown list that relies on a previously selected field. So after selecting a 'country' I would like the 'city' dropdown menu shows only cities from this country. I assume it should be done creating a new widget with a 'dependent_fields' but I do not succeed to do it. I am pretty sure I do not create a new widget properly. models.py: from django.db import models class Country(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=100) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse_lazy from .models import Person, City from .forms import PersonForm class PersonListView(ListView): model = Person context_object_name = 'people' class PersonCreateView(CreateView): model = Person form_class = PersonForm success_url = reverse_lazy('person_changelist') class PersonCreateView(CreateView): model = Person form_class = PersonForm context_object_name = "perons" template_name = "hr/person_form.html" success_url = reverse_lazy('person_changelist') forms.py: from django import forms from .models import Person, Country, City from easy_select2 import Select2 … -
How do I fill automatically a foreign key on a form of multiple pages in Django? (function based view)
I'm developing a website where the user have to compile a form to start an equipment purchase procedure. In my django website I've created several models with the Foreign Key referred to the principal model which is called MAIN. In particular I have these two models: MAIN and SPECIFICATIONS. SPECIFICATIONS has a foreign key which is ID_request and it connects to the MAIN model. models.py class MAIN(models.Model): ## attributes class SPECIFICATIONS(models.Model): ID_request = models.ForeignKey(MAIN, on_delete=models.CASCADE) Spec = models.CharField(max_length=100, blank=False) CliReas = models.CharField(max_length=100, blank=False) rif = models.IntegerField(default=0, null=False) MinMax = models.CharField(max_length=20, blank=True) I'm structuring the form into two pages, where in the first one the user has to compile some fields of the MAIN model. In the second one I would like to make the user fill 'Spec', 'CliReas', 'rif', 'MinMax' fields, but I want also the ID_request be automatically set to that of the previously entered device. Can you suggest me how I can do it? I'm using function-based views: views.py def new_2_4(request): form = SpecForm() if request.method=='POST': form1 = SpecForm(request.POST) if form1.is_valid(): form1.save() return redirect('/') context={'form1': form1} return render(request, 'new_2_4.html', context) And forms.py class SpecForm(ModelForm): class Meta: model = SPECIFICATIONS fields = ['ID_request', 'rif','Spec', 'CliReas', 'MinMax'] Thank you in … -
Requests in Django from different site
I am very new to Django, I am trying to request informations from another side to display them on my own. My site works and outside of Django I can request. I have no idea how to request and display the informations in Django neither where to do this in the project. Please help. -
User.save() got an unexpected keyword argument 'update_fields' while login
I am developing a blog website and i was working on editing profile information and made some changes in profile template and after making changes to template and suddenly get this error while login it was working before editing templates and now registration is also not working and i am not able login using admin panel User.save() got an unexpected keyword argument 'update_fields' Models.py class User(AbstractUser): profile_image = models.ImageField(("Profile Image"), upload_to='ProfileImage', max_length=None, blank = True,null = True) profile = models.TextField(("Profile"),blank = True) def save(self): super().save() img = Image.open(self.profile_image.path) if img.height > 400 or img.width > 400: new_img = (400, 400) img.thumbnail(new_img) img.save(self.profile_image.path) def __str__(self): return self.username' Views.py class userLogin(View): def get(self,request): return render(request,"account/login.html") def post(self,request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] #try: user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect('/') else: messages.error(request, "Invalid username or password.") return render(request,'account/login.html') I dont know what happened suddenly i didnt change anything other than things is teamplate -
Problem with updating and saving object in django-rest-framework
I have a problem with updating and saving object based on frontend input in Django-rest-frameweork. Everything seems to work fine, because this piece of code accually creates an object. The problem is whenever I want to save FE CartItem.amount = 10 this code returns value of 1. I am 100% sure I'm putting correct int value into the url. I am getting user_id, token, product_id and amount from this url: path('add-to-cart/<int:user_id>/<str:token>/<int:product_id>/<int:amount>/', add_item_to_cart, name="add-to-cart"), Then I use this function to either create of update an object: @csrf_exempt def add_item_to_cart(request, user_id, token, product_id, amount): if validate_user_session(user_id, token): user = CustomUser.objects.get(id=user_id) product = ProductStock.objects.get(id=product_id) if product.quantity < amount: return JsonResponse({'error':"You are trying to order more then we can provide!"}) try: existing_item = CartItem.objects.get(user=user, product=product) updated_amount = existing_item.amount + amount if updated_amount > product.quantity: existing_item.save(amount=product.quantity) return JsonResponse({'success':"Product updated in the database!"}) else: existing_item.save(amount=updated_amount) return JsonResponse({'success':"Product updated in the database!"}) except ObjectDoesNotExist: cart_item = CartItem(user=user, product=product, amount=amount) cart_item.save() return JsonResponse({'success':"Product created in the database!"}) else: return JsonResponse({'error':"You need to be logged in for that action!"}) Here are ProductStock and CartItem objects: class CartItem(models.Model): name = models.CharField(max_length=50, blank=True, null=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) product = models.ForeignKey(ProductStock, on_delete=models.CASCADE, blank=True, null=True) amount = models.IntegerField(default=0, blank=True, null=True) size = … -
Excluding a custom field from admin create object
Like here, I want to make a field only visible when editing the already existing object: I have a straight forward admin: @admin.register(Store) class StoreAdmin(admin.ModelAdmin): from = StoreAdminForm ... and I have a form with an extra field: class StoreAdminForm(forms.ModelForm): img = forms.ImageField() ... Now I want to exclude img when creating a new object. I tried extending the StoreAdmin class by: def add_view(self, request, extra_content = None): self.exclude = ("img",) return super().add_view(request) but this has no effect - I guess this just does not work on manually created fields? -
Correct approach to big model with no user accounts
I want to create django+react app that does not utilize user accounts in any way but it collects a lot of user input in a single page. Is there any way to allow user to look into his input a day later? Can i just store the object in cookies? Or can I save sessionid and load model when user refreshes website? Also- it will be like a big form saved to a single object. Is it good idea to create such a big model? For example- user provides whether or not does he have a windows in his room. If so he writes which wall is it on, it's height, width, distance from left corner, width of sill. Should it be a new model called, idk WindowConfig or something like that? It will be more readable but on the other hand it complicates serializers. -
Python requests verify certificat in production
I'm beginner in Django, python and I have an application in Django 2.2 and it communicates with vCenter REST API. Where I have two servers Server 1: 10.125.65.70 Server 2 : 10.126.80.80 I development I use verify = False But I can't use that in production. I would like to create an if condition, which checks if we want to establish a connection with or without certificate verification. I can't use this verify='/path/to/public_key.pem' because In production I use two different certificates between Vcsa(Server). import requests import os import json from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) os.environ["REQUESTS_CA_BUNDLE"] = os.path.join("/etc/ssl/certs/") req = requests.Session() req.verify = False class VmwareApi: def __init__(self): self.ip = "" self.user = "" self.password = "" self.arg1 = "" self.ses = "" self.params = "" def session(self): try: a = req.post( "https://" + self.ip + "/api/session", auth=(self.user, self.password), timeout=1, verify=False, ) self.ses = str(a.json()) except requests.exceptions.Timeout: return "ConnectTimeoutError" return req def param_loader(self): if self.params: self.params = json.loads(self.params) def vapirequestget(self): try: VmwareApi.param_loader(self) myreq = req.get( "https://" + self.ip + self.arg1, params=self.params, verify=False, headers={"vmware-api-session-id": self.ses}, timeout=1, ) return myreq except requests.exceptions.Timeout: return "ConnectTimeoutError" -
form.instance doesn't populate field
I have the following form for creating a user: class CreateAccount(UserCreationForm): class Meta: model = USER fields = ['first_name','last_name','username','email','employee_id','is_active','is_staff'] and it's view: class CreateAccountView(CreateView): model = USER form_class = CreateAccount template_name = 'createaccount.html' def form_valid(self, form): form.instance.employee_id = Employee.objects.get(username=self.kwargs.get('username')) return super().form_valid(form) def get_success_url(self): return reverse('People') I used form.instance to pass it an employee object, but it doesn't work and I get 'This field is required. ' error, I used it in the exact same way in my other apps and it worked fine, does anyone have any idea what seems to be different here? -
Django - Generic Relations
I have a website with different kinds of activities: Lessons ; Exercises ; Quizzes. So far, each type of activity corresponds to a specific Model and a table in the database. I would like to create an ordered path through these activities. For instance: Lesson 1 then Exercise 1 then Lesson 2 then Quizz 1 etc. I am considering to create a model named Activity that would store the following data: A number: the number of the activity in the path ; A One-To-One relationship to one given activity (lesson, exercise, quizz etc.). (1) I have seen that Django offers a GenericForeignKey to handle many-to-one relationship to different kinds of models, like many comments associated to a single lesson or a single exercise. Is there something similar for Generic OneToOne relationship? (2) I would like to track the progress of my users. To do so, I am considering having a many-to-many relationship called "done_activities" built in my User model and linked to my Activity model. Do you think this is an efficient way of approaching the problem ? -
How to update integer field in DRF
In my project there is video module, related to this module user can add vodeo bookmarks, class VideoBookmark(BaseModel, SoftDelete): video = models.ForeignKey(Video, on_delete=models.CASCADE) sort_order = models.PositiveSmallIntegerField(null=False, blank=False) name = models.CharField(max_length=254, null=True, blank=True) description = models.CharField(max_length=254, null=True, blank=True) duration = models.DurationField(default=timedelta()) start_time = models.DurationField(default=timedelta()) end_time = models.DurationField(default=timedelta()) mobile_thumbnail_image = models.ImageField(upload_to='video_bookmark_mobile_thumbnail', height_field=None, width_field=None, null=True, blank=True) web_thumbnail_image = models.ImageField(upload_to='video_bookmark_web_thumbnail', height_field=None, width_field=None, null=True, blank=True) def __str__(self): return str(self.name) Bookmark3 is in the order of "2" and when trying to add bookmark2 in the order of "2" the order of bookmark3 should be changed to the order of "3".I don't know how to implement this, Can you suggest a way to implement this? -
Circular Import error in Django occurs only when i import geemap package
I am trying to use geemap in combination with django to build a web app for plotting satellite data. I have installed the geemap package in my django project. My projects name is CustomMaps, and the directory structure is as below. enter image description here The code for my CustomMaps.urls.py is as below from django.contrib import admin from django.urls import path from django.conf.urls import include, url urlpatterns = [ path('admin/', admin.site.urls), path('plotmap/', include('PlotMap.urls')), ] The code for my PlotMap.urls.py is as follows from django.urls import path from django.conf.urls import include, url from .views import hello urlpatterns = [ path('hello/', hello, name = 'hello'), ] And my PlotMap.views.py is as follows from django.http import HttpResponse from django.shortcuts import render import geemap as gm #import pandas as pd def hello(request): map = gm.Map() return render(request, "PlotMap/hello.html", { "m" : map}) But I am getting the following error on running the project Exception in thread django-main-thread: Traceback (most recent call last): File "D:\Internship\Django App\MyProject\lib\site-packages\django\urls\resolvers.py", line 604, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in … -
get MongoDb ObjectId in Django Serializer
I am creating a Django server using django_rest_framework and mondogb(djongo). I want to use mongoDb generated ObjectId as primary key. How to get the mongoDb ObjectId from serializer class? This is my user model class User(AbstractUser): name = models.CharField(max_length=255) description = models.TextField(default='', blank=True) profile_pic = models.ImageField(upload_to='static/profile_pics/', blank=True) username = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] This is my user serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'name', 'description', 'profile_pic'] extra_kwargs = { 'password': {'write_only': True} } views.py class GetUserView(APIView): def get(self, request): data = UserSerializer(User.objects.filter(id=request.id)).data return Response(data) This returns a json object { 'id': '<id>' eg: 1 or 2 or 3 etc.. 'name': '<user-name>', 'username': '<username>', 'description': '<description>', 'profile_pic': '<profile_pic>' } But I want to get below mentioned id(mongoDb ObjectId) { 'id': 621343a45048323e635c4ae6 ... } -
Initial value of django form field with django tag value
I have created a django form. This form is used to update the values of an existing object. That's why I want to show initial values which are taken from django variables inside django tags. Here is the django form. class RevisionStatusForm(forms.ModelForm): """ Update Revision""" class Meta: model = Revision widgets = { 'status': forms.Select(attrs={'required': True}),} fields = ['status','remark'] on my HTML template, here is how it currently looks: <td>{{revisionstatusform.remark}}</td> Here is how I want it to work: <input type="text" name="remark" value="{{revision.remark}}">. I want to show revision.remark variable value inside input field created from django forms. I don't know how to do it. Can anyone help? -
How to get the authentificated user information in Model Serializer in Django Rest?
I have a LinkList object, which has owner property - the username of the User it belongs to. I am trying to have LinkLists be linked to the user that made the create request, however self.context['request'].user and CurrentUserDefault don't work in my create method, so I cannot create an instance of the LinkList object. The error I am getting: NOT NULL constraint failed: llists_linklist.owner_id Here is the serializer: class LinkListSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="lists-detail") owner = serializers.ReadOnlyField(source='owner.username') links = LinkSerializer(many=True) class Meta: model = LinkList fields = ['url', 'owner', 'name', 'public', 'links'] def create(self, validated_data): links = validated_data.pop('links', []) instance = super().create(validated_data) for item in links: instance.links.add(link=item) return instance The model: class LinkList(models.Model): owner = models.ForeignKey( User, related_name='lists', on_delete=models.CASCADE) name = models.CharField(max_length=100) description = models.CharField(max_length=250) public = models.BooleanField(default=False) links = models.ManyToManyField( Link, related_name='linklists') def __str__(self): return "%s - %s" % (self.owner, self.name) def save(self, *args, **kwargs): super().save(*args, **kwargs) -
html iterate through dictionary in django and button download
i am working on an app on django 2 pbl: i used defaultlist but not working nothing on my output , my button download is not working : i received this error :"AttributeError at /views.download_my_pdf 'str' object has no attribute 'read' " I want to download my home page to pdf what i did wrong please? Django views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict from django.http import HttpResponse from wsgiref.util import FileWrapper def home(request): if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = FileSystemStorage() name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'\\media\\'+name file_directory2 = d+'\\media\\'+name2 results,output_df =results1(file_directory,file_directory2) return render(request,"results.html", {"results":results,"output_df":output_df,}) return render(request, "index.html") def readfile(uploaded_file): data = pd.read_excel(uploaded_file, index_col=None) return data def results1(file1,file2): results_list = defaultdict(list) names_loc = file2 listing_file = pd.read_excel(file1, index_col=None) for x in date_index: if time>2h: results_list["List of samples better"].append(sample_id) if len(u_index) > 1: results_list["List of Samples "].append(sample_id) output_df = output_df.append(row_to_add, ignore_index=True) else: results_list["List of Samples not in the listing file"].append(sample_name[0]) except: print('The template name isnt good: {}'.format(sample_id)) return results_list, output_df.to_html() def download_pdf(request): filename = 'faults.pdf' … -
I want to check filtered field at drop-down in django-admin
When the classification field is checked, I want to filter only the values according to the classification filed so that it can be checked in the dropdown. and I installed django-clever-selects. i usually the choicefields were written in the models.py, but django-clever-selects seemed to be usually put in and used at helpers.py, so I did. when i checked in the account_classification field at models.py in admin (tuple content of helpers.py 'expenses'), i want to check only the filtered field in the account_category field (tuple content of helpers.py CATEGORY). In the form of the picture below. enter image description here # models.py class AccountBook(TimeStampedModel): branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=False) account_amount = models.PositiveIntegerField(validators=[MinValueValidator(0)], null=False, verbose_name="금액") # 금액 account_reference = models.CharField(max_length=200, null=True, verbose_name="참조내용") account_manager = models.CharField(max_length=10, null=False, verbose_name="담당자") account_recoder = models.CharField(max_length=10, null=False, verbose_name="기록자") # account_classification = models.CharField(choices=EXPENSES, max_length=100, null=True, blank=True, verbose_name="분류") # 분류 - 저장시킬 필드 # account_category = models.CharField(choices=CATEGORY, max_length=100, null=True, verbose_name="범주") # 범주 - 저장시킬 필드 # forms.py class AccountBookForm(ChainedChoicesForm, forms.ModelForm): account_classification = ChoiceField(choices=[('', (u'Select a classification'))] + list(EXPENSES)) account_category = ChainedChoiceField(parent_field='account_classification', ajax_url=reverse_lazy('ajax_chained_category'), empty_label=(u'Select category')) class Meta: model = AccountBook fields = ["branch", "account_classification", "account_category", "account_amount", "account_reference", "account_manager", "account_recoder"] views.py class SimpleChainView(FormView): form_class = AccountBookForm template_name = '/' success_url = '/' … -
Can we merge multiple pdf in django with weasyprint?
https://weasyprint.org/ I have two different pdfs and want to merge than using weasyprint so that whenever the user downloads the pdf it should download the pdf which consists of the both the pdf in single one -
The connection to postgresql on django is not working and some issues were found after migrating
`DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'todoDB', 'USERNAME': 'postgres', 'PASSWORD': 'admin', 'HOST': 'localhost', } }` command prompt error Traceback (most recent call last): django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: password authentication failed for user "admin" -
How to get highest bid for every item in an auction bidding site Django
So I have a Django auctions app, which has 3 models: Users, Listings, Bids. When a user tries to place a bid on some listing, I want to check if the new_bid field in Bid model is bigger than start current_bid field in Listing model and if the new_bid is <= 0, it should return a message. This is what I've done so far but when I click on 'Place bid' button, it does not implement this (it does not show any message for any of the above scenario and my count does not increase) meaning that the form is not submitting. Why is this not working? VIEWS.PY def listing_detail(request, listing_id): try: detail = get_object_or_404(Auction, pk=listing_id) except Auction.DoesNotExist: messages.add_message(request, messages.ERROR, "This is not available") return HttpResponseRedirect(reverse("index")) bid_count = Bids.objects.filter(auction=listing_id).count() context = {'detail': detail, 'bid_count': bid_count, 'bidForm': BidForm()} return render(request, 'auctions/details.html', context) @login_required def make_bid(request, listing_id): if request.method == 'POST': form = BidForm(request.POST) if form.is_valid: each_listing = Auction.objects.get(pk=listing_id) highest_bid = Bids.objects.filter(pk=listing_id).order_by('-new_bid').first() new_bid = form.cleaned_data.get['new_bid'] if new_bid <= 0: return render(request, 'auctions/details.html', {"message": "Input an amount greater than 0"}) # messages.add_message(request, messages.SUCCESS, "Input an amount greater than 0") elif new_bid <= highest_bid.new_bid: messages.add_message(request, messages.ERROR, "Amount is low, please increase the bid") else: …