Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to know which sub module are in use with python module?? unable to create requirement.txt for docker image
I am in the process of deploying my flask solution over docker. To deploy my flask solution over docker I need to prepare requirement.txt file. Due to not having information about which version of python module I am using , I am unable to prepare requirement.txt file. As I am using python and flask, so I have version information about flask and python but how to know which submodules required by flask and what's their version ?? -
django view download zip file via HTTP Response
I have a Django view that properly creates a zip folder but I am having trouble serving it to website here is the view def download_shp(request): template="download_shp.html" if request.method=="GET": data=request.GET.get("file_id") ZIPFILE_NAME="" for x,y,z in os.walk(MEDIA_ROOT): for i in y: if data[:-4] in i: shutil.make_archive(os.path.join(MEDIA_ROOT,i),"zip",os.path.join(MEDIA_ROOT,i)) ZIPFILE_NAME=os.path.join(MEDIA_ROOT,i+'.zip') response = HttpResponse(ZIPFILE_NAME, content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename='+ZIPFILE_NAME return response this is a pic of the zip file when I go to download the file it download but i get this error when trying to open it -
Unable to create process django python
I just want to open my Django project and that is copy from another computer. when I install some module in the current computer, its show like that Fatal error in launcher: Unable to create process using '"c:\me\tmsweb~3\backend\env\scripts\python.exe" "D:\myproject 2\backend\env\Scripts\pip.exe" install drf-generators' this python.exe file path is old computer file path and how can I change this file path? I already checked the path in an environment variable and it's correct and points to the current computer. -
Django CORS ORIGIN WHITELIST and ALLOWED_HOST not filtering anything
I'm trying to deploy a Django application (to make REST Apis ) and a React application (who use my Apis ) on the same VPS. I'm setting up CORS for Django, and i still can use my API with postman as i shouldn't since i only allow my VPS IP and localhost. I've tried first with ALLOWED_HOSTS = ["*"] and CORS_ORIGIN_ALLOW_ALL = True and everything went like it should, i could use my API from anywhere but now when i replace "*" with my allowed hosts and set cors origin allow all at False it's like nothing changed. I tried to remove/set http from both allowed hosts and whitelist but it changed nothing. CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ["MYIP","127.0.0.1"] ALLOWED_HOSTS = ["MYIP"] I use python 3.6, django 2.2 and react 16.8. Thank for helping -
Django - empty form cannot be saved in database
I have a form in which, user specifies lawyer-spec and save the data to the database. However I get an error that **null value in column "lawyer_spec" violates not-null constraint** So the data from the form is not processed properly. forms.py class MakeAppointmentForm(forms.ModelForm): first_name = forms.CharField(required=True) class Meta: model = LawyersSpec fields = ['lawyer_spec'] def __init__(self, *args, lawyer_id, pk, **kwargs): super().__init__(*args, **kwargs) lawyer_id_from_kwargs = lawyer_id lawyer_specs = LawyersSpec.objects.filter(lawyer=lawyer_id_from_kwargs) choices = [(spec.lawyer_spec, dict(CASES)[spec.lawyer_spec]) for spec in lawyer_specs] self.fields['lawyer_spec'].choices = choices views.py @method_decorator(user_required, name='dispatch') class MakingAppointmentView(CreateView): template_name = "make_appointment.html" form_class = TestPy.forms.MakeAppointmentForm model = TestPy.models.CalendarAppointmentsReserved def form_valid(self, form): calendar_model = TestPy.models.CalendarFreeSlot.objects.get(pk=self.kwargs.get('pk')) calendar_model.is_available = False calendar_model.save() self.object = form.save(commit=False) self.object.users_id = self.request.user self.object.calendar_free_id = calendar_model self.object.case = self.object.spec self.object.save() return redirect('home') models.py class LawyersSpec(models.Model): lawyer = models.ForeignKey('MyUser', on_delete=models.PROTECT) lawyer_spec = models.SmallIntegerField(choices=CASES) class CalendarAppointmentsReserved(models.Model): calendar_free_id = models.ForeignKey('CalendarFreeSlot', on_delete=models.PROTECT) users_id = models.ForeignKey('MyUser', on_delete=models.PROTECT) case = models.SmallIntegerField(choices=CASES) How can I process the data properly and save in the database? -
How to fix "Forbidden (403) CSRF verification failed. Request aborted." error in django
I am getting this common error in django.i am doing a project in django in a virtual environment folder. here is my setting.py file 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', ] my html file {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Instapic</title> <link rel="stylesheet" href="{% static 'assets/bootstrap/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/Login-Form-Clean.css' %}"> <link rel="stylesheet" href="{% static 'assets/css/styles.css' %}"> </head> <body> <div class="login-clean"> <form method="post"> {% csrf_token %} <h2 class="sr-only">Login Form</h2> <div class="illustration"> <div style="display: none" id="errors" class="well form-error-message"></div> <img src="{% static 'assets/img/logo.jpg' %}"> </div> <div class="form-group"> <input class="form-control" id="username" type="text" name="username" required="" placeholder="Username" maxlength="20" minlength="4"> </div> <div class="form-group"> <input class="form-control" id="email" type="email" name="email" required="" placeholder="Email" maxlength="100" minlength="6"> </div> <div class="form-group"> <input class="form-control" id="password" type="password" name="password" required="" placeholder="Password" maxlength="20" minlength="6"> </div> <div class="form-group"> <button class="btn btn-primary btn-block" id="go" type="submit">Create Account</button> </div><a href="#" class="forgot">Already got an account? Login here ...</a></form> </div> <script src="{% static 'assets/js/jquery.min.js' %}"></script> <script src="{% static 'assets/bootstrap/js/bootstrap.min.js' %}"></script> <script src={% static "assets/js/django-ajax.js" %}></script> <script type="text/javascript"> $(document).ready(function() { $('#go').click(function() { $.post("ajax-sign-up", { username: $("#username").val(), email: $("#email").val(), password: $("#password").val() }, function(data, status){ if (JSON.parse(data).Status == 'Success') { window.location = '/'; } else { $('#errors').html("<span>" + JSON.parse(data).Message + "</span>") … -
Python supervisord error: <class 'ConnectionRefusedError'>
I am trying to run my celery tasks in background using supervisor. I foolowed this article to setup celery and supervisor. However when I try to run below command : sudo supervisorctl reread I am getting following error : error: <class 'ConnectionRefusedError'>, [Errno 111] Connection refused: file: /usr/local/lib/python3.6/dist-packages/supervisor/xmlrpc.py line: 560 My environment details : Python 3.6.5 Django 1.11 (In a virtual environment) supervisord --version 4.0.4 -
How to use validate_unique validation in django form
Anyone know how to use validate_unique validate in django i used in view.py, it raise an validation error, that's good but this error is not showing me properly regist = UserModel(username=uname, email=email, name=name, password=password, status=1) regist.validate_unique() -
How to connect a Django rest framework into android app in testing environment?
I have built a django website for blog posts, and i have built rest APIs for it also so i can use it into my android app, but that website is working in my local host, now i have tried to connect it with an android app using retrofit and tried to make a simple call from the android app but it doesn't work, i just need the very basic steps to connect that local host to my android app and i will take care of retrofit calls and other coding stuff. I have already tried to create retrofit client passing BASE_URL = "http://127.0.0.1:8000" but it doesn't work too private static final String BASE_URL = "http://127.0.0.1:8000/api/"; private static RetrofitClient instance; private Retrofit retrofit; private RetrofitClient(){ retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } public static synchronized RetrofitClient getInstance(){ if(instance == null){ instance = new RetrofitClient(); } return instance; } public Api getApi(){ return retrofit.create(Api.class); } When making a simple call it the onFailure method triggers -
django images cannot be updated from defaults
I have an image upload function in django. However, images cannot be uploaded. The page is redirected to successURL. I don't understand the cause. The view is current because it uses multiple forms. #view def UserEdit(request): if request.method == 'POST': form = forms.UserUpdateForm(request.POST, instance=request.user) subform = forms.ProfileUpdateForm(request.POST, instance=request.user.profile) if all([form.is_valid(), subform.is_valid()]): user = form.save() profile = subform.save() return redirect('person:myaccount', username=request.user) else: form = forms.UserUpdateForm(instance=request.user) subform = forms.ProfileUpdateForm(instance=request.user.profile) return render(request, 'accounts/accounts_edit.html', { 'form': form, 'subform': subform, }) #form class ProfileUpdateForm(BaseModelForm): class Meta: model = profile fields = ('first_name','last_name','birthday','image',) class UserUpdateForm(BaseModelForm): class Meta: model = User fields = ('username','email',) #model class profile(models.Model): image = models.ImageField(upload_to='profile/',default='profile/default.jpg') #html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="text-center col-lg-6 col-md-6 col-sm-10 mx-auto"> <div class="form-group"> {{ form }} </div> <div class="form-group"> {{ subform }} </div> <button type="submit" class="fadeIn fourth btn btn-light">Submit</button> </div> </form> -
initializing Foreign Key models in code has no effect
I have a foreign key model like this: invite_discount_owner = models.ForeignKey('self', verbose_name='aaa', null=True, blank=True, on_delete=models.CASCADE, related_name='invited_customer') and in some part of my code, I want to initialize it with a correct data type: request.user.invite_discount_owner = discount_owner but it has no effect and this field stays empty! -
django: while files are preparing for download , show loading animation
I use Django , When files are preparing for download , I want to show loading circle animation , How can i understand files preparing finish time ? I try this code but its useless because it calculate is long for response request.start_time = time.time() print("start") print(request.start_time) print("final") print(time.time()) total = time.time() - request.start_time print("total unclear") print(total) print("total") print(int(total * 1000)) No error -
How to print the string value of a choices field
I have an integer field that provides 3 choices for a blog post: class Post(models.Model): STATUS_DRAFT = 0 STATUS_PUBLISHED = 1 STATUS_DELETED = 2 STATUS_CHOICES = ( (STATUS_DRAFT, 'draft'), (STATUS_PUBLISHED, 'published'), (STATUS_DELETED, 'deleted'), ) status = IntegerField(choices=STATUS_CHOICES, default=STATUS_DRAFT) When I render this in a template with {{ blog.status }} it prints the integer value (0, 1, 2). How can I call it to print the string value (draft, published, deleted)? -
Authorization model for REST API for ReactJs and Django
Hi I am trying to create an rest api using Django Framework and there is independent frontend part of ReactJs .Basically Reactjs will consume the Django rest_api .But I want to have authentication also provided to our api.So how can we proceed with it.Can anyone please explain? -
1054, "Unknown column 'user_account_id_fk_id' in 'field list'"
I focusing in insert log table that relate with user account and i have got a problem about inserting new row using django in views file. So it may came from my models. I Have no idea how to fixed this problem. I was change both of models settings and in views file by change queryset using get all and filter Models file class user_account(models.Model): user_account_id = models.IntegerField(primary_key=True, max_length=11, unique=True, null=False) username = models.CharField(max_length=50) password = models.CharField(max_length=255) display_name = models.CharField(max_length=100) mobile_no = models.CharField(max_length=50) email = models.CharField(max_length=255) is_delete = models.SmallIntegerField(max_length=1) create_date = models.DateTimeField() create_user_account_id = models.IntegerField(max_length=11) modify_date = models.DateTimeField() modify_user_account_id = models.IntegerField(max_length=11) delete_date = models.DateTimeField() delete_user_account_id = models.IntegerField(max_length=11) last_login = models.DateTimeField() is_authenticated = models.SmallIntegerField(max_length=1) class Meta: app_label = 'users' db_table = 'user_account' class user_account_log(models.Model): user_account_log_id = models.BigIntegerField(primary_key=True, max_length=20) user_account_id_fk = models.ForeignKey(user_account, unique=True, on_delete=models.DO_NOTHING, related_name = 'user_acc') action = models.CharField(max_length=100) title = models.CharField(max_length=100) description = models.TextField() refer_id = models.CharField(max_length=50) refer_table = models.CharField(max_length=50) class Meta: app_label = 'users' db_table = 'user_account_log' Views file user_log = user_account_log() user_log.action = "aaaa" user_log.title = "" user_log.description ="" user_log.refer_id = "AAAA" user_log.refer_table = "" user_log.user_account_id_fk_id = str(user_account.objects.get(user_account_id=request.user.user_account_id).user_account_id) # Save user_log.save() -
Django OperationalError: Parser Stack Overflow
I have a multi-page form for an accounting app in my project. The first page allows the user to select multiple creditors, the second to select multiple debtors, and the third generates a table so they can input the credit from each debtor to each creditor. Each page of the form passes the selected data to the next page via POST (using the UUID of the accounts in question), and the final page has the "submit" button that actually generates the transaction object in the database. When I use the form with a large number of debtors or creditors selected, I get an "OperationalError: Parser Stack Overflow." From the only other question on this topic I can find (django.db.utils.OperationalError: parser stack overflow) it looks like I need to either find a slimmer way of transmitting that data (perhaps by creating an "intermediary" model in the database to hold the data from each page so that each page need only be passed a single object). However, as you can see from the error below, it is the "account_list" that causes the overflow. This list comes from the query: Account.objects.all().order_by('type') So I am unsure that this would solve the problem. Alternatively, I … -
DRF formatting XLSX content
I am trying to set a different color on every second row in XLSX file. From the documentation I see that I can pass some conditions using body property or get_body() method, but this only allows me to set somewhat "static" conditions. Here is the ViewSet config responsible for rendering the XLSX file: class MyViewSet(XLSXFileMixin, ModelViewSet): def get_renderers(self) -> List[BaseRenderer]: if self.action == "export": return [XLSXRenderer()] else: return super().get_renderers() @action(methods=["GET"], detail=False) def export(self, request: Request) -> Response: serializer = self.get_serializer(self.get_queryset(), many=True) return Response(serializer.data) # Properties for XLSX column_header = { "titles": [ "Hostname", "Operating System", "OS name", "OS family", "OS version", "Domain", "Serial number", "Available patches", ], "tab_title": "Endpoints", "style": { "font": { "size": 14, "color": "FFFFFF", }, "fill": { "start_color": "3F803F", "fill_type": "solid", } } } body = { "style": { "font": { "size": 12, "color": "FFFFFF" }, "fill": { "fill_type": "solid", "start_color": "2B2B2B" }, } } -
form.is_valid() not working when using django forms for updating information to the databse
So I wanna be able to update information of a router in the database using a form, I wanna have a form pre-populated with that specific router details. The problem is that form.is_valid() is not working I tried using {{ form.errors }} {{ form.non_field_errors }} and print(form.errors) but none of them worked views.py (incomplete) def info_router(request, pk): rout = Routers.objects.get(sn=pk) if request.method == 'GET': # Insert the info in forms form = UpdateRouter() rout = Routers.objects.get(sn=pk) args = {'router': rout} return render(request, "router_info.html", args) if request.POST.get('delete'): # Delete router rout.delete() messages.warning(request, 'Router was deleted from the database!') return redirect("db_router") if request.method == 'POST': #Updating the form form = UpdateRouter(instance=Routers.objects.get(sn=pk)) print(form) print(form.errors) if form.is_valid(): data = UpdateRouter.cleaned_data mac = data['mac'] print(mac) return HttpResponseRedirect('db_router') else: print("Invalid form") return render(request, "db_router.html", {'form': form}) forms.py class UpdateRouter(ModelForm): class Meta: model = Routers fields = ['model', 'ip_addr', 'name', 'sn', 'mac'] template <form class="form-horizontal" action="" method="post"> {% csrf_token %} <div class="form-group"> <!-- Form with the router details --> <label class="control-label col-sm-2" for="text">Serial number:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="text" name="sn" value="{{ router.sn }}" readonly> </div> </div> <div class="form-group"> <label class="control-label col-sm-2" for="text">Model:</label> <div class="col-sm-10"> <input type="text" class="form-control" id="text" value="{{ router.model }}" name="model" readonly> </div> </div> <div … -
Django HoneyPot Change Password Issue
I would appreciate if you could give me any clue! As I don't have experience in this, probably I've misunderstood smth. I'm using honeypot, more specifically honeypot.middleware.HoneypotMiddleware with HONEYPOT_FIELD_NAME in my API (settings.py). As for the moment it's enough, I'm using the basic implementation for login, password change, reset from django.contrib.auth. In login I did a small customization so I added it in the url (authentication_form=CustomAuthenticationForm). So I don't konw what I'm missing because the login page works (it is also a form), but the password change, reset ones are returning 400 Bad Request. Honey Pot Error (honey_pot_fieldname). Request aborted. django: 2.1.2 django-honeypot: 0.7.0 Thanks in advance! -
django not responding via submit in frontend using post request in form
front end is not giving response to djangi function call via forms <form method="post" action="choose" class="login100-form validate-form" id="loginFrm"> {% csrf_token %} <span class="login100-form-title p-b-59"> Sign In </span> <div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex@abc.xyz"> <!-- <span class="label-input100">Email</span> --> <input class="input100" type="text" name="email" placeholder="Email address..."> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input" data-validate = "Password is required"> <!-- <span class="label-input100">Password</span> --> <input class="input100" type="text" name="pass" placeholder="Password"> <span class="focus-input100"></span> </div> <div class="flex-m w-full p-b-33"> <div class="contact100-form-checkbox"> <span class="txt1"> <a href="javascript:void(0)" class="txt2 hov1" id="goForgot"> Forgot Password? </a> </span> </div> </div> <div class="container-login100-form-btn"> <div class="wrap-login100-form-btn"> <div class="login100-form-bgbtn"></div> <button type="submit" class="login100-form-btn"> Sign In </button> </div> <a href="javascript:void(0)" class="dis-block txt3 hov1 p-r-30 p-t-10 p-b-10 p-l-30" id="goSignup"> Sign Up <i class="fa fa-long-arrow-right m-l-5"></i> </a> </div> </form> -
Django - How to use the exact same clean() method on multiple forms
I have multiple forms that uses the same clean() and clean_<field_name>() methods. My problem is that i write the exact same code for all my forms, something like: forms.py class FirstForm(forms.Form): ... clean(): <long clean code that repeats on all forms> clean_field1(): <clean_field1 code that repeats on all forms> class SecondForm(forms.Form): ... clean(): <long clean code that repeats on all forms> clean_field1(): <clean_field1 code that repeats on all forms> class ThirdForm(forms.Form): ... clean(): <long clean code that repeats on all forms> clean_field1(): <clean_field1 code that repeats on all forms> So my question is what it the best approach to write those clean() methods on 1 place and just call them on different forms? -
Upload multiple images Django admin and associate to another model
I am creating a property app and want to associate multiple images to one property. I want the images to be uploaded when the property is being created in the admin panel. Also, I want to return the array containing URLs of the images associated with the property when I return the properties details from the endpoint. How do I do this? Below is the code I have so far. # models.py from django.contrib.postgres.fields import ArrayField from django.db import models from django import forms class ChoiceArrayField(ArrayField): """ A field that allows us to store an array of choices. Uses Django's Postgres ArrayField and a MultipleChoiceField for its formfield. """ def formfield(self, **kwargs): defaults = { 'form_class': forms.MultipleChoiceField, 'choices': self.base_field.choices, } defaults.update(kwargs) # Skip our parent's formfield implementation completely as we don't # care for it. # pylint:disable=bad-super-call return super(ArrayField, self).formfield(**defaults) class Property(models.Model): DURATION = ( ('Short Term', 'Short Term'), ('Long Term', 'Long Term') ) RENT_TYPE = ( ('Shared Home', 'Shared Home'), ('Entire Home', 'Entire Home') ) FURNISHING = ( ('Fully Furnished', 'Fully Furnished'), ('Semi Finished', 'Semi Furnished'), ('Unfurnished', 'Unfurnished') ) AMENITIES = ( ('Free Parking', 'Free parking space'), ('Clean Water and Treated Water', 'Clean and Treated Water'), ('Security', 'Security'), ('Ensuite', … -
Using supervisord for Celery for duplicate django projects
Goal On my server, I have two "identical" Django projects: one for staging and one for production (they both have their own MySQL database). I am trying to set up Celery using supervisord for both of these projects but I can't manage to do it. What I currently have Production: project-production/project/settings.py # Celery BROKER_URL = 'redis://localhost:6379/0' CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_DEFAULT_QUEUE = 'production' CELERY_DEFAULT_ROUTING_KEY = 'production' Production: project-production/project/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='redis://localhost:6379/0') app.config_from_object('project.settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Production: project-production/supervisord.conf [program:celeryd0] directory=/absolute/path/to/project-production command=/absolute/path/to/project-production-virtualenv/bin/celery worker --app=project -l info stdout_logfile=/absolute/path/to/project-production-logs/celeryd.log stderr_logfile=/absolute/path/to/project-production-logs/celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 Staging: project-staging/project/settings.py # Celery BROKER_URL = 'redis://localhost:6379/1' CELERY_BROKER_URL = 'redis://localhost:6379/1' CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERY_DEFAULT_QUEUE = 'staging' CELERY_DEFAULT_ROUTING_KEY = 'staging' Staging: project-staging/project/celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='redis://localhost:6379/1') app.config_from_object('project.settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Staging: project-staging/supervisord.conf [program:celeryd1] directory=/absolute/path/to/project-production command=/absolute/path/to/project-production-virtualenv/bin/celery worker --app=project -l info stdout_logfile=/absolute/path/to/project-staging-logs/celeryd.log stderr_logfile=/absolute/path/to/project-staging-logs/celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=600 What I tried Using different BROKER_URL for redis (/0 & /1), setting different CELERY_DEFAULT_QUEUE and CELERY_DEFAULT_ROUTING_KEY for each project, launching celery with or without supervisord. The problem Everything works fine when I use the supervisord command for … -
How to customize the "description" of the manytomany inline in the admin panel
I have those extremely simple models: class Activity(BaseModel): name = models.CharField(max_length=200, blank=True, null=True) class Person(BaseModel): activities = models.ManyToManyField('Activity', related_name='persons') In the admin.py I've made an inline for this and it works, like this: class PersonActivitiesInlineAdmin(admin.StackedInline): model = Profession.persons.through fk_name = 'person' class PersonAdmin(admin.ModelAdmin): inlines = (PersonActivitiesInlineAdmin, ) My problem is that the string describing the inline, in the admin interface, is like Profession: Person_activities object (831) Profession: Person_activities object (832) Profession: Person_activities object (835) Profession: Person_activities object (838) So how to customize the "description" of the manytomany inline in the admin panel? -
form is not valid to django why
the model: class authentifier(models.Model): matricule =models.CharField(max_length=254, blank=True, null=True) password = models.CharField(max_length=254, blank=True, null=True) nom =models.CharField(max_length=254, blank=True, null=True) prenom=models.CharField(max_length=254, blank=True, null=True) statut = models.CharField(max_length=254, blank=True, null=True) the code forms.py for authentification : from django import forms class UserLoginForm(forms.Form): print(666) matricule = forms.CharField(required=True , widget=forms.TextInput) password = forms.CharField(required=True , widget= forms.PasswordInput) template html : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width , initial- scales=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <body> <form> <form method="POST"> {% csrf_token %} <tr><th><label for="id_matricule">Matricule:</label></th><td><input type="text" name="matricule" id="Matricule"></td></tr> <tr><th><label for="id_password">Password:</label></th><td><input type="password" name="password" id="password"></td></tr> <input type="submit" value="Se Connecter"> </form> </body> </html> I found that form.is_valid() = false - but i have no idea how to get the reason WHY... i need to do authentification with matricule and password