Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named all apps in my settings.py
I have been trying to set up my website on Pythonanywhere, but unfortunately it says 'No module named dal' where dal is a installed app in settings.py,if i remove dal from the installed apps it goes to the next one in the list. i don't know why its bringing this errors because i used pip install -r requirements.txt to install all the apps in the settings.py and they working perfect in production.This are my files /var/www/bolaji90_pythonanywhere_com_wsgi.py import os import sys path = '/home/bolaji90/prissue-consumer-complaints' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'corrfeed4.settings' from django.core.wsgi import get_wsgi_application from django.contrib.staticfiles.handlers import StaticFilesHandler application = StaticFilesHandler(get_wsgi_application()) File directory SERVER ERROR LOG 2016-10-18 17:13:36 Traceback (most recent call last): 2016-10-18 17:13:36 File "/bin/user_wsgi_wrapper.py", line 154, in __call__ 2016-10-18 17:13:36 2016-10-18 17:13:36 app_iterator = self.app(environ, start_response) 2016-10-18 17:13:36 File "/bin/user_wsgi_wrapper.py", line 170, in import_error_application 2016-10-18 17:13:36 2016-10-18 17:13:36 raise e 2016-10-18 17:13:36 ImportError 2016-10-18 17:13:36 : 2016-10-18 17:13:36 No module named dal 2016-10-18 17:13:36 2016-10-18 17:13:37 Traceback (most recent call last): 2016-10-18 17:13:37 File "/bin/user_wsgi_wrapper.py", line 154, in __call__ 2016-10-18 17:13:37 2016-10-18 17:13:37 app_iterator = self.app(environ, start_response) 2016-10-18 17:13:37 File "/bin/user_wsgi_wrapper.py", line 170, in import_error_application 2016-10-18 17:13:37 2016-10-18 17:13:37 raise e 2016-10-18 17:13:37 ImportError 2016-10-18 … -
Manual Forms in Django adding in text
I am straying away from DRY forms for once but am struggling to define my forms to be style with bootstrap accordingly. I have setup my fields as follows: <div class="form-group"> {{ form.name.errors }} <label for="{{ form.name.id_for_label }}">Analysis Name:</label> <input class="form-control" for="{{ form.name }}"> </div> However, even though this seems to work, I am constantly getting the following "> printed after each field. Is this the best way to handle manual forms in Django? -
Correct way to define a RetrieveAPIView view class
After reading the documentation of django-rest-framework, this is what I have done: serializers.py: class UserRegistrationDetailSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( User._meta.pk.name, ) views.py class RegistrationDetailView(generics.RetrieveAPIView): serializer_class = serializers.UserRegistrationDetailSerializer permission_classes = ( permissions.AllowAny, ) lookup_field='email' def get_queryset(self): email = self.kwargs.get('email') user = get_object_or_404(User, email = email) if user: if settings.get('SEND_ACTIVATION_EMAIL'): self.send_activation_email(user) elif settings.get('SEND_CONFIRMATION_EMAIL'): self.send_confirmation_email(user) return User.objects.all() urls.py: urlpatterns = [ url(r'^register/(?P<email>\w+|[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/$', views.RegistrationDetailView.as_view(), name='register_detail'), ] I have defined def get_queryset(self): instead of just providing the queryset variable because I wanted to send an email to the user if the user exists in the database. It works as required but since I am new to djngo-rest-framework, I am not quite sure if this is the right way to do this. Am I doing anything unnecessary here? -
Weird behavior in Django queryset union of values
I want to join the sum of related values from users with the users that do not have those values. Here's a simplified version of my model structure: class Answer(models.Model): person = models.ForeignKey(Person) points = models.PositiveIntegerField(default=100) correct = models.BooleanField(default=False) class Person(models.Model): # irrelevant model fields Sample dataset: Person | Answer.Points ------ | ------ 3 | 50 3 | 100 2 | 100 2 | 90 Person 4 has no answers and therefore, points With the query below, I can achieve the sum of points for each person: people_with_points = Person.objects.\ filter(answer__correct=True).\ annotate(points=Sum('answer__points')).\ values('pk', 'points') <QuerySet [{'pk': 2, 'points': 190}, {'pk': 3, 'points': 150}]> But, since some people might not have any related Answer entries, they will have 0 points and with the query below I use Coalesce to "fake" their points, like so: people_without_points = Person.objects.\ exclude(pk__in=people_with_points.values_list('pk')).\ annotate(points=Coalesce(Sum('answer__points'), 0)).\ values('pk', 'points') <QuerySet [{'pk': 4, 'points': 0}]> Both of these work as intended but I want to have them in the same queryset so I use the union operator | to join them: everyone = people_with_points | people_without_points Now, for the problem: After this, the people without points have their points value turned into None instead of 0. <QuerySet [{'pk': 2, … -
Simple docker example only appears to expose db container and not web
I clone this repo (it's pretty much based on docker docs here) and run docker-compose up. Docker builds the 2 containers and I see the output from db_1 (psql looks to be completely ready) but nothing at all from web_1, no output whatsoever. I go to my host IP + 8000 and nothing is running there. I am using docker toolbox for mac. It's pretty much the simplest possible example of using Docker - any idea why I'm not seeing anything from my Django container? Thanks in advance, -
Import error in django REST serializer
I'm have 3 models: Album, Photo and standard User. Album have foreign key to user and photo have foreign key to album and user. And i want to UserSerializer have nested Serializers for Albums and photos, but it's seems to be cycle and Django REST give error: File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\unittest\loader.py", line 428, in _find_test_path module = self._get_module_from_name(name) File "C:\Users\User\AppData\Local\Programs\Python\Python35-32\lib\unittest\loader.py", line 369, in _get_module_from_name import(name) File "D:\code\active\photo-hub\photo-hub\api\tests.py", line 8, in from .serializers import RegisterSerializer File "D:\code\active\photo-hub\photo-hub\api\serializers.py", line 14, in from api.serializers import AlbumSerializer, PhotoSerializer ImportError: cannot import name 'AlbumSerializer' But how can i get urls of user's albums and photos without nesting Serializers? serializers.py: from django.contrib.auth.models import User from rest_framework import serializers from rest_framework import mixins from api.models import Album, Photo import api class UserSerializer(serializers.HyperlinkedModelSerializer): albums = AlbumSerializer(required=False) photos = PhotoSerializer(required=False) class Meta: model = User fields = ('url', 'pk', 'username', 'email', 'albums', 'photos') class PhotoSerializer(serializers.HyperlinkedModelSerializer): album = serializers.HyperlinkedRelatedField(view_name='album-detail', queryset=Album.objects, required=False) user = serializers.HyperlinkedRelatedField(view_name='user-detail', queryset=User.objects, required=False) class Meta: model = Photo fields = ('url', 'pk', 'name', 'image', 'creation_date', 'user', 'album',) read_only_fields=('creation_date', ) class AlbumSerializer(serializers.HyperlinkedModelSerializer): user = serializers.HyperlinkedRelatedField(view_name='user-detail', queryset=User.objects, required=False) photos = serializers.HyperlinkedRelatedField(view_name='photo-list', queryset=Photo.objects, many=True, required=False) class Meta: model = Album fields = ('url', 'pk', 'name', 'creation_date', 'user', 'photos',) read_only_fields=('creation_date',) models.py: from django.db … -
Django ORM - Create an alias of select_retaled field in values()
I am trying to rename the unreadable field agreement_vendors_merchandise_list__merchandise_unique_id into some_alias using extra, but get Uknown column "agreement_vendors_merchandise_list__merchandise_unique_id" error, and yet if I don't use any alias, all is ok. What am I doing wrong ? Can I use extra with select_selected whatsoever ? orders_qs = Order.objects.select_related('agreement_vendors_merchandise_list')\ .extra(select={'some_alias': 'agreement_vendors_merchandise_list__merchandise_unique_id'})\ .values('some_alias') The model: class Order(models.Model): agreement_vendors_merchandise_list = models.ForeignKey(AgreementVendorsMerchandiseList, on_delete = models.CASCADE, related_name = 'agreement_vendors_merchandise_list') class AgreementVendorsMerchandiseList(models.Model): merchandise_unique = models.ForeignKey(MerchandiseUnique, on_delete = models.CASCADE,related_name = 'pricelist_merchandise_unique') UPDATE: This code (without alias) works perfect: orders_qs = Order.objects.select_related('agreement_vendors_merchandise_list')\ .values('agreement_vendors_merchandise_list__merchandise_unique_id') -
How do a job at given time
I have to do it using Schedule, I'm using django def new_job(request): print("I'm working...") file=schedulesdb.objects.filter (user=request.user,f_name__icontains ="mp4").last() file_initiated = str(f_name) os.startfile(f_name_initiated) I need to do it with filtered time in db GIVEN DATETIME = schedulesdb.objects.datetimes('request_time', 'second').last() schedule.GIVEN DATETIME.do(job) -
How to cascade an update in a one-to-many relationship?
I think this is best explained with an example. class GrandParent(models.Model): pass class Parent(models.Model): grandparent = models.ForeignKey(GrandParent, null=True, blank=True, default=None) class Child(models.Model): parent = models.ForeignKey(Parent, null=True, blank=True, default=None) grandparent = models.ForeignKey(GrandParent, null=True, blank=True, default=None) So we have three classes. Child has a foreign key to Parent and GrandParent, and Parent has a foreign key to GrandParent. In the Django Admin area I click on a Parent record (P1) and set its foreign key to a GrandParent record (GP1). I would like this to cascade to all the Child records. In other words, every Child record which already has a foreign key to P1 should automatically get a foreign key to GP1. Is there a Django way to do this? Thank you. -
Upload image in Django Rest Framework
I try to upload image in DRF. When I send PUT request in Postman, it's updated. But I try in AngularJS, it returns current image url and doesn't change anything. Following browser photo in Angular site. It says "Success uploaded" but it returns current image URL. views.py class AvatarUploadAPIView(generics.CreateAPIView, mixins.UpdateModelMixin,): queryset = UserProfile.objects.all() serializer_class = AvatarUploadSerializer parser_classes = (MultiPartParser,) lookup_field = 'user_id' def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) serializers.py class AvatarUploadSerializer(ModelSerializer): class Meta: model = UserProfile fields = [ "avatar", "id" ] models.py class UserProfile(TimeStampModel): avatar = models.ImageField( upload_to="avatars", max_length=255, blank=True, default=DEFAULT_USER_AVATAR, verbose_name=_("Avatar") ) I also tried FileUploadParser but it doesn't. How to solve it? -
django rest framework: use per object permissions in a HyperlinkedRelatedField
I have problems filtering on HyperLinkRelatedField by objects permission. It looks like the Hiperlinkrelatedfield does not have objects permissions into account. This is a simplified case of mi real code. I have two models: class Assay(models.Model): assay_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, unique=True) class Meta: db_table = 'assay' permissions = (('view_assay', 'View Assay'),) class AssayProp(models.Model): assay_prop_id = models.AutoField(primary_key=True) assay = models.ForeignKey(Assay, related_name='props') type = models.ForeignKey(Cvterm) value = models.CharField(max_length=255) class Meta: db_table = 'assayprop' unique_together = ('assay', 'type') permissions = (('view_assayprop', 'View AssayProp'),) In the serializer I woul like to have a props serializer in Assay to return links to AssayProp: class AssayPropSerializer(serializers.ModelSerializer): class Meta: model = AssayProp class AssaySerializer(serializers.ModelSerializer): props = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='assayprop-detail') class Meta: model = Assay The viewsets: class AssayViewSet(ModelViewSet): # lookup_field = 'uniquename' queryset = Assay.objects.all() serializer_class = AssaySerializer permission_classes = (CustomObjectPermissions,) filter_backends = (DjangoObjectPermissionsFilter, DjangoFilterBackend) filter_class = AssayFilter class AssayPropViewSet(ModelViewSet): # lookup_field = 'uniquename' queryset = AssayProp.objects.all() serializer_class = AssayPropSerializer permission_classes = (CustomObjectPermissions,) filter_backends = (DjangoObjectPermissionsFilter, DjangoFilterBackend) I am running a test to check that the props that are returned by the props field of the Assay serializer are the ones that the user is granted to view. When the test is run the user … -
compose file with intermediate container do migration django
I have read the about how to control docker container by waiting response from the other by listening to port. But it is not my case. I have to start the order by this 1. postgres container 1. migration container 1. Django container Therefore wait-for-it or dockerize is not my choice https://docs.docker.com/compose/startup-order/ Because migration and Django container will race to postgres I had tried wait_for, but is an unsupported config option https://github.com/docker/compose/issues/374#issuecomment-126312313 My temporary solution is postgres container do a migration. By that I have to load Django and every plugin into it which is huge and clumsy My goal is: 1. postgres container start first 1. migration container do migration 1. Django container wait migration finish and then access to postgres What is the best practice for my problem? -
In Django, how to assign one model to another model using a form?
I am not sure that I am asking the correct question, but here is my setup. survey_form.html <form action="" method="post"> {% csrf_token %} {% if questions %} {% for question in questions %} <div class="form-group"> <label for="{{ question.id }}">{{ question.question_text }}</label> {{ form.response_text }} </div> {% endfor %} {% else %} <p>No questions currently!</p> {% endif %} <button type="submit" class="btn btn-default">Submit</button> </form> forms.py class SurveyForm(forms.ModelForm): class Meta: model = SurveyResponse fields = ['response_text'] models.py class SurveyResponse(models.Model): question = models.ForeignKey(SurveyQuestion) response_text = models.CharField(blank=False, max_length=500) views.py class SurveyResponseCreate(generic.CreateView): model = SurveyResponse fields = ['response_text'] success_url = reverse_lazy('content/thankyou.html') template_name = 'content/surveyresponse_form.html' def get_context_data(self, **kwargs): context = super(SurveyResponseCreate, self).get_context_data(**kwargs) context['questions'] = SurveyQuestion.objects.all() return context def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): instance = form.save(commit=False) question = SurveyQuestion.objects.get(id=form.data['question']) response = SurveyResponse.objects.create(question=question, response_text=form.data['response_text']) response.save() return HttpResponseRedirect('/thankyou/') else: return self.form_invalid(form) So when I run server and go to /survey/, the form displays: <form action="" method="post"> <input type='hidden' name='csrfmiddlewaretoken' value='HS8Tzq1Z2wI8JIG7Q5fj6VB960aHEkUh' /> <div class="form-group"> <label for="1">Question1</label> <input id="id_response_text" maxlength="500" name="response_text" type="text" /> </div> <div class="form-group"> <label for="2">Question2</label> <input id="id_response_text" maxlength="500" name="response_text" type="text" /> </div> <button type="submit" class="btn btn-default">Submit</button> </form> I want the form to display a Question from the Question model and create an input box … -
'ascii' codec can't decode byte 0xff in position 11: ordinal not in range(128)
I am using django-imagekit to create thumbnails of my image field. class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) image = ProcessedImageField(upload_to= generate_random_filename, processors=[ResizeToFill(640, 640)], format='JPEG', options={'quality': 60}) avatar = ImageSpecField(source='image', processors=[ResizeToFill(96, 96)], format='JPEG', options={'quality': 60}) Now I created a serializer for the above model using django-rest-framework: class UserRegistrationSerializer(serializers.ModelSerializer): class Meta: model = User fields = tuple(User.REQUIRED_FIELDS) + ( User.USERNAME_FIELD, User._meta.pk.name, 'image', 'avatar', ) I have created a generics.CreateAPIView to save a new user but, it gives error: UnicodeDecodeError at /register/ 'ascii' codec can't decode byte 0xff in position 11: ordinal not in range(128) Unicode error hint The string that could not be encoded/decoded was: "����\u I don't understand this. Please help. It works fine if I remove avatar from the serializer. -
Support of Polyhedral and TIN in GeoDjango
I have an application based on django/geodjango + postgresql/postgis. I need to store 2D et 3D objects. I didn't see any 'binding' in django for POLYHEDRALSURFACE and TIN, can someone tell me any information about this ? I found this post very instructive. http://postgisand3d.blogspot.fr/2008/06/new-geometries-in-postgis.html -
Comparing two Dates, Change date depending on other
So i have two dates a start date and end date, now obviously the start date cannot be after the end date. I am using jquery to validate the input, so my idea was to see if the start date is greater than the end date if so change the end date to the date that is in the start date field. The problem is i don't know how to compare then in a if statement that will automatically change the second date. Can anyone advice me on this matter? Thank you -
Django. What packges do you recommend for these needs?
I am learning Django and I read 2 or 3 books. I feel that it is time to go for packages. So I would like to know what ones do you recommend me for the following needs. 1 - User Authentication / Accounts Management I have been using django built in user auth. 2- User social auth I learned python-social-auth 3- Ajax I did not use any package, I used ajax for many things and it takes me a lot of time, for example on forms, pagination ... 4- Image thumbnails I used solr-thumbnail 5- Database searching I have been using haystack to bind with sorl 6- Form Using django model forms 7 - Design Nothing Thank you -
Build API with ASP.NET Web API on Django project
We are currently building our event management platform at a company i work for, The authentication service is being built with ASP.NET identity framework. The main event management platform is built in Django using python, which i have built. We are also planning on building a custom admin portal in ASP.NET MVC, which will manage users and event data. The problem is that the C# guys(Who are contractors albeit very experienced developers) want to build out the API using ASP.NET for the event app which is built in django, using the Database first model that .NET provides, thus the database migrations will be handled by Django, but the actual API will be built using ASP.NETS Web API, directly from the database. This approach does not seem to make much sense in my opinion as it would make a lot more sense to build out the the API using Django rest framework and manage the database migrations for the event app. Instead of tightly coupling the database with Web API. Either way both approaches are are effectively doing the same thing, but i don't think it's efficient to constantly manage two environments, migrations in one environment and api management in the … -
How to implement captcha in the Django rest framework's custom Authentication class
I have scrached my head over this for almost 3-4 days. Let me explain the situation. I have a DRF(Django REST Framework) class based view with a custom authentication class. As far as I understand, you can override the authenticate method of DRF's BaseAuthentication class to implement your custom authentication, while you can only raise predefined Exceptions provided from DRF if the authentication fails. My problem is, I am trying to find a way to return custom response i.e; the captcha HTML to the frontend directly from the authentication class, so as to achieve no authentication related code in my view. To have a better understanding of my situation I am providing a pseudo code below. class ExampleView(APIView): authentication_classes = (ExampleCustomAuth, ) def get(self, request): pass This is the view and this part is absolutely fine. class ExampleCustomAuth(BaseAuthentication): def authenticate(self, request): req = request request = req._request { This part of code decides if its required for a captcha or not } if captcha_required: response = HttpResponse() response.status_code = 401 response['WWW-Authenticate'] = 'Captcha" id="%s"'% (id) response.content = loader.render_to_string('captcha.html') return response # This is where it goes wrong I believe, its not possible to return a response right from here. I … -
Django: Complex Permission Model
Suppose I have users, projects, memberships and in every membership a role is specified (for example: admin, read-only, user, etc.). The memberships define the relation between users and projects and the corresponding role. Now I have a problem: how can I use the permission system of Django to assure that only admins can edit projects and the other roles are not allowed to edit projects? The project list template should look like this: {% for project in object_list %} {# user.has_perm('edit_project', project) #} {% endfor %} What is the best way of doing this? How can I implement the permission based on the membership role? -
Django - having to set multiple type handlers when serializing json response
I am trying to return a JSON from Django view to client, and have the code below: ... return JsonResponse({'some_qs':json.dumps(list(some_qs), ensure_ascii=False, default=date_default).encode('utf8'), 'sum':json.dumps(sum, ensure_ascii=False).encode('utf8')}) The problem is that some_qs contains dates and decimals. Unless I specify default function in json.dumps, I will end up with Decimal('400.0000') is not JSON serializable or datetime('....') is not JSON serializable. I have learnt how to handle the situation when you have ONLY dates or ONLY decimals. In such cases, I use functions like so: def date_default(obj): if hasattr(obj, 'isoformat'): return obj.isoformat() else: raise TypeError def decimal_default(obj): if isinstance(obj, decimal.Decimal): return float(obj) raise TypeError and call set the default param of json.dumps to date_default or decimal_default respectively. The question What syntax for json.dumps should be used to pass handlers for BOTH date and decimals ? -
Too many requests on Grappelli admin edit form with autocomplete_lookup_fields build
I have Django Grappelli model admin form SampleInline with inline model form SampleAttributeInline. class SampleInline(SuperInlineModelAdmin, admin.StackedInline): model = Sample inlines = [SampleAttributeInline,] extra = 0 class SampleAttributeInline(SuperInlineModelAdmin, admin.TabularInline): model = SampleAttribute #unificated_name and unificated_value are ForeignKey model fields raw_id_fields = ('unificated_name','unificated_value',) autocomplete_lookup_fields = { 'fk': ['unificated_name', 'unificated_value',] } extra = 0 This form usually has many inline instances, so during form building I see multiple equal requests that look like this: [19/Oct/2016 13:10:12] "GET /grappelli/lookup/related/?object_id=&app_label=articles&model_name=unificatedsamplesattributename HTTP/1.1" 200 30 [19/Oct/2016 13:10:12] "GET /grappelli/lookup/related/?object_id=&app_label=articles&model_name=unificatedsamplesattributevalue HTTP/1.1" 200 30 [19/Oct/2016 13:10:12] "GET /grappelli/lookup/related/?object_id=&app_label=articles&model_name=unificatedsamplesattributename HTTP/1.1" 200 30 [19/Oct/2016 13:10:12] "GET /grappelli/lookup/related/?object_id=&app_label=articles&model_name=unificatedsamplesattributevalue HTTP/1.1" 200 30 while there obviously should be only two. How to make only two requests and apply response to all corresponding inline form elements? I use super-inlines, hence SuperInlineModelAdmin, but it should not affect my problem since it is only to make this whole thing nestable under other inlines. -
Index data from not related models in Django-Haystack Solr
Hello Internet people, I have a model to which multiple other models point through foreign keys, like: class MainModel(models.Model): name=models.CharField(max_length=40) class PointingModel1(models.Model): color=models.CharField(max_length=40) main_model=models.ForeignKey(DyndbComplexExp) class PointingModel2(models.Model): othername=models.CharField(max_length=40) main_model=models.ForeignKey(DyndbComplexExp) So I want to return the name of the MainModel by searching for color and othername fields in the PointingModels. Is there any way to do this? Any help is welcomed! Thanks. -
Python- running tests: Cannot delete or update a parent row: a foreign key constraint fails
I am starting to learn Python and Django, having never used them before. I'm following the tutorial at: https://docs.djangoproject.com/en/1.10/intro/tutorial05/ and have got as far as the 'Running Tests' section. When I try to run the test using the command: python manage.py test polls the tutorial says that I should get an error that says: AssertionError: True is not False However, when I run this, having followed what the tutorial says, the error that I'm getting says: django.db.utils.IntegrityError: (1217, 'Cannot delete or update a parent row: a foreign key constraint fails') My models.py file looks like this: from __future__ import unicode_literals import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Can anyone explain why I'm getting a different error to the one the tutorial tells me to expect? What am I doing wrong here? -
Django custom login view -> Session not persistent
Environment: Django 1.9.6 Python 3.5 I've made a custom User Model for user and permission management. Now i have a problem at my login view, which i do not understand. def login_user(request): if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: # User Object is fine... if user.is_active: login(request, user) # Login passes -> request.user is OK and request.session _session_cache is filled corretly.. if 'next' in request.POST.keys(): redirect_to_next = request.POST['next'] else: redirect_to_next = settings.LOGIN_REDIRECT_URL return HttpResponseRedirect('/auth/main/') redirect_to_next = request.GET.get('next','/') return render(request, 'authentication/login.html', {'form': LoginForm, 'next' : redirect_to_next} ) After i redirect to another page the session is deleted.. And request.user = AnonymousUser. Here the output from the session variable after i call the login() method.. {print(request.session.__dict__) 'modified': True, '_SessionBase__session_key': 'bn8qxxxxx', 'serializer': <class 'django.core.signing.JSONSerializer'>, 'model': <class 'django.contrib.sessions.models.Session'>, 'accessed': True, '_session_cache': {'_auth_user_hash': 'f5fxxxxxx', '_auth_user_id': '3f5b3fd1-XXXXXX', '_auth_user_backend': 'django.contrib.auth.backends.ModelBackend'}} and then i redirect to another page.. {print(request.session.__dict__) {'modified': False, '_SessionBase__session_key': None, 'serializer': <class 'django.core.signing.JSONSerializer'>, 'accessed': False} Can someone help me? Thanks BR