Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I set up my Django function to run in the background from button onclick?
I have a Django project and one of the functions currently runs onclick of my html - def follow(request): api = get_api(request) followers = tweepy.Cursor(api.followers_ids, wait_on_rate_limit=True).items() for x in followers: try: api.create_friendship(x) except Exception: pass return render(request, "followed.html") The function runs and follows the followers of the authorised user. My issue is that when deployed on my pythonanywhere web app the function will load in the browser and then timeout after around 10 minutes. I have tested on users up to 100 followers and it all works. This would be fine but the Twitter API has a rate limit and so for some users who have large followings this function will take a long time to complete. Is there a way of diverting to the followed.html and keeping the function running in the background until it is completed? I have added the oauth functions just in case they are needed too - def auth(request): # start the OAuth process, set up a handler with our details oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) # direct the user to the authentication url # if user is logged-in and authorized then transparently goto the callback URL auth_url = oauth.get_authorization_url(True) response = HttpResponseRedirect(auth_url) # store the … -
Reverse for 'sales' with no arguments not found. 1 pattern(s) tried: ['sales/(?P<pk>\\d+)/$']
I have seen a lot of relatable questions and answers, I just haven't understood even after tweaking my code why it doesn't seem to respond. I am new to django, I am hoping someone can point me in the right direction. Views.py @login_required def add_user_sales(request , pk): current_user = request.user context = {} context["data"] = MadeSale.objects.get(id=pk) profiles = UserProfile.get_profile() for profile in profiles: if profile.profile_name.id == current_user.id: if request.method == 'POST': form = SalesForm(request.POST) if form.is_valid(): upload = form.save(commit=False) upload.posted_by = current_user upload.profile = profile upload.save() messages.success(request, f'Hi, Your data has successfully been updated' ) return redirect('addProduct') else: form = SalesForm() return render(request,'addProduct.html',{"user":current_user,"form":form}, context) linked url <nav class="navbar" style="margin-left: auto;"> <ul class="ul" style="margin-left: auto;"> <li class="li"><a href="{% url 'user' %}">Home</a></li> <li class="li"><a href="{% url 'sales'add_user_sales.pk %}">Sales</a></li> ***(This line is the culprit)*** <li class="li"><a href="{% url 'total' %}">Total</a></li> <li class="li"><a href="{% url 'margin' %}">Margin</a></li> <!-- For DevelopmentPurposes --> <li class="li"><a href="http://127.0.0.1:8000/admin/">Admin Dashboard</a></li> <li class="li"><a href="{% url 'monthlyTotal' %}">Total</a></li> </ul> </nav> my url url(r'sales/(?P<pk>\d+)/$', views.add_user_sales, name='sales'), -
Hi I have injected Tinymce using JavaScript file into django got 404 page not found error
My Code In setting Stat files are set as below>> In admin i i rejistered it like below>>>JS file mentioned below STATICFILES_DIRS= [os.path.join(BASE_DIR, 'static'), ]``` ```@admin.register(Blogpost) class BlogpostAdmin(admin.ModelAdmin): class Media: js = ('blog/tiny.js',)``` ``` var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://cdn.tiny.cloud/1/no-api-key/tinymce/5/tinymce.min.js"; document.head.appendChild(script); script.onload=function () { tinymce.init({ selector: '#id_content',``` -
Django Admin Customization (Change list display by the user)
At Django Admin, we can use "list_display" to choose which column to show. I want to customize Django admin so that we can decide which column to show dynamically (Not using "list_display) I want the user to be able to use something like a checkbox. Again, not by changing Python codes. I tried the following but it seems nothing to do with the display of listing. Dynamic fields in Django Admin It seems I need to override/extend some Django template using JavaScript but I am not so sure. Any comment would be greatly appreciated. (I much prefer to implement it in admin rather than outside of admin, though.) Many thanks, -
Django send mail from docker container how to expose port
The mail sending works fine without the docker container. I think I actually opened the SMTP Port. Here is my docker-compose file: version: "3.9" services: db: <some postgres setup> api: build: . command: python manage.py runserver 0.0.0.0:8000 --settings=api.settings.production volumes: - .:/code ports: - "8000:8000" - "587:587" - "25:25" expose: - 587 - 25 env_file: - ./.env.dev depends_on: - db entrypoint: /entrypoint.sh mail: build: . command: python manage.py qcluster --settings=api.settings.production depends_on: - api It doesn't work to send mails no matter if I send it as an async task with django q or directly with django.core.mail.send_mail Here is my mail settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mail' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_USE_SSL = False I get an OSError OSError: [Errno 99] Cannot assign requested address -
Get current post's category
So as the title says, i need to get the current post's category to use it in a "related posts" section, more precisely what to put in cat_posts = Post.objects.filter(Category=????) (don't mind the comments variable since i removed part of my PostView from this post) here's my code views.py def PostView(request, slug): template_name = 'post-page.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.filter(active=True) cat_posts = Post.objects.filter(Category=Post.Category) cat_posts = cat_posts.order_by('-Date')[:3} return render(request, template_name, {'post': post, 'cat_posts':cat_posts}) models.py class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class Post(models.Model): title = models.CharField(max_length=120) Category = models.CharField(max_length=120, default='None') Thumbnail = models.ImageField(null=True, blank=True, upload_to="images/") Text = RichTextField(blank=False, null=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) Overview = models.CharField(max_length=400) Date = models.DateTimeField(auto_now_add=True) main_story = models.BooleanField(default=False) def __str__(self): return str(self.title) def get_absolute_url(self): # return reverse('about', args=(str(self.id))) return reverse('home') -
HTML to PDF also with keeping the CSS & bootstrap styling in Django
I am trying to render an HTML page into PDF in Django by following this GitHub tutorial link. My views.py: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('app/pdfpage.html', data) return HttpResponse(pdf, content_type='application/pdf') #Automaticly downloads to PDF file class DownloadPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('app/pdfpage.html', data) response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341233") content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response However I almost copy all the code from that tutorial link except pdfpage.html, I put there my custom made HTML page also with bootstrap and CSS styling. Now my problem is after converting and saving this pdf, it lost all the styling and bootstrap styling stuff, but those are also important for me. how can I solve this problem? -
Geonode Error: ModuleNotFoundError: No module named 'geonode.local_settings'
Hi I'm installing geonode in Ubuntu 20.04 I followed the steps in this guide, but I have an error when I want to install the webserver (Step 6) https://docs.geonode.org/en/master/install/advanced/core/index.html#postgis-database-setup Traceback (most recent call last): File "./geonode/wsgi.py", line 30, in application = get_wsgi_application() File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> django.setup(set_prefix=False) File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> self._setup(name) File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> self._wrapped = Settings(settings_module) File "/home/xrdpuser/.virtualenvs/geonode/lib/python3.8/site-packages/django> mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.8/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'geonode.local_settings' What am I doing wrong? This is my geonode.ini is the same as that of the guide by changing this virtualenv = /home/xrdpuser/.virtualenvs/geonode Thank you Regards Abel Quesi -
Adding a redirect to CreateAPIView
I want to redirect the user to the AddQuestionsView after the user creates a quiz(after adding title). My CreateQuiz class CreateQuizzView(CreateAPIView): serializer_class = CreateQuizSerializer My serializers.py file class CreateQuizSerializer(serializers.ModelSerializer): class Meta: model = Quizzer fields = ['title'] def create(self, validated_data): user = self.context['request'].user new_quiz = Quizzer.objects.create( user=user, **validated_data ) return new_quiz Can i add redirect by adding any Mixin or change need to change the GenericView. -
Django feeding file data to a model
If you got a form that asks the user for a file upload and the file after some preprocessing gets a data dict which is fed to the model. How is the preprocessing step is to be done in this case? In the subclassed FormView's is_valid method one can do form.files to get the file obj, read it , preprocess it there and then feed the data to a model instance. But I think this would block the thread. What's the correct way? -
Modal Form Not Showing in Django
I have the the following modal that I am trying to use as a Create/Edit form for my SQLite3 data but nothing ever appears. I can connect this form to it's own URL and that works fine, but I am looking to include it within the same /communications url just as a pop-up (enabling the user to stay on the same screen and quickly fill out the form). Any clue as to why this is not working? models.py class Communications(models.Model): team = models.CharField(max_length=200) title = models.CharField(max_length=200) date = models.CharField(max_length=200) def __str__(self): return self.communication forms.py class CommunicationsForm(forms.ModelForm): class Meta: model = Communications fields = '__all__' urls.py path('communications/', views.CommunicationsView.as_view(), name='communications'), views.py class CommunicationsView(generic.ListView): template_name = 'polls/communications.html' context_object_name = 'comms_list' def get_queryset(self): """Return the last five published questions.""" return Communications.objects.order_by('id') def CommCreation(request): form = CommunicationsForm() context = {'form':form} return render(request, 'polls/communications.html', context) polls/communications.html: <div class="modal-body"> <form method="POST"> {% csrf_token %} {{form}} <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save changes</button> </div> </form> </div> -
Ajax request call when new data is added in database
I want to create some kind of AJAX script or call that continuously will check the database if any new object is created (Django framework). I have tried using: setInterval(function()) It is working fine, but I want to know if it is the proper method, because there will be a lot of unnecessary requests which can increase server load. -
DRF ManyToManyFields with a Through Model
I have this M2M relation with through model as class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) Please note that, I have extra fields date_joined and invite_reason in the through model. Now, I want to serialize the Group queryset using DRF and thus I choose the below serializer setup. class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = "__all__" class GroupSerializer(serializers.ModelSerializer): members = PersonSerializer(read_only=True, many=True) class Meta: model = Group fields = "__all__" and it is returning the following response, [ { "id": 1, "members": [ { "id": 1, "name": "Jerin" } ], "name": "Developer" }, { "id": 2, "members": [ { "id": 1, "name": "Jerin" } ], "name": "Team Lead" } ] Here, the members field returning the Person information, which is perfect. But, How can I add the date_joined and invite_reason field/info into the members field of the JSON response? -
Django-jsignature Fields Mixin
I have the below Model. class Job(models.Model): site_address=models.TextField() site_code=models.CharField(max_length=50) client=models.CharField(max_length=50) main_contractor=models.CharField(max_length=50) date_due=models.DateField() date_complete=models.DateField(null=True,blank=True) date_received=models.DateTimeField(auto_now_add=True) job_description=models.TextField() materials=models.TextField(blank=True) assigned_to=models.ForeignKey(User, on_delete = models.SET_NULL,null=True,blank=True) and also the below Django-signature model. class JSignatureModel(JSignatureFieldsMixin): name = models.CharField(max_length=50, blank=True, null=True) everything works ok and i can display, create a signature and save no problems. The issue is when i add the below. class JSignatureModel(JSignatureFieldsMixin): name = models.CharField(max_length=50, blank=True, null=True) sig = models.ForeignKey(Job, on_delete=models.CASCADE) when displayed it is asking me to manually select the job i want it to be related to instead of automatically been added when the job form is submitted. i have this working on another model which uses a foreign key link to the Job model. Is it because it's inheriting from JSignatureFieldsMixin and not models.Model? Im new to Django and Python and just trying to figure things out. Thanks -
Como fazer o deploy do python 32bits com django no Heroku?
Preciso utilizar a versão de 32bits do python para rodar a conexão com o Oracle, porem quando eu faço o deploy ele utiliza a versão do python 64 bits porem so funciona se for 32bits, alguem sabe como faço para rodar, pois não encontrei em nenhum lugar. -
Django template if condition on a key
I have a for loop through a dictionary. And I would like to have a condition on my key but I get an error. Here is my code : {% for key, value in price_list.items %} <li class="list-group-item"> <span style="margin-top: 7px;"> {{key}} </span> <span style="color: #F60;font-weight: bold;"> {{value}}€ </span> {% if {{key}} == 'Krefel' %} <a class="flux_cta gift__cta" href="#" style="font-size: 13px;height: 41px;float: right;padding-top: 11px;margin-right: 10%;" > Voir l'offre </a> {% endif %} I can't just check if the key is part of the dictonary as I am in a for loop. Any idea how I can adress the problem? Thanks -
Django form missing
So I'm trying to make a form to appear after user is authenticated. When the user authenticated then the form appears on the home page but it never appears. I'm pretty sure I'm doing something wrong ether in paths or view but can't figure this out. When I do the same code to external new template it works fine but I want form to appear on the same page. Here is the code: VIEWS.PY def vpn(request): form = vpn_form(request.POST or None) if form.is_valid(): form.save() context ={ 'form': form } return render(request, 'loginas/home.html', context) URLS.PY urlpatterns = [ # / path('', views.home, name='home'), # TEMPORARY path('signin', views.sign_in, name='signin'), path('signout', views.sign_out, name='signout'), path('callback', views.callback, name='callback'), path('', views.vpn, name='vpn'), models.py class VPN(models.Model): name = models.CharField(max_length=125) surname = models.CharField(max_length=125) description = models.TextField() date_to = models.DateField() date_from = models.DateField() forms.py from .models import VPN class vpn_form(forms.ModelForm): class Meta: model = VPN fields = ('name', 'surname', 'description', 'date_to', 'date_from') home template {% extends "loginas/layout.html" %} {% load static %} {% block content %} <div class="container"> <h1 class="d-flex justify-content-center"> </h1> <p class="d-flex justify-content-center"></p> {% if user.is_authenticated %} <form> {{form.as_p}} </form {% else %}<div class="d-flex justify-content-center"> <a href="{% url 'signin' %}" class="btn btn-primary btn-large ">Login</a> </div> {% endif … -
how to get data from different table using ajax in form of checkbox in django
Here i want to have my contactperson data in form of checkbox but using ajax call,I am able to bring in form of dropdown but after doing changes for converting it in form of checkbox its not working can anyone tell me how to change it views.py def add_project(request): error = "" if not request.user.is_staff: return redirect('admin_login') cpphone = '' cpemail = '' cust1 = Customer.objects.all() if request.method == 'POST': d = request.POST['customer'] c = request.POST['contactperson'] pn = request.POST['pname'] pl = request.POST['plength'] pt = request.POST['ptype'] pc = request.POST['pcost'] ptech = request.POST['ptechnologies'] psd = request.POST['psdate'] ped = request.POST['pedate'] pdesc = request.POST['pdescription'] d1 = Customer.objects.get(customer_id=d) contactperson1 = Contactperson.objects.get(person_id=c) cpphone = Contactperson.objects.get(person_id=c).person_phone cpemail = Contactperson.objects.get(person_id=c).person_email # print(cpphone, cpemail) try: Allproject.objects.create(customer=d1, contactperson=contactperson1, contactpersondetails=cpphone, contactpersonemail=cpemail, project_name=pn, project_length=pl, project_type=pt, project_cost=pc, project_technologies=ptech, project_startdate=psd, project_enddate=ped, project_description=pdesc) error = "no" except: error = "yes" d = {'error': error, 'cust': cust1} return render(request, 'projectfolder/add_project.html', d) def load_courses(request): cust_id = request.GET.get('customer') # print(cust_id) proj = Contactperson.objects.filter(customer_id=cust_id) return render(request, 'projectfolder/courses_dropdown_list_options.html', {'proj': proj}) add_project.html here i am only posting main fields that i want to be in form of checkbox See here i have contact person in form of select dropdown but i want that in checkbox format for each value <form class="row … -
Show Groupnames in a dropdown list
I am working on a studentresult website in Python and Django. Now I want to ask to the database to give me the names of the groups that are in the database. Using the standard db.sqlite3 database from django. In the Dropdown menu I get three white bars because I have three groups now. When I the Class DisplayGroups to id = Models.IntegerField(id, flat=True) change return.self.group_name to return self.id then the dropdownlist shows me the ID that the group has. But how can I show the name of the group. Tried a lot: Changed to group in the model Changed to groupname in the model Changed a few of the commands in the views.py Made a new database item Groepen and changed query to that. views.py from django.shortcuts import render, redirect from .models import DisplayGroups, DisplayUsername from django.contrib.auth.models import User, Group def index(request): response = redirect('/login') return response def home(response): return render(response, "home/home.html") def bekijk(request): DisplayGroup = Group.objects.all() print(DisplayGroup) DisplayNames = User.objects.all() print(DisplayNames) return render(request, "home/bekijk.html", {"DisplayGroups": DisplayGroup,"DisplayUsername":DisplayNames}) models.py from django.db import models # Create your models here. class DisplayGroups(models.Model): group_name = models.CharField(max_length=200) def __str__(self): return self.group_name class DisplayUsername(models.Model): username = models.CharField(max_length=100) def __str__(self): return self.username The html page {% … -
webpack-cli Running multiple commands at the same time is not possible
I am trying to made a full stack project using react and django from the tuto of bad traversy of react and django here react it is a django app i flow the tuto and when it coming to excute the flowing command npm run dev and dev it is "dev":" webpack --mode development ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/main.js", i have some errors they are (venv) youssef@youssef-HP-EliteBook-840-G3:~/Desktop/fullstack$ npm run dev > fullstack@1.0.0 dev /home/youssef/Desktop/fullstack > webpack --mode development ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/ [webpack-cli] Running multiple commands at the same time is not possible [webpack-cli Found commands: 'bundle', './leadmanager/frontend/src/index.js' webpack-cli Run 'webpack --help' to see available commands and options npm ERR! code ELIFECYCLE npm ERR! errno 2 npm ERR! fullstack@1.0.0 dev: webpack --mode development ./leadmanager/frontend/src/index.js --output-path ./leadmanager/frontend/static/ npm ERR! Exit status 2 npm ERR! npm ERR! Failed at the fullstack@1.0.0 dev script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /home/youssef/.npm/_logs/2020-12-29T13_19_24_663Z-debug.log -
Introducing JavaScript events with my django template
I have develop quite numbers of web app with django but am seeking to improve UIs with JavaScript, I haven't done something like this before, but with my researches I have found somethings about events. But I will like if someone can just point me through how to implement it and get started easily, because I heard JavaScript is very hard to debug -
No ready() function when starting django with uvicorn
I have a problem because when starting a Django application by uvicorn, Django's AppConfig don't seem to be running ready() function. When I'm starting by Djnago's runserver command, ready function is correctly loaded. Can you help me to overcome this problem? settings.py """ Django settings for mtg_django project. Generated by 'django-admin startproject' using Django 3.1.3. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pukj_o)6-!^i$oeh-9c1zik4w*v68!pkdux)nc_79fzjffp*j6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'rest_framework', 'mtg.apps.MtgConfig' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mtg_django.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mtg_django.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases # DATABASES = { … -
Django - queryset based on list interval
I have a Django model and want to get a Queryset based on the order_by clause which is set to a time field in descending order. I do NOT want to return all these objects. I just want to return the objects in the interval start to end. For now I get all the objects in Queryset list and manually slice the python list (list[start:end). The problem is that the list contains over 100k records. So it is a time consuming option. Is there any way in which I can pass this start and end parameter to Django and it only returns the queryset list after applying that slice. -
Serializing many to many relationship with attributes does not show attribute in the relationship
My conceptual model is that there are DemanderFeature objects which have LoadCurve objects linked to them in a many-to-many relationship, along with a single attribute indicating "how many times" the two are associated, using an attribute in the many-to-many relationship called number. I have been struggling for quite a while now, reading many answers on stackoverflow but I just cannot get it to work in exactly the way that I want. This is my desired output, when looking at the detail view of a DemanderFeature: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "name": "testdemander", "loadcurves": [ {"name": "lc", "number": 5}, {"name": "lc2", "number": 10} ], // Other DemanderFeature fields removed for brevity... } ] The closest I have been able to get to this is with this setup: Models class LoadCurve(models.Model): created = models.DateTimeField(auto_now_add=True) finalized = models.BooleanField(default=False) owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) name = models.CharField(max_length=100) length = models.IntegerField(default=0) deleted = models.BooleanField(default=False) demanderfeatures = models.ManyToManyField("DemanderFeature", through="DemanderFeatureToLoadCurveAssociation") class Meta: ordering = ['name'] constraints = [ models.UniqueConstraint(fields=["owner", "name"], condition=models.Q(deleted=False), name="loadcurve_unique_owner_name") ] class DemanderFeature(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) demanderfeaturecollection = models.ForeignKey(DemanderFeatureCollection, on_delete=models.CASCADE) loadcurves = models.ManyToManyField("LoadCurve", through="DemanderFeatureToLoadCurveAssociation") deleted = models.BooleanField(default=False) geom = gis_models.PointField(default=None) … -
does not show forms errors in django
I want show required errors but not showing. I made custom errors in form.py but it does not show either my current or default and why? When I submit a blank form I want it to appear, my created error this is my code --> home.html {% extends "home/base.html" %} {% block content %} <h2>Sign up Form</h2> <div class="frm"> <form method="post" novalidate> {% csrf_token %} {{form}} <button type="submit">sign up</button> </form> </div> {% endblock %} forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import get_user_model User = get_user_model() class SignUpForm(UserCreationForm): username = forms.CharField(max_length=30) username.error_messages['required'] = ('Username field is required') email = forms.EmailField(max_length=200) def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'inp' for field in self.fields.values(): field.error_messages = {'required':'The field {fieldname} is required'.format( fieldname=field.label)} class Meta: model = User fields = ('username', 'email', 'password1', 'password2','mob', )