Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to link route and mixin method in drf
I have mixins in views: class ReservationList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Reservation.objects.all() serializer_class = ReservationSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class ReservationDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView): queryset = Reservation.objects.all() serializer_class = ReservationSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) I have routes: urlpatterns = [ path('houses/<int:pk>/reserve/', ...), path('houses/<int:pk>/cancel_reservation/', ...) ] I want to connect route houses/<int:pk>/reserve/ with method post of ReservationList class. Also I want to connect houses/<int:pk>/cancel_reservation/ with delete method of ReservationDetail class. So, when user types houses/<int:pk>/cancel_reservation url, drf must run delete method of ReservationDetail class. How to do it? -
How to enable batch upload with django 2.x (or 3)?
I have this model that accepts files, calculates the md5 sum and if that value is not yet in the database the file is stored. It works for one file at a time. class RawFile(models.Model): # use the custom storage class fo the FileField orig_file = models.FileField( upload_to=media_file_name, storage=file_system_storage) md5sum = models.CharField(max_length=36, default=timezone.now, unique=True) created = models.DateField(default=timezone.now) def save(self, *args, **kwargs): print('Saving new raw file.', self.md5sum) if not self.pk: # file is new md5 = hashlib.md5() for chunk in self.orig_file.chunks(): md5.update(chunk) self.md5sum = md5.hexdigest() if not self.id: self.created = timezone.now() print('Saving new raw file.', self.md5sum) super(RawFile, self).save(*args, **kwargs) def __str__(self): return basename(self.orig_file.name) @property def abs_path(self): return f'{MEDIA_ROOT}/{self.orig_file}' @property def filename(self): return basename(self.abs_path) @property def rawtools_status(self): path = dirname(self.abs_path) if isfile('QcDataTable.csv'): return 'Done' elif isfile(join(path, 'rawtools.txt')): return 'Running' return 'New file' @property def href(self): return os.path.dirname('/'+self.orig_file.name) def link(self): print(self.href) return mark_safe(r'<a href="{}">Output</a>'.format(self.href)) link.short_description = 'Browse' # pipelines/forms.py from django import forms from .models import RawFile I changed the upload form so that multiple files can be uploaded at the same time, though here only the last file in the batch gets stored. class UploadRawForm(forms.ModelForm): orig_file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = RawFile fields = ['orig_file'] error_css_class = 'error' required_css_class = … -
Django - Import sheet but with columns in different language than defined in models
I'm creating a database and want to use the django-import-export package. My columns are like this: models.py class Objects(models.Model): selection_for_institute = models.IntegerField # Auswahl für Institute in Excel sheet inventory_number = models.IntegerField(primary_key=True) # Inventarisierungsnummer in Excel amount = models.IntegerField # Anzahl in Excel v_amount = models.IntegerField # V-Anzahl in Excel ... Because the users of this database will be primarily german and there will be even symbols like äöüß/- in the column headers, I need aliases so they can be imported. Because (of course) now it cannot find the required columns in the given .xlsx file. I added the german word in comments for you to understand what the excel headers will be like. I hope you can help me with this. -
what do these methods basically do in models.py
I am reading some codebase and I have this slight confusion in models.py. Here is the code . class Product(models.Model): DISCOUNT_RATE = 0.10 id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) description = models.TextField() price = models.FloatField() sale_start = models.DateTimeField(blank=True, null=True, default=None) sale_end = models.DateTimeField(blank=True, null=True, default=None) photo = models.ImageField(blank=True, null=True, default=None, upload_to='products') def is_on_sale(self): now = timezone.now() if self.sale_start: if self.sale_end: return self.sale_start <= now <= self.sale_end return self.sale_start <= now return False def get_rounded_price(self): return round(self.price, 2) def current_price(self): if self.is_on_sale(): discounted_price = self.price * (1 - self.DISCOUNT_RATE) return round(discounted_price, 2) return self.get_rounded_price() def __repr__(self): return '<Product object ({}) "{}">'.format(self.id, self.name) My concern is that what do methods such as current_price do here ? Are they a fields in Product model. I am slightly unaware of creating models with methods . -
I want to register a model on my django admin and i got this error
description][1] https://i.stack.imgur.com/Ux6x3.jpg and this is my code from django.contrib import admin from .models import Destination Register your models here. admin.site.register(Destination) -
Not able to redirect to a page after login in Django
I have a login form that allows a user to log in after registration. If the user is authenticated, the user will then be redirected to a different page. But during the process, I want to use Simple-JWT authentication in order to generate the tokens and use it further in my re-directed template. However, the re-direction of the page specified does not work. Here's what I had done: settings.py: #all default settings LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'dash' views.py: def login(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): username = request.POST['username'] password = request.POST['password'] new_user = authenticate(username = username, password = password) if new_user is not None: url = 'http://localhost:8000/api/token/' #JWT URL for tokens values = { 'username' : username, 'password' : password } r = requests.post (url, data = values) tokens = r.json() print("You're logged in.") return Response(token, template_name = 'users/dash.html') #after login, tokens will be generated and the user will access the dash template. else: login_form = LoginForm() return render(request, "users/login.html", {"login_form" : login_form}) def dash(request): return render(request, 'users/dash.html') forms.py: class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) urls.py: path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('login/', my_views.login, name = 'login'), path('dash/', my_views.dash, name … -
Why only homepage is opening after adding letsencrypt ssl in django project and rest of pages are displaying 404 not found?
I have recently added letsencrypt ssl on the [website][1] and now it's working fine for the homepage and other pages are coming up with 404 error. Let me know what could be the possible reason. Here is the site block configuration file in /etc/nginx/sites-available/eprofitsure server{ listen 80; listen [::]:80; server_name eprofitsure.com www.eprofitsure.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/rajeshreddy/eprofitsure/eprofitsure8886; } listen 443 ssl; # managed by Certbot # RSA certificate ssl_certificate /etc/letsencrypt/live/eprofitsure.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/eprofitsure.com/privkey.pem; # managed by Certbot #include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot # Redirect non-https traffic to https if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot location /media/ { root /home/rajeshreddy/eprofitsure/eprofitsure8886; } location ~ /.well-known { allow all; } location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } [1]: https://eprofitsure.com -
Django signals not working when placed outside models.py
I'm trying to print some text after Django model in an app has been saved. I have created a signal for that in a signals.py file in the same application. However, it's not working as expected (i.e., the function is not being called and text is not being printed) But if I place the receiver function in the models.py file just below the model that I created, it's working fine (i.e., the function is being called and text has been printed) I have gone through the documentation to check if there is any need to place the signals in a specific file or location. It looks like there isn't any such restriction. https://docs.djangoproject.com/en/3.0/topics/signals/#django.dispatch.receiver Why is this behaving differently if there is no such restriction? signals.py: from django.db.models.signals import post_save from django.dispatch import receiver from aws_envs.models import UserStack @receiver(post_save, sender=UserStack) def create_user_stack(sender, **kwargs): print("creating user stack now") models.py: class UserStack(BaseModel): name = models.CharField(max_length=50) email = models.EmailField(unique=True, max_length=50, blank=False) enabled = models.BooleanField(default=True) def save(self, *args, **kwargs): print(f"Creating stack with data: {self.name, self.email}") super(UserStack, self).save(*args, **kwargs) def __str__(self): return self.name, self.email -
how to add edit button in every row of table to edit respective row content
I'm working in Django. i print the table by using the for loop in html page. here i have a Django form which should popup when press edit and update the database by new value <table class="table"> <thead> <tr> <th> # </th> <th> Application Name </th> <th> Category </th> <th> Update </th> </tr> </thead> <tbody> {% for item in data %} <tr> <td> {{ forloop.counter }} </td> <td> {{ item.0 }} </td> <td> {{ item.1}} </td> <td> <button>Edit</button> edit </td> </tr> {% endfor %} </tbody> </table> <form method="post" action = 'manageapp'> {% csrf_token %} {{ form.as_p}} <button type="submit" >Submit</button> </form> i also need to have prefilled respective entry of perticular row -
Filtering by calculated field with django_filters
I have a model like this class Document(models.Model): desc = models.CharField(max_length=255, blank=True, verbose_name="Description") document = models.FileField(upload_to='uploaded') I created a table for displaying the objects like this class DocumentTable(django_tables2.Table): class Meta: model = Document template_name = "django_tables2/bootstrap.html" fields = ['id', 'desc', 'document'] and want to add a filter to it by uploaded documents names. I have access to these names by means of document.path, they are like 'uploaded/source_file.bmp'. But as I see, to filter them we need some additional dances. Could you please prompt me which exactly? The error currently is FieldError at /main_django_tables2 Cannot resolve keyword 'source_file_name' into field. Choices are: desc, document, id I tried adding calculated field to the Document class @property def source_file_name(self): return self.document.name and class DocumentFilter(django_filters.FilterSet): desc = django_filters.CharFilter(lookup_expr='icontains') source_file_name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Document fields = ['desc', ‘source_file_name’] class DocumentListView(django_tables2.views.SingleTableMixin, FilterView): model = Document table_class = DocumentTable template_name = 'core/main_form.html' filterset_class = DocumentFilter It seems we need something like class IsVeryBenevolentFilter(admin.SimpleListFilter): title = 'is_very_benevolent' parameter_name = 'is_very_benevolent' def lookups(self, request, model_admin): return ( ('Yes', 'Yes'), ('No', 'No'), ) def queryset(self, request, queryset): value = self.value() if value == 'Yes': return queryset.filter(benevolence_factor__gt=75) elif value == 'No': return queryset.exclude(benevolence_factor__gt=75) return queryset from https://books.agiliq.com/projects/django-admin-cookbook/en/latest/filtering_calculated_fields.html but … -
Filtering nested foreign keys in Django
I'm creating a Scrum board app. An organization can have multiple Boards, and a Board can have many Tasks. I'm trying to create a view which contains all tasks of the organization one is in. To simplify: models.py of various apps class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) class Board(models.Model): name = models.CharField(max_length=100) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) class Organization(models.Model): name = models.CharField(max_length=100) class Task(models.Model): name = models.CharField(max_length=100) board = models.ForeignKey(Board, on_delete=models.CASCADE) views.py def home(request): tasks = Task.objects.filter(**NOT SURE HOW TO FILTER**) context = { 'tasks': tasks, } return render(request, 'tasks/home.html', context) Currently, in the **NOT SURE HOW TO FILTER** I'm trying board.organization=request.user.profile.organization. However, I get the error SyntaxError: expression cannot contain assignment, perhaps you meant "=="? It looks like this is because of board.organization. On the one hand, I need to reference the organization through the Task's board. On the other hand, Django doesn't accept this. How can I overcome this problem? -
How to connect python django with raspberry pi?
I'm now trying to connect python django with raspberry pi. I'd like to print the result of raspberry pi (rasbian) on python django webpage. And because I have to deploy the django project on Github, I also have no idea how to set Raspberry pi files' path though I successfully connect django with raspberry pi. Anybody can help me? Thank you in advance! -
Invalid pk (Model Object) does not exist - Django REST Framework
class MerchantSerializer(core_serializers.BaseModelSerializer): """ MerchantSerializer """ bank_account_details = serializers.JSONField() merchant_entity_id = serializers.UUIDField() class Meta: model = paylater_models.Merchant fields = ('merchant_entity_id', 'bank_account_details',) def create(self, validated_data): """ create :param validated_data: :return: """ # with transaction.atomic(): # Normalizing and separating information bank_account_data = validated_data.pop('bank_account_details') validated_data.update({'merchant_number': core_utils.generate_alphanumeric_strings()}) # Creating merchant instance instance = super(MerchantSerializer, self).create(validated_data) # Creating bank account details for the newly created merchant bank_account_data.update({'merchant': instance}) bank_account_serializer = BankAccountDetailSerializer(data=bank_account_data) bank_account_serializer.is_valid(raise_exception=True) bank_account_serializer.save() return instance class BankAccountDetailSerializer(core_serializers.BaseModelSerializer): """ BankAccountDetailSerializer """ bank_name = serializers.CharField(max_length=256) account_number = serializers.CharField(max_length=18) ifsc = serializers.CharField(max_length=11) class Meta: model = paylater_models.BankAccountDetail fields = ('bank_name', 'account_number', 'ifsc', 'merchant',) def validate_account_number(self, account_number): """ validate_account_number :param bank_name: :return: """ if re.search('[0-9]{9,18}', str(account_number)) is not None: return account_number raise paylater_exceptions.InvalidBankAccountNumberError() def validate_ifsc(self, ifsc): """ validate_ifsc :param ifsc: :return: """ if re.search('[A-Za-z]{4}[a-zA-Z0-9]{7}', ifsc) is not None: return ifsc raise paylater_exceptions.InvalidIFSCError() These are my serializers. I wish to create a Merchant and add Bank account details. It gives me a Invalid pk \"Merchant object (f7f3f77a-7f18-4a27-ac39-1f182d233006)\" - object does not exist. What am I doing wrong here? I understand that the problem is with the merchant instance that I'm passing to BankAccountDetailSerializer But I don't really know what it is and how to fix this. -
using django application with local host forever
I wanna create an application for a store to maintain his inventory.I chose django to develop this app with local host, since the size of the data is too small.But, I'm confused how the user can run the command "py manager.py runserver" everytime.Is there any alternative for this to start the server automatically when the system starts. -
passing label value to views.py django
Before i asked this question, I have searched online and found similar solutions. However, it does not work for my case. I would like to pass template value to views.py. I tried using request.POST.get('value') but it does not work. I would like the name of the selected student to be saved in the database when the submit button is clicked. Here is my UI: Here are my codes: Views.py def AbsentStudent(request, id=None): classGrp = None attendance= 0 today = datetime.datetime.now() group = GroupInfo.objects.get(id=id) q1 = Namelist.objects.filter(classGrp=id).values('name','id') #get the student name of the specific group q2 = MarkAtt.objects.all().values('studName__name','id') #get the name of attended students fr the lab q3 = q1.difference(q2) #to get the absentee names: name and id only form_class = studStatus form = form_class(request.POST) if request.method == 'POST': if form.is_valid(): a = form.save(commit=False) a.currentDate = datetime.datetime.now().date() a.classGrp = group a.attendance = attendance a.studName = request.POST.get('value') //get the value from template: not working #getId = request.POST.get('id') #tried.studName = getId.get(id=getId) form.save() return redirect('editStudStatus',id) else: form = studStatus(request.POST ) context = { 'q3' : q3, 'group' : group, 'form' : form, 'today' :today, # 'q5' : q5 } return render(request,'studDetails.html',context, {'form':form}) Template: <tbody> {% for q in q3 %} <tr> <form method="post" enctype="multipart/form-data"> … -
Getting error : Object of type User is not JSON serializable in django python
i am new here in django python, when i am trying to get data, from 3 tables, i am getting error Object of type User is not JSON serializable, can anyone please help me why i am getting this error ? here i have added my views.py and models.py file views.py # views.py from tokenize import Token from django.contrib.auth import authenticate from rest_framework import status from rest_framework.exceptions import ValidationError from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_200_OK from rest_framework.views import APIView from rest_framework.response import Response from django.conf import settings from rest_framework.permissions import AllowAny from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password from django.core.exceptions import ValidationError from django.core.validators import validate_email from . import utils import jwt import json from trialrisk.models import UserProfile, Company, InviteUser class UserProfile(APIView): def post(self, request): try: data = request.data user_id = data['user_id'] user_data = User.objects.all().select_related('user_profile').select_related('company') return Response({"success": True, "status": "Success", "data": user_data}, status=status.HTTP_201_CREATED) except Exception as exp: print("Unexpected exception occurred: " + str(exp)) return Response({"success": False, "error": "Unexpected error occurred, please report this to Admin"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile") usertype = models.SmallIntegerField() title = models.CharField(max_length=255, null=True) dob = models.CharField(max_length=255, null=True) address = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255, null=True) city = models.CharField(max_length=255, null=True) zip = models.CharField(max_length=255, … -
How to insert value into random row instead of appending to the end in django?
@login_required def add_temp(request, example_id: int=None): Templist.objects.create(id=example_id) return JsonResponse({'status': 'ok'}) With create method by default, it just appends to the end of table. This is not what I want. The existing Templist database, for example id value 1 37 2 8 3 43 4 32 5 338 I want to insert a new value 99 into random row between 1 and 5, like a stream text. id value 1 37 2 8 3 43 4 99 <- new value 5 32 6 338 How to solve it in a simple way? -
How to redirect to a page after successful login and implement tokens within the templates in Django?
I am completely new to using JWT authentication in Django and don't know how to implement tokens within each template of my application. I am using JWT (JSON Web Tokens) instead of sessions. Scenario: I have a login form that uses AJAX where after clicking the submit button, it points to my API and takes the credentials of a registered user. If authenticated, I intend to use JWT authentication and access the dashboard page, and include those tokens within the page (instead of using sessions). However, I am not redirecting to the specified URL after logging in. Furthermore, I have used Simple-JWT in order to generate tokens but don't know how to include them in my template (AJAX call) in order to access an API. I have tried the following: views.py: I have created a login form that doesnt access the values. Instead, I have used AJAX in my template in order to point it towards the LoginAPI below: def login(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): pass #not doing anything here since all I need is a form for logging in. else: login_form = LoginForm() return render(request, "users/login.html", {"login_form" : login_form}) #Login API that gets called … -
Get coordinates from Point Django
I use class with PointField to store coordinates in database. # models.py from django.contrib.gis.db import models class MapPoint(models.Model): p = models.PointField() def __str__(self): return self.p Coordinates I get from template using AJAX. # views.py def mapper(request): if request.method == "GET": if request.is_ajax(): lat = float(request.GET.get('lat')) lng = float(request.GET.get('lng')) pnt = Point(lat, lng) MapPoint.objects.create(p=pnt) return render(request, 'map_in.html') Then I want to show all points in other template # views.py def mapper_done(request): query = MapPoint.objects.all().values() out_list = list(query) return render(request, 'map_out.html', {'out_list': out_list}) It returns: {'id': 1, 'p': <Point object at 0x7f42c712b670>} How can I get coordinates from Point? I want something like this: ID: 1, lat: 42.326565 lng: 52.325874 As I see, I need to iterate through querySet. But how? And sorry for bad English:) -
Getting a django error: get() returned more than one userData -- it returned 2
I am trying to build a coupon system in Django, and here I'm trying to display the balance that a person has with a vendor by comparing the database, after pressing the submit button. However, I'm facing the above mentioned error. Here is the html: {% block content %} <div class="container"> <h1>Welcome to your page, @{{ user.username }}</h1> <h3>Select vendor to check your balance!</h3> <br> <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Check Balance</button> {% endbuttons %} </form> {% if args.model %} <h4>You need to pay Rs {{ args.model }} to vendor {{ args.choice }} </h4> {% endif %} </div> {% endblock %} The urls.py: from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'profiles' urlpatterns = [ path('adminKaLogin/', views.adminKaPage, name="adminHome"), path('userLogin/', views.userKaLog, name="userHome"), ] The forms.py from django import forms from django.contrib.auth import get_user_model vendor_choices = [ ('1','Vendor 1'),('2',"Vendor 2"), ("3", "Vendor 3"), ] class select_vendor_form(forms.Form): Vendor_choices = forms.ChoiceField(choices=vendor_choices, widget=forms.RadioSelect) The views.py def userKaLog(request): form = select_vendor_form() if request.method=="POST" and form.is_valid(): choice = form.cleaned_data['Vendor_choices'] print(choice) records = userData.objects.get(Vendor_number = ('choice')).aggregate(Sum('itemPrice')) args = {'form': form, 'choice': choice, 'model':records} return render(request, 'profiles/useLogin.html', args) else: return … -
How can i make this query with django
For a bible site i can make a search with all the verses of the book like 'Genesis', or with the chapter 'Genesis 1' but i also want to search a verse like 'Genesis 1:1' How can i split the 1:1 so i can search for the verse also def get_queryset(self): query = self.request.GET.get('q') object_list = Verse.objects.all() if query: query = query.split() book = query[0] object_list = object_list.filter(book__icontains=book) if len(query) > 1: chapter = query[1] object_list = object_list.filter(chapter=chapter) return object_list -
how to fix the debugging and running error in pycharm community version?
{ def _exec(self, is_module, entry_point_fn, module_name, file, globals, locals): ''' This function should have frames tracked by unhandled exceptions (the _exec name is important). ''' if not is_module: pydev_imports.execfile ( file , globals , locals ) # execute the script else:} here i got an error while debugging and running.console says "in exec pydeventer code hereimports.execfile ( file , globals , locals ) ".plz help to fix it -
Django raw SQL query - looping over args and then using it in query
I have this code: class AllData(APIView): def get(self, *args): with connection.cursor() as cursor: cursor.execute( "SELECT authapi_user.id, authapi_tweet.created_on FROM authapi_tweet INNER JOIN authapi_user ON authapi_user.id = authapi_tweet.author_id ORDER BY created_on DESC;") I want the conditional part 'On' to match all the author_id's that will be passed through from *args. I know how to use the args data in the query but how can I dynamically change the number of conditions it's going to check so it iterates through all author_ids? -
How make a correctly authenticate?
I'm triyng make a authenticate with Django, alterate the model adding USERNAME_FIELD, and create a view to make the login, but still no working. I'm using the email as username Django==2.2.8 django-cors-headers==3.2.0 django-filter==2.2.0 djangorestframework==3.10.3 My code: User Model: class User(AbstractBaseUser, UGCModel): class Meta: app_label = 'user' first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=254, unique=True) username = models.CharField(max_length=150, unique=True) email_verified = models.BooleanField(default=False) genre = models.CharField(max_length=1, choices=GENRES, blank=True) date_of_birth = models.DateField(blank=False, null=True) cep = models.CharField(validators=[v.validate_cep], max_length=100) USERNAME_FIELD = 'username' def __str__(self): return '(User)%s' % self.email My View: def post(self, request, format=None): errors = None serializer = self.get_serializer(data=request.data) if not serializer.is_valid(): errors = serializer.errors else: username = request.data['username'] password = request.data['password'] user = authenticate(self, username=username, password=password) if user: pass else: errors = 'check username or password' if not errors: login(request, user) user.relationships.flush_cache() data = {'detail': 'authenticated', 'super' : user.super_user, 'key': Token.objects.get(user=user).key} return Response(data, status=status.HTTP_200_OK) detail = {'detail': errors} return Response(detail, status=status.HTTP_400_BAD_REQUEST) And I add this to settings: AUTH_USER_MODEL = "user.User" The user has created sucessful: uid: "_e8f35f44afa8" username: "vini@gmail.com" password: "123123" first_name: "vini" cep: "05407-002" last_name: "morais" email: "vini@gmail.com" date_of_birth: null But the authenticate always fail. vini@gmail.com 123123 check username or password Bad Request: /login WARNING:django.request:Bad Request: /login [20/Dec/2019 23:51:03] "POST … -
Authentication for two projects running simultaneously
I have two Django projects running simultaneously on localhost. One on port 8000 and the other 9000. When I log in on project 1, project 2 logs out and when I log in project 2, project 1 logs out. Anyone know why?