Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mixed Content warning over http
I've deployed my django rest framework project, it works fine and running on docker, the site is loading over https but images, videos are being loaded over http, and getting Mixed content warning, and browser also showing insecure even if actual site has ssl certifate. I searched for related questions but didn't solve my problem. mysite.conf server { server_name cp.mysite.com; location / { proxy_pass http://127.0.0.1:3180; # docker container listens here proxy_read_timeout 3600s; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/cp.mysite.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/cp.mysite.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = cp.mysite.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name cp.mysite.com www.cp.mysite.com; listen 80; return 404; # managed by Certbot } docker nginx.conf upstream django { server django:5000; } server { listen 80; location / { proxy_pass http://django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-Host $host; client_max_body_size 100M; proxy_redirect off; } location /media/ { alias /usr/share/nginx/media/; } } settings.py SESSION_COOKIE_HTTPONLY = True CSRF_COOKIE_HTTPONLY = True X_FRAME_OPTIONS = "DENY" SECURE_PROXY_SSL_HEADER = … -
Sending files through Socket from Javascript to Django
I am trying to add a feature in my chat app(with Django-channels) that allows users sending files. I am searching for a way that sends files from Javascript to Django. I am using this code in Javascript : // Access the file using fileInput.files[0] var file = fileInput.files[0]; // Read file data using FileReader API var reader = new FileReader(); reader.onload = function(event) { var fileContent = event.target.result; // Send file data via WebSocket var data = { 'command': 'file_included_message', 'file': { 'name': file.name, 'content': fileContent, }, }; chatSocket.send(JSON.stringify(data)); }; reader.readAsDataURL(file); and this code for the consumer(in Django): file_content = file_data['content'] # Base64 encoded file content # Save the file to a temporary location file_content_decoded = base64.b64decode(file_content) # Save the file to a temporary location file_path = os.path.join(settings.MEDIA_ROOT, str(file_name)) with open(file_path, 'wb') as file: file.write(file_content_decoded) -
how to extand two header file in same template before login other and after login another header file
how to extand two header file in same template before login other and after login another header file {% if not request.user.is_authenticated %} {% extends 'portal/v1/base-template.html' %} {% else %} {% extends 'portal/v1/auth/base-template.html' %} {% endif %} -
What is currently a good approach to input masks when using Django model forms?
I'm trying to find out what the best current approach is for input masks in Django when using model forms. I have tried: https://dobsondev.com/2017/04/14/using-jquery-mask-to-mask-form-input/ and https://imask.js.org/guide.html#masked-number but both approaches require that I catch the postback and remove the masking to prevent the model form validation from failing. I can't help but wonder if there is a more eloquent approach/plugin. -
Unit Test for a QuerySet class
I need to unit test a queryset class. I don't have a chance to refactor the class. class MyQuerySet(models.QuerySet): def my_method(self, my_flag=True): ...some logic... return self.annotate(....some logic here...) Since my_method uses self.annotate and import within the method, things get harder. Should I extend this class in unit test class? class MyQuerySetTestCase(TestCase, MyQuerySet): Or should I mock whole QuerySet? @mock.patch("path.to.MyQuerySet") class MyQuerySetTestCase(TestCase, query_set_mock): query_set_mock = QuerySet() How should I approach to this code? -
How to deal with multi-page react application with django?
Has anyone built a multi page react app using ReactJS, Django and Django-REST. I have a good idea on how to achieve it. But the problem i want to build a multi html page app with ReactJS. There will be some endpoints which deliver HTML and others which deliver API data. For delivering HTML, i will use Django templates and for API data i will use DJango-REST. I can make a GET request for an HTML page from a react component with Axios, but the problem is i will need a way to render this HTML response from the frontend. My plan is to rewrite the DOM using document.write(ReturnedHTML). Will there be any potential performance problems with this approach? The returned HTML file will be extremely simple with the only difference being the React files being imported. Have not started yet. Asking for design approaches. -
Any one can help me in Gmail Push notifications
I am woriking on email client app in django i want to enable realtime notification in my app i had use my service accout credential and topic name but when i enable it rase an excepion as preconditation failed this is my code def setup_gmail_push_notification(): SCOPES = ['https://www.googleapis.com/auth/gmail.modify'] credentials = service_account.Credentials.from_service_account_file('automate-38413-b49e282b6eeb.json',scopes=SCOPES) # Create the Gmail API service service = build('gmail', 'v1', credentials=credentials) # Define your webhook URL webhook_url = 'https://1ad5-182-178-213-15.in.ngrok.io/Gamil/Login/gmail-webhook/' # Create the push notification watch request request_body = { 'labelIds': ['INBOX'], # Specify the label(s) to watch for notifications 'topicName': 'projects/automate-83413/topics/gmail-push-notification', 'labelFilterAction': 'INCLUDE', 'pushConfig': { 'pushEndpoint': webhook_url, 'payloadFormat': 'FULL' } } try: # Send the watch request # request = service.users().watch(userId='me', body=request_body) request = {'labelIds': ['INBOX'],'topicName': 'projects/automate-383413/topics/gmail-push-notifications'} service.users().watch(userId='me', body=request_body).execute() response = request.execute() # Handle the push notification setup response print('Gmail push notification setup successful:', response) except Exception as e: # Handle authentication errors return(e) -
Django custom model field do work after save
I've got a custom model field class VaultField(CharField): which is used like: class MyClass: secret = VaultField(max_length=200, blank=True) It should save that field's value to HashiCorp Vault and store the Vault path in the database. That's all nice and easy when the Vault path is static, but what I'd like to do is to build the Vault path based on the model instance ID. But none of the methods from_db_value, to_python, get_prep_value are being called post save and therefore don't have any data about the instance. Is there any way to run field code post save? To get the path /fields/[my-class-name]/[my-class-id]. -
Django admin page has CSS styling? [duplicate]
This is what my Django admin page looks like, it is not a major issue but is quite frustrating.Django admin page with no CSS styling No clue how to fix it or why it started happening, any help would be appreciated ! I tried using python manage.py collectstatic but it did't work. As well as checking my static root which appears fine ( STATIC_URL = "/static/" STATICFILES_DIRS = [BASE_DIR / "static/css"] ) -
I have the following view in Django REST Framework to follow a profile:
my views.py: class FollowView(APIView): permission_classes = [IsAuthenticated] def post(self, request, pk): user_profile = get_object_or_404(Profile, pk=pk) user = request.user if user_profile.user == user: return Response({"error": "You cannot follow your own profile."}, status=status.HTTP_400_BAD_REQUEST) try: follower = get_object_or_404(Profile, user=user) user_profile.follower.add(follower) user_profile.save() except Exception as e: print(e) return Response({"error": "An error occurred while trying to follow this profile."}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response({"success": "You are now following this profile."}, status=status.HTTP_200_OK) my models.py: user= models.OneToOneField(User, on_delete= models.CASCADE) follower= models.ManyToManyField('self', related_name= 'followed_by', blank= True, symmetrical= False) However, when I make a POST request to this view, the follower relationship is not actually saved to the database. The response is successful but the profile is not followed. What am I missing here to properly save the follower relationship? -
Fatal: Reference is not a Tree:
I'm trying to do the bookmarks project of "Antonio Mele - Django 4 by example" and when I get to this command in the shell pip install git+https://github.com/django-extensions/django-extensions.git@25a41d8a3ecb24c009c5f4cac6010a091a3c91c8 I get the error fatal: reference is not a tree: 25a41d8a3ecb24c009c5f4cac6010a091a3c91c8 ERROR: Command errored out with exit status 128: git checkout -q 25a41d8a3ecb24c009c5f4cac6010a091a3c91c8 Check the logs for full command output. Does anyone know why this happens? Note: pip install git+https://github.com/python-social-auth/social-app-django.git@20fabcd7bd9a8a41910bc5c8ed1bd6ef2263b328 worked with no problem but this one just doesn't work -
MySQL ERROR 1045 (28000): Access denied for user
I want to connect to a readonly MySQL-DB to my Django WebAPP. Using Django, MySQL-Workbench or MySQL-Shell always resulted in the same error: ERROR 1045 (28000): Access denied for user 'db-foo-read'@'125.67.891.26' (using password: YES) I was able to connect via HeidiSQL-Client using the same configurations, but only if the library is set to libmysql-6.1.dll Choosing a different .dll always resulted in the same Error 1045 (28000) : Access denied... Django Database Settings: 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db-foo', 'USER': 'db-foo-read', 'PASSWORD': 'djlkwajldljwj1ldwa1', 'HOST': '125.67.891.26', 'PORT': '3306', }, What i tried: changing the libmysql.dll @ C:\Program Files\MySQL\MySQL Server 8.0\lib to the HeidiSQL libmysql-6.1.dll -
Django-Select2 Bootstrap5 Theme
I'm having a problem getting the Django-Select2 Bootstrap5 theme working. The select2 element is displaying the correct field from the DB, and my search function works correctly, it's just the theme aspect that's the problem. select2_init.js $(document).ready(function () { $('#id_school').select2({ theme: 'bootstrap-5', }); }); base.html {% load static %} <!DOCTYPE html> <html lang="en" data-bs-theme="dark"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}{% endblock %}</title> {% block css %} <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'css/custom.css' %}" type="text/css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css"/> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css"/> {% endblock %} </head> <body> {#TODO: Messages#} <div class="container flex-fill pt-5"> {% block content %} {% endblock %} </div> <div class="container"> <footer class="d-flex justify-content-between mt-3 my-4 border-top"> <p>© 2023 Company</p> </footer> </div> {% block js %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.7/dist/umd/popper.min.js" integrity="sha384-zYPOMqeu1DAVkHiLqWBUTcbYfZ8osu1Nd6Z89ify25QV9guujx43ITvfi12/QExE" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.min.js" integrity="sha384-Y4oOpwW3duJdCWv5ly8SCFYWqFDsfob/3GkgExXKV4idmbt98QcxXYs9UoXAB7BZ" crossorigin="anonymous"></script> <script src="{% static 'js/select2_init.js' %}"></script> {% endblock %} </body> </html> register.html {% extends 'base.html' %} {% load static %} {% block css %} {{ block.super }} {{ form.media.css }} {% endblock %} {% block title %} Maths Root: Register {% endblock %} {% block content %} <h1>Create an account</h1> <p>Please use the form below to register.</p> <form method="post"> {% csrf_token %} … -
Django | <title> object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used
I get an error using with using form.save(commit=False) and I cannot figure out what I'm doing wrong. My view looks something like this: views.py def make_electable(request, election_id): election = get_object_or_404(CommissionElection, id=election_id) if request.method == 'POST': form = MakeElectable(request.POST) if form.is_valid(): electable = form.save(commit=False) electable.election.set(election) form.save() forms.py class MakeElectable(forms.ModelForm): class Meta: model = ElectablePerson fields = ['commission',] commission = forms.ModelChoiceField(queryset=Commissie.objects.all(), widget=forms.RadioSelect()) models.py class CommissionElection(models.Model): title = models.CharField(max_length=64) commission = models.ManyToManyField(Commissie) electable_time = DateRangeField() voting_time = DateRangeField() class ElectablePerson(models.Model): commission = models.CharField(max_length=128) election = models.ManyToManyField(CommissionElection) The error I get is: "<ElectablePerson: ElectablePerson object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. I don't see why the object is None. I suspect it has something to do with the manytomanyfield. -
Python developer
First of all, I have learned all main concepts for this programming language(python) After that I have no idea what I should do next. My first question was how I started I had already got answer. At the moment, I am searching how to get requests from websites through the library requests. Now I am wondering how to get a job ??? I tried many times through the internet websites like hh, My question is how easily learn libraries for the python programming language . firstly , My attempts were successfully , because I tried through the replit.com this website provide me fully access to the any labrary . -
Django: dumpdata cannot connect to database
We have a legacy Django application and I am trying to migrate the old app to a new location. The Django version is 2.2. I want to execute dumpdata command to load the output fixture to the new location. The old machine containing the app has default configurations for database i.e. it is using a PostreSQL installed in the same machine and use localhost as address. When running dumpdata, I cannot seem to connect to the database. (venv) software# python manage.py dumpdata > dump.json CommandError: Unable to serialize database: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I also tried the command python manage.py inspectdb to check the connection and it is still not able to connect. I can access the admin page of the app and can view details which is a clear indicator that database is running well and can index what is on the admin page. Why am I getting this error? Could it be I am using wrong machine user? -
Django Rest Framework test not working with DRF APIClient() instance
I am trying to run this Django test of my DRF API endpoint: def test_list_settlements(self): url = reverse('settlements:settlement_api-list', kwargs={'team_slug':'team-slug'}) try: team = Team.objects.get(slug=self.venue.team.slug) # Check if the team from the URL is one of the user's teams except Team.DoesNotExist: raise Http404("No team matches the given slug for this user.") pdb.set_trace() url = reverse('settlements:settlement_api-list', kwargs={'team_slug': 'team-slug'}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 1) self.assertEqual(response.data[0]['id'], self.settlement.id) I set the pdb.set_trace() to see if I could discover anything fishy, and I'm super stumped. With the client, I verified it's properly logged in, and can make calls to any other endpoint successfully returning values. In swagger, if I use this particular end point, of which the reverse() computes to /a/team-slug/settlements/api/ it will return all the settlements correctly in the swagger UI. But when I make the call here with self.client.get(url), it returns a 404. When the pdb.set_trace() starts, I can call the client, and other endpoint calls successfully, but this particular one gives me a 404. I cannot for the life of me figure out why it works in every other situation (being Swagger UI and my dev environment calling from localhost:8000), except my test APIClient() instance, which can successfully call other endpoints in … -
iOS - Django Python - Oauth2
I am trying to build an authentication system for an iOS app. Those are the steps: The user will log via Google oauth and will receive an auth code. iOS app will send to BE this auth code and will exchange with an access token. The BE will create a new token using Django Oauth Toolkit and send back to iOS app and will be stored into keychain. Now the problem I have: When the app launches freshly (previously logged in), I try to use .onAppear and inside I have GIDSignIn.sharedInstance.restorePreviousSignIn, and make a call to Auth server that issued my token to verify if it is still active and renew it using the refresh token. The url that I want to use is /o/introspect/, but is there any way to send the token without sending client id and client secret? I don't want them to be exposed on the iOS app. Or should I create a new url that accepts only the token and verifies? Thank you! -
Django complex data display in template
I am not able to proceed with data display. My db is: type month user First 2023-05-01 1 second 2023-04-01 1 second 2023-05-01 1 First 2023-03-01 1 second 2023-02-01 1 First 2023-02-01 1 second 2023-02-01 1 I want to display this data in template like below: Type First data: user 2023-05-01 2023-04-01 2023-03-01 2023-02-01 1 Yes No Yes Yes Notes: I need to filter last 6 months data for each user, seperate them by type and display whether they were present in each month or note. I have tried regroup with below code: {% regroup datadump by type as ret_type %} <ul> {% for type in ret_type %} <li>{{ type.grouper }} <ul> {% for data in type.list %} <li style="padding-left:20px;">{{data.user}}</li> {% endfor %} </ul> </li> {% endfor %} </ul> I am not able to make table with each month for last six months and show it there. -
save django pghistory tracker
So I want to track some fields in model,therefore I used pghistory this is my code: @pghistory.track( pghistory.BeforeUpdate( "trailer_changed", condition=Q( old__rate__df=F("new__rate"), old__truck__df=F("new__truck"), ), ), fields=["rate", "truck"], model_name="loadtracker", ) but problem is that, if I change only "rate" field, it also saves unchanged value of "truck" field too, then when I want to display changes on front, I get messed up, because there is also unchanged values too, example: if I change only truck field 10 times, in DB result will be like this rate - truck value1 - changed_value1 value1 - changed_value2 value1 - changed_value3 value1 - changed_value4 value1 - changed_value5 value1 - changed_value6 value1 - changed_value7 value1 - changed_value8 ... how can I resolve this? that would be good if I save for unchanged field "None" or null or something else Btw, what is the best practice to save history tracker? for other models I have to track about 10 fields, and is it ok to use like that? or should I create tracker table for every field? -
Searching objects by pressing button in django
I want to create a search form but using button instead of text input. I have a table with categories and each category has a button that leads to subcategories that share this category. When I click the button I somehow want to send name of the category to the view and filter subcategories that will be then rendered to specific template. Here is my template: <table> <thead> <tr> <th>ID</th> <th>Category name</th> <th>Updated at</th> <th>Subcategories</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> {% for category in categories %} <tr> <td>{{category.id}}</td> <td>{{category.name}}</td> <td>{{category.updated|date:"d.m.Y G:i:s"}}</td> <td><a href="#">Subcategories</a></td> <!-- This link should be modified --> <td><a href="#">Edit</a></td> <td><a href="#">Delete</a></td> </tr> {% endfor %} </tbody> </table> So as you can see I have a link 'Subcategories' which should open subcategory page where I will display all subcategories of that category Here is my models.py: class Category(models.Model): name = models.CharField(max_length=100, null=True, blank=True) icon = models.CharField(max_length=50, null=True, blank=True) updated = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) icon = models.CharField(max_length=50, null=True, blank=True) updated = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Subcategories' def __str__(self): return self.name I have no idea how to do this. I'm … -
Dependant permissions in django rest framework
I have a query - Suppose I have a notebooks (Physics,Chemistry,Math,...) and I want to put note in these notebooks by implementing some permissions - If I have permissions to view notebooks and I must be able to see all/some note books in drop down I should be able to add/delete/view note inside any notebook if I am allowed to access that notebook and allowed to add/delete/view note inside that notebook What could be best approach to implement this situation best I walk around stack overflow but did not find any answer regarding it -
Why DRF modelserializers are returning 400 error code instead of 404, for the objects (foreign keys) they couldn't find?
I've been using modelserializers for a while, without noticing that when we enter an out-of-range id in request_body for foreign key fields, drf returns a 400 status code instead of 404! Is it right to do so? How can we change this behavior to return 404 status code in our modelserializers? -
Date Validatind Error When Trying To Migrate From sqllite to mssql in django
from django.db import models from tinymce import models as tinymce_models from django.core.exceptions import ValidationError from django.utils import timezone # Create your models here. class Role(models.Model): roleName = models.CharField(max_length=200) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="Role" def __str__(self): return self.roleName class CMSUser(models.Model): fullName =models.CharField(max_length=200) email =models.CharField(max_length=200) password =models.CharField(max_length=200) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="User" def _str_(self): return self.fullName class Campus(models.Model): campusName = models.CharField(max_length=200,unique=True) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="Campus" def __str__(self): return self.campusName class Group(models.Model): groupName =models.CharField(max_length=200) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="Group" def __str__(self): return self.groupName class Menu(models.Model): menuName =models.CharField(max_length=200) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="Menu" def _str_(self): return self.menuName class Content(models.Model): contentTitle =models.CharField(max_length=200) contentImage =models.ImageField(upload_to='upload/content/') contentData =tinymce_models.HTMLField() menuID =models.ForeignKey(Menu, on_delete=models.CASCADE) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat =models.DateTimeField(db_column='createdAt', blank=True, null=True, auto_now_add=True) … -
How to use the field "email" as "username" in django?
Hello everyone I am new to django and I am creating a project where I created a database with a table "tblusuarios" and managed to insert the necessary data such as name, surname, email, password, however, when I go to make the login I am using the field "mail" as username, but so far fails to make the login. Any advice you can offer me? User model: class TblUsuarios(AbstractBaseUser, models.Model): nombre = models.CharField(max_length=80) apellidos = models.CharField(max_length=80, blank=True, null=True) correo = models.CharField(max_length=80, unique=True) telefono = models.CharField(max_length=11, blank=True, null=True) password = models.CharField(max_length=80) foto = models.ImageField(upload_to='images/') tbl_roles = models.ForeignKey(TblRoles, models.DO_NOTHING, default=1) # object = CustomAccountManager() USERNAME_FIELD = 'correo' #le damos el username por defecto a la tabla REQUIRED_FIELDS=(['nombre']) class Meta: db_table = 'tbl_usuarios' View function: def login_user(request): if request.method == 'POST': correo = request.POST['email'] password = request.POST['password'] user = authenticate(request, username = correo, password = password) print(user) if user is not None: login(request, user) messages.info(request, 'Has ingresado correctamente a la aplicacion!!') return redirect('home') else: messages.error(request, 'Ha ocurrido un error a la hora de iniciar sesion!') return redirect('login') else: context = {} return render(request, 'users/login.html', context) Login form: {% extends "layouts/layout.html" %} {% block content %} {% if user.is_authenticated %} <h2>Ya estas logueado en …