Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to generate random integers using django forms.py?
I just started learning Django and have a problem: I initially used a class-based view to save information from the front end or user. I then decided to switch to forms.py. My problem is I cannot generate a random number to be saved using forms.py. I do not know if I should recreate this in forms or models. This was the code I wrote in views.py: def createproformastandard(request): now = datetime.datetime.now() year = now.year month = now.month day = now.day if len(str(day)) == 1: day = "0" + str(day) if len(str(month)) == 1: month = "0" + str(month) today = str(year) + "/" + str(month) + "/" + str(day) date = str(year) + str(month) + str(day) randint = str(random.randint(1000, 9999)) rand = str("TSCL") + date + "-" + randint + str("-P") rand = str(rand) while len(ProformaReceipt.objects.filter(rand=rand)) != 0: randint = str(random.randint(1000, 9999)) rand = date + randint rand = int(rand) form = CreateProformaReceipt() if request.method == 'POST': form = CreateProformaReceipt(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'proforma/proforma_form_standard.html', context) -
How to query Django objects based on a field value in the latest ForeignKey?
I have a Django application to store hourly price and volume (OHLCV candle) for several markets. What I'm trying to achieve is to compare the latest volume of all markets and set top10 = True to the 10 markets with the highest volume in the latest candle. What is the most efficient way to do that ? EDIT: The queryset should select all the most recent candle in every markets and sort them by volume. Then return the 10 markets the top 10 candles belong to. models.py class Market(models.Model): top10 = JSONField(null=True) class Candle(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, related_name='candle', null=True) price = models.FloatField(null=True) volume = models.FloatField(null=True) dt = models.DateTimeField() -
Django change model, migrate, and update the existing records
I had a Django model defined as: from users.models import User class Record(models.Model): user = models.ForeignKey( User, on_delete=SET_NULL, null=True) ... I realized that it would be better to rewrite the above model as: from userprofile.models import UserProfile class Record(models.Model): user = models.ForeignKey( UserProfile, on_delete=SET_NULL, null=True) .... How can I migrate (so the new definition of the model Record) is used, without having to lose the old Record instances in the databases? What is the general process of such migrations? Because if I migrate with the new definition of Record, I lose access to the old Record objects so I can't update them. However, if I don't migrate, Django won't let me use UserProfile as the user field. -
Running a Django using gunicorn in docker with reload gives TypeError
Django version: 2.2.23 Everything was working fine. However, when I try to use the --reload flag with gunicorn, it results in the following error: [2021-06-08 09:48:07 +0000] [79] [INFO] Starting gunicorn 19.7.1 [2021-06-08 09:48:07 +0000] [79] [INFO] Listening at: http://0.0.0.0:8000 (79) [2021-06-08 09:48:07 +0000] [79] [INFO] Using worker: sync /usr/lib/python3.8/os.py:1023: RuntimeWarning: line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used return io.open(fd, *args, **kwargs) [2021-06-08 09:48:07 +0000] [81] [INFO] Booting worker with pid: 81 Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/local/lib/python3.8/dist-packages/gunicorn/reloader.py", line 42, in run for filename in self.get_files(): File "/usr/local/lib/python3.8/dist-packages/gunicorn/reloader.py", line 28, in get_files fnames = [ File "/usr/local/lib/python3.8/dist-packages/gunicorn/reloader.py", line 29, in <listcomp> re.sub('py[co]$', 'py', module.__file__) File "/usr/lib/python3.8/re.py", line 210, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or bytes-like object This is my dockerfile: #20.04-LTS FROM ubuntu:focal RUN apt update # install python RUN apt install -y git python python3 python3-dev python3-pip python3-virtualenv && pip3 install --upgrade pip ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 RUN mkdir /web WORKDIR /web ADD requirements.txt /web/ RUN pip3 install -r requirements.txt COPY . /web My docker-compose: version: '2' services: web: build: . depends_on: … -
Django OneToOneField to multiple models and multi OneToOneField
I have the following models: class District(models.Model): pk_district = models.AutoField(primary=True) class Block(models.Model): pk_block = models.AutoField(primary=True) class Community(models.Model): pk_community = models.AutoField(primary=True) class RelateOne(models.Model): pk_object = models.OneToOneField('District or Block or Community') name = models.CharField() class RelateTwo(models.Model): pk_object = models.OneToOneField('District or Block or Community') name = models.CharField() I want the RelateOne or RelateTwo model to associate District or Block or Community, and then I can use it like this: district = District.objects.get(pk=1) district.relate_one.name district.relate_two.name block = Block.objects.get(pk=1) block.relate_one.name block.relate_two.name Block.objects.select_related('relate_one','relate_two') How should I set up the model correctly? -
Stripe API, How can I get"customer_email" when Checkout Session executed
I want Django App to send a confirmation email to a customer when webhook is executed, In order to send an email, I need to get the customer's email address when they make payment. But the JSON posted by stripe Webhook always sends customer_email with null value. Here's the result from the part of Webhook object. { "api_version": "2020-08-27", "created": 1623048315, "data": { "object": { "allow_promotion_codes": null, "amount_subtotal": 1, "amount_total": 1, "billing_address_collection": null, "cancel_url": "http://3.129.28.xxx/subscriptions/cancel/", "client_reference_id": "1", "currency": "jpy", "customer": "cus_Jcrw9AXrxWB91I", "customer_details": { "email": null, "tax_exempt": "none", "tax_ids": [] }, "customer_email": null, "id": "cs_test_a1gup9kG1ArIxORROMUbKqg6eBnIknoYdgQARcr3AS14DGo2gLFfVnxxxx", You can see "customer_email": null, And "customer_details"'s "email" is also null, Therefore I thought I need to get "customer_email" when "create_checkout_session" is executed. So I added "customer_email=userEmail" in create_checkout_session view.py @csrf_exempt def create_checkout_session(request): if request.method == 'GET': # domain_url = 'http://localhost:8000/' domain_url = 'http://3.129.28.206/' stripe.api_key = settings.STRIPE_SECRET_KEY try: checkout_session = stripe.checkout.Session.create( customer_email=userEmail, client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=domain_url + 'subscriptions/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'subscriptions/cancel/', payment_method_types=['card'], mode='subscription', line_items=[ { 'price': settings.STRIPE_PRICE_ID, 'quantity': 1, } ] ) return JsonResponse({'sessionId': checkout_session['id']}) except Exception as e: return JsonResponse({'error': str(e)}) But it does not work. So I tried a different attempt. customer_email = request.org.billing_email It also does not work. and there is … -
Django Rest Framework PyJWT Token Invalid header padding
I am using Django Rest Frame Work and I'm trying to get authenticated user info, using token in session views.py: # Get Authenticated User Data class UserAPIView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): return Response(UserSerializer(request.user).data) JWTAuthentication class JWTAuthentication(BaseAuthentication): def authenticate(self, request): token = request.COOKIES.get('jwt') print('token = ', token) if not token: return None try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) print('payload = ', payload) except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed('unauthenticated') user = User.objects.get(pk=payload['user_id']) if not user: raise exceptions.AuthenticationFailed('User not found!') return (user, None) @staticmethod def generate_jwt(id): payload = { 'user_id': id, 'exp': datetime.datetime.now() + datetime.timedelta(days=1), 'iat': datetime.datetime.utcnow() } return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256') But I got this error Invalid header padding this is the Traceback [08/Jun/2021 10:44:09] "GET /api/account/user/ HTTP/1.1" 500 134862 token = b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE2MjMyMzU0NDcsImlhdCI6MTYyMzE0MTg0N30.qnNZw3M5YiLMalc78wknjtuTOztHbjyr2swHyK1xuGY' Internal Server Error: /api/account/user/ Traceback (most recent call last): File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\api_jws.py", line 186, in _load header_data = base64url_decode(header_segment) File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\utils.py", line 42, in base64url_decode return base64.urlsafe_b64decode(input) File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\base64.py", line 133, in urlsafe_b64decode return b64decode(s) File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\base64.py", line 87, in b64decode return binascii.a2b_base64(s) binascii.Error: Invalid base64-encoded string: number of data characters (37) cannot be 1 more than a multiple of 4 this is the rest of Traceback During handling of the above exception, another exception occurred: File … -
Django admin - User and group extend
Iam trying to update my user model in Django's admin Panel. I want to add a field/column in Admin panel named "Group" for Users. This field will have the option to select any value from the existing Groups (single option only/Dropdown). I tried to search for the document but I couldnt found out the relevant information to manipulate the User Admin panel. Although I do found a few blogs and video where they have created a new app and extend the User model. Is it possible to update Admin panel for User? Please suggest any document or blog or any approach to achieve the goal. -
Can login in production but not in development [closed]
I have backed up my postgres database from production and am using it in my dev environment. Everything works as it does in production aside from authentication. When I try to login with the correct details it fails. I thought this could be because of something in settings.py however I don't really have anything added (maybe I need something?) -
How to perform a validation according to types, instead of field by field, in Django?
In Django, before calling the "save" method of an instance, it is possible to implement your own validation by defining the "clean" or "full_clean" method in the corresponding model. The problem is that in that case it would be necessary to check each of the fields and add a particular behavior; however, what I want is a more general behavior, so that if you enter a type that does not match the one defined in the model, such field will be saved as None. Example: Let's suppose an application, with the following model: class Company(models.Model): name = models.CharField(max_length=255, null=True, blank=True) date_of_formation = models.DateTimeField(null=True, blank=True) assets = models.FloatField(null=True, blank=True) And assume we have these 3 json data inputs: input_1 = { "pk": 1, "name": "Alexander", # right type "date_of_formation": "2021-01-01", # right type "assets": 500023.658 # right type } input_2 = { "pk": 2, "name": ["Alex", "Vero"], # WRONG type "date_of_formation": "2021-01-01", # right type "assets": 523658 # right type } input_3 = { "pk": 3, "name": ["Alex", "Vero"], # WRONG type "date_of_formation": 65, # WRONG type "assets": "523658" # WRONG type } The behavior I would expect is something like: Company.objects.create(**input_1) Company.objects.create(**input_2) Company.objects.create(**input_3) >> Company.objects.get(pk=1).__dict__ { "id": 1, "name": "Alexander", … -
Why we cannot use select_related for ManyToMany fields
let's say i have the following fields class ABC(models.Model) whatever=models.ManyToManyField('DEF') class DEF(models.Model) something=models.CharField() I want to retrieve ABC along side each DEF it's connected to, why i cannot do this ? ABC.objects.filter(pk=123).select_related('DEF').get() I believe we can do this in one SQL query like so select * from ABC inner join ABC_DEF on ABC.id = ABC_DEF.ABC_ID inner join DEF on DEF.id = ABC_DEF.DEF_ID -
How to filter Django serializer data?
I'm trying to filter data based on userName in JWT. This is how I've been trying to do it: views.py: class TestView(APIView): permission_classes = (IsAuthenticated,) def get(self, request): token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1] data = {'token': token} try: valid_data = VerifyJSONWebTokenSerializer().validate(data) user = valid_data['user'] request.user = user person = Person.objects.filter(userName=request.user) except ValidationError as v: print("validation error", v) return Response(person[0]) This works as I can get the Person data with print("Person: ", person[0]). The return Response(person[0]) however returns an error: TypeError: Object of type Person is not JSON serializable. I guess I could use a serializer class to return a valid JSON, am I right? I have this in my serializers.py: class TestSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' I just don't know how to use this with my view. If I use serializer instead of person = Person.objects.filter(userName=request.user), how is the filtering supposed to be done? Please correct me if I'm not on right track at all. -
Semgrep: Looking for wrong import
How would I go on about making Semgrep check if my codebase is important the wrong module from the wrong place? E.g. in my django project: from gettext import gettext but we should really do from django.utils.translation import gettext Any ideas on how to achieve this with semgrep? -
What is actual meaning of r'^ icon in every urls? can any one explain what is his meaning and how important this are in details [duplicate]
This is the code in question: url(r'^dreamreals/', ListView.as_view(model = Dreamreal, template_name = "dreamreal_list.html")), ) -
Threading: Restarting a thread
I have a django project that I am currently working on. I have several threads that I use to fill a database through API requests when the user asks for a database update using a button. This works great. My problem is that I would like users to be able to refresh the database more than once while the server is active (in the future). Since threads can't be restarted once they finish, I'm not really sure how to proceed to achieve what I want. Here are my threads: agencies_thread = threading.Thread(target=fill_agencies, name="Database Updater1") companies_thread = threading.Thread(target=fill_companies, name="Database Updater2") contracts_thread = threading.Thread(target=fill_contracts, name="Database Updater3") orders_thread = threading.Thread(target=fill_orders, name="Database Updater4") projects_thread = threading.Thread(target=fill_projects, name="Database Updater5") resources_thread = threading.Thread(target=fill_resources, name="Database Updater6") I'm thinking that the threads have to be recreated everytime someones presses the button, but adding those lines ^^ in my views.py function that manages the database loading can't really work considering my function: elif urlRequest[:12] == 'loading.html': # PAGE DE CHARGEMENT global updateValue if updateValue == 0: agencies_thread.start() companies_thread.start() contracts_thread.start() orders_thread.start() projects_thread.start() resources_thread.start() updateValue = 1 updateState = 0 if agencies_thread.is_alive(): agenciesState = 'en cours de chargement' else: agenciesState = 'Chargement terminé' updateState += 1 if companies_thread.is_alive(): companiesState = 'en … -
How to pass value/variable from one function to another in django - views
Not able to pass a variable from one function to another. @api_view(['GET']) def UserList(request): loc = User.objects.all() latest_id = User.objects.latest('userid').userid #want to pass this variable into DetailList function serializer = UserSerializer(loc, many=True) return Response(serializer.data) @api_view(['GET']) def DetailList(request): loc = Detail.objects.all() serializer = DetailSerializer(loc, many=True) return Response(serializer.data) and finaly want to use that userid variable to add the data into Detail table. class UserAPIView(APIView): def post(self, request ): userid = request.data.get('userid') name = request.data.get('name') age = request.data.get('age') gender = request.data.get('gender') address = request.data.get('address') phone = request.data.get('phone') user_serializer = UserSerializer(data={"name": name, "age": age, "gender": gender}) detail_serializer = DetailSerializer(data={"userid": userid,"address": address, "phone": phone}) if user_serializer.is_valid(raise_exception=True): user_serializer.save() if detail_serializer.is_valid(raise_exception=True): detail_serializer.save() return Response({'status': 'Success'}) not able to pass variable data through declaring global , as getting error Nulltype is not callable. -
SQL to Queryset Django
i want to use this query in django, i have tried and read the django document but i still can't understand it Sql to QuerySet Django SELECT * FROM movie as m INNER JOIN similarity as s ON m.`movie_id` = s.first_movie WHERE `movie_id` = 1 ORDER BY `s`.`similarity_score` DESC -
Nginx error_page will not display
I can't configure nginx custom error pages /etc/nginx/sites-enabled/mysite looks like this error_page 404 /custom_404.html; location = /custom_404.html { root /usr/share/nginx/html; internal; I tried other paths as well looked all over the internet and still nothing that helped. I wasl also following this tutorial but no luck If anyone knows the solution for this and have a time to respond it would be awsome. Thank you all. -
Django-Beard MP_Node save to database with post request
I am new to django and I am trying to understand Django-beard. What I want is to save the data to the db, but for the models I have inherited from MP_Node. Here is the models: class Update(MP_Node): name = models.CharField(max_length=30) update = models.TextField() date = models.DateField(auto_now_add=True) node_order_by = ['created'] I am using viewsets for the views part and it takes care of the CRUD: class UpdateViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly] serializer_class = UpdateSerializer queryset = Update.objects.all() Can someone help me understand how do I save the data using POST or PUT? Currently I am getting the error that the path and depth fields are required but it is supposed to be generated automatically. I am using all the fields while serializing but I tried to set a particular few fields but then I am getting the error from the database level that Depth cannot be a not null constraint. class UpdateSerializer(serializers.ModelSerializer): class Meta: model = Update fields = '__all__' Is there a way to save the data using the MP_Node? -
How can check Bookings related to specific saloon in django
How can a saloon check the booking like how many people reserve the time slot for different service. When i click on check booking button is show the error 'WSGIRequest' object has no attribute 'saloon' Model.py class Booking(models.Model): saloon = models.ForeignKey(SaloonRegister, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) service = models.CharField(max_length=40) time = models.TimeField() date = models.DateField() View.py class SaloonCheckBooking(TemplateView): template_name = 'saloonCheck.html' def get(self, request, *args, **kwargs): checkBooking = Booking.objects.get(saloon_id=self.request.saloon.id) return render(request, self.template_name, {'checkBooking': checkBooking}) -
trying to setup mysql on ubuntu for django but getting error 'django.db.utils.OperationalError: (1046, 'No database selected')'
my Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'DATABASE' : 'DjangoProject', 'USER' : 'myprojectuser', 'PASSWORD' : 'Akbar@123456', 'HOST': 'localhost', 'PORT': '', # 'default-character-se' : 'utf8', # 'NAME': BASE_DIR / 'db.sqlite3', } } SHOW DATABASES command on terminal mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | DjangoProject | | information_schema | | mysql | | performance_schema | | sample | | sys | +--------------------+ 6 rows in set (0.00 sec) mysql> error File "/usr/local/lib/python3.8/dist-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.8/dist-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1046, 'No database selected') I have granted the user rights on the database but it still showing error, please help i want to run mySql just like sqlite3 where you can see your databases in the admin panel, and works same once settings are made, please tell if there is gui interface for mySQL and also how to see your database on the browser, -
Data not saving in database in Django
I am trying to save data into the database from the website. My web page is taking the data(image from my system) but in the database , its not showing up. If i add manually then its creating a new user entry and storing it. Here are my files: models.py class Details(models.Model): name = models.CharField(max_length=122) username = models.CharField(max_length=122) email = models.EmailField(max_length=122) password = models.CharField(max_length=20) def __str__(self): return self.name class Image_Data(models.Model): img_User = models.ForeignKey( Details, blank=True, null=True, on_delete=models.CASCADE) img_password = models.ImageField(null=True, blank=True) def __str__(self): return str(self.img_password) forms.py class ImageForm(ModelForm): class Meta: model = Image_Data fields = ('img_password',) labels = { 'img_password': 'Add your image ', } widgets = { 'img_password': forms.FileInput(attrs={'class': 'form-control', 'placeholder': 'Upload from device'}) } views.py def register_new_b(request): saved = False if request.method == "POST": # take whatever is posted to the Details Form form = ImageForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your message has been sent!') return HttpResponseRedirect('/register_new_b?saved=True') else: form = ImageForm() if 'saved' in request.GET: # sends saved var in GET request saved = True return render(request, 'register2.html', {'form': form, 'saved': saved}) here is what i get in database upon saving the image -
Docker run, after docker-compose build could not translate host name “db” to address: Name or service not known
I have currently a system built with docker-compose, it creates a Django application. I've use a database inside a container (postgresql) in my testing build. I want upload my docker image to docker-hub. When i run $ sudo docker-compose up Server goes up sucecesfully Recreating rest_api_db_1 ... done Recreating rest_api_web_1 ... done Attaching to rest_api_db_1, rest_api_web_1 db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2021-06-08 07:22:10.698 UTC [1] LOG: starting PostgreSQL 13.3 (Debian 13.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit db_1 | 2021-06-08 07:22:10.699 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2021-06-08 07:22:10.699 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2021-06-08 07:22:10.708 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2021-06-08 07:22:10.719 UTC [26] LOG: database system was shut down at 2021-06-08 07:15:22 UTC db_1 | 2021-06-08 07:22:10.726 UTC [1] LOG: database system is ready to accept connections web_1 | Operations to perform: web_1 | Apply all migrations: admin, api_bus_routes, auth, contenttypes, sessions web_1 | Running migrations: web_1 | No migrations to apply. web_1 | Watching for file changes with StatReloader web_1 | Performing system … -
Django images not displaying properly,static images not displaying
image I am a beginner and I have no idea what the problem is I did give URL and DIR in settings.py STATIC_URL = '/static/' STATICFILES_DIR = [(os.path.join(BASE_DIR, 'static'))] my index.html {% extends 'base.html' %} {% load static %} {% block title %} <title>Home page</title> {% endblock title %} {% block content %} <div class="container"> <div class="row"> <div class="col-lg-4"> <img src="{% static 'images/stickynotes.jpg' %}" alt="Notes" width="1500" hwight="993"> </div> <div class="col-lg-4"> <img src="{% static 'images/stickynotes.jpg' %}" alt="Notes" width="1500" hwight="993"> </div> <div class="col-lg-4"> <img src="{% static 'images/stickynotes.jpg' %}" alt="Notes" width="1500" hwight="993"> </div> </div> </div> {% endblock content %} my base.html <!doctype html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous"> {% block title %} {% endblock title %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="{% url 'index' %}"><img src="{% static 'images/logo.png' %}"</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link" href={% url 'index' %}>Home</a> <a class="nav-link" href={% url 'todolist' %}>Todo List</a> <a class="nav-link" href={% url 'contactus' %}>Contact Us</a> <a class="nav-link" href={% url 'aboutus' %}>About Us</a> </div> </div> </div> </nav> </head> <body class="bg-secondary"> {% block content %} {% … -
How to include Token in Header using Django Rest Framework
I am working with Token Authentication using Django REST Framework. I am generating a new token during User Registration. I need to pass this token to the frontend including in header. These are my code: settings.py: INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', ... ] urls.py: (project level) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('accounts.urls')), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] urls.py: (app level) urlpatterns = [ path('signup/', views.Register.as_view({"post":"register"}), name='users'), path('login/', views.Login.as_view({"post":"create"}), name='login'), path('profile/', views.Profile.as_view({"get":"list"}), name='profile'), ] views.py: # Register View class Register(viewsets.GenericViewSet, mixins.CreateModelMixin,): serializer_class = UserRegisterSerializer def register(self, request): data_dict = self.request.data firstname = data_dict['firstname'] lastname = data_dict['lastname'] username = data_dict['username'] email = data_dict['email'] password = data_dict['password'] mobile = data_dict['mobile'] data = userRegistrationModel.objects.create(firstname=firstname, lastname=lastname, username=username, email=email, password=password, mobile=mobile) if data: user = data.set_password(password) data.save() token = Token.objects.create(user=data) return Response({"message": "Registered Successfully", "code": "HTTP_201_CREATED", "Token": token.key}) else: return Response({"message": "Sorry Try Next Time!!!", "code": "HTTP_403_FORBIDDEN"}) # Login View class Login(viewsets.GenericViewSet, mixins.CreateModelMixin,): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def create(self, request, *args, **kwargs): data_dict = self.request.data email = data_dict['email'] password = data_dict['password'] data = authenticate(email=email, password=password) if data: users = Token.objects.filter(user=data).first() userData = UserRegisterSerializer(data) return Response({"message": "Login Successfully", "code": "HTTP_200_OK", "token": users.key, "user": userData.data}) else: return Response({"message": "Invalid Login", "code": "HTTP_401_UNAUTHORIZED"}) # Profile View …