Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integration of Datastax(Spark, Cassandra, Solr) with a Django website
I am looking for options for Integration of Datastax(Spark, Cassandra, Solr) with a Django(python) website.Has anyone done this implementation and if possible can you please let me know the steps? Thanks, DP -
Best practices for GeoDjango Models
I have a classic GeoDjango model from django.contrib.gis.db import models class Location(models.Model): vessel = models.ForeignKey(Vessel, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, blank=True) point = models.PointField() However usage seems quite clumsy; >>> foo = somevessel.location_set.create(point=Point(5, 23)) >>> foo.point.x 5.0 I still want to store the location as a point but would prefer to interact with the model with more native looking code, something like >>> foo = somevessel.location_set.create(latitude=5, longitude=12) >>> foo.latitude 5.0 Is this against best practices? And is there a simple way to achieve this in Django? -
Django Forms Validation message not showing
I'm trying to restrict file type, size and extension that can be uploaded in a form. The functionality seems to work, but the validation error messages are not showing. I realize that if file._size > 4*1024*1024 is probably not the best way - but I'll deal with that later. Here's the forms.py: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url', 'product_file'] labels = { 'name': 'Product Name', 'url': 'Product URL', 'product_type': 'Product Type', 'description': 'Product Description', 'image': 'Product Image', 'image_url': 'Product Image URL', 'price': 'Product Price', 'product_file': 'Product Zip File', } widgets = { 'description': Textarea(attrs={'rows': 5}), } def clean(self): file = self.cleaned_data.get('product_file') if file: if file._size > 4*1024*1024: raise ValidationError("Zip file is too large ( > 4mb )") if not file.content-type in ["zip"]: raise ValidationError("Content-Type is not Zip") if not os.path.splitext(file.name)[1] in [".zip"]: raise ValidationError("Doesn't have proper extension") return file else: raise ValidationError("Couldn't read uploaded file") ...and here's the view I'm using for that form: def post_product(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ProductForm(data … -
Making EMail address unique in DJango authentication system
I need to make the EMail field of the DJango authentication system unique. I am using Python 3.6.3 and DJango 1.11.7 In order to do so, I found this: Making email field unique with Django User admin When following it, I add the code below to __init__.py under the application folder that represents the authentication. I have also tried adding it to the __init_-.py file for the project. from django.contrib.auth.models import User User._meta.get_field("email")._unique = True Either way, I still get the same error (which is listed below). How do I solve it? TIA C:\WORK\Software\Python64bitv3.6\python.exe manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001F9D03BCEA0> Traceback (most recent call last): File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\WORK\Software\Python64bitv3.6\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen … -
Docker container stops responding to network calls
I've my django application running using gunicorn inside docker container. Randomly, the container stops responding to network calls. Container is up and running. I've checked the stats too for cpu or memory usages and they seem to be fine. My docker version: Client: Version: 1.13.0 API version: 1.25 Go version: go1.7.3 Git commit: 49bf474 Built: Tue Jan 17 09:50:17 2017 OS/Arch: linux/amd64 Server: Version: 1.13.0 API version: 1.25 (minimum version 1.12) Go version: go1.7.3 Git commit: 49bf474 Built: Tue Jan 17 09:50:17 2017 OS/Arch: linux/amd64 Experimental: false Curl command response: * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 8001 (#0) > GET /api/health/ HTTP/1.1 > User-Agent: curl/7.35.0 > Host: localhost:8001 > Accept: */* > No response for above is received. Although ping inside the container works fine. If it's a known problem, solution would be great otherwise what all other parameters / tools I should look into to debug this or fix this ? -
Django celery worker to send real-time status and result messages to front end
In a django app I'm running async tasks and would like to show progress, errors etc to the user. If there are errors, the user should be redirect to a page where additional input or some action is required to fix the problem. What is the best way to communicate from the celery work back to the front end? Here's a basic structure in pseudo code: # views.py from tasks import run_task def view_task(): run_task.delay() return render(request, 'template.html') # tasks.py from compute_module import compute_fct @shared_task def run_task(): result = compute_fct() # how to catch status update messages from compute_module while compute_fct is running?? if result == 'error': handle_error() else: handle_succes() # compute_module import pandas as pd def compute_fct(): # send message: status = loading file df = pd.read_csv('test.csv') # send message: status = computing val = df['col'].mean() if val is None: return {'status':'error'} else: return {'status':'success','val':val} What I would ideally want: compute_module.py module uses python native logger. By separation of duties I want to keep the logging as generic as possible and use the standard python/django loggers. But they don't seem to be designed to send messages to front end. celery task somehow handles the logs and instead of displaying … -
password authentication in django returning false
Jwt broken, tried to do it manually but it keeps returning false In [2]: me = User.objects.all()[1] In [3]: me.password Out[3]: 'password' In [4]: me.username Out[4]: 'cchilders' In [5]: me.email Out[5]: 'cchilders' In [9]: me.check_password('password') Out[9]: False -
Save a form with Django from a view
I need to save a form with Django from my views. I'm geting data from an API and need to save direct on my database: form = NewSubject() #API request form.owner = request.user #Another fields form.teacher = teacher form.group = request.user.group form.save() But I get: Exception Value: NOT NULL constraint failed: subjects_subject.owner_id So I tried by another way: form = NewSubject() #API request subject = form.save(commit=False) subject.owner = request.user #Another fields subject.teacher = teacher subject.group = request.user.group form.save() Now, the form is saved, but I allways get the error: Exception Value: 'NewSubject' object has no attribute 'cleaned_data' -
ImportError: No module named 'posts.urls'
I am new to Django and started making my first Django app using django official tutorial from https://docs.djangoproject.com/en/2.0/intro/tutorial01/. I have installed python3.5.2 and pip 9.0.1, using Ubuntu 16.04, Django version is 2.0. my urls.py file has following code from django.contrib import admin from django.urls import path from django.conf.urls import url, include urlpatterns = [ path('posts/', include('posts.urls')), path('admin/', admin.site.urls), ] If there is anything you can help me work this out. below is the error i am getting after running command - python manage.py runserver here is the error i am getting Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fe20fe92d08> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = … -
CRUD Operation in Python Django REST
I am trying to implement simple CRUD operation in Django Rest. I have successfully created, GET and POST . Now, I want to update the row data with PUT and delete a row with DELETE. Currently, my table looks like :- id item_1 item_2 item_3 date_created date_modified 1 test1 test2 test3 16-12-2017 16-12-2017 2 ex1 ex2 ex3 16-12-2017 16-12-2017 API End point :- localhost/itemlist If we GET localhost/itemlist it returns the list of items. If we POST localhost/itemlist with fields item_1, item_2, item_3 , it creates the row. Now, I want to use PUT to update a particular row. Like, if I want to update the value of item_3 where item_1 == "test1" DELETE should delete the row where item_1 == ex1 urls.py from django.conf.urls import url, include from rest_framework.urlpatterns import format_suffix_patterns from .views import ItemView urlpatterns = { url(r'^itemlists/$', ItemView.as_view(), name="create"), } urlpatterns = format_suffix_patterns(urlpatterns) views.py : from rest_framework import generics from .serializers import itemlistSerializer from .models import itemlist class ItemView(generics.ListCreateAPIView): queryset = itemlist.objects.all() serializer_class = itemlistSerializer def perform_create(self, serializer): serializer.save() serializers.py from rest_framework import serializers from .models import itemlist class itemlistSerializer(serializers.ModelSerializer): class Meta: """Meta class to map serializer's fields with the model fields.""" model = itemlist fields = … -
How is a Python class successfully imported from a seemingly wrong module path?
The following line from the official documentation of the Graphene Django Integration works just fine: from graphene_django import DjangoObjectType Yet, the class DjangoObjectType is defined in graphene_django.types, as the project's source code may show. Moreover, running the following after the above from import inspect print(inspect.getmodule(DjangoObjectType)) yields this output: <module 'graphene_django.types' from '<myVirtualEnv>/lib/site-packages/graphene_django/types.py'> How is this possible? -
In certain cases(when copying text from word) when creating an object I get a Key error
I have a blog site with a form for creating and updating posts. For certain content, when I copy/paste from a word document into the form for creating/editing I get a key error. It doesn't happen for text that is directly written into the form and it doesn't always happen for text that is copied from Microsoft word. I am completely flummoxed about this. Any help would be much appreciated. here is bpaste with the relevant code: https://bpaste.net/show/51c4aa8d7834 -
Configuring 2 Form Views to a URL - django
I have two different FormView classes, and I'm trying to link them to corresponding url patterns as shown below. My urls.py contains: urlpatterns= [ #pattern: /nutrients/ url(r'^main/$', views.MainView.as_view(), name='main'), url(r'^register/$', views.UserFormView.as_view(), name='register'), url(r'^profile/$', views.ProfileFormView.as_view(), name='profile') ] The FormView classes are: class MainView(TemplateView): template_name = 'profile.html' def get(self, request, *args, **kwargs): user_form = UserForm(self.request.GET or None) profile_form = ProfileForm(self.request.GET or None) context = self.get_context_data(**kwargs) context['profile_form'] = profile_form context['user_form'] = user_form return self.render_to_response(context) class UserFormView(FormView): form_class = UserForm template_name = 'profile.html' success_url = '/' def post(self, request, *args, **kwargs): user_form = self.form_class(request.POST) profile_form = ProfileForm() if user_form.is_valid(): user_form.save() return self.render_to_response( self.get_context_data( success=True ) ) else: return self.render_to_response( self.get_context_data( user_form=user_form, ) ) class ProfileFormView(FormView): form_class = ProfileForm template_name = 'profile.html' success_url = '/' def post(self, request, *args, **kwargs): profile_form = self.form_class(request.POST) user_form = UserForm() if profile_form.is_valid(): profile_form.save() return self.render_to_response( self.get_context_data( success=True ) ) else: return self.render_to_response( self.get_context_data( profile_form=profile_form, user_form=user_form ) ) But I keep getting the following error ImportError: Import by filename is not supported. from my import module. Any ideas, leads or solutions would be greatly appreciated because I've been stuck for the past 3 weeks with no working solution. I have read through solutions from https://krzysztofzuraw.com/blog/2016/two-forms-one-view-django.html as well as documentation notes … -
Data model issues related to foreignkey
I'm attempting to get my data model correct, but I keep getting errors the model doesn't exist depending on the order of the models or a SQL error stating there is no foreign or candidate key in the table. I'm struggling to get the User tables coid field to relate to my FacilityDimension model on coid, it keeps trying to relate on formattedusername. I've simplified all models and removed fields that aren't key fields. I'm working with an existing data set except for the User table and QVFormAccessRequest. This is the Custom User table: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) coid = models.CharField(max_length=5) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); def get_short_name(self): return self.username # REQUIRED_FIELDS = "username" def __str__(self): return '%s - %s %s' % (self.username, self.first_name, self.last_name) Here is my Facility Model: class FacilityDimension(models.Model): coid = models.CharField(db_column='Coid',primary_key=True, serialize=False, max_length=5) # Field name made lowercase. class Meta: managed = False db_table = 'Facility_Dimension' CFO table: class QvDatareducecfo(models.Model): cfo_ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='CFO_NTName',max_length=11, primary_key=True) # Field name made lowercase. class Meta: managed = False db_table = 'QV_DataReduceCFO' def … -
Linking stylesheet to Django website on Apache
I'm trying to get my Django website to use a stylesheet that until now worked just fine on a development server. As you can see below, I've been using the static files loader until now but no luck ever since I deployed it on Apache. I'm hardcoding it now but that doesn't work either. I used collectstatic thus I should have all static files I need. I modified Apache config file to serve static files (I followed tutorial). <!-- {% load static %} <link href='{% static "stylesheet.css" %}' rel='stylesheet' type='text/css'>--> <link href='var/www/html/site/static/stylesheet.css' rel='stylesheet' type='text/css'> Any ideas? -
Displaying the last object of nested relationship
i'm having trouble with returning data from many to many relationship between two models. i wan't to show all Currency? objects with their newestTickerobject related to that currency based on thecreated_at` field. i'm wondering how i can create such an output in json? desired output [ { "id": 1, "name": "Bitcoin", "symbol": "BTC", "img": "/media/static/img/currencies/bitcoin_uzSOQkH.png", "tickers": { "rank": 1, "price_dkk": "111239.222648", "market_cap_dkk": 1861795518438, "percent_change_1h": "0.03", "percent_change_24h": "2.44", "percent_change_7d": "46.80", "created_at": "2017-12-12T20:11:49.995851Z" } } ] view class CurrencyGetView(ProtectedResourceView): def get(self, request): currencies = CurrencySerializer(Currency.objects.all(), many=True) return JsonResponse(currencies.data, safe=False) serializers class TickerSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Ticker fields = ('rank', 'price_dkk', 'market_cap_dkk', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d', 'created_at', ) class CurrencySerializer(serializers.HyperlinkedModelSerializer): tickers = TickerSerializer(many=True) class Meta: model = Currency fields = ('id', 'name','symbol', 'img', 'tickers',) models class Ticker(models.Model): rank = models.IntegerField() price_dkk = models.DecimalField(max_digits=20, decimal_places=6) market_cap_dkk = models.BigIntegerField() percent_change_1h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_24h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_7d = models.DecimalField(max_digits=4, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = _('Ticker') def __str__(self): return self.id class Currency(models.Model): symbol = models.CharField(max_length=4, default='BTC', unique=True) name = models.CharField(max_length=20, default='Bitcoin', unique=True) img = models.ImageField(upload_to = 'static/img/currencies', blank=True) is_active = models.BooleanField(default=False) tickers = models.ManyToManyField(Ticker) class Meta: verbose_name_plural = 'currencies' def __str__(self): return self.name -
Django CreateView wit ForeignKey field
I want to add phone number to person. models.py class Person(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) description = models.CharField(max_length=64) class Phone(models.Model): CHOICES = ( ('P', 'personal'), ('C', 'company') ) person = models.ForeignKey(Person) number = models.CharField(max_length=20, unique=True) type = models.CharField(max_length=1, choices=CHOICES) views.py class PersonCreate(CreateView): model = Person fields = ['first_name', 'last_name', 'description'] class PhoneCreate(CreateView): model = Phone fields = '__all__' urls.py url(r'^(?P<pk>\d+)/$', PersonDetailView.as_view(), name = 'detail'), url(r'^(?P<pk>\d+)/addPhone$', PhoneCreate.as_view(), name='phone_create') Now it works like this. I am entering Person detail view (url: 'detail'). Here I have a button Add Address. It redirects me to view (url: 'phone_create') but I still have to choose person. How to create phone number to person from detail view automatically? -
How to override intermediate delete confirmation queryset in admin, I need not show related objects
I have a master model with 1 to 10,000 related objects, when I choose to delete one of them, confirmation delete view takes too long to show and I really do not need to show them in that confirmation in admin. How can I overrides intermediate confirmation queryset? Thanks in advance. -
Django get coupon code and check the boolean value ("is available") in another column for that code
I currently have a model for coupon codes that looks like this [code_number | code_available] class CouponCode(models.Model): code_number = models.CharField(max_length=256,default='') code_available = models.BooleanField() And i am using ajax to send a request to the server to see if the code is still available var couponCode = document.getElementById('id_coupon').value; $.ajax({ url: '/ajax/validate_coupon_code/', data: { 'coupon_code': couponCode }, dataType: 'json', success: function (data) { if (data.is_available) { alert("Coupon code is available."); } else { alert("not available") } } }); Where it stands right now my code checks if the code exists and returns a boolean value whether it exists or not def validate_coupon_code(request): coupon_code = request.GET.get('coupon_code', None) data = { 'is_available': CouponCode.objects.filter(code_number=coupon_code).exists(), #code number 'is_bool': CouponCode.objects.filter(code_number=True).exists() #boolean column } return JsonResponse(data) But what I am trying to do is get the coupon code and check the corresponding field in the code_available column to see if it is still set to True and return that. I feel like im close but i cant seem to get to it ::note the "is_bool" part is where i was trying to make this work -
build_absolute_uri inside model in Django
I'm using Django 2.0 In my application's models.py file I have defined get_absolute_url() to get the absolute URL of the instance. from django.conf import settings from django.http import request class ShortUrl(models.Model): short_key = models.CharField(max_length=25, blank=True) def get_absolute_url(self): reverse_url = reverse('short-url', kwargs={'key': self.short_key}) if hasattr(settings, 'SHORT_URL_HOST'): url_host = settings.SHORT_URL_HOST else: url_host = request.build_absolute_uri("/").rstrip("/") return url_host + reverse_url If is working fine. But in else statement, I want to get complete URI of current host concatenated with the reverse URL. But this gives error as module 'django.http.request' has no attribute 'build_absolute_uri' How can I return full absolute URI with domain name from model's get_absolute_url(self) function? -
custom name of a flash message Django
I'd like to flash a message in a template, which there is a ton of information on, but I haven't seen any way to give it a custom name, which would allow it to have the appropriate class or id for styling. In Laravel: webpage.php @if (session()->has('login_success')) <div id="loginFlash">{{ session('login_success') }}</div> @endif Where login_success is defined before rendering the page So far with Django: webpage.html {% for message in messages %} <div id="{{ message.tags }}"> {{ message }} </div> {% endfor %} But I can't get message.tags to return a SINGLE custom value. For instance: messages.add_message(self.request, messages.INFO, self.request.user.username, 'loginFlash') This returns: <div class="loginFlash info"> username </div> How to remove the second argument? It seems like all of the message methods already specify at least one tag. Thanks so much! -
Google calendar API returning different results than API explorer
I'm using the python client library to make a request to the google calendar API. It works fine but I'm not getting all of the events on the calendar. If I go to the API explorer however, I get everything and in a different format (for example it includes a "summary" key which I need.) Why is that? credentials = ServiceAccountCredentials.from_json_keyfile_name(SERVICE_ACCOUNT_JSON_FILE_PATH, scopes) http_auth = credentials.authorize(Http()) calendar = build('calendar', 'v3', credentials=credentials) currentTime = datetime.datetime.now() maxTime = currentTime + relativedelta(months=+1) #do this to get all events on this day maxTime = maxTime.replace(minute=59, hour=23, second=59) currentTime = currentTime.isoformat('T') + '-06:00' maxTime = maxTime.isoformat('T') + '-06:00' response = calendar.events().list(calendarId="*******", singleEvents=True, maxResults=2500, showHiddenInvitations=True, timeMin=currentTime, timeMax=maxTime).execute() return JsonResponse(response) -
KeyError like model name (django)
I have problem with django-rest-framework (dynamic rest) I have KeyError like model name error https://pste.eu/p/ngrm.html models.py class PersonalData(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) third_name = models.CharField(max_length=30) gin_number = models.IntegerField(unique=True) login = models.CharField(max_length=45) password = models.CharField(max_length=45) phone_number = models.CharField(max_length=75) email = models.EmailField() born_date = models.DateField() passport = models.OneToOneField(Passport) snils = models.OneToOneField(Snils) inn = models.OneToOneField(Inn) drivers_license = models.OneToOneField(DriversLicense) photo = models.ForeignKey(DocumentImages) serializers.py from dynamic_rest.serializers import DynamicModelSerializer from res_employee.models import PersonalData class PersonalDataSerializer(DynamicModelSerializer): class Meta: model = PersonalData name = 'personal_data' fields = '__all__' urls.py from rest_framework import routers from res_employee.views import PersonalDataViewSet router = routers.SimpleRouter() router.register(r'^test', PersonalDataViewSet) urlpatterns = router.urls -
creating extrarow for django queryset
my model Table col_1 col_2 col_3 ################## 1 a 3 2 b 5 3 c 6 i did in view.py results = Item.all() for result in results total=+ result.col_3 i have total=14 How to do same through model method total()? I mean: results.total() will return 14 -
Django - Adding password validations in a ModelForm
I have made a ModelForm in Django for the registration of new user. It has 4 fields (username, email, password, and confirm_password). I want to add some validations for password. For example, if password is shorter than 8 characters or password is similar to the username, then raise an error message. How can I do this? Here is my forms.py file: from django.contrib.auth.models import User from django import forms class user_form(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput) confirm_password = forms.CharField(widget = forms.PasswordInput) class Meta: model = User fields = ['username','email', 'password','confirm_password']