Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django webpack loader render_bundle error
We have a legacy Django-webpack app using Django webpack loader. The app code moved into a /app directory and the render_bundle stopped working. The error message is File "/usr/local/lib/python3.9/site-packages/webpack_loader/templatetags/webpack_loader.py", line 22, in render_bundle tags = utils.get_as_tags( File "/usr/local/lib/python3.9/site-packages/webpack_loader/utils.py", line 71, in get_as_tags bundle = _get_bundle(loader, bundle_name, extension) File "/usr/local/lib/python3.9/site-packages/webpack_loader/utils.py", line 47, in _get_bundle bundle = loader.get_bundle(bundle_name) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 116, in get_bundle filtered_chunks = self.filter_chunks(chunks) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 58, in filter_chunks ignore = any(regex.match(chunk) File "/usr/local/lib/python3.9/site-packages/webpack_loader/loader.py", line 58, in <genexpr> ignore = any(regex.match(chunk) TypeError: expected string or bytes-like object webpack-stats.json {"status":"done","publicPath":"http://localhost:8001/","chunks":{"app":[{"name":"app.js","publicPath":"http://localhost:8001/app.js","path":"/app/static/dist/app.js"}]}} I hard-coded our STATICS_URL to try to match the documentation on django-webpack-loader DJANGO STATICS_URL: /app/static/dist/ WEBPACK PATH(output.path): /app/static/dist WEBPACK_LOADER: WEBPACK_LOADER = {"DEFAULT": {"CACHE": not DEBUG}} Code that triggers the error: {% render_bundle 'app' %} inside a index.html -
How to restrict website access? for whole domain site?
I have website django based, i need access control domain based like. I already established django own auth system and 2-auth system. I need for whole domain access control even for the static files. If that possible only access code not username and password, and this need to be hard coded env or something like this. Django version v4.0, Hosting Heroku -
JSON POST and GET 404 (Not Found)
I am trying to create an API in Django but am receiving the following errors message in the JavaScript console. GET http://127.0.0.1:8000/edit/undefined 404 (Not Found) POST http://127.0.0.1:8000/edit/undefined 404 (Not Found) Does anyone know how to fix this problem? API url: path("edit/<int:post_id>", views.edit, name="edit") views.py def edit(request, post_id): try: post = Post.objects.get(user=request.user, pk=post_id) except Post.DoesNotExist: return JsonResponse({"error": "Post does not exist."}, status=404) if request.method == "GET": return JsonResponse(post.serialize()) else: return JsonResponse({"error": "Need a GET request."}, status=404) JavaScript Function function edit_email(id){ console.log("edit button is clicked") document.querySelector('#post_itself').style.display = 'none'; document.querySelector('#date_and_time').style.display = 'none'; document.querySelector('#likes').style.display = 'none'; const textarea = document.createElement('textarea'); //get post fetch(`/edit/${id}`) .then(response => response.json()) .then(post => { textarea.innerHTML = `${post.post}` document.querySelector('#p_user').append(textarea); }) //save the post fetch(`/edit/${id}`,{ method: 'POST', post: JSON.stringify({ post: textarea.value }) }) } HTML {% for post in page_obj.object_list %} <div class = "individual_posts"> <a href="{% url 'username' post.user %}"><h5 id="p_user" class = "post_user">{{ post.user }}</h5></a> <h6 id = "post_itself">{{ post.post }}</h6> <h6 id="date_and_time" class = "post_elements">{{ post.date_and_time }}</h6> <h6 id="likes" class = "post_elements">{{ post.likes }}&#x1F44D;</h6> {% if post.user == request.user %} <button id="editButton" class="edit_button">Edit</button> {% endif %} </div> {% endfor %} I think something might be wrong in the way I am passing in the id to the API, … -
set calculated property on model only once
im using python3 + django, and i have a model of User with few fields an admin page where all the users are presented a form page where a single user is presented and can be updated an external API with 2 endpoints: GET /api/users/name (get all names for all the users) GET /api/users/:id/name (get name for user by id) i want to add a name property to be presented on admin page (as a column) and on a form page (read-only, not changeable) how can i add this "calculated" property without calling an api more than needed? -
how can i show a manytomany foeld values in a form?
i wrote a code about music and used ManyToManyField() as genre but when i try to show genres it just show : Genre['a number'] template: {% extends 'pages/base.html' %} {% block content %} <form> {% if mdata.image %} <img src="mdata.image.url" height="500" width="500"> {% endif %} {% for field in form %} <p>{{ field.label }} : {{ field.value}}</p> } {% endfor %} </form> <a href="{% url 'pages:edit_music' mdata.id %}">edit</a> {% endblock %} -
Model register save user created django admin
I'm using django admin, and I have a model in wich I have a created_user property. The problem is that I dont know how to register the user from the django admin. Someone know how to do this? -
dj allauth get password when its resetted
I need to provide the raw password of an allauth user to a third party provider when he resets his password. So everytime when the password gets resetted I call the @receiver(password_reset). However, then the password was already salted. I need to get the raw password data to realise the password change also at an external service. How would get the new "raw" password, which wasn't already salted or how could I desalt it? @receiver(password_reset) def password_change_callback(sender, request, user, **kwargs): #run third party api call containing the new password -
Read Only for specific rows Django not the empty filelds
I am trying to create read only field for specific row where is values , and i wrote this script , with this script after saving the page i can not edit the empty rows ,in the page. class Calender(admin.TabularInline): model = models.Calendar def get_readonly_fields(self, request, obj=None): if obj: return self.readonly_fields + ("registrations", "calendar") return self.readonly_fields -
Best practices for managing Django auth using sessions and token based methods in same project
I'm trying to add API support via django-rest-framework for all the views in my project. Assume that all the views return a JSON response and are function based. How can I best handle this situation without re-writing a lot of code? Here is what I have at the moment: views.py @login_required @require_POST def get_data(request): #.... core logic .... return JsonResponse({'msg': '<...>'},status=200) @api_view(['POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def api_get_data(request): return get_data(request) urls.py url(r'^get_data/$', views.get_data, name='get_data'), url(r'^api/v1/get_data/$', views.api_get_data, name='api_get_data'), I'm using CSRFmiddleware, so I get CSRF blanket protection for all views. Is there a better approach than the above to achieve/ensure: REST API calls work without CORS/CSRF token Browser-based calls work only with CORS/CSTF token I'd appreciate any help or suggestions on how to design/organize the project for this use case. -
Django signup form doesn't submit data or save in database or valid and invalid errors working
$ I was trying to submit this following codes , it never submit or saved in database or give any reaction , even the warnings or (valid and invalid of bootsrap5.2 in not working) , i need support, thank you alot $ this is code in the (views.py), from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login as signin from django.contrib.auth import authenticate # This can replace the 3 uppers from .forms import SignUpForm def signup(request): form = SignUpForm() if request.method == 'POST' and 'btnsignup2' in request.POST: form = SignUpForm(request.POST) if form.is_valid(): user = form.save() signin(request, user) return redirect('index') else: form = SignUpForm() context = { 'basic': {'main': 'Project', }, 'form': form } return render(request, 'accounts/signup-dj.html', context) $ this is code in the (forms.py) from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login as signin from django.contrib.auth import authenticate from django.contrib.auth.models import User class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=250, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['first_name', 'last_name', 'email', 'username', 'password1', 'password2'] $ this is (urls.py) from django.urls import path from . import views urlpatterns = [ path('login', views.login, name="login"), path('signout', views.signout, name="signout"), path('signup', views.signup, name="signup"), ] $ this is code in the (HTML) {% extends 'base.html' … -
Using Javascript to parse Django Data in Leaflet Maps
Hi I am wondering if anyone can help me figure this problem out. I am trying to add addresses from my Django database into a Javascript which will convert the addresses to long/lat coordinates, and thus allowing me to use those new coordinates as markers on a leaflet map. Currently I have the map loaded in. <body> <div id="map"></div> <script> var map = L.map('map').setView([37.116386, -98.299591], 5); L.tileLayer('https://api.maptiler.com/maps/basic-v2/256/{z}/{x}/{y}.png?key=APIKEY', { attributions: '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>' }).addTo(map) var marker = L.marker([37.116386, -98.299591]).addTo(map); </script> </body> Basically I want to replace the marker values with the value I render from the address provided in Django that I would filter through. {% for address in addresses %} <a>{{address.addresses}}</a> {% endfor %} If I were to filter say the business associated with the address, I would want it to render that marker for that specific business address. If anyone can help it would be greatly appreciated. -
Why are my converted Markdown HTML tags returned as text?
A function in my views.py file converts Markdown files and returns the HTML to another function which is used to show the current entry (entry()). In entry(), I have a dictionary that is gives a HTML template access to the converted content. However, when the tags like <h1> and <p> are shown on the page instead of being hidden. So, <h1>CSS</h1> <p>CSS is a language that can be used to add style to an <a href="/wiki/HTML">HTML</a> page.</p> is shown instead of CSS CSS is a language that can be used to add style to an HTML page. -- How do I get rid of the tags on the page and have them actually be used in the HTML file? entry.html: {% block body %} <div class="entry-container"> <div class="left"> {{ entry }} </div> <div class="right"> <a href="{% url 'edit' %}" class="edit-btn"> <button class="edit">EDIT</button> </a> </div> </div> {% endblock %} views.py: import markdown from . import util def entry(request, name): entry = util.get_entry(name) converted = convert(entry) if util.get_entry(name) is not None: context = { 'entry': converted, 'name': name } global current_entry current_entry = name return render(request, 'encyclopedia/entry.html', context) else: return render(request, "encyclopedia/404.html") def convert(entry): return markdown.markdown(entry) urls.py: path('<str:name>', views.entry, name='entry'), util.py: def … -
Django not using the form tag
In my Django template I don't wanna use {{form]] tag. Is there any way I can save the HTML form to my models without using {{form}} tag? myform.html <form id="firstform" action="{% url 'saveview' %}" method="POST"> {% csrf_token %} <input type="text" name="brand" id="brand"> <input type="text" name="series" id="series"> <input type="text" name="model" id="model"> <input type="submit" class="btn btn-primary" id="save-button" name="save-button" value="SAVE"> </form> views.py def saveview(request): return render(request,'myform.html') -
Null in response which should't exist Django
When I send request in Postman like this: it returns me all fields fine expect the profile_photo. profile_photo in response is null and I don't know what is the problem. It should be the new uuid photo name. Here is my model: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(max_length=150, blank=True) last_name = models.CharField(max_length=150, blank=True) city = models.CharField(max_length=150, blank=True) description = models.CharField(max_length=1000, blank=True) profile_photo = models.CharField(max_length=500, blank=True) date_joined = models.DateTimeField(default=timezone.now) about = models.TextField(_( 'about'), max_length=500, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomAccountManager() object = models.Manager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'city'] def __str__(self): return self.email This is my view: class CustomUserUpdate(generics.UpdateAPIView): permission_classes = [IsAuthenticated] queryset = User.objects.all() serializer_class = UserUpdateSerializer def get_object(self): return self.request.user This is my serializer. Here i am setting the new photo name. When I print the new name here like this: print(instance.profile_photo) it shows me the new file name fine. But in the response i get null. class UserUpdateSerializer(serializers.ModelSerializer): profile_photo = serializers.FileField(required=False) class Meta: model = User fields = ('email', 'first_name', 'last_name', 'city', 'description', 'profile_photo') def __init__(self, *args, **kwargs): super(UserUpdateSerializer, self).__init__(*args, **kwargs) self.fields['email'].required = False self.fields['description'].required = False def update(self, instance, validated_data): if … -
InconsistentMigrationHistory with devstack make dev.provision command
I followed this guide All of the services can be run by following the steps below. For analyticstack, follow Getting Started on Analytics_. NOTE: Since a Docker-based devstack runs many containers, you should configure Docker with a sufficient amount of resources. We find that configuring Docker for Mac_ with a minimum of 2 CPUs and 6GB of memory works well. Install the requirements inside of a Python virtualenv_. .. code:: sh make requirements The Docker Compose file mounts a host volume for each service's executing code. The host directory defaults to be a sibling of this directory. For example, if this repo is cloned to ~/workspace/devstack, host volumes will be expected in ~/workspace/course-discovery, ~/workspace/ecommerce, etc. These repos can be cloned with the command below. .. code:: sh make dev.clone You may customize where the local repositories are found by setting the DEVSTACK_WORKSPACE environment variable. Be sure to share the cloned directories in the Docker -> Preferences... -> File Sharing box. Run the provision command, if you haven't already, to configure the various services with superusers (for development without the auth service) and tenants (for multi-tenancy). NOTE: When running the provision command, databases for ecommerce and edxapp will be dropped and … -
How to put data from DRF form in function
thank you for reading, i have problem in Django Rest Framework project, i wrote only backend, and i must return url with user info from fields: models.py class Payment(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT) # we cannot delete user with money # em email = models.CharField(max_length=255, blank=False, null=True) # m shop_id = models.CharField(max_length=30, blank=False, null=True) # oa amount = models.DecimalField(default=0, max_digits=12, decimal_places=2) class Curency(models.TextChoices): UAH = 'UAH' USD = 'USD' EUR = 'EUR' KZT = 'KZT' RUB = 'RUB' # currency currency = models.CharField( max_length=10, choices=Curency.choices, default=Curency.USD ) # o order_id = models.CharField( max_length=255, null=True, blank=False, unique=False) # s sign = models.CharField(max_length=255, blank=False, null=True) url = models.CharField(max_length=1000, null=True) def __str__(self): return f'Payment {self.user} of game {self.order_id}' serializers.py class PaymentSerializer(serializers.ModelSerializer): # in order to work you should add related_name in Action model class Meta: model = Payment fields = '__all__' # balance is read only, because i don't want someone create account # with money read_only_fields = ('id', 'shop_id', 'sign', 'user', 'email') views.py class PaymentViewSet(viewsets.ModelViewSet, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, ): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, ) serializer_class = PaymentSerializer queryset = Payment.objects.all() def get_queryset(self): """Return object for current authenticated user only""" return self.queryset.all() def perform_create(self, serializer): serializer.save(user=self.request.user) serializer.save(email=self.request.user.email) shop_id = … -
Saving a PDF Document generated in js.PDF to a Django Project Directory
I currently create a PDF in Django using js.PDF that gets download to wherever the web browser directs it to on my local computer. I would like to instead have it saved in a directory in my Django project that is hosted in Pythonanywhere.(i.e. /home/abraner/ABS/absdatabase/pdfs) Below is my current JavaScript code. Any suggestions would be appreciated. async function generatePDF(){ document.getElementById("downloadButton").innerHTML = "Currently downloading, please wait"; var downloading = document.getElementById("whatToPrint"); var doc = new jsPDF('1', 'pt'); await html2canvas(downloading, { allowTaint: true, useCORS: true, width: 798 }).then((canvas) => { doc.addImage(canvas.toDataURL("image/png"), 'PNG', 5, 5, 585, 800); }) doc.save("Document.pdf"); window.location.replace('../emailproposal'); } -
React.js and Django switching foreign key into name problem
I got Game model with 2 foreign keys away_team and home_team, both come from Club model. I got data from them rendered from the API to React.js like this: const AllGames = () => { //Simplified Game object const [games, setGames] = useState([{ away_score:"", away_team:"", home_score:"", home_team:"", id:'' }]); //Simplified Club object const [clubs, setClubs] = useState([{ name:'', id:"" }]) useEffect(() => { loadAllGames(); },[]) useEffect(() => { loadAllClubs(); }, [games]) const loadAllClubs = () => { getAllClubs() .then((data) => { setClubs(data) }) .catch((error) => console.log(error)) } const loadAllGames = () => { getAllGames() .then((data) => { setGames(data) }) .catch((error) => console.log(error)) }; With this piece of code everything is loaded smoothly, the problem is when I try to render the data: return ( <Base> {games.map((game) => { return ( <p> Home) {game.home_team}: {game.home_score} Away){game.away_team}: {game.away_score} </p> ) })} </Base> ) } export default AllGames; The output looks like Home) 1: 34 Away) 2: 51 It displays id of the club instead of a name. I know there was a function to switch game.home_team and game.away_team from being id's to being proper names (aka: text variables like "Team Name Example") TLDR; I need to swap home_team or away_team in games … -
How to create a graphql mutation with a relation in Django
I have a problem with creating mutations in graphql that contain a relation. I don't know where to start. For example - three classes of models: class HotelGuests(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=46, default='noname') lastname = models.CharField(max_length=46, default='noname') email = models.EmailField(max_length=254) tel_number = models.CharField(max_length=12, blank=True, null=True) class Rooms(models.Model): room_number = models.PositiveSmallIntegerField() min_vacancy = models.PositiveSmallIntegerField(default=1) max_vacancy = models.PositiveSmallIntegerField(default=7) class Reservations(models.Model): BOOKING_STATUS = { (0, 'Do zatwierdzenia'), (1, 'Zatwierdzona'), (2, 'Zrealizowana'), (3, 'Anulowana'), } price = models.FloatField(default=0) prepayment_price = models.FloatField(default=0, blank=True, null=True) number_of_guests = models.PositiveSmallIntegerField() date_from = models.DateField(default=now) date_to = models.DateField(default=now) description = models.TextField(blank=True, null=True) booking_status = models.PositiveSmallIntegerField(default=0, choices=BOOKING_STATUS) hotel_guest = models.ForeignKey(HotelGuests, on_delete=models.CASCADE) room = models.ForeignKey(Rooms, on_delete=models.SET_NULL, blank=True, null=True) Three classes of graphql types: class HotelGuestType(DjangoObjectType): class Meta: model = HotelGuests fields = ('id', 'name', 'lastname', 'email', 'tel_number') class RoomType(DjangoObjectType): class Meta: model = Rooms fields = ('id', 'room_number', 'min_vacancy', 'max_vacancy') class ReservationType(DjangoObjectType): class Meta: model = Reservations fields = ('id', 'price', 'prepayment_price', 'number_of_guests', 'date_from', 'date_to', 'description', 'booking_status', 'hotel_guest', 'room',) And three classes of node: class HotelGuestNode(DjangoObjectType): class Meta: model = HotelGuests filter_fields = ['id', 'name', 'lastname', 'email', 'tel_number'] interfaces = (relay.Node, ) class RoomNode(DjangoObjectType): class Meta: model = Rooms filter_fields = ['id', 'room_number', 'min_vacancy', 'max_vacancy'] interfaces = (relay.Node, … -
This Field can not be changed Django Validation Error
All I am trying to create valiadtion check that will check after saving the "Name" and "Address that field can not be changed, How I can do that? class Institution(CustomModel): name = models.CharField(max_length=256, null=False, blank=False, verbose_name=_('Name')) address = models.ForeignKey('Address', on_delete=models.PROTECT, null=False, blank=False, verbose_name=_('Address')) -
How do I access data from a dictionary in a HTML template?
When I try to use data from a dictionary, I get the error: 'tuple' object has no attribute 'get' This happens when I click on a link that should take me to the page of the entry. The entry is a Markdown file that I get from util.get_entry(title). How do I access data from a dictionary in my HTML template (entry.html)? Do I need to convert the Markdown into HTML? entry.html: {% extends "encyclopedia/layout.html" %} <!-- {% load static %} --> {% block title %} {{ name }} {% endblock %} {% block style %}{% endblock %} {% block body %} <div class="left">{{ entry }}</div> <div class="right"> <a href="{% url 'edit' %}"> <button class="edit">Edit</button> </a> </div> {% endblock %} views.py: from . import util def entry(request, name): if util.get_entry(name) is not None: return render(request, 'encyclopedia/entry.html'), { 'entry': util.get_entry(name), 'name': name } else: return render(request, "encyclopedia/404.html") urls.py: path('<str:name>', views.entry, name='entry'), -
Getting 0 all the time when dividing in annotation
I get next query qs = Supplier.objects.annotate( goods_with_sales=Count('goods', filter=Q(goods__history__sales__gt=0)), ).annotate( goods_sales_percent=(F('goods_with_sales') / Value(500)) * Value(100), ) SQL query SELECT Count("wb_good"."id") filter (WHERE "wb_stockshistory"."sales" > 0) AS "goods_with_sales", ((count("wb_good"."id") filter (WHERE "wb_stockshistory"."sales" > 0) / 500) * 100) AS "goods_sales_percent" FROM "wb_supplier" left outer join "wb_good" ON ( "wb_supplier"."id" = "wb_good"."supplier_id") left outer join "wb_stockshistory" ON ( "wb_good"."id" = "wb_stockshistory"."good_id") GROUP BY "wb_supplier"."id" Why I get always 0.0? I'm use Django 4.0 and PostgreSQL. -
Simple password login/logout using django and session storage. Stay logged in not working
I am trying to make a password protected page in a website using django. There is no need for any username, just a user to enter a password to gain access. That's fine, but I've got a checkbox so that they can choose to stay logged in for the session, but then on the actual protected page itself, a logout button should they wish to. My idea is to set a session variable when submitting the log in form if the box is checked, check for that variable at the start of the function to go straight to the page if it exists on revisiting and to delete the variable and return to login page if logout is pressed. However I can't make it work, I am trying all sorts of syntaxes.. does it want the session variable to be a dictionary? I'm quite a novice and not very good at knowing syntax. If someone could look at my functions and help I'd be very grateful. def investors(request): """ A view show the investor login page (or investors page if a correct password is in session) and load the investors page if a correct password is entered. Also set a … -
Trying to create simple API with Django Rest Framework
I think something is wrong with imports. the error is ImproperlyConfigured but don't know what it is. Followed along with tutorial https://medium.com/swlh/build-your-first-rest-api-with-django-rest-framework-e394e39a482c doing the same coding Here is some of my code. I added my installed apps in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'my_api.apps.MyApiConfig', ] created serializer.py: from rest_framework import serializers from .model import Hero class HeroSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Hero fields = ('name', 'alias') views.py: from django.shortcuts import render from rest_framework import viewsets from django.views import View from django.http import HttpResponse from .serializers import HeroSerializer from .models import Hero # Create your views here. class HeroViewSet(viewsets.ModelViewSet): queryset = Hero.objects.all().order_by('name') serializer_class = HeroSerializer class IndexView(View): def get(self, request): return HttpResponse('This is Home Page!') my_api/urls.py (urls of my app): from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'heroes', views.HeroViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path("home/", views.IndexView.as_view, name="home")] my_API/urls.py (urls of my project): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_api.urls'))] models.py: from django.db import models # Create your models here. class Hero(models.Model): name = models.CharField(max_length=50) alias = models.CharField(max_length=50) def __str__(self): return self.name -
How to remove "this field is not required" in django?
I found posts with similar problem, but the solutions dont seem to work with me. Or maybe I am missing something. I created a form in Django, but as a default it seems that every mandatory fields have this "this field is required" text above. Ideally, I would like to have this only when someone tries to submit a form and a field is missing. form.py class ElderFlowerChampFormAdmin(ModelForm): fieldsets=[ ("Look",{'fields':[ ('look_colour','look_clarity','look_effervescence')]}), } widgets = { 'user': forms.Select(attrs={'class':'form-control','required':'True'}), 'look_colour':forms.Select(attrs={'class':'form-control','required':'True'}), } view.py def elderflowerchamp(request, product_id): global ChampageRating product = Product.objects.get(pk=product_id) url = request.META.get('HTTP_REFERER') submitted = False try: if request.method == "POST": reviews = ChampageRating.objects.get(pk=product_id) if request.user.is_superuser: form = ElderFlowerChampFormAdmin(request.POST, instance=reviews) if form.is_valid(): form.save() return redirect('home') else: form = ElderFlowerChampForm(request.POST, instance=reviews) if form.is_valid(): ChampageRating = form.save(commit=False) ChampageRating.user = request.user ChampageRating.save() return redirect('home') else: #This part goes to the page, but doesnt submit reviews = ChampageRating.objects.get(pk=product_id) if request.user.is_superuser: form = ElderFlowerChampFormAdmin else: form = ElderFlowerChampForm if 'submitted' in request.GET: submitted = True except: reviews = None if request.user.is_superuser: form = ElderFlowerChampFormAdmin(request.POST) if form.is_valid(): data = ChampageRating() data.rating = form.cleaned_data['rating'] data.look_colour = form.cleaned_data['look_colour'] data.ip = request.META.get('REMOTE_ADDR') data.product_id = product_id data.user_id = request.user.id data.save() messages.success(request, 'Thank you! Your review has been submitted.') return redirect('home') else: form …