Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a custom log middleware in django?
I want to keep track of every records which are done by the user in my system. For this I used the django admin LogEntry model and created log like this. It works but in my app there are hundreds of view for create,update, delete so this process will be very long so I think writing the middleware will be better idea but I got no idea how can i write logic in middleware for this? Any small help will be greatful. views if form.is_valid(): form.save() # creating log LogEntry.objects.log_action(user_id=request.user.pk, content_type_id=ContentType.objects.get_for_model(Category).pk, object_id=category.pk, object_repr=force_text(category), change_message='Category updated.', action_flag=2 ) return redirect('list_categories') middleware class LogMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response -
I am new to django. I tried using django-taggit-autosuggest but autosuggestion doesn't show up in template. Please help me. Thank you
IN http://127.0.0.1:8000/taggit_autosuggest/list/ -> I am able to see list of tags In my installed apps: INSTALLED_APPS = [ 'taggit', 'taggit_autosuggest', ] urlpatterns = [ url(r'^taggit_autosuggest/', include('taggit_autosuggest.urls')), ] base.html <head> <link href="{% static 'jquery-autosuggest/css/autoSuggest-upshot.css'%}"> <script src="{% static 'jquery-autosuggest/js/jquery.autoSuggest.minified.js'%}"> </script> </head> models.py from taggit_autosuggest.managers import TaggableManager class Discussions(models.Model): txt = models.TextField(blank=True, null=True) tags = TaggableManager() def __str__(self): return self.txt forms.py class DiscussionsForm(forms.ModelForm): class Meta: model = Discussions fields = ('txt', 'tags') def __init__(self, *args, **kwargs): super(forms.ModelForm, self).__init__(*args, **kwargs) self.fields['txt'].widget.attrs['class'] = 'form-control' self.fields['tags'].widget.attrs['class'] = 'form-control' -
Are both the raw queries same for left join?
While working with left join I wanted to have a search string - which would be dynamic. So, I had two queries Query 1: songs = Song.objects.raw(initial_query_string + ''' as sinpl left join songs on sinpl.song_id=id ) as songs left join (select song_id, votes, bool_or(thirdpartyuser_id=%s) as is_requested from (select * from core_priorityrequests where client_id=%s and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes ) as cpr on songs.id=cpr.song_id left join (select core_blocksong.song_id from core_blocksong where core_blocksong.unblock_flag = 'f' and core_blocksong.client_id=%s) as c on c.song_id = songs.id where c.song_id is null and songs.name ilike %s or songs.artist ilike %s limit %s offset %s''', [request.anon_user.id, restaurant.client.id,restaurant.client.id,search_string,search_string,limit,offset,]) Query 2: songs = Song.objects.raw(initial_query_string + ''' as sinpl left join songs on sinpl.song_id=id where explicit=False ) as songs left join (select song_id, votes, bool_or(thirdpartyuser_id=%s) as is_requested from (select * from core_priorityrequests where client_id=%s and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes ) as cpr on songs.id=cpr.song_id where songs.name ilike %s or songs.artist ilike %s limit %s offset %s left join (select core_blocksong.song_id from core_blocksong where core_blocksong.unblock_flag = 'f' and core_blocksong.client_id=%s) as c on c.song_id = songs.id where c.song_id is null''', [request.anon_user.id, restaurant.client.id,search_string,search_string,limit,offset,restaurant.client.id,]) … -
"Cannot read property 'product' of undefined". how to get rid of that problem in javaScript
Want to add products to cart but displaying product is undefined. How to fetch values from data-property and i've also tried $(this).data('data-product) but this one is also not working <button data-product = {{product.id}} data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> var updateBtns = document.getElementsByClassName('update-cart'); for (var i = 0; i < updateBtns.length; i++) { updateBtns[i]=addEventListener('click',function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) }) } -
Is it possible to create a Model that creates sub models in Django?
Please excuse my way of asking the question, but what I mean is this: Is there a way to create a Model in Django, that acts as a "Mother Model" in which I can create sub models.? In my particular example, I am working on a sales website portal in Django, in which I want to create a class called Sales_Process as the "Mother Model" and then Negotiation, Deal and Quote as "Sub Models" that get created using Sales_Process. The user should be able to add more "Steps" to its Sales Process on the admin panel. Thank you so much in advance. -
GeoDjango setup issue
Error: OSError: /usr/local/lib/libgdal.so: caanot open shared object file: No such file or directory unable to load app 0 (mountpoint='') (callable not found or import error) As i see many solutions for this problem but nothings Works for me, From last 2 days i am trying to set up the GeoDjango Project. but did'nt succeed GDAL VERSION: gdal-3.1.0 PROJ VERSION: proj-7.0.1 GEOS VERSION: geos-3.8.1 here below is my django setting library Path:- GDAL_LIBRARY_PATH="/usr/local/lib/libgdal.so" GEOS_LIBRARY_PATH="/usr/local/lib/libgeos_c.so" my Ubuntu Version is 18.04, as When I check this Path, there will be the file present by the name of libgdal.so, libgeos_c.so . But while compile time it will always show the error , No such file or directory According to the Below link Solution I set the Path of inside ld.so.conf , But nOthings works for me GeoDjango - GDAL library giving error As i set the library Path also , in the /etc/ld.so.conf/ , See below :- include /etc/ld.so.conf.d/*.conf /usr/local/lib And After that sudo ldconfig But it will again Show me the Error when I do my docker-compose up Any help will be Highly Appreciated , as I am stuck in this problem from last two days -
Getting rid of useless digits like the 0 in 7.0 or 10.0 in python
I am working with Django and I have a project where I define a Student object that has the fields of grade 1 and grade 2, in this class, I build a function that gives back the grade of the student in question although I encountered a problem, the useless digit when I've got an integer number. That is because I am adding and dividing two float numbers but I want to make the function so that it returns an integer if the result is also one but I don't know how. This is what I've got so far: PS. The class Student inherits from Person, a class that contains credentials about a person like name email and so on but I don't think that really matters here. class Student(Person): grade_1 = models.FloatField(validators=[validate_grade], null=True, blank=True) grade_2 = models.FloatField(validators=[validate_grade], null=True, blank=True) study_field = models.CharField(max_length=50) year = models.PositiveIntegerField(validators=[validate_year], blank=True, null=True) remarks = models.TextField(max_length=300, blank=True, null=True) def get_grade(self): if self.grade_1 is None and self.grade_2 is None: return "No grades yet" elif self.grade_2 is None: return self.grade_1 elif self.grade_1 is None: return self.grade_2 else: return (self.grade_1 + self.grade_2)/2 -
Date detail view error " NoReverse match at orderlist "
I have two models Order and Date. I'm trying to create a view function where a user can click on view URL and will able to see the date details of a specific order.But I'm keep on getting this error "Reverse for 'date-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['dates/(?P[0-9]+)/$']" from order_list.html view URL tag Models: from django.db import models from django.conf import settings from django.contrib.auth.models import User class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) date = models.ForeignKey('Date', null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ) status = models.CharField(max_length = 100, choices = status_choices) def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) URLS: from django.urls import path,include from django.contrib.auth import views as auth_views from .views import order_list,create_order,update_order,delete_order,login_page,logout_page, simple_upload, upload_ingredients, update_profile,dateDetailView app_name = 'accounts' urlpatterns = [ path('dates/<int:pk>/', dateDetailView, name='date-detail') ] Views: def dateDetailView(request, pk): date = Date.objects.get(pk=pk) orders = Order.objects.filter(date = … -
How to filter querysets dynamically with ajax and dropdown menu
I have in my views the following code: def stato_patrimoniale(request): now=datetime.datetime.now() now=now.year ... if Ricavi.objects.count()>0: for year, month, totale in(Ricavi.objects.values_list( 'data_pagamento_acconto__year', 'data_pagamento_acconto__month'). annotate(totale=ExpressionWrapper(Sum(F('acconto')), output_field=FloatField())).values_list('data_pagamento_acconto__year', 'data_pagamento_acconto__month', 'totale')): if id not in incassi.keys() and year == now: incassi[id]=list(defaults) index=month-1 incassi[id][index]=totale The now variable is used to filter my data in the queryset, where my ricavi is the following models: class Ricavi(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True, blank=True) # numero_lavorazione acconto=models.DecimalField() data_pagamento_acconto=models.DateField() Now I want to replace the now variable witha a form that give me the possibility to choose the year and update my views. I have created another app with the following model that with a form gives the possibility to add new year: class Timing(models.Model): reference_year = models.DecimalField(max_digits=4, decimal_places=0, default="2020") Now I want to create a dropdown button that contains all the reference_year filled and when the client click on one of them, the now variable in my def stato_patrimoniale(request): is updated. How could I get this aim? -
Get 404 1668 in CMD and can't connect my css file im html
Here's my script in base.html, the left of the picture is about my tree. I checked the href should be correct and I've load static at very top of the html file. However I still cannot connect the css file anyone can help he here? Thanks! href="{% static 'css/master.css' %}" for refer, please see the picture since idk why I can't post a picture yet, thanks! https://i.stack.imgur.com/JuJvW.png -
Django Tutorial - install the previously cloned copy of Django
I was following this tutorial when this error occurred. I would appreciate it if anyone could tell me what is going wrong here. https://docs.djangoproject.com/en/3.0/intro/contributing/ (djangodev) (base) XXXX@XXXX-MacBook-Air hello_django % python -m pip install -e /path/to/your/local/clone/django/ ERROR: /path/to/your/local/clone/django/ is not a valid editable requirement. It should either be a path to a local project or a VCS URL (beginning with svn+, git+, hg+, or bzr+). -
Use Django Forms just to verify HTML form data and not for rendering
Im my project I have used normal html forms with custom formatting and in various places included CRUD operation using table also. I was wondering is there any way to pass the data from my html forms to Django Forms for validation, as I can't use Django Forms for rendering the forms on my page due to the complexity of the project but I still would like to use the built in validations of Django Forms before I insert the data into Database. -
How to set optional parameters using Django?
I need to set optional parameters using Django. I try a method saw on Stack Overflow but it didn't work. My code : views.py : def get(self, request, id_document, optional_parameters = 'owner'): #code here urls.py : url(r'^getdoclist/(?P<id_document>[^/]+)/$', Get_DocumentList.as_view()), url(r'^getdoclist/(?P<id_document>[^/]+)/(?P<owner>[^/]+)/$', Get_DocumentList.as_view()), it didn't work using this method :( Thanks if you could help me -
child error in inlineformset only display the error if parent has error
i'm trying to display error child message in inline formset , but it show the error if my parent class has an error as well , if the parent has not any error it will save the form!? this my template <form method="POST">{% csrf_token %} {{formset.management_form}} <p> {{form.name| add_class:'col-12 text-center d-inline text-center'}} {% if form.name.errors %} <div class="error mx-auto"> {{form.name.errors}} </div> {% endif %} <div class="col-12 p-0 border-top border-light "> <table class="customeTable col-12 table-responsive-sm info text-center table1 mx-auto mb-2 "> <tbody class="tbody tb1 "> {% for content in formset.forms %} <tr class="p-0 col-12"> <td class=""> {{content.title| add_class:'col-12 text-center'}} {% if content.title.errors %} <div class="error mx-auto"> {{content.title.non_field_errors}} {{content.title.errors}} </div> {% endif %} </td> <td class=""> {{content.note| add_class:'col-12 text-center'}} {% if content.note.errors %} <div class="error mx-auto"> {{content.note.non_field_errors}} {{content.note.errors}} </div> {% endif %} </td> </tr> </tbody> <tfooter> {% if form.number.errors %} <div class="error mx-auto"> {{form.number.errors}} </div> {% endif %} </body> my inline formset MyInlineFormSet = inlineformset_factory( Parent,Child,form=ChildForm,fields=('title','note'),extra=1) but it only display to title and note error if parent (number , name) has an error !? thanks for reply , -
need to make my create post FBV not include the user currently signed in
hi guys so I just started studying django about 1.5 weeks ago so im like really new but I'm finally starting to understand the gist of everything and I wanted to test myself by making a blog app w/o help on tutorials on youtube and I did finish the app (like everything works) but theres one part thats really bugging me. So in my create_post FBV, I wanted to make it so that when the signed in user makes a post, my postform doesn't show the username, but only the title and the content to create. but when I first excluded it, the post wouldn't create since the computer doesn't know who the user is. I tried looking stuff up for the longest time and what to do and not searching on youtube, but the best thing I could find was passing it initial. After i finished everything else I saw someone did it by using a CBV but i only just started reading the source code and documentation for like two days so I'm no where near comfortable with them. This is my code: @login_required def create_post(request): form = PostForm(initial={'author':request.user}) if request.method == 'POST': form = PostForm(request.POST, initial={'author':request.user}) if … -
get count of a Subquery
I want to annotate a count field in my queryset with a subquery filter: My code: module_attempts = Subquery(ModuleProgressAttempt.objects.filter( module_progress__module__id=OuterRef('pk')).only('pk')) real_instances = VirtualClassRoomModule.objects.filter( id__in=[vc.id for vc in vc_classrooms]).annotate( attendees_count=Count(module_attempts), ) Here module_progress__module__id is the id of the current VirtualClassRoomModule of the annotation iteration. The count is basically the length of the ModuleProgressAttempt filtered queryset. Currently the count is always 1 , eventhough the ModuleProgressAttempt.objects.filter( module_progress__module__id=<Current-module-id>) returns more than one object. -
How to query the objects having all the given objects in Many To Many Field?
I was trying to find out one way where I can query all the objects of one table which are having the given objects as ManyToMany Field. Please take below example: class Post(models.Model): title = models.CharField(max_length=50) text = models.CharField(max_length=1000) pub_date = models.DateTimeField('date published') author = models.CharField(max_length=30) mail = models.EmailField() class Tag(models.Model): name = models.CharField(max_length=15) posts = models.ManyToManyField(Post, related_name="tags") Here I want to fetch all the posts having both "python" and "django" in the tag list. I can do that at the python level by fetching all the Posts and then checking their tags. is there any way we can directly fetch it from the DB? Using the DJango QuerySet. Any help would be appreciated!! Thanks in Advance!! -
Authorization Token in Headers not showing up in the Unit Test
I have been unit-testing my views in Django. After searching through Stack Overflow, I figured I can add token in the request header like so: access_token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjMifQ.7oLMOMBCGc46Wt_lQhjwQWoTDh6gJVsTusTAgibv1Kw' class MainPageViewTest(TestCase): def setUp(self): client = Client(HTTP_AUTHORIZATION=access_token) topic1 = Topic.objects.create(name='one') pin = Pin.objects.create(name='one', paragraph1='one') social = Social.objects.create(name='google') user = User.objects.create(nickname='tom', id=3, social_service=social) pin.topic.add(topic1) user.topics.add(topic1) def tearDown(self): Pin.objects.filter(name='one').delete() Topic.objects.filter(name='one').delete() User.objects.filter(nickname='tom').delete() def test_get_main_view_pins(self): response = self.client.get('') self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['pins'][0]['text1'], "one") However, when I test it, it keeps throwing me an error. The error code is 402 which is set by myself to indicate the absence of the header token. Let me show you the decorator through which the request goes: def login_required(func): def wrapper(self, request, *args, **kwargs): header_token = request.META.get('HTTP_AUTHORIZATION') if header_token == None: return JsonResponse({"message": "THE TOKEN IS EMPTY"}, status=402) decoded_token = jwt.decode(header_token, SECRET_KEY, algorithm='HS256')['id'] user = User.objects.get(id=decoded_token) user_id = user.id kwargs['user'] = user kwargs['user_id'] = user_id try: if User.objects.filter(id=decoded_token).exists(): return func(self, request, *args, **kwargs) else: return JsonResponse({"message": "THE USER DOES NOT EXIST"}) except jwt.DecodeError: return JsonResponse({"message": "WRONG_TOKEN!"}, status=403) except KeyError: return JsonResponse({"message": "KEY ERROR"}, status=405) except User.objects.filter(id=decoded_token).DoesNotExist: return JsonResponse({"message": "USER NOT FOUND"}, status=406) return wrapper So, as the decorator proves, 402 means I have no token in the headers. I thought you … -
How to activate an existing virtualenv projects? [Windows, Django, Python]
I'm a beginner to Django and Python, and I've never used virtualenv before. However, I do know the exact commands to activate and deactivate virtual environments (online search). However, this learning course takes time and sometimes I need to split the work over 2 days. When I create a virtualenv today and do some work, I'm unable to access the same virtualenv tomorrow. Even when I navigate to that folder and type in .\venv\Scripts\activate, it says "system cannot find specific path". How can I open already existing virtual environments and the projects within them? Could it be that I need to end my previous session in a certain way for me to access it the next time? -
Choice field for multiple items in a field
If i have 5 diffent sport in Sports then in Intrest model i want to put level to each of those 5 sports seprately,and want to print.How to do it. exampl:cricket=Advance basketball=beginer class Sports(models.Model): Sport=models.CharField(max_length=30) class User(models.Model): user=models.CharField(max_length=30) class Intrest(models.Model): user_name=models.Foreignkey(User,on_delete=models.CASCADE) sport=models.Foreignkey(Sports,on_delete=models.CASCADE) LEVEL=( ('1','Beginer'), ('2','Intermediate'), ('3','Advance'), ('4','Nevel Played'), ) Level=models.CharField(max_length=30,choices=LEVEL) -
Python dictionary to kwargs customization using comprehension
I use comprehension to build a dictionary to apply some filtering in Django dynamically. How can i modify the **filters in order to unpack the dictionary into custom arguments? filters = { key: value for key, value in [date1,date2,date3] } then print(**filters) Instead of date1=date1,date2=date2,date3=date I want: date1_gte=date1,date2_gte=date2,date3_gte=date3 -
Dynamic Django Bootstrap accordion inside for loop not loading
I've been working on an online portfolio and have been using the Django framework to do so. For a projects tab, I pass in an object (projects) containing the details of all my projects and try to show them through in an accordion through a for loop in a dynamic template. But the tabs do not collapse upon clicking them. I have no idea why. {% block content %} <h1>Projects</h1> <div class="accordion accordion-md" id="projectsAccordion" role="tablist" aria-multiselectable="true"> {% for project in projects %} <div class="card"> <div class="card-header" role="tab" id="{{ project.name }}heading"> <a data-toggle="collapse" data-parent="#projectsAccordion" href="#{{ project.id }}" aria-expanded="false" aria-controls="{{ project.name }}"> <h5 class="mb-0"> {{ project.name }} </h5> </a> </div> <!-- card header --> <div id="{{ project.id }}" class="collapse" role="tabpanel" aria-labelledby="{{ project.name }}heading" data-parent="#projectsAccordion"> <div class="card-block px-3 my-2"> <p>{{ project.description }}</p> <p>Timeframe: {{project.start_date}} - {{project.end_date}}</p> {% if project.motivation %} <p>Motivation: {{ project.motivation }}</p> {% endif %} <ul class="list-inline list-unstyled"> {% for tech in project.technologies.all %} <li class="list-inline-item"><p>{{ tech.name }}</p></li> {% endfor %} </ul> <button type="button" href="{{ project.link }}" target="_blank" class="btn btn-primary align-text-top project-link"> Code </button> </div> <!-- card body --> </div> <!-- collapse --> </div><!-- card --> {% endfor %} </div> <!-- accordion --> {% endblock %}``` -
im getting error in install Gdal library on heroku
devs, can anybody please tell me how to install gdal library on Heroku because I'm getting an error while I'm deploying my project on Heroku. I got two errors as follows: ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_s4gq6_a/GDAL/setup.py'"'"'; file='"'"'/tmp/pip-install-_s4gq6_a/GDAL/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info cwd: /tmp/pip-install-_s4gq6_a/GDAL/ Complete output (75 lines): WARNING: numpy not available! Array support will not be enabled /app/.heroku/python/lib/python3.6/distutils/dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running egg_info creating /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info writing /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info/PKG-INFO writing dependency_links to /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info/dependency_links.txt writing top-level names to /tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info/top_level.txt writing manifest file '/tmp/pip-install-_s4gq6_a/GDAL/pip-egg-info/GDAL.egg-info/SOURCES.txt' Traceback (most recent call last): File "/tmp/pip-install-_s4gq6_a/GDAL/setup.py", line 151, in fetch_config p = subprocess.Popen([command, args], stdout=subprocess.PIPE) File "/app/.heroku/python/lib/python3.6/subprocess.py", line 729, in init restore_signals, start_new_session) File "/app/.heroku/python/lib/python3.6/subprocess.py", line 1364, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '../../apps/gdal-config': '../../apps/gdal-config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/pip-install-_s4gq6_a/GDAL/setup.py", line 249, in get_gdal_config return fetch_config(option, gdal_config=self.gdal_config) File "/tmp/pip-install-_s4gq6_a/GDAL/setup.py", line 154, in fetch_config raise gdal_config_error(e) __main__.gdal_config_error: [Errno 2] No such file or directory: '../../apps/gdal-config': '../../apps/gdal-config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File … -
How to add HttpResponseRedirect instead of Response(serializer.data) in PUT request?
How can I override PUT request and instead of returning data add HttpResponseRedirect(reverse('home'))? class ItemAPIView(RetrieveUpdateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsCompanyAdmin, ) serializer_class = ItemSerializer def get_object(self): get_object_or_404(...) -
authentication with simple user
good morning i have a problem with my login function when i submit it didn't login successufuly when i print(user.email) it give me the email of superuser not the email of simple user what is my errors def login(request): context = {} print("ok ok ok ok ok") user = request.user print(user.email) if user.is_authenticated: return render(request, "login.html") print("ok ici") form = LoginForm(request.POST or None) if request.POST: form = LoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.POST['email'] password = form.cleaned_data.POST['password'] user = authenticate(request, email=email, password=password) print(email) if user: login(request, user) if user.user_type == '1': return render(request, "administrateur.html") elif user.user_type == '2': return render(request, "entrepreneur.html") else: print("errors") form = AuthenticationForm() context['login_form'] = form return render(request, "entrepreneur", context)