Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sometimes ValueError raised after I deployed Django app using Python 3.9.5 with Apache 2.4 on windows10 home addition
In the development environment everything working good, However as soon as I deployed the Application with Apache24 webserver on Windows 10 Home, sometimes I get this error, when I refresh the page everything working good again... This is the full error Message: ValueError at /books set_wakeup_fd only works in main thread of the main interpreter Request Method: GET Request URL: http://196.221.149.169:8080/books Django Version: 3.2.4 Exception Type: ValueError Exception Value: set_wakeup_fd only works in main thread of the main interpreter Exception Location: C:\Python39\Lib\asyncio\proactor_events.py, line 632, in init Python Executable: C:\Apache24\bin\httpd.exe Python Version: 3.9.5 Python Path: ['C:\Users\eunan\church', 'C:\Python39\python39.zip', 'C:\Python39\Lib', 'C:\Python39\DLLs', 'C:\Apache24\bin', 'C:\Python39', 'C:\Python39\lib\site-packages'] Server time: Sat, 19 Jun 2021 08:45:35 +0000enter image description here -
the username and request.user name has the same value but django python doesnt' recognise it as the same
why am i getting not the same user Here is what in my views.py def upost(request, username): if request.method == 'GET': vng_u = request.user us = username vd_u = get_object_or_404(User, username=username) p_o_u = Name.objects.filter(user=vd_u).order_by('id').reverse() if request.user.is_anonymous: return redirect('login') else: if (vng_u == us): s = "same" else: s = "not" pgntr = Paginator(p_o_u,1) pn = request.GET.get('page') pgobj = pgntr.get_page(pn) return render(request, "network/users.html", { "xp": p_o_u, "pc": pgobj, "postuser": us, "uv": vng_u, "s":s }) here is what in my html {% if uv == postuser %} same {%else%} not the same {% endif %} {{s}} <div id="post-users"><br> Viewer: <strong id="v1">{{uv}}</strong><br> Poster: <strong id="v2">{{postuser}}</strong> {% for x in xp %}<br><hr> Content: {{x.content}}<br> {{x.timestamp}} {% endfor %} </div> and here is what appears on the html web page -
What might be the problems to use Profile attributes to authenticate users in Django?
I am trying to authenticate users in Django using either username or phone_number and password. We have to extend the User model to add phone_number as a new attribute and I did it using OnetoOneField from the Profile model and used phone_number to authenticate users using custom authentication backend as: from django.contrib.auth.backends import BaseBackend from django.contrib.auth.hashers import check_password from django.contrib.auth import get_user_model from django.db.models import Q from .models import Profile class MyBackend(BaseBackend): def authenticate(self, request, username=None, password=None): User = get_user_model() try: user = User.objects.get(Q(username=username)|Q(email=username)) except User.DoesNotExist: try: profile = Profile.objects.get(phone = username) user = profile.user except Profile.DoesNotExist: user = None if user and user.check_password(password): return user else: return None It seems like it works while logging in using the admin login portal but I found the suggestions of using CustomUserModel to achieve this. Is it safe to do this? or Do I have to create CustomUserModel inheriting from AbstractBaseUser? -
Flutter Web and Django routing directly from URL
I have Flutter web and Django backend (REST API). I want to serve flutter web from Django directly. Every thing works fine if I start from domain (localhost:8000) and navigate to (localhost:8000/others) from web. But it shows 404 if I push URL (localhost:8000/others) direct from browser. Note: On flutter only it works properly (used Navigator 2.0). But on intregating with Django its not working. -
Django ImproperlyConfigured: Application labels aren't unique
Question How do I configure my app and label my application correctly so that I don't run into a Application labels aren't unique error and so that it works? I understand that I can rename auth. I do not wish to rename auth. settings.py INSTALLED_APPS = [ ..., core.auth, ... ] $ python manage.py shell_plus returns Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/apps/registry.py", line 95, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: auth I added the following: core/auth/init.py default_app_config = 'core.auth.AuthConfig' core/auth/apps.py from django.apps import AppConfig class AuthConfig(AppConfig): name = "core_auth" label = "core_auth" verbose_name = "Core Auth" $ python manage.py shell_plus Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/stackoverflow/dev/venv/lib/python3.7/site-packages/django/apps/config.py", line 228, in create if not issubclass(app_config_class, … -
Tom-Select as Django Widget
I would like to use tom-select as an Django autocomplete select-widget. In the corresponding database table (Runners) are several hundred rows, so that I can't load all into the html page. In the model RaceTeam I have a ForeignKey to Runner. The select widget will be used in whole pages and in html fragments (via htmx). I tried subclass django.forms.Select, but this sucks all db rows into widget.choices. -
how to return number of distinct values django
i'm working on project for an hotel family = 'family' single = 'single' room_types = ( (family , 'family'), (single , 'single'), ) class Room(models.Model): room_no = models.IntegerField(unique=True) beds = models.IntegerField(default=2) balcon = models.BooleanField(default=False) room_type = models.CharField(max_length=15,choices=room_types,default=single) this is my views(query) lists = Room.objects.order_by().values('balcon ','beds','room_type').distinct().annotate(total=Count('beds',distinct=True)+Count('balcon',distinct=True)+Count('room_type',distinct=True)) i expect the query to return something like this beds: 4 , balcon : True , room_type : single , total : 10 beds: 3 , balcon : True , room_type : family, total : 4 and so on but it doesnt return as i expected ! is it possible to make a group by based on several fields and count based on that selected fields please ? thank you for helping .. -
django How to add multiple images with foreignkey
in our application, users must add a ad through the form Models.py: class Ad(models.Model): title=models.CharField('Заголовок',max_length=150,null=False,blank=False) content=models.TextField('Описание',max_length=500) price=models.PositiveIntegerField('Цена',help_text='0 = Договорная') date=models.DateTimeField('Дата',auto_now_add=True) def __str__(self): return self.title class Meta: verbose_name='Обьявление' verbose_name_plural='Обьявлении' class Images(models.Model): image=models.ImageField('Изображение',upload_to='upload_images/%Y/%m/%d/') ad=models.ForeignKey(Ad,on_delete=models.CASCADE) class Meta: verbose_name='Фото' verbose_name_plural='Фото' Views.py: def add_new(request): if request.method=='POST': form=AddForm(request.POST) if form.is_valid(): valid_form=form.save() for image in request.FILES.getlist('images'): photo=Images(ad=valid_form,image=image) photo.save() return HttpResponseRedirect('/') else: form=AddForm() return render(request,'add_post.html',{'form':form}) and as a result, ad.title is added to the database, and if I write photo = Images (ad = valid_form.pk, image = image), then an error occurs. help me please -
Missing required flag: » -a, --app APP parent app used by review apps
Guys I am trying to run my app, but everytime I have this problem. I tried to run it also with only -app flag. Here is what I tried: heroku run --app movie-raterr I got a message: Error: Missing required flag: » -a, --app APP parent app used by review apps heroku run » Error: Missing required flag: » -a, --app APP parent app used by review apps When I tried to run only with -app flag I got another kind of error: heroku run bash at Run.run (C:/Users/Mateusz/AppData/Local/heroku/client/7.54.1/node_modules/@heroku-cli/plugin-run/lib/commands/run/index.js:27:19) at Run._run (C:/Users/Mateusz/AppData/Local/heroku/client/7.54.1/node_modules/@oclif/command/lib/command.js:44:31) -
how to get some filtered results from class based views in Django rest framework?
My models.py from django.db import models from django.contrib.auth.models import User import datetime from django.utils import timezone # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' def __str__(self): return str(self.standard) + ' class' class User_details(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) email = models.EmailField(max_length=30) mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return self.name class Mentor(models.Model): name = models.CharField(max_length=30) details = models.TextField() ratings = models.FloatField(default=2.5) class Meta: verbose_name_plural = 'Mentors' def __str__(self): return self.name class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() end_time = models.DateTimeField() isDoubtClass = models.BooleanField(default=False) doubtsAddressed = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_name class SavedClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) name = models.ForeignKey(User_details, on_delete=models.CASCADE) is_registered = models.BooleanField(default=False) is_attended = models.BooleanField(default=False) class Meta: verbose_name_plural = 'SavedClasses' def __str__(self): return 'SavedClass : ' + str(self.class_details) my serializers.py from rest_framework import serializers from . import models class LiveClass_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass fields = '__all__' class User_details_serializer(serializers.ModelSerializer): class Meta: model = models.User_details fields = '__all__' class LiveClass_details_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass_details fields = '__all__' class Mentor_serializer(serializers.ModelSerializer): class Meta: … -
'tuple' object has no attribute 'user'
Thank you so much for your help, i really appreciate it. I get this error "'tuple' object has no attribute 'user'" Anybody can tell me if my codes is right. im trying to make artist followers system. View.py @api_view(['GET']) @permission_classes([IsAuthenticated]) def artist_follow(request, pk): artist = Artist.objects.get(pk=pk) current_user = User.objects.get(pk=request.user.id) # check the current user already followed the artsit, if exist remove it else add if artist.followers().user.filter(user=current_user).exists(): # This line throw error artist.followers().user.remove(current_user) else: artist.followers().user.add(current_user) return Response(status=status.HTTP_200_OK) Model.py class Artist(models.Model): name = models.CharField(unique=True, max_length=100) ..... def __str__(self): return self.name def followers(self): return ArtistFollower.objects.get_or_create(artist=self) class ArtistFollower(models.Model): artist = models.OneToOneField(Artist, on_delete=models.CASCADE) user = models.ManyToManyField(User, related_name='user_artist_followed') def __str__(self): return self.artist.name -
How to get Image file size in django model?
I wanna save image file size in database after uploading it. How can I do that in django models? It'll also work if I can get the size in the views. But since there can be multiple images in one Community post, I am unable to get the size for each of them. My models.py file: from django.db import models import os class Community(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=500) def __str__(self) -> str: return self.title class CommunityImages(models.Model): post = models.ForeignKey(Community, on_delete=models.CASCADE) height = models.IntegerField(null=True, blank=True) width = models.IntegerField(null=True, blank=True) image = models.ImageField(upload_to='communityImages/%Y/%m/%d', blank=True, null=True, height_field='height', width_field='width') @property def images_exists(self): return self.communityImages.storage.exists(self.communityImages.name) def community(self): return self.post.id def __str__(self): return "%s %s " % (self.post_id, self.image, ) class Meta: verbose_name_plural = "Community Images" My views.py file: from django.http import JsonResponse from .models import CommunityImages, Community import json import os def image_detail(request, post_id): community_post = {} communityPostImages = list(CommunityImages.objects.filter(post=post_id).values('id','image', 'height', 'width')) for i in range(len(communityPostImages)): communityPostImages[i]['img_name'] = os.path.split(communityPostImages[i]['image'])[-1] communityPostImages[i]['type'] = os.path.splitext(communityPostImages[i]['img_name'])[-1].replace('.', '') communityPostImages[i]['dimension'] = str(communityPostImages[i]['height']) + "x" + str(communityPostImages[i]['width']) community_post['communityPostImages'] = communityPostImages data = json.dumps(community_post, indent=4, sort_keys=False, default=str) return JsonResponse(data, safe=False) Thanks in advance! -
how do I properly write django helper functions in order to check for new rows, and if the data was changed?
I am trying to write two functions in Django as helpers where it will help me to check if new data is coming or if the existing data was changed for further update is_new_row - will understand if the row is new and add it to an array that will be bulk created is_data_modified - will look for the row in the old data and understand if the data of that row is changed and will update only if its changed old_data = Person.objects.all() for row in api_data: if is_new_row(row, old_data): new_rows_array.append(row) else: if is_data_modified(row, old_data): ... # do the update else: continue helpers def is_new_row(row, old_data): ?? def is_data_modified(row, old_data): ?? -
Django-crontab can't make model query
I have a model inside tools app called ApiKeys and tried to update the model in specific time intervels. I used django-crontab for this purpose. CRONJOBS = [ ('*/1 * * * *', 'tools.cron.reset_api_calls','>>logs.log') ] function - from .models import ApiKeys def reset_api_calls(): try: keys = ApiKeys.objects.all() for key in keys: key.api_calls = 0 key.save() except Exception as e: print(e) model - class ApiKeys(models.Model): key_token = models.CharField(max_length=50, primary_key=True) api_calls = models.IntegerField(default=0) las_used_date = models.DateTimeField(default=timezone.now) But it gives error log - no such table: tools_apikeys Note: The table does exist in database and accessible through django-shell and views.py as well. -
How to create own model that can authenticate like admin user in django
I create own model user but can't authenticate it like in admin user # myapss/models.py from django.db import models from django.contrib.auth.hashers import make_password, check_password from django.db.models.manager import Manager class MyOwnManager(Manager): ... class MyOwnUser(models.Model): username = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=255) ... objects = MyOwnManager() I want to authenticate this model without using AbstractUser or AbstractBaseUser #myapps/views.py from .models import MyOwnUser def login(request): # Authentication -
Kafka custom logging handler makes django app unlisten on port
I have a django app and I need to send my logs to the kafka server. So I implemented a custom handler as below: import logging from kafka import KafkaProducer class KafkaHandler(logging.Handler): def __init__(self, hosts=['DEFAULT_KAFKA_HOST:DEFAULT_KAFKA_PORT'], topic='DEFAULT_KAFKA_TOPIC'): logging.Handler.__init__(self) self.producer = KafkaProducer( bootstrap_servers=hosts, security_protocol='SASL_SSL', sasl_mechanism='SCRAM-SHA-512', sasl_plain_username='KAFKA_USER', sasl_plain_password='KAFKA_PASSWORD', value_serializer=lambda v: json.dumps(v).encode('utf-8'), linger_ms=10) self.topic = topic The problem here is that when I run the django app via python manage.py runserver in my local app runs without any trouble but my localhost doesn't listen on the specific port. output of netstat -tulpn: (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN - tcp6 0 0 :::80 :::* LISTEN - tcp6 0 0 ::1:631 :::* LISTEN - udp 0 0 127.0.0.53:53 0.0.0.0:* - udp 0 0 0.0.0.0:631 0.0.0.0:* - udp 0 0 0.0.0.0:5353 0.0.0.0:* - udp 0 0 0.0.0.0:54922 0.0.0.0:* - udp6 0 0 :::58148 :::* - udp6 0 0 :::5353 :::* - But after I comment out the producer initialization everything works … -
Celery retry exception errors
I'm working on a project that requires me to reschedule tasks and I'm running into a problem. Would appreciate any feedback. I get a celery.exceptions.Reject error when attempting to retry a celery task. I've tested with a minimal tasks.py as listed below. Here is the code. tasks.py: from celery import Celery, Task from celery.utils.log import get_task_logger from django.conf import settings app = Celery('tasks', broker=settings.CELERY_BROKER_URL, backend=settings.CELERY_RESULT_BACKEND) logger = get_task_logger(__name__) @app.task(bind=True) def task_process_notification(self): try: if not random.choice([0, 1]): # mimic random error raise Exception() requests.post('https://httpbin.org/delay/5') except Exception as e: logger.error('exception raised - retry in 5 secs') raise self.retry(exc=e, countdown=5) Celery log traceback: [2021-06-19 04:21:19,342: INFO/MainProcess] celery@macbook-pro-16.lan ready. [2021-06-19 04:21:23,762: INFO/MainProcess] Received task: stocks.tasks.task_process_notification[ff372faa-febf-4d47-8628-2851a740cac3] [2021-06-19 04:21:23,765: ERROR/ForkPoolWorker-9] stocks.tasks.task_process_notification[ff372faa-febf-4d47-8628-2851a740cac3]: exception raised - retry in 5 secs [2021-06-19 04:21:23,775: ERROR/ForkPoolWorker-9] stocks.tasks.task_process_notification[None]: exception raised - retry in 5 secs [2021-06-19 04:21:23,777: WARNING/ForkPoolWorker-9] Task stocks.tasks.task_process_notification[ff372faa-febf-4d47-8628-2851a740cac3] reject requeue=False: Traceback (most recent call last): File "/Users/TLK3/PycharmProjects/stratbot/stocks/tasks.py", line 303, in task_process_notification raise Exception() Exception During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/app/task.py", line 721, in retry S.apply_async() File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/canvas.py", line 235, in apply_async return _apply(args, kwargs, **options) File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/app/task.py", line 561, in apply_async return self.apply(args, kwargs, task_id=task_id or uuid(), File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/app/task.py", line … -
How to list integer field of distinct values in ascending order in Django
I am using django as backend and PostgresSql as backend. One problem I'm getting is sorting the distinct values in ascending order. I Have Distinct values in filter as: 16,14,4,64,8,6,12,10,18,2,32,24 now i want those values as 2,4,6,8,10....... I have code like this to get those distinct values filter_cores = Processor.objects.distinct().values('cores') HOW I CAN DO IN ASCENDING ORDER? -
how can i delete a permission from a group
I'm working on a small project using Django / Rest Framework, and now i would like to add soem permissions / Groups. I would like to know how can i add and delete a permission from a group i already did some research on Google and here i found only how to add but i'm steel looking for a way to delete a permission from a group, this is what i found : from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) Can someone explain to me how to delete a permission from a group ? Thank you -
Better ways to generate codes in django (python)
I am working on an authentication project where I am applying different features like email verification, password reset and these features rely on emails. Now i want to send a code to the user through an email and verify that on the backend. Now to generate the code(5-digit), this is what i did; import random code = random.randint(10000, 99999) print(code) I just want to know is this a better way to do so. Are there any drawbacks or just fine. -
bootstrap5 - how to next and prev button reduce the area?
I want to use bootstrap carousel. But the next and previous buttons are too long up and down to use the nevbar. how to next and prev button reduce the area? -
django.urls.exceptions.NoReverseMatch: Reverse for 'drafts' with keyword arguments '{'pk': 3}' not found. 1
Iam getting error "django.urls.exceptions.NoReverseMatch: Reverse for 'drafts' with keyword arguments '{'pk': 3}' not found. 1" I have created a button for delete view, and it is not working. whebever iam clicking on button the above error is coming. Kindly help here is the code : in views.py class DraftsView(ListView): model=models.NewPost context_object_name='newpost' class DraftsEditView(DetailView): context_object_name='draft_view' model=models.NewPost template_name='blogapp/newpost_details.html' # pk_url_kwarg="id" class DraftsUpdateView(UpdateView): fields=('Author','Title','Text') model=models.NewPost class DraftsDeleteView(DeleteView): model=models.NewPost context_object_name='newpost' success_url=reverse_lazy("blogapp:drafts") In urls.py urlpatterns=[url('about/',views.about,name='about'), url('register/',views.register,name='register'), url('user_login/',views.user_login,name='user_login'), url('newpost/',views.NewPostView,name='newpost'), url('drafts/',views.DraftsView.as_view(),name='drafts'), # path('drafts/<int:pk>/',views.DraftsEditView), path('<int:pk>',views.DraftsEditView.as_view(),name='view_draft'), path('update/<int:pk>/',views.DraftsUpdateView.as_view(),name='update'), path('delete/<int:pk>/',views.DraftsDeleteView.as_view(),name='delete') ] in newpost_details.html <a href="{% url 'blogapp:delete' pk=draft_view.pk %}"> <input class="btn btn-danger" type="text" name="" value="Delete"> </a> -
How to pass values to input field's value with spaces
<form action="handleAppointment/" method="post" > {% csrf_token %} <div class="inputfield"> <label for="doctor" class="label">Doctor</label> <input type="text" name="doctor" id="doctor" class="input" value={{ doctorName.name }} > </div> this is my form i want full value from database.but here {{doctorName.name}} is showing value which is before space. def bookAppointment(request , id ): doctor = Doctor.objects.filter(id = id ).first() print(doctor.name) context = {'doctorName': doctor} return render(request , 'patient/appointmentForm.html' , context) after running this code it shows ' Tapan Shah ' as output in terminal. which is full name but it shows ' Tapan ' before space value in frontend. -
Deploy django with apache2 error - ModuleNotFoundError: No module named 'encodings'
I tried to deploy my django app to my local vagrant but show the error below. '/var/www/venv/lib/python3.8/lib/python38.zip', '/var/www/venv/lib/python3.8/lib/python3.8', '/var/www/venv/lib/python3.8/lib/python3.8/lib-dynload', Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f69c61ddc40 (most recent call first): <no Python frame> This code is log with apache2 tail /var/log/apache2/error.log <VirtualHost *:80> ServerName 192.168.2.26 DocumentRoot /var/www/django_app WSGIScriptAlias / /var/www/django_app/dj_rest_ql/wsgi.py # adjust the following line to match your Python path WSGIDaemonProcess 192.168.2.26 processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/venv/lib/python3.8 WSGIProcessGroup 192.168.2.26 <directory /var/www/django_app> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /var/www/django_app/static/ <Directory /var/www/django_app/static> Require all granted </Directory> </VirtualHost> This is directory deployment /var/www/django_app /var/www/venv Is everyone used to meet this problem, please give me the solution, Thanks you in advance. Or if anyone have an good article for deploy djano with apache2 or nginx, please recommend me some. -
How to pass a token to views that require authentication in django rest framework
I have an app that stores users and their posts. To view the page of a user, I want it to require authentication for a given user. I'm not quite sure how to implement this because before without DRF, I'd just check if the current user was the same as the id requested in the url like page/users/10. DRF generates tokens for each user which I have specified when they register with this: class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": Token.objects.get(user=user).key }) Each token keys to a user like here: What I am wondering is how can I get each of these tokens to be used to authenticate the user. If the user logs in with his account, how will I be able to get the token and then pass it to the restricted views?