Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't pass the input value from html to views
I am trying to create a add to cart function using django but unfortunately iám reaceiving an error "POST http://localhost:8000/update_item/ 500 (Internal Server Error)" Please help. Thanks in advance views.py def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('action:', action) print('productId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) if action == 'add-cart': input_value = int(request.GET['quantity']) orderItem.quantity = input_value orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) function updateUserOrder(productId, action){ console.log('User is logged in, sending data...') var url = '/update_item/' fetch(url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId': productId, 'action': action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data', data) location.reload() }) } -
Use static files in django/html for download gives 404
I am creating a web application in django when I wanted to create a static file download with html. I went into urls.py and modified it to have this at the end: static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Then I added this to index.html: {% load static %} <a href={% static "file.zip" %} download>Download File</a> Then I added these lines to mysite.settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I then went into my base directory and added a directory called static. I added the file file.zip into that directory, then went to the terminal and did a cd to the base directory. Finally, I run the command: python3 manage.py runserver I then go to the server adress and click Download File. At the bottom of the browser I then see: File.zip Failed- no file So I look back to the terminal and I see: "GET /file/AutoKMS.zip HTTP/1.1" 404 1760 in orange. I see that this has a 404 at the end, so i look to stack overflow. I have spent days finding the answer, and so far i have tried: Django Static files 404 Download static file displayed in the list Django https://docs.djangoproject.com/en/3.0/howto/static-files/ How do you make a working static file download with … -
From DetailView First detail page of the post are working but other Detail page are showing Page not found (404)
These following Error are displayed. """ Page not found (404) Request Method: GET Request URL: https://oil4us.com/**post/4/** Raised by: posts.views.PostDetailView No Category matches the given query.""" Why did post/4 page not find. If my views.py's code is wrong, I won't see any detail page of the post from the DetialView. But something is wrong. How to fix these problem? -
Django: caching in session / memory a complex object
I am developing my first Django project with version 3.0. There is a complex Python object I need to store somewhere in memory. On one of my Django apps, each html page implies several dozens of queries to Django because it serves as a proxy for a WMS server. The object stores some of the parameters used for querying the WMS server from Django (preferences for viewing the WMS map). I tried storing the object in session. This proved to be difficult due to the complexity of the object. Besides, even if this can achieved, this implies deserializing the object dozens of times for each HTML page. I finally gave up on this solution. So, eventually, I just created a Python Dictionary stored in the views.py module of the Django app, which stores the object with as associated key the request.user.id from Django (users must be logged in to use this Django app). My Django project won't have to support too many users (tops, 100-200 users), so I am not worried about the dictionary consuming too much memory. Of course, when the Django server is rebooted, the objects are lost, but that is an acceptable drawback. Maybe someone can have … -
got error at heroku stage : Push local changes
C:\Users\Rohan\python-getting-started>heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 8:39:00 PM web.1 | Traceback (most recent call last): 8:39:00 PM web.1 | File "c:\users\rohan\appdata\local\programs\python\python38\lib\runpy.py", line 194, in _run_module_as_main 8:39:00 PM web.1 | return _run_code(code, main_globals, None, 8:39:00 PM web.1 | File "c:\users\rohan\appdata\local\programs\python\python38\lib\runpy.py", line 87, in run_code 8:39:00 PM web.1 | exec(code, run_globals) 8:39:00 PM web.1 | File "C:\Users\Rohan\AppData\Local\Programs\Python\Python38\Scripts\gunicorn.exe_main.py", line 5, in 8:39:00 PM web.1 | File "c:\users\rohan\appdata\local\programs\python\python38\lib\site-packages\gunicorn\app\wsgiapp.py", line 9, in 8:39:00 PM web.1 | from gunicorn.app.base import Application 8:39:00 PM web.1 | File "c:\users\rohan\appdata\local\programs\python\python38\lib\site-packages\gunicorn\app\base.py", line 11, in 8:39:00 PM web.1 | from gunicorn import util 8:39:00 PM web.1 | File "c:\users\rohan\appdata\local\programs\python\python38\lib\site-packages\gunicorn\util.py", line 9, in 8:39:00 PM web.1 | import fcntl 8:39:00 PM web.1 | ModuleNotFoundError: No module named 'fcntl' [DONE] Killing all processes with signal SIGINT 8:39:00 PM web.1 Exited with exit code null -
Fixing Replies to Comments Section as it is appearing as a new comment
In my project, I have a comment section which is working fine but now that I have tried to add replies to these comments knowing that it is just another comment to a comment, it gets a little bit complex, every time I add a reply to a comment it appears as a new comment instead of a reply. I think that the error might be in the views section but I don't know how to fix it. Here is the models.py class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE) user = models.ForeignKey( User, on_delete=models.CASCADE) reply = models.ForeignKey( 'Comment', on_delete=models.CASCADE, null=True, related_name="replies") content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} by {}'.format(self.post.title, str(self.user.username)) Here is the views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter( post=post, reply=None).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') reply_id = self.request.POST.get('comment_id') comment_qs = None if reply_id: comment_qs = Comment.objects.get(id=reply_id) comment = Comment.objects.create( post=post, user=self.request.user, content=content, reply=comment_qs) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] … -
non English url path gets error 500 in production server in my django project
I have "myproject" in django that is for mywebsite.com I have url's such as "mywebsite.com/path1" that is working perfectly in both development (27.0.0.1:8000) and production server I have url's such as "mywebsite.com/مسیر۱" that is working perfectly in development (27.0.0.1:8000) server but gets error 500 in production server I have no idea what could be the problem. Any advice in this regard is highly appreciated -
How I can Put my all Django Admin posts to my localhost View?
My Recent Post in Django Administration Kamran object (4) Kamran object (3) Kamran object (2) Kamran object (1) How I can show these posts in my localhost View? -
JSONDecodeError Django Javascript JSON
I am getting a JSON Decode error at /charge when data = json.loads(request.body). I am working with stripe api as well as fetch api. The full error is this: Traceback (most recent call last): File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/antariksh/Desktop/Python Files/Owlet/Menu/views.py", line 151, in charge data = json.loads(request.body) File "/usr/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) That is the error. My code for the /charge/ view is this: @csrf_exempt def charge(request): if request.method == 'POST': print(request.POST) transaction_id = uuid.uuid4().hex data = json.loads(request.body) print(data) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, isComplete=False, status='Created') else: order, customer = guestOrder(request, data) total = data['form']['total'] order.transaction_id = transaction_id order.isComplete = True order.status = 'Accepted' order.save() ShippingAddress.objects.create( customer = customer, order = order, address = data['shipping']['address'], city = data['shipping']['city'], state … -
Transaction atomic on long process in django
Suppose I have celery task that run 10 worker thread. Each worker thread request 100 web service respectively from another server to receive data from it and save these data on database. I want if one worker that request from server, raise an exception, all received data, rolled back and not save in database. So I can set @transaction.atomic decorator for celery task. I want to know is it the right approach or not because for each task I open transaction and this remain open (It takes an average of 8 minutes) until all 100 web service called successfully. I am using django 2.2.7 and postgresql as database. -
Django Many2Many Through relation, getting properties from Through class
I'm trying to create a project where you can create ready meals by adding choosen ingredients into its recipes. In my models I had created 3 classes. One for ingredients (containing things like suggesteg portion, proteins, price etc.) Second class for ready products which are connected with Ingredient class via M2M relaction throught my 3rd class ReceipeIngredient where i want to specify weight of ingredient needed for that specific products. My problem is that I don't know how to access weight property from ReceipeIngredient class in my Product class. class Ingredient(models.Model): name = models.CharField(max_length=50, unique=True) protein = models.FloatField() carbohydrates = models.FloatField() fat = models.FloatField() quantity_per_portion = models.IntegerField(blank=True) price = models.DecimalField(max_digits=100, decimal_places=2, blank=True) class Product(models.Model): name = models.CharField(max_length=50) ingredient = models.ManyToManyField(Ingredient, through="ReceipeIngredient") @property def total_carbohydrates(self): return self.ingredient.aggregate(Sum("carbohydrates"))["carbohydrates__sum"] @property def total_protein(self): return self.ingredient.aggregate(Sum("carbohydrates"))["carbohydrates__sum"] / 100 * ReceipeIngredient.objects.get( ingredient=Ingredient.objects.get(name=self.ingredient.name), product=Product.objects.get(name=self.name) ).weight class ReceipeIngredient(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) weight = models.IntegerField() -
Invite users through email in django
I am working on a django project. I have to handle multiple users for that web application. At this moment I want to develop a system where admin invites other users using an email. In that email signup, link will be sent with a proper secure way. I want to give validation to that link. If the user does not signup within 7 days, the link will be disabled. I also want to ensure that the link works fine only with the corresponding email recipient. If the user tries to send the link to another email, the link will not work. I don't know how to do this in django. I need a proper guideline to develop this system. -
Django-tables2 send parameters to custom table template
I'm trying to use a custom table template to embed the django-filter fields on my table. So I copied the django-tables2 bootstrap.html template in a new file custom_table.html. Then I added it the following code in the thead section: {% if filter %} <tr> {% for filter_field in filter.form.fields %} <td> {{ filter_field }} </td> {% endfor %} <td> <button class="login100-form-btn" type="submit">Filter</button> </td> </tr> {% endif %} So the problem is : how can I send the filter to the table template? -
Django url tag not recognizing the pattern
I'm having an issue with the url. somewhere in my url.py i defined: path('servicesexpanded/<str:id>', views.servicesexpanded, name='servicesexpanded') which by my account: loads servicesexpanded / id which is passed to the views.py and further processed. when i try to add a href like follows: href="{% url nexturl %}" where nexturl is : 'servicesexpanded/1' i get the following error: Reverse for 'servicesexpanded/1' not found. 'servicesexpanded/1' is not a valid view function or pattern name. And i don't have any clue how to solve it! Can smbdy help me out? Thanks! -
HOW TO HANDLE TOKEN AUTH USING DJANGO AS FRONTEND
i am build a webapp using django both for the frontend and the backend. i know is unusual but i am doing for the following reason: I am not very familiar with languages other then python but i want to understand more how the frontend and backend work together I am planning in the future to learn other tools to handle the front end such as react and angular and after i will probably remake the frontend but the backend will stay the same For the moment i am just working on registration and retrieving user details On the backend i have a custom user with email and password with one-to-one relation with a details model with all the user details (name, address etc...) in the frontend i have a services.py to handle api request to the backend # users_fe/services.py from django.conf import settings import requests import json URL_CREATE_USER = settings.BACKEND_URL + '/user/create/' URL_TOKEN = settings.BACKEND_URL + '/user/token/' ME_URL = settings.BACKEND_URL + '/user/me/' DETAILS_URL = settings.BACKEND_URL + '/user/me_details/' CREATE_USER_DETAILS_URL = settings.BACKEND_URL + '/user/create_details/' def create_user(email, password): """ create basic user with just email and password """ params = {'email':email, 'password': password} r = requests.post(URL_CREATE_USER, params) r.raise_for_status() return r def get_token(email, … -
Django post_save not firing but post_delete in same signals.py file does
I am hoping someone can explain to me why post_save is not working when post_delete seemingly is and they're very similar and in the same signals.py file: models.py: import uuid from django.db import models from django.db.models import Sum from django.conf import settings from products.models import Product from shows.models import ShowsTickets class Order(models.Model): order_number = models.CharField(max_length=32, null=False, editable=False) full_name = models.CharField(max_length=50, null=False, blank=False) email = models.EmailField(max_length=254, null=False, blank=False) phone_number = models.CharField(max_length=20, null=False, blank=False) country = models.CharField(max_length=40, null=False, blank=False) postcode = models.CharField(max_length=20, null=True, blank=True) town_or_city = models.CharField(max_length=40, null=False, blank=False) street_address1 = models.CharField(max_length=80, null=False, blank=False) street_address2 = models.CharField(max_length=80, null=True, blank=True) county = models.CharField(max_length=40, null=True, blank=True) date = models.DateTimeField(auto_now_add=True) delivery_cost = models.DecimalField(max_digits=6, decimal_places=2, null=False, default=0) products_total = models.DecimalField(max_digits=6, decimal_places=2, null=True, default=0) tickets_total = models.DecimalField(max_digits=6, decimal_places=2, null=True, default=0) order_total = models.DecimalField(max_digits=6, decimal_places=2, null=False, default=0) grand_total = models.DecimalField(max_digits=6, decimal_places=2, null=False, default=0) def _generate_order_number(self): """Generate a random, unique order number using UUID""" return uuid.uuid4().hex.upper() def update_total(self): """Update grand total each time a line item is added, accounting for delivery costs. """ self.products_total = (self.productlineitems.aggregate( Sum('productlineitems_total'))['productlineitems_total__sum']) or 0 self.tickets_total = (self.ticketlineitems.aggregate( Sum('ticketlineitems_total'))['ticketlineitems_total__sum']) or 0 self.order_total = self.products_total + self.tickets_total self.delivery_cost = settings.STANDARD_DELIVERY_CHARGE self.grand_total = self.order_total + self.delivery_cost self.save() def save(self, *args, **kwargs): """Override the original save method to … -
How can I instantiate a Subclass of my Django AbstractBaseUser with FactoryBoy
I've been trying to use Factory Boy to make my writing of Unit Tests easier. However, the library is being less than cooperative when I'm trying to instantiate instances of my custom user class The custom class inherits from AbstractBaseUser and PermissionsMixin, as per the guide of enter link description here. Everyime I try to instantiate this class like so: class LogoutTests(TestCase): def setUp(self): self.employee_password = "foo" self.manager_password = "bar" self.test_employee_user = EmployeeFactory.create(self.employee_password) self.test_manager_user = ManagerFactory.create(self.manager_password) However, I keep getting this error message: factory.errors.FactoryError: Cannot generate instances of abstract factory ManagerFactory; Ensure ManagerFactory.Meta.model is set and ManagerFactory.Meta.abstract is either not set or False. I have tested this with other models and only my custom User model generates this error due to it possibly inheriting from AbstractBaseUser. Any help with this? For reference, my custom user class: class Employee(AbstractBaseUser, PermissionsMixin): class Meta: abstract = False first_name = models.CharField(max_length=250, default="Thibault", blank=False) last_name = models.CharField(max_length=250, default="Dupont", blank=False) email = models.EmailField(max_length=250, unique=True, blank=False, null=True) employee_number = models.OneToOneField(EmployeeNumber) is_manager = models.BooleanField(default=False, blank=False) is_employed = models.BooleanField(default=True, blank=False) is_active = models.BooleanField(default=False) objects = EmployeeManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.get_full_name() def get_short_name(self): return '{0}. {1}'.format(self.first_name[0], self.last_name) def get_full_name(self): return '{0} {1}'.format(self.first_name, self.last_name) def … -
updating data under form without refreshing - django
i'm using django 3 and i'm working on a comment system this is in my model.py: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') profile = models.ForeignKey(Profile, on_delete=models.CASCADE) text = models.TextField() created_date = models.DateTimeField(default=datetime.datetime.now()) this is what i have in view.py: def post(request, slug): post = get_object_or_404(Post, slug=slug) profile = Profile.objects.get(user=request.user) if request.is_ajax(): comment_text = request.POST['comment'] if len(comment_text)>0: comment = Comment.objects.create(post=post, profile=profile, text=comment_text) comment.save() data = { 'message': "Successfully submitted form data." } return JsonResponse(data) context = { 'post':post, } return render(request, 'blog/post.html', context) and this is what i have in my template: <!-- Add a Comment --> <div class="card my-4"> <h5 class="card-header">Leave a Comment:</h5> <div class="card-body"> <form method="post" class='my-ajax-form' data-url="{{ request.build_absolute_uri|safe }}" > {% csrf_token %} <div class="form-group"> <textarea class="form-control" name="comment" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> <!-- Comments --> {% for comment in post.comments.all %} <hr> {% if comment %} <div class="media mb-4"> <img class="d-flex mr-3 rounded-circle profile-img" src="{{post.profile.img.url}}" > <div class="media-body"> <strong>{{ comment.profile }}</strong> <div class="d-flex justify-content-between flex-wrap"> <p>{{ comment.text|linebreaks }}</p> {{ comment.created_date| date }} </div> </div> </div> {% endif %} {% empty %} <p>No comments here yet :(</p> <hr> {% endfor %} </div> </div> </div> </section>> <!-- end blog Area --> {% endblock %} … -
Django custom SQL execution problem. Query always shows [none]
I'm trying to query data from the database table. but every time it shows [none].here is my Django view.django view code here is my Html code- [enter image description here][2] and here is my database table- [enter image description here][3] [2]: https://i.stack.imgur.com/DjqQq.png`enter code here` [3]: https://i.stack.imgur.com/oxgYM.png -
Delete multiple rows in django
I am trying to delete severals rows at the same time in django. I am using datatables. The way how I am doing it is to create a boolean to_delete in my model, when the checkbox is selected, I am calling the function delete_multiple_company in my view. However, this doesn`t work. Any idea, what I am doing wrong please. Many Thanks, I`ve created my view: views.py def delete_multiple_company(request, company_id): company = get_object_or_404(Company, pk=company_id) company = Company.objects.get(pk=company_id) company.objects.filter(to_delete=True).delete() return HttpResponseRedirect(reverse("company:index_company")) urls.py url(r'^(?P<company_id>[0-9]+)/delete_multiple_company/$', views.delete_multiple_company, name='delete_multiple_company'), models.py class Company(models.Model): to_delete = models.BooleanField(default=False) index.html <a href="{% url 'company:delete_multiple_company' company.id %}" id="table" class="btn btn-default btn-sm active float: right" style="float: right;"><span class="fa fa-plus"></span>Delete Companies</a> <table id="dtBasicExample" class="table table-striped table-hover"> <thead> <tr> <th>Select</th> <th>#</th> <th>Checked ?</th> </tr> </thead> <tbody> {% for company in companys.all %} <tr> <td id="{{ company.id }}"><input type="checkbox" class="companyCheckbox" name="checkedbox" id="{{ company.id }}" value="{{ company.id }}"></td> <td>{{ company.id }}</td> <td>{{ company.to_delete }}</td> </tr> {% endfor %} </tbody> </table> -
Print all names from ManyToManyField except one in Django?
I have to write a query to print all the names inside the ManyToManyField except my own. The model is like this: models.py class Chat(models.Model): room_name= models.CharField(max_length=100) creator= models.ForeignKey(User, on_delete= models.CASCADE, related_name="owner") chatting_to= models.ManyToManyField(User, related_name="chatting_to", null=True) messages = models.ManyToManyField(Message, blank=True) In each Chat object there are two users in the ManyToManyField chatting_to one is the current user and other is the person he's chatting with. I have to print the list of all the users that he's chatting with. My current approach is this chat= Chat.objects.filter(chatting_to= request.user) and I'm printing all the chatting_to users for each object inside the template. But with this one I'm getting my user object with that second one too which is inside the ManyToManyField. How to print all the users in the chatting_to ManytoManyField excluding my the authenticated user. -
Image Update threw generic.UpdateView not working
I have a Books model class with the following attributes : class Books(models.Model): def get_absolute_url(self): return reverse("books:detail-books", kwargs={"book_id": self.pk}) ....... id = models.AutoField(primary_key=True) title = models.CharField(max_length=200, blank=False) author = models.CharField( verbose_name="Author (if not you)", max_length=200, blank=True) pub_date = models.DateField(null=True, blank=True) original_poster = models.ForeignKey( PersoUser, on_delete=models.CASCADE) price = models.DecimalField( max_digits=6, decimal_places=2, default=0, validators=[ MinValueValidator(0) ]) cover = models.ImageField( default="cover/default_cover.jpg", upload_to="cover") def __str__(self): return f"{self.title} de {self.author}" And the user who has posted a book can update it threw a class based view : class UpdateBook(LoginRequiredMixin, UserPassesTestMixin, generic.UpdateView): model = Books form_class = CreateForm template_name = "books/update_book.html" def form_valid(self, form): form.instance.original_poster = self.request.user return super().form_valid(form) def test_func(self): book = self.get_object() if book.original_poster == self.request.user: return True return False the form : class CreateForm(forms.ModelForm): class Meta: model = Books exclude = ["original_poster"] When I try to update the price, title or other fields it's working fine but when I try to update the cover image it's not working at all and no error is displayed. It's working when directly updating from the django administration, does anyone have a clue ? I'm quite confused since there is no ptoblem with other fields, thanks in advance -
Why doesn't Django migration work in Ubuntu?
So I've just deployed my Django application through EC2. Then I noticed an error regarding my models.py, and made some changes in the local computer. Then I git pushed the modified code, then pulled it in the Ubuntu server. Then I ran python manage.py makemigrations and python manage.py migrate in the Ubuntu server, hoping the changes in my models.py is applied. Then I got the message saying all migrations have been applied. But what I noticed was that NOTHING has changed. To be more precise, I altered a field from URL field into CharField, but it still remains as URL field. What could be the problem? Thanks. -
ImageField leads to page not found in production when i click save button
I have a Django project that has got an image field in the models.py. It works fine in the development environment but in the production environment, it leads to the page not found error when I save the object. Here is my product model in models.py I have also modified my settings.py correctly to serve media and static files while in production. Kindly help, I have really tried but I need your assistance -
ANDROID VOLLEY + JWT TOKEN AUTHENTICATION + DJANGO REST FRAMEWORK
I am currently developing an android chat app. I am very new to Android Studio, JWT Token Authorization, and Django Rest Framework. Right now I am having issue to work on the Django side. So basically I was setting up a login page from my Android, and I want it to login using phone number and password as the needed credentials. However, I also want to use JWT Token Auth to make my application more secure. Currently I have my project urls.py pointing to one of the JWT Token API urls.py from django.contrib import admin from django.urls import path,include from django.conf.urls import include, url from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path('admin/', admin.site.urls), path('account/',include('restaccount.urls')) , path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), ] This would lead to the server page which was *PS : The phone number fields should be the default username field..(I have made some trial modifications on my code prior I post this). I also have set up a models that was inherit from AbstractUser models.py class RegisterUser(AbstractUser): phone_number = PhoneField(name='phone_number',unique=True) birthday = models.DateField(name ='birthday',null= True) nickname = models.CharField(max_length=100,name = 'nickname') def __str__(self): return self.phone_number Currently I have tried to make a lot of modifications to …