Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter objects group by day
I am trying to filter a user activity against the date. Suppose I have a check in/out functionality in my application. When listing out the logs I wanted to show up each day's activities differently. Anyone ever tried this before? Thanks in advance. -
How to make sure email is not received in spam when sent with Django EmailMessage class?
I have the following settings in my settings.py file. EMAIL_HOST = 'mail.domain.com' EMAIL_HOST_USER = 'me@domain.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True A user in my Django application is able to send an email to a client with a PDF attachment using the EmailMessage class. Here is the code: email = EmailMessage() email.subject = 'Demo subject' email.body = self.request.GET.get('email_body', '') email.from_email = 'Full Name <user@domain.com>' email.to = ['{}'.format(self.request.GET.get('to_address'))] email.attach_file(os.path.join(settings.MEDIA_ROOT, 'quotation_email.pdf')) email.send() My questions are, Since I can create a code to send the email as a different person, will the email not be marked as spam in certain domains? I have access to a mail server which is already setup. Can I map the email accounts to the user accounts in the Django application in such a way that Django uses the email server as a medium to send email based on the logged in users? Why do I need to provide an email and password in settings.py file when I may never use that email account to send any mail? Can I not log in to the email every time someone sends an email? -
Django rest ModelViewSet methods missing
I have a model: class Project(models.Model): stakeholders = models.ManyToManyField(User, blank=True) name = models.CharField(max_length=50, blank=True, null = True, ) A serializer: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' urls.py: router = routers.DefaultRouter() router.register(r'projects', ProjectViewSet) urlpatterns = router.urls And a view: class ProjectViewSet(viewsets.ModelViewSet): queryset = Project.objects.all() serializer_class = ProjectSerializer I am expecting my ModelViewSet to provide me CRUD operations on Project model, I am using drf docs and what I see is following: all the methods are basically missing, and I am not sure what that extra /api/ endpoint is? -
Django - Join two table in view and use it in template
I'm using python 3.4.5 with Diango 2.0.2 I have 2 tables with a foreign key. For some reasons, I need to use 2 tables to store these data. I want to generate a table which contain the following information. program.name , program.program_id , program.filter(user=request.user.id).status models.py class Program(models.Model): name = models.CharField(max_length=128, null=True, blank=True, default=None) program_id = models.AutoField(primary_key=True) class ProgramInfo(models.Model): pid = models.ForeignKey(Program, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) status = models.CharField(max_length=10, default=1003) views.py def program_list(request): program = Program.objects.all() return render(request, 'panel/program_list.html', {'program': program}) template {% for prog in program %} <tr> <td> {{ prog.name }} </td> <td> {{ prog.program_id }} </td> <td> {{ "program's status of existing user" }} </td> </tr> {% endfor %} How to generate a table which contain the following information? program.name , program.program_id , program.filter(user=request.user.id).status I have 2 solutions, (1) generate a table and pass it to template (2) send the program table to template, and use something like program.filter(user=request.user.id).status in "td" But I don't know how to do it for these 2 solutions. -
Is it possible to do a post save when a specific field on a model changes?
If it is possible to do a post save based on a field change, would the code look something like this? Note: I want a Car object to get created each time the address of the House model changes. def create_car(sender, **kwargs): if kwargs['??????']: car = Car.objects.filter(user=kwargs['instance'].user) post_save.connect(create_car, sender=House.address) I'm not sure what would go in the kwargs. Thanks! -
Django: Form Model Validation
I have an understanding issue with Form Model Validation. I have a model and additional I am adding an email_confirm field in my form. However, the validation doesn't work. Anyone who can help me to understand why? class TransactionProfileModelForm(forms.ModelForm): email_confirm = forms.EmailField() class Meta: model=TransactionProfile fields = [ 'email', 'email_confirm', 'address_line_1', 'address_line_2', 'city', 'country', 'postal_code', 'state' ] def clean_email(self): email = self.cleaned_data.get('email') email_confirm = self.cleaned_data.get('email_confirm') if email and email_confirm and email != email_confirm: raise forms.ValidationError("Emails don't match.") return email However, if I am trying this code here it works: def clean_email_confirm(self): email = self.cleaned_data.get('email') email_confirm = self.cleaned_data.get('email_confirm') if email and email_confirm and email != email_confirm: raise forms.ValidationError("Emails don't match.") return email_confirm -
object() takes no parameters when trying to delete model instance
Every time I try to delete an instance of a specific model, I get the error: object() takes no parameters I looked for this error message, but all posts refer to a wrong init setup, which I don't have. It's driving me nuts! Any idea what is causing this? Here is the model: class CharacterSheet(models.Model): objects = ModelManager() save_name = models.CharField(max_length=150, blank=True, null=True) character_name = models.CharField(max_length=150, blank=True, null=True) root = models.TextField( default="{'lastId':'0', 'lastPlayerAddedId':'0', 'is_root':'true', 'type': 'section', 'direction': 'vertical'}") created = models.DateField(auto_now_add=True) edited = models.DateField(auto_now=True) color = models.IntegerField(default=random_color) template = models.ForeignKey('self', related_name="copies", on_delete=models.Empty, null=True) saved_on_profile = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) @property def root_json(self): return json.loads(self.root) def save(self, *args, **kwargs): """Save method override""" super(CharacterSheet, self).save(*args, **kwargs) for character in self.characters.all(): character.save() Full error stack: File "/home/vvdrrltv/virtualenv/rolegate.com_rolegate__django/3.5/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/vvdrrltv/virtualenv/rolegate.com_rolegate__django/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/vvdrrltv/virtualenv/rolegate.com_rolegate__django/3.5/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/vvdrrltv/virtualenv/rolegate.com_rolegate__django/3.5/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/vvdrrltv/virtualenv/rolegate.com_rolegate__django/3.5/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/vvdrrltv/virtualenv/rolegate.com_rolegate__django/3.5/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/vvdrrltv/virtualenv/rolegate.com_rolegate__django/3.5/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/home/vvdrrltv/virtualenv/rolegate.com_rolegate__django/3.5/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/home/vvdrrltv/virtualenv/rolegate.com_rolegate__django/3.5/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = … -
Can't get value from CharField in Django
There was a following problem. It is not possible to get the value of the username field in the User class. If output through print - everything is correct, but if passed as a parameter, it gives django.db.models.fields.CharField. Through str and _ str _ it passes the same thing. @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance, usrname=instance.username) I use the parameter as follows - usrname = models.CharField(max_length=100, default = '') upload = 'img/users/%s' % usrname img = models.FileField(upload_to=upload, blank=True) Tell me, please, what I'm doing wrong. -
Django mails not being saved (File backend)
I have configured Django to use a file backend for email sending on my local machine. This seemed to work fine earlier on, and all mails were recorded in the directory I had specified in my settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = '/code/mails/' However, this suddenly stopped working. I have checked the permissions of the folder, and this seems to be fine. There is no error that I can see. I'm using docker, and when I start the Python server I have the logs shown in my terminal. Normally when there is an error I see it there. But nothing appears. To test things, I have renamed the folder and tried sending a mail. This time, no error appears either. In production, where my settings.py are different but all else is the same, the emails are sent out just fine. So the code seems to be working, but the local filebased backend seems to be a problem. Anybody any idea? -
django-filter custom filter not get queryset
First of all, I'm beginner in Django-filter if you could offer best solution, I'll be glad to hear it. I need to filter QuerySet by ForignKeys' fields. And exactly author and worker. Model.py class Object(models.Model): class Meta: abstract = True author = models.ForeignKey('Users.User', on_delete=models.CASCADE) class Task(Object): priority_choices = ( ('high', 'Высокий'), ('middle', 'Стандартный'), ('low', 'Низкий'), ) status_choices = ( ('open', 'Открыта'), ('done', 'Выполнена'), ('close', 'Закрыта'), ) name = models.CharField(max_length=140) description = models.TextField() end_date = models.DateField() worker = models.ForeignKey('Users.User', on_delete=models.CASCADE, related_name='worker_set') priority = models.CharField(max_length=15, choices=priority_choices) status = models.CharField(max_length=15, choices=status_choices) Filters.py class TaskFilter(filters.FilterSet): my_tasks = filters.BooleanFilter( label="Мои задачи", method='my_task_filter', widget=forms.CheckboxInput() ) tasks_for_me = filters.BooleanFilter( label="Задачи для меня", method='tasks_for_me_filter', widget=forms.CheckboxInput() ) commented_tasks = filters.BooleanFilter( label="Я комментировал", method='commented_tasks_filter', widget=forms.CheckboxInput()) class Meta: model = Task fields = ['my_tasks', 'tasks_for_me', 'commented_tasks'] def my_task_filter(self, queryset, name, value): print(1, self, queryset, name, value) return queryset.filter(author_id=self.request.user.id) def tasks_for_me_filter(self, queryset, name, value): print(2, self, queryset, name, value) return queryset.filter(worker_id=self.request.user.id) def commented_tasks_filter(self, queryset, name, value): print(3, self, queryset, name, value) return queryset.filter(comment__author_id=self.request.user.id) According to prints in filters.py I get: 1 <TaskManager.filters.TaskFilter object at 0x7f87290dea90> <QuerySet [<Task: Task object>, <Task: Task object>, <Task: Task object>]> my_tasks False 2 <TaskManager.filters.TaskFilter object at 0x7f87290dea90> <QuerySet []> tasks_for_me True 3 <TaskManager.filters.TaskFilter object at 0x7f87290dea90> <QuerySet … -
How to pass information from html form to django view
I am creating a website where users can follow certain stocks and see news based on what they follow. I have the following models.py : from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save class Stock(models.Model): name = models.CharField(max_length = 50) ticker = models.CharField(max_length = 50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed_stocks = models.ManyToManyField(Stock, blank=True) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class Article(models.Model): stock = models.ForeignKey(Stock, on_delete=models.CASCADE, default = 0 ) title = models.CharField(max_length = 200) url = models.URLField() description = models.TextField() def __str__(self): return self.title Here is my register view, upon signing up for the site, users are redirected to another page where they can follow stocks for the frist time : def register(request): if request.method == "POST": form = ProfileRegistrationForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password') user = authenticate(username=username, password= raw_password) login(request, user) return redirect(follow_stocks_post_registration) else: form = ProfileRegistrationForm() return render(request, 'core/register.html',{'form':form}) Now, once redirected I want users to see a list of all the Stocks in our database and be able … -
Change time zone depending on the user in django project
I am trying to change the time zone in my project, depending on what the user has selected. To do that I have a field in my database, where I keep all possible locations: timezone = models.CharField(max_length=40, null=True, blank=True, choices=[(n,n) for n in pytz.all_timezones]) but the problem is that when I try to change the time zone it does not work. ---- setting.py ---- USE_TZ = True TIME_ZONE = 'Europe/Madrid' ---- Dashboard (view.py) ----> output @login_required def dashboard(request): from datetime import datetime, timedelta import pytz print "Normal:" + str(datetime.now()) # Normal:2018-04-19 08:39:51.484283 print "TimeZone:" + str(timezone.now()) # TimeZone:2018-04-19 06:39:51.484458+00:00 u = User.objects.get(user=request.user) # u: Alejandroid timezone_selected = u.timezone # timezone_selected: u'Canada/Saskatchewan' timezone.activate(pytz.timezone(timezone_selected)) print "Normal:" + str(datetime.now()) # Normal:2018-04-19 08:40:02.829441 print "TimeZone:" + str(timezone.now()) # TimeZone:2018-04-19 06:40:04.329379+00:00 As you can see, it only returns me the local time defined in TIME_ZONE and in UTC time. I'm working with Django 1.8 How do I make it work? Thank you very much. -
Creating a model instance on post save
I'm attempting to create an instance of Car when a user creates an instance of model House. Models.py class House(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) address = models.CharField(max_length=100) def __str__(self): return self.user.username class Car(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) makemodel = models.CharField(max_length=100) def __str__(self): return self.user.username def create_car(sender, **kwargs): if kwargs['created']: car = Car.objects.create(user=kwargs['instance']) post_save.connect(create_car, sender=House) #have to figure out how to have multiple senders When I go into the admin and create an instance of the House model for any user, I get the following error. "Cannot assign "<House: jason>": "Car.user" must be a "User" instance." Any thoughts would be appreciated! -
Django not recognizing field override for Current User in Serializer
I am having an issue in setting the user automatically in django rest framework. In my models.py I have the following: Models.py class Space(models.Model): creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Serializers.py class SpaceSerializer(serializers.HyperlinkedModelSerializer): creator = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CreateOnlyDefault(serializers.CurrentUserDefault())) class Meta: model = Space fields = '__all__' The intent is that the creator field will be set during creation through the API. When I issue a POST request to create the model, i get the following error: "IntegrityError at /api/space/ NOT NULL constraint failed: apiapp_space.creator_id I assume the serializer is not even using this field override, as when I set null=True in my model, it seems to save correctly with the creator field set to null. Note that I have also tried using serializers.ModelSerializer. How can I get django to recognize this field override? -
Django not finding CSV file in base directory
I wrote a function that imports CSV data into one of my Django models. I got this function to work before, though now it doesn't seem to be working at all (the dashboard page loads, though nothing is actually imported). I have a feeling that its because Django isn't finding the CSV file in the base directory. Here is the code I have: views.py: ### IMPORTING DATA FROM CSV FILES INTO DJANGO DB/MODELS ### def import_data(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) directory = os.path.join(BASE_DIR) count = 0 for root, dirs, files in os.walk(directory): for filename in files: if filename.endswith(".csv"): file_path = os.path.join(root, filename) with open(file_path) as f: reader = csv.reader(f) for i, row in enumerate(reader): target_string = "Year" if target_string in row: next(reader) for row in reader: print "importing file number %d" %(count) objects = [ MeterData( name = row[0], date = strftime(row[1], "%m-%d-%Y"), meter = row[2], usage = row[3], oldrate = row[4], newrate = row[5], oldcost = row[6], newcost = row[7], savings = row[8], ) for row in reader if row[0] != "End of Data" ] MeterData.objects.bulk_create(objects) count += 1 print "Imported %d files! All done!" %(count) return render(request, "Dashboard/dashboard.html") Again, I think I remember this function working before, and I … -
Writing your first Django app, part 3¶, polls questions do not show on browser
I am following DJango tutorial. return HttpResponse(template.render(context, request)) does not return polls question and I get the message that 'No polls are available.' I have exactly followed tutorial but I cannot get the result. -
render multiple template from a single view in django
I want to send context data to one html and want to render different html. After login user is redirected to this dashboard view. Here I want to render two html file, the context value will be sent to one html let say temp1.html file, but user can see temp2.html file. In temp2.html and other html file, I will include temp1.html file. Is there any way to do so? views.py def dashboard(request): print('in dashboard view') object = UserSelection.objects.get(user=request.user) if object.user_type == 'candidate': val_cand = CandidateDetail.objects.filter(candidate_username=request.user) if val_cand: print('Candidate filled data') #Already filled data data = CandidateDetail.objects.get(candidate_username=request.user) return render(request, 'dashboard.html',{'obj':object.user_type, 'data':data}) else: print('new user') #Registered but not filled data return render(request, 'dashboard.html', {'obj':object.user_type}) else: val_emp = EmployerDetail.objects.filter(name=request.user) if val_emp: print('Employer filled data') #Already filled data data = EmployerDetail.objects.get(name=request.user) return render(request, 'dashboard.html',{'obj':object.user_type, 'data':data}) else: print('new user') #Registered but not filled data return render(request, 'dashboard.html', {'obj':object.user_type}) -
python-django template-inheritance not working when referencing multiple blocks in base
I am fairly new to django and am trying out template-inheritance but not able to get it work. I cannot get all the blocks in a page to be displayed simultaneously. Not sure if I am missing something in urls, views or settings. I am using Python 3.6 in venv / Django 2.0.4 on PyCharm Details of my example below - myhome being project name and smarthome being app name Folder Structure base.html navtopbar.html navsidebar.html smarthome urls.py smarthome views.py -- Initially i had this as base.html but based on advice in thread below, changed to navtopbar. But then not sure how to get application to display navsidebar simultaneously settings I followed the advice in this thread but not able to get it to work yet. Appreciate any help here. -
Can't install django on mac
Im trying to install django but I keep getting this error Collecting django Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping Could not find a version that satisfies the requirement django (from versions: ) No matching distribution found for django im doing pip install django But for some reason its not working -
django render template variables and tags via ajax
I want to use Django+jquery-ajax to refresh my blog's new comments. The code is as follows: views.py: @require_POST def wirte_comment(request): """ajax new article comment""" if request.user.is_anonymous: login_url = reverse('login') return JsonResponse({'status': 'redirect', 'login_url': login_url}) # logined article_id = int(request.POST.get('article_id')) comment_form = ArticleCommentForm(request.POST) article = get_object_or_404(Article, id=article_id) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.author = request.user new_comment.article = article new_comment.save() create_action(request.user, article, verb=f"{request.user.username} commentted《{article.title}》") # comment html with open('blog/templates/blog/add_comment.html') as f: html = f.read() return JsonResponse({'status': 'ok', 'html': html}) else: return JsonResponse({'status': 'ko'}) I sent the HTML of the new comment as a string to the front end: add_comment.html: <div class="comment"> <p class="comment-author"> <a href="{% url 'account:user_detail' article.author %}"> {% avatar article.author 25 class="circle-avatar" %} </a> <a href="{% url 'account:user_detail' article.author %}"> {{ article.author }} </a> {{ comment.created |date:'y/m/d h:i' }} </p> <p>{{ comment }}</p> </div> article.html <script> $(document).ready(function () { $('#new_comment').click(function () { var text = $('#text').val(); $.post(comment_url, { article_id: article_id, content: text }, function (data) { if (data['status'] === 'redirect') { window.location.href = data['login_url']; } if (data['status'] === 'ok') { $('#comment-list').prepend(data['html']); } } ); }); }); </script> And then there's a problem: When I submit a new comment,it's rendered like this: {% avatar article.author 25 class="circle-avatar" %} {{ article.author }} … -
How to generate primary key using other fields in django models
I a trying to generate a primary key using the other fields of the model. unique_id = models.CharField(max_length=10, primary_key=True) restaurant_name = models.CharField(max_length=100) manager_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True) mobile_no = models.CharField(unique=True, validators=[validate_mobile], max_length=10) state = models.CharField(choices=STATES, max_length=2) city = models.CharField(max_length=20) pincode = models.CharField(max_length=8, validators=[validate_pincode]) street_address = models.CharField(max_length=100) password = models.CharField(max_length=256) -
Django user model
I have a Django app where I have extended the user model. (see below). I have one type of user that has 3 properties - email, full_name and an avatar. I am going to be having multiple types of users. Maybe Teachers, Students, Parents, Alumni, etc (not my field, but an example). Should I put fields that they all have in common in this below User model and then create a model that has properties that the 4 don't share (e.g. grade you teach, or year in school, year graduated? I'm making this up on the fly, but you see what I mean) with a foreign key to join them. I'm trying to extend this page . I'm not sure what the related_name arg means. class Teach(AbstractBaseUser): user = models.ForeignKey(User, related_name='teacher') classes = models.EmailField(...) year_started_teaching = models.. class Student(AbstractBaseUser): user = models.ForeignKey(User, related_name='teacher') year_graduating = models.Integer() class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) full_name = models.CharField(max_length=255, blank=True, null=True) avatar = models.ImageField(upload_to='images/', blank=True) is_active = models.BooleanField(default=True) # can login staff = models.BooleanField(default=False) # staff user non superuser admin = models.BooleanField(default=False) # superuser timestamp = models.DateTimeField(auto_now_add=True) Or should I have 4 separate models that each have the users in it. At some point, … -
is_authenticated is always True even after remove all user's sessions
Using Django, I'm trying to login out a user but in server side as I'm using Django just for backend as our frontend is developed useing Reactjs + Node, and my problem is related when I try to login out the user. This is what I'm doing for this: from django.contrib.sessions.models import Session for s in Session.objects.all(): data = s.get_decoded() if data.get('_auth_user_id', None) == str(user.id): s.delete() auth.logout(context) the problem is that even when the logout code is executed, if I call the logout API again, user.is_authenticated is always True. What do I have to do to receive False without checking the Session table manually to detect if the user is loged in ir not? Regards -
django celery raise exception : ImproperlyConfigured
I used redis, celery, django, django-celery-results but i got an error log in /var/log/celery/celery.log Pool callback raised exception: ImproperlyConfigured('settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.',) folloing is my project structure - proj - config - settings __init__.py base.py local.py production.py - proj __init__.py celery.py and following is proj/proj/celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and following is proj/config/settings/production.py from .base import * DEBUG = True ALLOWED_HOSTS = '*' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': get_secret("DATABASES", "NAME"), 'USER': get_secret("DATABASES", "USER"), "PASSWORD":get_secret("DATABASES", "PASSWORD"), "HOST":get_secret("DATABASES", "HOST"), "PORT":get_secret("DATABASES", "PORT") }, } STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Celery Setting CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'django-db' #CELERY_RESULT_BACKEND = 'redis://localhost:6379' #CELERY_ACCEPT_CONTENT = ['application/json'] #CELERY_RESULT_SERIALIZER = 'json' #CELERY_TASK_SERIALIZER = 'json' WSGI_APPLICATION = 'config.wsgi.application' I have no idea what the problem is... Please help me... -
Django authenticate user is not working
I am athenticating user and redirecting him to index page: def sign_user(request): username = request.POST['login'] password = request.POST['pwd'] user = authenticate(username=username, password=password) if user is not None: print('success:' + username + " " + password) return redirect('/') this is index view: def index(request): user = request.user print(user) And as a result here I get: AnonymousUser What do I do?