Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make models fields readonly in all admin pages
My project has multiple Models and custom admin pages for the models. All the Models inherit from a "BaseModel". For business functionality, we had to update our "Base model" to include 2 new fields. Given that all models inherit these 2 new fields, they are now showing up in admin pages as editable fields. As per business functionality, these two fields should be displayed as read-only fields For making fields readonly we normally use readonly_fields = [read only..] in admin class. Is there a way to achieve this without touching all the admin classes? -
How can I block certain words from being used in Django forms?
So I am creating a website where users can make posts, but I want to block certain words from being used in the Django form. For example, I don't want them to mention CP, or anything else illegal. How could I block these words from being displayed or throw an error message at the user I haven't really tried anything, but I have been researching, to no luck. Here is the post model. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=75) text = models.TextField(max_length=250) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True,auto_now_add=True) tags = TaggableManager() def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse('mainapp:post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title And here is the form class PostForm(forms.ModelForm): class Meta(): model = Post fields = ('title','text') widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'textareaclass'}), } And here is the CreatePostView class CreatePostView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'mainapp/post_details.html' form_class = PostForm model = Post def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I want it so that it throws an error if you include a word that's blocked Thank you for any help that you can give :) -
Django abstract model field depends on children attributes
I want to code some model structure containing abstract parent model and child models with same fields but different names, help_text and related_name. How better and shorter implement this behavior? Is there any solutions at all? class AbstractModel(models.Model): class Meta: abstract = True name = None code = None rel_field = models.OneToOneField(RelatedModel, on_delete=models.CASCADE, primary_key=True, related_name=code) field = models.CharField(name, null=True, help_text=HELP_DICT.get(code, None)) class ChildOne(AbstractModel): name = "child one name" code = "one" class ChildTwo(AbstractModel): name = "child two name" code = "two" child_field = SomeAnotherField() I want to make ChildOne.field == models.CharField("child one name", help_text=HELP_DICT.get("one", None) ...) ChildTwo.field == models.CharField("child two name", help_text=HELP_DICT.get("two", None) ...) and RelatedModel.one == ChildOne RelatedModel.two == ChildTwo -
How to create a one time link on Django for video file
i need to create a one time link on Django for my videos from theft. Please show an example of how something can be done. Sorry for my bad English -
Issue while trying to use a tag
I'm trying to use this tag which allow me to check if a map got permissions in the site I'm working on using Geonode. {% get_obj_perms request.user for resource.get_self_resource as "layer_perms" %} {% if "view_resourcebase" in layer_perms %} When I used it in other files, everything works fine but in this file, the page I'm on crash and when I check the apache log I have this problem. [Thu Sep 12 01:05:26.388898 2019] [wsgi:error] [pid 18375:tid 140402620434176] VariableDoesNotExist: Failed lookup for key [resource] in u"[{'False': False, 'None': None, 'True': True}, {}, {}, {'facet_type': 'layers', 'is_layer': True, u'view': <django.views.generic.base.TemplateView object at 0x7fb1dce66390>}]" -
IOError: [Errno 13] Permission denied: '/home/ubuntu/autobot/nohup.out'
I used virtual env to host my python project on to the local host but when visit my localhost, the website is IOError at /gobot/dcae3db9ad68d046e97d503da41a068aed8663feec28882d94 [Errno 13] Permission denied: '/home/ubuntu/autobot/nohup.out' Why am I getting this error ? Please help. Internal Server Error: /gobot/dcae3db9ad68d046e97d503da41a068aed8663feec28882d94 Traceback (most recent call last): File "/home/ubuntu/autobot/myproject/myprojectenv/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/home/ubuntu/autobot/myproject/myprojectenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/autobot/myproject/myprojectenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/autobot/myproject/myprojectenv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/autobot/myproject/myprojectenv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "/home/ubuntu/autobot/myproject/myprojectenv/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/home/ubuntu/autobot/myproject/myprojectenv/local/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/ubuntu/autobot/gobot/views.py", line 360, in dispatch return generic.View.dispatch(self, request, *args, **kwargs) File "/home/ubuntu/autobot/myproject/myprojectenv/local/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/ubuntu/autobot/gobot/views.py", line 352, in get -
Django admin, setting TIME_ZONE not showing correct datetime
I have set these settings on my project: TIME_ZONE = 'Asia/Almaty' USE_TZ = True Asia/Almaty will add extra 6 hours to UTC. When I create my models objects in django admin, it shows date times likes this: Where time should be 9:21. It still shows UTC datetime. date command on my linux machine returns this: Thu Sep 12 11:41:21 +06 2019 Why django admin still shows wrong datetime? -
How to update (put/post request) related fields with Django rest api?
I'm new to Django. Within the Django rest framework, I'm struggling with the put & post request on a table that's linked to other table(s). The main table I want to update via API is person, that's basically where contact details are kept. It joins to 2 other tables, email, phone, where each of them only contains 1 piece of information (as their name stated). What I'm trying to achieve is that when I submit a put/post request to person's api, it also updates email, phone without needing to update each of them respectively. Below are some code: Models: class Person(models.Model): id = models.AutoField(primary_key=True) last_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) email = models.ManyToManyField('Email') phone = models.ManyToManyField('Phone') class Meta: ordering = ['last_name', 'first_name'] def __str__(self): return f'{self.first_name} {self.last_name}' class Phone(models.Model): phone = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return f'{self.phone}' class Email(models.Model): email = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return f'{self.email}' Serializers: class PersonSerializer(serializers.ModelSerializer): email = serializers.StringRelatedField(many=True) phone = serializers.StringRelatedField(many=True) class Meta: model = Person fields = ('id', 'last_name', 'first_name', 'email', 'phone') class PhoneSerializer(serializers.ModelSerializer): class Meta: model = Phone fields = ('id', 'phone') class EmailSerializer(serializers.ModelSerializer): class Meta: model = Email fields = ('id', 'email') Views: class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = … -
“How to fix ‘raise EOFError’ error in python django when running program”
i'm trying to convert python 2.7 to 3.7 and django 1.8 to 2.x, when trying to convert code in program,i'm getting an Error: " File "/usr/lib/python3.6/multiprocessing/connection.py", line 389, in _recv raise EOFError EOFError " my code is: def _recv(self, size, read=_read): buf = io.BytesIO() handle = self._handle remaining = size while remaining > 0: try: chunk = read(handle, remaining) except InterruptedError: continue n = len(chunk) if n == 0: if remaining == size: raise EOFError else: raise OSError("got end of file during message") buf.write(chunk) remaining -= n return buf -
Exclude model fields in all admin pages
My project has multiple Models and custom admin pages for the models. All the Models inherit from a "BaseModel". For business functionality, we had to update our "Base model" to include 2 new fields. Given that all models inherit these 2 new fields, they are now showing up in admin pages. As per business functionality, these two fields should not be displayed in the admin pages. For excluding fields we normally use excludes = [fields to be excluded..] in admin class. Is there a way to achieve this without touching all the admin classes? -
Django. How i can get list of Users with a duplicate?
i have array like this: [1, 1, 1, 2, 3]. How i can get users with a duplicate? For example this query return list without duplicate list= User.objects.filter(id__in=[1, 1, 1, 2, 3]) for example it will be users with id's: 1, 2, 3 but i need list of users like this: 1, 1, 1, 2, 3 -
How to query related models in django models.py
I have a user model which looks like this: class User(AbstractUser): first_name = models.CharField(max_length=70) last_name = models.CharField(max_length=70) middle_name = models.CharField(max_length=70, blank=True) email = models.EmailField( max_length=254, unique=True, verbose_name='Email Address', blank=True ) is_student = models.BooleanField(default=False, verbose_name='Student') is_superuser = models.BooleanField(default=False, verbose_name='Administrator') is_teacher = models.BooleanField(default=False, verbose_name='Teacher') is_staff = models.BooleanField(default=False, verbose_name='Staff') is_registrar = models.BooleanField(default=False, verbose_name='Registrar') and in my StudentPorile model I have a field called class_advisor which is related to User model and I need to get the users with is_teacher field is True. Now, how do i filter User model so it will just return Users with is_teacher=True value? here's my StudentProfile model: class StudentProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) lrn = models.CharField(max_length=20) landline_number = models.CharField(max_length=11, null=True, blank=True) mobile_number = models.CharField(max_length=11, null=True, blank=True) address = models.TextField(max_length=300, blank=True) mothers_name = models.CharField(max_length=50) fathers_name = models.CharField(max_length=50) contact_person_name = models.CharField(max_length=50) contact_person_number = models.CharField( max_length=12, verbose_name='Phone number of Contact Person') # class_advisor = IM STUCK HERE year_level = models.OneToOneField(Year_Level, on_delete=models.SET_NULL, null=True) section = models.OneToOneField(Section, on_delete=models.SET_NULL, null=True) -
edit content of table and send changes to database
I have a table that made it editable!something like this. <table> <tr> <th>Name</th> <th>Code</th> </tr> {% for item in list %} <tr> <td contenteditable='true'>{{item.name}}</td> <td contenteditable='true'>{{item.code}}</td> </tr> {% endfor %} </table> also I have a 'submit' button end of the table to submit users changes. now my questions are how to send edited data to my server? how to find which content was edited? which item of the list and which attribute of that was edited? also is there any better idea to editable table? I use django2 on my backend side. -
django raises MultiValueDictKeyError at / 'file'
I'm trying to create a view for uploading a .csv file and parsing it on the template but it's returning a MultiValueDictKeyError at / 'file' The template has <form method="POST" enctype="multipart/form-data">{% csrf_token %} <div class="file-field input-field"> <div class="btn"> <span>Upload a CSV FILE</span> <input type="file" name="file"> </div> <div class="file-path-wrapper"> <input class="file-path validate" type="text"> </div> <button class="waves-effect waves-light btn teal" type="submit">Upload</button> </div> </form> Then my views has import csv, io def data_upload(request): template = "home.html" csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'Please upload a .csv file.') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quoteschar="|"): _, created = Table.objects.update_or_create( page=column[0], keyword=column[1], interval=column[2], email=column[3], billing=column[4], notes=column[5], ) context = {} return render(request, template, context) I'm wondering why it's returning the error(?). -
'_csv.writer' object has no attribute '_committed'
I am getting this error "'_csv.writer' object has no attribute '_committed' " while saving and download the CSV file at the same time I haven't tried anything because I am facing this error for the first time. def index(request): if request.method == "POST": url = request.POST.get('url', '') username = request.POST.get('username','') r = requests.get(url) soup = BeautifulSoup(r.content, features="lxml") p_name = soup.find_all("h2",attrs={"class": "a-size-mini"}) p_price = soup.find_all("span",attrs={"class": "a-price-whole"}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="product_file.csv"' for name,price in zip(p_name,p_price): writer = csv.writer(response) writer.writerow([name.text, price.text]) csv_file = csv.writer(response) csv_save_obj = csv_save(username=username,csv_file=csv_file) csv_save_obj.save() return response return render(request, 'index.html') -
Django: Load template at runtime
I am trying to implement a plugin system with the app in my Django proyect. I am using Django 2.2 with Python 3.7 in a virtual environment and I have a method that loads the plugin (app). Then I have the applications in the apps directory and at runtime if the user installs one of these plugin (app) 1. I load the app in the INSTALLED_APPS variable (works fine). 2. I create and execute the migrations (works fine). 3. Charge the app url in the main urlpatterns (works fine). def InstallApps(self, pk): app = PyApp.objects.get(id=pk) app.installed = True app.save() with open('installed_apps.py', 'a+') as installed_apps_file: if installed_apps_file.write('apps.{}\n'.format(app.name.lower())): print('yes') else: print("no") # I load the app in the settings.INSTALLED_APPS variable with open('%s/installed_apps.py' % BASE_DIR, 'r') as ins_apps_file: for line in ins_apps_file.readlines(): settings.INSTALLED_APPS += (line.strip().rstrip('\n'), ) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False apps.clear_cache() apps.populate(settings.INSTALLED_APPS) # Create and execute the migrations call_command('makemigrations', app.name.lower(), interactive=False) call_command('migrate', app.name.lower(), interactive=False) # Reload urlpatterns in memory urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: clear_url_caches() reload(sys.modules[urlconf]) return redirect(reverse('base:apps')) The problem is that when I try to navigate over the url of the recently installed plugin (app) it tells me that it doesn't find … -
Construct QuerySet that returns a list of the five objects with highest IntegerField values in the database
I am following the official Django tutorial and creating a polling website. I have the following models.py: from django.db import models class Question(models.Model): questionText = models.CharField(max_length = 100) pubDate = models.DateTimeField('published date') def __str__(self): return self.questionText class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choiceText = models.CharField(max_length = 200) votes = models.IntegerField(default=0) def __str__(self): return self.choiceText I would like the homepage to display the top 5 most voted on questions, but am struggling to construct the proper QuerySet to get this result. The only thing I have thought of doing is: def index(request): questions = Question.objects.order_by(*question.choice_set.votes*) #I left *question.choice_set.votes* like that because I'm not sure how to properly express that in code or if it is possible in this example Also, would it be better to give the Question class a method like returnMostVotedOn(numberOfQuestions) or is using a QuerySet the correct method? Thanks in advance. *If anyone can think of a better question title feel free to change it, I was struggling to briefly define my question. -
How to solve ImproperlyConfigured Error while using django.views.generic classes
models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Award_list(models.Model): award_id=models.AutoField(primary_key=True) award_name=models.CharField(max_length=50,blank=False) award_image = models.ImageField(default='award.jpg', upload_to='award_pics') def __str__(self): return f'{self.user.award_name} Profile' def save(self,*args,**kwargs): super().save(*args,**kwargs) img = Image.open(self.award_image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.award_image.path) class Meta: verbose_name_plural = 'Award' views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import( ListView, DetailView, CreateView, UpdateView, DeleteView from . models import Award_list class AwardCreateView(LoginRequiredMixin,CreateView): models=Award_list fields=['award_name','award_image'] def form_valid(self,form): if request.user.is_superuser: return super().form_valid(form) award_list_form.html {% extends "users/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Blog Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content %} urls.py from django.urls import path from .views import ( # PostListView, # PostDetailView, AwardCreateView, # PostUpdateView, # PostDeleteView, # UserPostListView ) from . import views urlpatterns = [ path('movies/awards/new/',AwardCreateView.as_view(),name='award-create') ] Getting Error ImproperlyConfigured at /movies/awards/new/ AwardCreateView is missing a QuerySet. Define AwardCreateView.model, AwardCreateView.queryset, or override AwardCreateView.get_queryset(). I have tried using template_name in url AwardCreateView.as_view() and views AwardCreateView but it's work getting same error ImproperConfigured. -
Password change field reset password django
I created a password reset system through email using django, but when I am at the password page, if I enter the password and confirmation right, it doesn't do anything just reloads the page and seems to throw in error in form.errors, but if i try to show the error nothing comes up. In addition, how do you make it so only one email can be assigned to a user. So when registering or changing your info, the same email can't be used with two accounts. Here is the code to my password reset page: {% extends 'base.html' %} {% block head %} <link href="\static\accounts\css\forms.css" rel="stylesheet"> <script src="\static\registration\js\emailvariable.js"></script> {% endblock %} {% block body %} {% if validlink %} <h3 style="text-align: center">Change password</h3> <form id="login-form" method="post"> {% csrf_token %} <input placeholder="Password" id="id_password" name="password" type="password" class="form-control"> <input placeholder="Confirm Password" id="id_password2" name="password2" type="password" class="form-control"> <div style="text-align:center;"> <button type="submit" class="btn btn-outline-dark centerbutton">Change password</button> </div> {% if form.errors %} <p class=" label label-danger"> <div style="text-align: center"> {{ error | escape }} </div> </p> {% endif %} </form> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} … -
Django can't load static files
I'm trying to load static files in my django project to the html template. My project structure as follow: base settings __init__.py defaults.py urls.py wsgi.py data web migrations static css fonts img js templates base base.html pages blank.html __init__.py admin.py apps.py models.py tests.py urls.py views.py I defined the following in my defaults.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'web/templates'), ], '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', ], }, }, ] STATIC_URL = 'web/static/' STATICFILES_DIRS = [ ] my views.py in the "web" app: from django.shortcuts import render # Create your views here. def blank_page(request): return render(request, 'pages/blank.html') urls.py in "web" app: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.blank_page, name='index'), ] urls.py in "base" app: from django.contrib import admin from django.conf import settings import sys admin.site.site_header = os.environ.get('ADMIN_SITE_HEADER') or 'Django administration' urlpatterns = [ path('admin', admin.site.urls), path('', include('web.urls')) ] if settings.DEBUG or 'test' in sys.argv: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns When i use href in my html template in base.html when calling to the root url from localhost i can't get the static file: {% load staticfiles %} <link rel="stylesheet" href="{% static 'css/style.css' … -
Video streaming in Django: can it be done the same way as flask?
The following method from Miguel Grinberg has worked quite well for me in Flask, but I'm migrating my app to Django, and I was wondering if this can be recreated with built-in Django functions? from flask import Flask, render_template, Response from camera import Camera app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) This works quite well because my streams are motionJPEG, and that's what this code was designed for. I'm specifically wondering about the Response(gen(Camera)), mimetype='multipart/x-mixed-replace';boundary=frame') bit. how would I use a generator to place an incoming frame onto a url/route defined in urls.py? -
Is there a gui interface in moviepy to select the start and end time from video to trim it from webpage django
i want a user to select the start and end using some gui in django ! https://i.imgur.com/n40Shf0.png (something like this) For the time being the below mentioned code is what im doing. But it is not user friendly video.html <video controls> <source src="{{ url }}" type="video/mp4"></source> </video> <div class="row"> <form class="col s12" method="POST"> {% csrf_token %} <div class="row"> <div class="input-field col s6"> <input name="start_time" type="text" class="validate"> <label for="start_time">Start Time</label> </div> <div class="input-field col s6"> <input name="end_time" type="text" class="validate"> <label for="end_time">End Time</label> </div> </div> <input type="submit" value="Start" class="btn"> </form> </div> view.py if request.method == 'POST': start_time = int(request.POST.get('start_time')) end_time = int(request.POST.get('end_time')) path = "C:/Users/Macklon/Desktop/summer/cctv_modified/media/" clip = VideoFileClip(path+video).subclip(start_time, end_time) time = datetime.now().strftime("%H.%M.%S") print(clip.to_videofile(path+time+".mp4")) return render(request, "stream/video_list.html", {"url":video_url,"video_name":video_name}) -
RegexField is not passing validation
As a part of my form I'm using a RegexField with the regex pattern r'^\d{3}'. Once the form is submitted, I'm getting a KeyError when security_code = cleaned_data['security'] is reached. I understand that once a form's is_valid() method is called, the cleaned_data dictionary only retains those key/values that pass validation. I'm not understanding however why a user supplied string to this form field is not passing validation in this case. If I switch the RegexField to a CharField, then data for both fields appears in the cleaned data. from django import forms class CreditCardForm(forms.Form): cc_number = forms.CharField() security = forms.RegexField(r'^\d{3}', max_length=3) def clean(self): cleaned_data = super().clean() card_number = cleaned_data['cc_number'] security_code = cleaned_data['security'] if card_number and security_code: if card_number.startswith('4') and len(security_code) != 3: raise forms.ValidationError("Invalid credit card information") class CommentPage(View): def get(self, request): cc_form = CreditCardForm() return render(request, 'member_access/access.html', {'form' : cc_form}) def post(self, request): submitted_cc_form = CreditCardForm(request.POST) if submitted_cc_form.is_valid(): return HttpResponse("Submission successful!") return HttpResponse(reverse('member_access:user_login')) -
Custom permissions issue in DRF
Im working through Django for APIs by William Vincent and came across this authentication code in my Blog API. Basically it makes it so only the author of a blog post can edit/delete it. It seems too short to me, or missing some code. Mostly the "if author == request.user" wouldnt that just return True or False? Where is the code that actually restricts unauthenticated users? I think im missing something fundamental here. Code: # posts/permissions.py from rest_framework import permissions class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): # Read-only permissions are allowed for any request if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the author of a post return obj.author == request.user code here and here is the class it inherits from: class BasePermission(object): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True -
How do I throw a custom error that specifies what field needs to be filled out
How do I specify what field needs to be filled out when giving an error in django. Right now the error is just "this field is required," but how do I change this field into the actual field like password, or username or something. So instead of the normal error: "This field is required" it should give: "Password is required or Email is required," based of the field. Here is the code for the errors: {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p class=" label label-danger"> <div style="text-align: center"> {{ error }} </div> </p> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %}