Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set model default value to a result bring returned by a function?
I've got a function inside my model which generates a random value for the model field and I need to set that value as a default for the model field. I've got the following model class Info(TimeStampedModel): info_id = models.UUIDField(primary_key=True) generated_url = models.TextField( null=False, blank=False, default=random ) def random(self): return 'customer.random.domain.com.' + ("".join(random.choices(string.ascii_uppercase + string.digits, k=5))) I wish the default value for the generated_url to be coming from the method inside the model named as random. but I get the following exception at Runtime: TypeError: random() missing 1 required positional argument: 'self' If I add parenthesis at the end of the function name as generated_url = models.TextField( null=False, blank=False, default=random() ) Then in that case I get a compile time error as the same: TypeError: random() missing 1 required positional argument: 'self' -
I get an error while using this command i don't know why?
ALTER USER kalyan CREATEDB; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATEDB' at line 1 -
generate pdf not working in single function
I am getting table data from the database and I added a button in HTML and I trying to get pdf by clicking on the button but it's not working. when I am using a separate function in view one for rendering data and another for generates pdf then time it's working but I want to use in single function for generating pdf and render my table. views.py def render_to_pdf(request, template_name, context_dict={}, filename="document"): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="'+filename+'".pdf"' template = get_template(template_name) html = template.render(context_dict) pisa_status = pisa.CreatePDF( html, dest=response, link_callback=context_dict) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response def training_completed_attendance(request): xyz=trainingMaster.objects.filter(status='Active').order_by('code') context={ 'xyz':xyz, } if request.POST.get('pdf_download'): pdf= utils.render_to_pdf(request, 'dashboard/generate_pdf.html', context, filename='training conpleted') return HttpResponse(pdf, content_type='application/pdf') return render(request,'dashboard/training_completed_report.html',context) html <table class="table table-bordered text-center" border="1" id="table1"> <form method='post'> {% csrf_token %} <button type="submit" name='pdf_download'>Download</button> </form> <tr> <th>Male</th> <th>Female</th> <th>Total</th> </tr> </tr> {% for x in xyz %} <td style="width: 13%; text-align: center; " class="table-cell-label">{{x.male}}</td> <td style="width: 13%; text-align: center; " class="table-cell-label">{{x.female}}</td> <td style="width: 13%; text-align: center; " class="table-cell-label">{{x.total}}</td> {% endfor %} -
AUTH_USER_MODEL refers to model 'user.User' that has not been installed
I am creating a new project in django with a structure like the following: trakkiamultitennant __init__.py asgi.py settings.py urls.py wsgi.py users migrations __init__.py admin.py apps.py models.py serializers.py tests.py urls.py views.py I have updated the app in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'users', ] AUTH_USER_MODEL = 'user.User' Models.py class User(AbstractUser): is_company = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) is_client = models.BooleanField(default=False) @property def full_name(self): return self.first_name + " " + self.last_name class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(max_length=500, default=0) phone = models.CharField(max_length=50, default=0) address = models.CharField(max_length=500, default=0) gstin = models.CharField(max_length=50, default=0) but when I try to makemigrations it gives me the following error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'user.User' that has not been installed What am I missing? -
Django DRF Update field with GET method
I have a object table it has a available field which is True by default. I want to make this available field false when API calls through GET method. -
Defining path to image in django
I have a user input some information on a form, and this is used to generate an image that I wish to display on a webpage, however I am unable to work out how I should define the path to the image. I have a user input some information on a form, and this is used to generate an image: make_image.py sns_plot = sns.heatmap(data_from_user) fig = sns_plot.get_figure() fig.savefig(f"{outputs_dir}/{patient.patient_id}/output.png") #patient.patient_id is a also generated by the form I then write some html again based on user inputs and wish to add a link to the image created write_html.py #this is some prewritten html with open(f"{data_dir}/recommendations/{treatment}.html", "r") as file: data = file.read() # here I want to add the image image = f'<img src="output.png" alt = “User generated image”>’ data=data+image #Here i save the amended html with open( f"{outputs_dir}/{patient.patient_id}/treatments/{treatment}{order}.html", "w" ) as file: file.write(data) I am using django and this is my view views.py class TreatmentTemplateView(TemplateView): template_name = "../templates/patient/treatment_detail.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context["patient_id"] = self.kwargs["patient_id"] result = find_treatment(context["patient_id"]) context = result[0] context["patient"] = result[1] return context This view puts integrates the html generated in the functions above, the text side of things works fine, it is just … -
Search for user first name and last name together in django
I have a web page where it display the user's details such as their first name and last name, username, email etc. But I only can search either the user's first name or the last name in the search bar, how do I make it so that the user is able to type both the user's first name and last name and display the details out? This is how my web page looks like as shown in the picture below (Ex: The staff name display is admin (First name) and Tan (Last name): views.py @login_required() def allstaff(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = User.objects.filter(Q(first_name__icontains=search_post) | Q(last_name__icontains=search_post) | Q( username__icontains=search_post) | Q(email__icontains=search_post)) if not allusername: allusername = User.objects.all().order_by("-date_joined") else: allusername = User.objects.all().order_by("-date_joined") page = request.GET.get('page') paginator = Paginator(allusername, 3) try: allusername = paginator.page(page) except PageNotAnInteger: allusername = paginator.page(1) except EmptyPage: allusername = paginator.page(paginator.num_pages) context = {'allusername': allusername, 'query': search_post} return render(request, 'allstaff.html', context) allstaff.html {% extends "home.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <div … -
init function inside serializer class in django rest framework
This is a question of comprehension rather than code issue. I came across a code snippet of other person who has used init function inside the serializer class. I had to write update code on it. I wrote overriding the update method inside that serializer class which is as follows: class ProfileInfoApiview(UpdateAPIView): serializer_class = ProfileInfoSerializer def get_object(self): return self.request.user My serializer that i have wrote: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["name", "mobile","user_type"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) print("iam init") for field in self.fields: self.fields[field].required = True def update(self, instance, validated_data): print("iam update") user = instance user_type = validated_data.get("user_type") if user_type: if user_type == "student": Student.objects.create(user=user) if user_type == "parent": Parent.objects.create(user=user) if user_type == "teacher": Teacher.objects.create(user=user) instance.save() super(ProfileSerializer,self).update(instance,validated_data) return instance The confusion here is the init function that was written above. I just wrote the update function. The init was there already. Even if I remove the init function it works as expected and even I keep it there, it works fine. The print command is working that means init is working. But what is its use there?? If it does something why it is working when I removed it?? When is the init function called … -
Django Migrate table creation not consistent - multiple Legacy Databases
I'm a new Django user and I seem to have some issues creating tables with Django migrate to my legacy database (SQL Server). Basically, I have 3 legacy databases (comp1_db, comp2_db, comp3_db) whereby I've setup the routing as follows (Basically the exact same for each): **db_routers.py** class comp1Router: route_app_labels = {'contenttypes','shared_invoice_detail'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'comp1_db' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'comp1_db' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'comp1_db' return None class comp2Router: route_app_labels = {'contenttypes','shared_invoice_detail'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'comp2_db' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'comp2_db' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'comp2_db' return None class comp3Router: route_app_labels = {'contenttypes','shared_invoice_detail'} def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return … -
sublime text: Go to definition not working for source code in python site-packages
I want to check the source code of python packages in sublime text I have a django project folder as MainProject |-- src <-- contains the django project code |-- venv <-- contains all the virtual env related stuff Now from inside the MainpProject folder I do subl -n -a . It opens the sublime text editor In the below example when i try to right click and then select Go to definition on the get_user_model from django.contrib.auth import get_user_model It does not go to the file venv/lib/python3.9/site-packages/django/contrib/auth/__init__.py How to setup this. because i have to keep going through the source code a lot -
vscode: Go to definition in a django project is not working for source code in site-packags
I have a django project folder as MainProject |-- src <-- contains the django project code |-- venv <-- contains all the virtual env related stuff Now from inside the MainpProject folder I do code -a . It opens the vscode. In the below example when i try to right click and then select Go to definition on the get_user_model from django.contrib.auth import get_user_model It does not go to the file venv/lib/python3.9/site-packages/django/contrib/auth/__init__.py How to setup this. because i have to keep going through the source code a lot -
Making concurrent voice calls with python(Django)
I am trying to build a system with Django and Telnyx where I would need to initiate 2-way concurrent calls, maybe 5-10 concurrent calls from a session which will actively access the database. I am worrying about efficiency as python is a single threaded Language. What is the best possible way to do that? Any other stack to suggest is also appreciated. -
I was making Mood Based Recommendation system website and faced this issue while running the server. used django framework and python language
C:\Users\abc Sharma\Firefox Downloads\MoodieFoodie-master\MoodieFoodie-master>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self.args, **self.kwargs) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise exception[1] File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django_init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\importlib_init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in find_and_load File "", line 984, in find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap3' Traceback (most recent call last): File "C:\Users\abc Sharma\Firefox Downloads\MoodieFoodie-master\MoodieFoodie-master\manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\abc … -
Custom Authentication Login in Django via email
I am trying to understand login methods in Django. So because I want to login with email not username. I wrote a custom authentication backend and exposed it in settings.py AUTHENTICATION_BACKENDS = ( 'accounts.backend.EmailAuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ) class EmailAuthenticationBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **kwargs): try: user = Account.objects.get(email=email) if user.check_password(password): return user except user.DoesNotExist: pass And in view user_login how I authenticate the user. And it's actually works. I mean kind of... def user_login(request): nxt = request.GET.get("next") form = UserLoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(email=email, password=password) login(request, user) if next: return redirect(next) return redirect("/") context = { "form": form } return render(request, "accounts/user_login.html", context) the authenticate() method is returns the user. But redirect() is not working because in browser thinks user not logged in. I am not sure about how to handle the session part. and custom UserLoginForm class UserLoginForm(forms.Form): email = forms.CharField() password = forms.CharField() def clean(self, *args, **kwargs): email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") if email and password: user = authenticate(email=email, password=password) if not user: raise forms.ValidationError("user not exist") if not user.check_password(password): raise forms.ValidationError("incorrect password") return super(UserLoginForm, self).clean(*args, **kwargs) The second issue is if email or password wrong. it doesn't … -
django IIS maxAllowedContentLength
I have a django web site with a form uploading a video. It's running on IIS. When I click the upload button it writes The page was not displayed because the request entity is too large. I tried according to this answer to set Maximum allowed content length to 104857600 but it didn't help. How can I fix it? -
Highlight new posts in django/react
I have Post model in django which has Channel as foreign key. What I want to do is , whenever there is a new post in post model, that channel should get highlighted and that should be user specific. What I am thinking is whenever new post is created, there will be one flag is_highlighted which will be set to true. Is this the right way to do? any other better way? TIA class Post(models.Model): user = models.ForeignKey( User, on_delete=models.DO_NOTHING, blank=True, null=True, related_name="post_user_id") channel = models.ForeignKey( Channel, on_delete=models.DO_NOTHING, blank=False, null=False, related_name="post_channel_id") and channel model is class Channel(models.Model): channel_name = models.CharField( max_length=250, help_text="Channel channel_name") -
Example domain error in django on reset password
I am writing program to reset password in django. After filling email id and send link to change password when i click on link it goes to example domain page.why this is happning. setting.py INSTALLED_APPS = ['django.contrib.auth',] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'rexhoney4@gmail.com' EMAIL_HOST_PASSWORD = 'mecgfweiszkipmgw' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'TestSite Team <noreply@example.com>' enter image description here -
Django add_argument invalid literal for int() with base 10: '--s_p=test'
I want to get --s_p as str and --s_t as str, --places for multiple int def add_arguments(self, parser): parser.add_argument("--s_p",type=str), parser.add_argument("--s_t",type=str), parser.add_argument('--places',nargs='+', type=int) So, I use this command, but I have error as title python manage.py mycommand --s_p=test --s_t=test --places=1 2 Why does this happen??? -
Update View - Page not found
I am attempting to create an update view for a build log(subpost). My URL structure is /post/pk/buildlog/pkz/update The error I am getting is Page not found Raised by: blog.views.UpdateBuildLog ... post/<int:pk>/build-log/<int:pkz>/update/ [name='build-log-update'] The current path, post/118/build-log/53/update/, matched the last one. view class UpdateBuildLog(UpdateView): model = BuildLog form_class = BuildLogupdateForm template = 'blog/buildlog_update.html' url path('post/<int:pk>/build-log/<int:pkz>/update/', UpdateBuildLog.as_view(), name='build-log-update') I believe the error is being caused because of the two primary keys not being passed into the view but I cant figure out how to pass the second primary key(pkz) into the view -
How to maintain user session across different devices and browsers from the access code email link in django
After validating the user, I'm sending out the access token to user's email along with the link to come back to the same page. [![Access Token email][1]][1] [1]: https://i.stack.imgur.com/OWezf.png This works well when the user opens the email in the same browser where he has been validated but if he opens the mail on his mobile or some other browser and clicks the link, he is taken back to the first validation page where he has to enter his user details again. How can I maintain the same session across different platforms in Django. I know there are some methods to do that like, we need an API which takes an encrypted request id as a parameter which will be included as a token in the access code email link to landing page. The API will decrypt the encrypted request id and then return the payload back associated to the same request id and we can use the data on the Front End to identify the user and resume the access-code verification step. But I donno, how to implement that or if there is any better solution? -
Django server not starting
I am unable to start the server, it's giving me the error below, i am using only one model and migrations seems to be fine, any clue where i am going wrong in this File "C:\Users\atifs\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\atifs\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\management\commands\runserver.py", line 138, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\management\commands\runserver.py", line 65, in get_handler return get_internal_wsgi_application() File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\atifs\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\atifs\Documents\pythonmate_website\pythonmate\mysite\wsgi.py", line 17, in <module> application = get_wsgi_application() File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\handlers\wsgi.py", line 127, in __init__ self.load_middleware() File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\handlers\base.py", line 58, in load_middleware mw_instance = middleware(adapted_handler) TypeError: __init__() takes 1 positional argument but 2 were given -
Free text in Select2ListView django-autocomplete-light
:) I'll expose my case as detailed as possible: I'm using the functionality of autocomplete to automatically populate a value that is dynamic into the form. The form has several values, when you fill the first 3 I'm able to run an operation (with those values) and return a suggested value to the user. I needed to adapt a bit the return of parameters but I achieved it with Select2ListView class MyFunctionAutocomplete(autocomplete.Select2ListView): def get_list(self): if not self.request.user.is_authenticated: return [""] try: field1_pk = self.forwarded["field1"] field2_pk = self.forwarded["field2"] field3_pk = self.forwarded["field3"] except AttributeError: return [""] try: ObjField1 = ModelField1.objects.get(pk=field1_pk) ObjField2 = ModelField2.objects.get(pk=field2_pk) ObjField3 = ModelField3.objects.get(pk=field3_pk) return_value = ObjField1.get_result(param1=ObjField2, param2=ObjField3) except (ModelField1.DoesNotExist, ModelField2.DoesNotExist, ModelField3.DoesNotExist): return [""] return [return_value] With this code I'm able to do what I need when the requirements (forwarded value) are present. So far, so good My problem: I cannot ADD any value as an extra option. This value IS NOT a ForeignKey, it's a simple Float. I want the user to be able to use my suggested value or instead just replace it by another value of their choice. Let's say in the dropdown they have the value 3.22221 and they want to write 12.11. Since it can be … -
Issue Django Migrations Tree - Deployment Pythonanywhere
guys I have been having this issue when managing Django migrations on deployment, and I would like yo know what approach should I take: I am developing an application using Django and I am using Pythonanywhere to deploy the webapp, I am using sqlite as the database. I understand the Django Migrations work like a tree or a sequence (001, 002), but every time I make a change in a field locally it works fine because the tree have been save and the sequence have not changed, but when deploying the changes through github (having deployed the webapp and calling the migrations and migrate command, which creates another migrations files and sequence), usually I got an error indicating that the migration tree is broken; so I have to go to the app's migration folder and delete them and call again the migrations and migrate command. This is causing me a lot of problems due that I do not want to mess with schema of the database and loss the information. So, It is just me or anyone else is having this issue the migrations tree, not only on pythonanywhere but on others servers. Thank you guys! -
How do I use the Django rest framework to prolong a JWT session token?
I'm using Django 3.2 with the django.auth.contrib app and djangorestframework-jwt==1.11.0. How do I prolong/reissue a new session token upon receiving a request for an authenticated resource and validating the user can access that resource? I use the following serializer and view to login the user and issue the initial token class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): username = data.get("username", None) password = data.get("password", None) user = authenticate(username=username, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password is not found.' ) try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) update_last_login(None, user) except User.DoesNotExist: raise serializers.ValidationError( 'User with given email and password does not exists' ) return { 'username':user.username, 'token': jwt_token } class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) response = { 'success' : 'True', 'status code' : status.HTTP_200_OK, 'message': 'User logged in successfully', 'token' : serializer.data['token'], } status_code = status.HTTP_200_OK return Response(response, status=status_code) I have this in my settings file to keep the session to 1 hour initially JWT_AUTH = { # how long the original token is valid for 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), } The client submits the session token … -
How settings Redis not working in channels Layer?
I am trying to use django_redis's RedisChannelLayer as django channels's channel layer backend. Which results in the websocket opening and closing instantly. But it work fine with In memory channel layer. CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, }