Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can't deal with this association - django app
hope you are doing well ! I don't know what to do in this case, this is the association I want to create an activity itself can have 0 till many activities , this is models.py the attribute are just an examples class Activity(models.Model): name = models.CharField() a_id = models.Foreignkey(a, on_delete=models.CASCADE) can anyone guide me ?, thank you in advance :) -
How do i use user_passes_test view specific page?
My User Model SELLER = "SELLER" CUSTOMER = "CUSTOMER" USER_TYPE_CHOICES = ( ('SELLER' , 'Seller'), ('CUSTOMER' , 'Customer'), ) class User(AbstractBaseUser,PermissionsMixin): email = models.EmailField( max_length=255, unique=True) user_type = models.CharField(max_length=200,choices=USER_TYPE_CHOICES,null=True) last_login = models.DateTimeField( blank=True, null=True) is_staff = models.BooleanField( default=False) is_superuser = models.BooleanField( default=False) is_active = models.BooleanField( default=True) date_joined = models.DateTimeField(default=timezone.now) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Meta: ordering = ['email'] def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) def get_full_name(self): return self.email def get_short_name(self): return self.email I have two user_types one seller and one customer how i can use user_passes_test decorator to see if the user.user_type is seller so he can see the seller view only seller can see the seller view def seller_home(request,pk): try: seller = Seller.objects.get(id=pk) except User.DoesNotExist: raise Http404("Seller Does Not Exisit") sellerproducts = Product.objects.filter(seller=seller) totalsellerproducts = sellerproducts.count() context = {'seller':seller,'sellerproducts':sellerproducts,"totalsellerproducts":totalsellerproducts } return render(request,"seller_home.html",context) -
how to connect model instance in django
Code Description I have a model called Hospital who is the the user having OneToOne relationship with the user model. the Hospital Model is like a profile for the user. I have another model called patient which has a Foreginkey relation with the User like a One to many relationship. This means the user model can have many patient. I have another model called Card which has a OnoToOne relationship with the Patient and a foreignKey relationship with the Usermodel. this means a patient can have one card and that particular card can only belong to one patient and also the card belongs to the hospital not just the patient thats why i added a foreign key to relationship to the user model. I have another Model called Diagnoses which also have a ForiegnKey relation with the PatientModel and a foreignkey relationship with the User model because the diagnoses is not just for the patient but also the hospital. This means a patient has a card, and can have many diagnoses. Using this method, successfully, a user can have many patient. Now my problem is, when a user want to create a new card or diagnoses for a specific patient, … -
Updating scikit-learn: 'SVC' object has no attribute '_probA'?
We updated to Python 3.8.2 and are getting an error with scikit-learn: Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/management/commands/rssmlscore.py", line 22, in handle run.build_and_predict(days=options['days'], rescore=options['rescore']) File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/utils/run.py", line 96, in build_and_predict predict_all(filename) File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/models/predict_model.py", line 135, in predict_all voting_predicted_hard, voting_predicted_soft = predict_from_multiple_estimator(fitted_estimators, X_predict_list, File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/models/train_model.py", line 66, in predict_from_multiple_estimator pred_prob1 = np.asarray([clf.predict_proba(X) File "/home/ubuntu/myWebApp/server_modules/rss_ml_score/models/train_model.py", line 66, in <listcomp> pred_prob1 = np.asarray([clf.predict_proba(X) File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/sklearn/svm/_base.py", line 662, in _predict_proba if self.probA_.size == 0 or self.probB_.size == 0: File "/home/ubuntu/myWebApp/.venv/lib/python3.8/site-packages/sklearn/svm/_base.py", line 759, in probA_ return self._probA AttributeError: 'SVC' object has no attribute '_probA' Do I need to use another library in addition to sci-kit learn to access _probA? -
Django Channels middleware use ORM
I have troubles checking the user token inside of middleware. I'm getting token from cookies and then I need to query database to check if this token exists and belongs to user that made a request. routing.py from channels.routing import ProtocolTypeRouter, URLRouter import game.routing from authentication.utils import TokenAuthMiddlewareStack application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': TokenAuthMiddlewareStack( URLRouter( game.routing.websocket_urlpatterns ) ), }) middleware.py from rest_framework.authentication import TokenAuthentication from rest_framework.exceptions import AuthenticationFailed from rest_auth.models import TokenModel from channels.auth import AuthMiddlewareStack from django.contrib.auth.models import AnonymousUser from django.db import close_old_connections ... class TokenAuthMiddleware: """ Token authorization middleware for Django Channels 2 """ def __init__(self, inner): self.inner = inner def __call__(self, scope): close_old_connections() headers = dict(scope['headers']) if b'Authorization' in headers[b'cookie']: try: cookie_str = headers[b'cookie'].decode('utf-8') try: # no cookie Authorization=Token in the request token_str = [x for x in cookie_str.split(';') if re.search(' Authorization=Token', x)][0].strip() except IndexError: scope['user'] = AnonymousUser() return self.inner(scope) token_name, token_key = token_str.replace('Authorization=', '').split() if token_name == 'Token': token = TokenModel.objects.get(key=token_key) scope['user'] = token.user except TokenModel.DoesNotExist: scope['user'] = AnonymousUser() return self.inner(scope) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) And this gives me django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I also tried the following … -
How to get total amount per year-month for certain category in DetailView, Django?
I have a table with expenses categories and when I click on the certain category it redirects me to this DetailView page. Then I want to show the year-month costs summary for chosen category to look similiar to this what I already got (summary per year-month but not for certain category). How can I achieve that? This is what I got for now and got stucked: def category_summary(): summary_by_year_month = Expense.objects.annotate( month=TruncMonth('date')).values('date').annotate( amount=Sum('amount')).order_by() return summary_by_year_month MODELS.PY class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' The most confusing part about this problem for me is how can I retrieve this information only for chosen category and show it to user in DetailView? Thank you in advance for any help. -
Pass request.user to dispatch method
Env: Python 3.6, Django 3.0, DRF 3.11, JWT Authorization Hello everybody. I have a simple class in my API where I want to check user permissions in each method get, pass etc. I planned to check user privileges at dispatch but it doesn't work. Simplify code, my current class looks more or less like this: class ExampleClassName(APIView): can_do_sth = False def dispatch(self, request, *args, **kwargs): print(request.user) # Here is AnonymousUser if request.user.username == "GreatGatsby": self.can_do_sth = True return super(ExampleClassName, self).dispatch(request, *args, **kwargs) def get(self, request): print(request.user) # Here is correctly Logged user if self.can_do_sth: return Response("You can do it") return Response("You can't") def post(self, request): print(request.user) # Here is correctly Logged user if self.can_do_sth: return Response("You can do it") return Response("You can't") How can I pass request.user to dispatch method? -
413 Request Entity Too Large - Regular Fix Not Working
I'm deploying a Django application online using AWS Elastic Beanstalk. It worked fine for a while, but some change is causing the application to throw a '413 Request Entity Too Large nginx/1.18.0' error when I try to upload a file. Here are my logs: stdout log: ---------------------------------------- /var/log/web.stdout.log ---------------------------------------- Sep 8 19:59:39 ip-172-31-16-39 web: Bad Request: / Sep 8 21:27:14 ip-172-31-16-39 web: Not Found: /static/tinymce/css/prism.css Sep 8 21:27:14 ip-172-31-16-39 web: Not Found: /static/tinymce/js/prism.js Sep 8 21:27:14 ip-172-31-16-39 web: Not Found: /favicon.ico Sep 8 21:27:16 ip-172-31-16-39 web: Not Found: /static/tinymce/css/prism.css Sep 8 21:27:16 ip-172-31-16-39 web: Not Found: /static/tinymce/js/prism.js access log: ---------------------------------------- /var/log/nginx/access.log ---------------------------------------- 192.241.237.101 - - [07/Sep/2020:09:35:44 +0000] "GET /hudson HTTP/1.1" 400 59666 "-" "Mozilla/5.0 zgrab/0.x" "-" 3.134.93.214 - - [07/Sep/2020:10:07:18 +0000] "HEAD /robots.txt HTTP/1.0" 404 0 "-" "-" "-" 189.39.247.131 - - [07/Sep/2020:11:25:33 +0000] "GET / HTTP/1.1" 400 59689 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7" "-" 195.54.160.21 - - [07/Sep/2020:12:20:29 +0000] "GET /solr/admin/info/system?wt=json HTTP/1.1" 400 60308 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36" "-" 195.54.160.21 - - [07/Sep/2020:12:21:47 +0000] "GET /?XDEBUG_SESSION_START=phpstorm HTTP/1.1" 400 60242 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 … -
How do I return custom response/status code in Django?
I want to return status code different from 100 <= self.status_code <= 599, as written in Django's HttpResponseBase class. Is there are any easy way to bypass this restriction? -
Django: Use JSON and requests in my django app
I am using JSON, re and requests to get the number of followers from an instagram page: import json import re import requests PROFILE = 'espn' response = requests.get('https://www.instagram.com/' + PROFILE) json_match = re.search(r'window\._sharedData = (.*);</script>', response.text) profile_json = json.loads(json_match.group(1))['entry_data']['ProfilePage'][0]['graphql']['user'] print(profile_json['edge_followed_by']['count']) I am wondering how I can then add this to my django project to use that number to display on my website, updating each time someone vists the page to reflect the dynamic number. I had a look around but I dont really understand where you would add this code. I would image it would be added in the views section to then be rendered in the html page but not sure what the format would be. The view for the page I would like it to be used for example is View.py: def index(request): post = Post.objects.all()[0] recent_posts = Post.objects.all()[1:4] latest_posts = Post.objects.all()[:5] data = {"post":post, "recent_posts":recent_posts, "latest_posts":latest_posts} return render(request, 'index.html', data) Also as an extra question - how would the process differ if I was using a Generic Class-Based view vs a function view. Thank you very much. -
columns from django.db.models.query.QuerySet
With a raw query the columns for the SQL that will be executed can be accessed like this. query_set = Model.objects.raw('select * from table) query_set.columns There is no columns attribute for django.db.models.query.QuerySet. How do you get the columns or the SQL that will be executed from a django.db.models.query.QuerySet instance? -
Django 3. Having trouble passing dropdown menu selection from .html to forms
I'm still new to Django (2 weeks or so). I've been struggling the past few days with passing a string from an html file to forms. My project lets the user choose a state from a dropdown menu (Michigan and Ohio for now, I'll add the rest later). When the state is selected, it will take that string and pull a list of counties of that state from a spreadsheet. This is where the problem lies. I've searched far and wide and I just can't seem to find a solution. The major holdback to many of these solutions is I don't want to "submit" with a button. I want the user to "select" a state, then select a county without a page refresh. I've also included a screenshot of the webpage. So far the dependent dropdowns work perfectly thanks to a youtube tutorial. The "submit" button in the picture is cosmetic for now. Thanks in advance for helping out. Let me know if you have any questions regarding models or anything else regarding the code. views.py def StateForm_Page(request): context = {} stateChoice = 'Michigan' //hardcode a state so if the post fails, the function can still find an excel sheet … -
Django - How do I get the files submitted to a form?
In my Django project, I have this view: def create_format(request, **kwargs): if request.method == 'POST': form = FormatUpdateForm(request.POST) if form.is_valid(): business_type = int(request.POST.get('business_type')) ... more fields ... constitutive_act_copy = clean_str(request.POST.get('constitutive_act_copy')) return HttpResponseRedirect(reverse('formats:formats')) elif request.method == 'GET': form = FormatUpdateForm() return render(request, 'format_form.html', context={'form': form, 'autocomplete': SearchableData.objects.all()}) I have many fields, some of which are FileFields. I want to create an object with the data obtained from the form, and I can do that for all fields except the FileFields. What is the correct way to obtain the Files uploaded in the form and use them as attributes when creating an object? -
How to keep a modal open in an if statement in template
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Order Completed</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% if accepted_order %} <div class="collapse" id="collapseAcceptedCreatorOrders"> <div class="card card-body"> <h1>Buyer: <a href="{% url 'buyer_page'%}">{{ accepted_order }}</a></h1> <a href="{% url 'dashboard' %}"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Mark As Bought </button> </a> <a href="{% url 'dashboard_withdraw_order' %}"><button>Withdraw</button></a> </div> </div> {% endif %} I am trying to show a modal when a user clicks a button, inside this if statement. The only issue is when the button is clicked, the modal pops up for a split second and then disappears. When I use the button outside of the if statement it works fine, but I need to use it in the if statement. How can I do this? Thanks. -
Django command line logging on AWS elastic beanstalk
I have deployed a django web app to AWS via elastic beanstalk, and am having trouble finding relevant logs. Where can I find logs that would have the same content as if I was running "python manage.py runserver" locally in my terminal. Thanks! -
Django-import save the file used to upload data
I am new to django and looking for help to save file used to import data in django. In django admin interface, under booksmanagement i am able to upload csv file and data is uploaded into booksmanagement table. But i need help to save the uploaded file into FileImported Trying to store the uploaded file, books.csv to file field under FileImported table. I am doing this first time, may be i am not passing the rite attribute to obj = kwargs['file_name']. Any help will be appreciated. Thank you ! import_export_books.py class Resourcebooks(resources.ModelResource): def get_instance(self, instance_loader, row): try: params = {} for key in instance_loader.resource.get_import_id_fields(): field = instance_loader.resource.fields[key] params[field.attribute] = field.clean(row) return self.get_queryset().get(**params) except Exception: return None def before_import(self, dataset, *args, **kwargs): #for i, v in kwargs.items(): # print (" ", i, ": ", v) #output = file_name : books.csv user : test obj = kwargs['file_name'] print(obj) file_name = kwargs.get('file_name', 'unknown') name = os.path.splitext(file_name)[0] file_size = kwargs.get('file_size', '0') file_extension = kwargs.get('file_extension', 'unknown') user = kwargs.get('user', 'unknown') file_name_model_object = FileImported.objects.get_or_create(file=obj,filename=file_name, name=name, size=file_size, extension=file_extension, user=user) models.py class FileImported(models.Model): filename = models.CharField(max_length=30) name = models.CharField(max_length=30) size = models.FloatField(default="1") extension = models.CharField(max_length=30) date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(Cuser, on_delete=models.CASCADE) … -
How can resolve problem between models.py?
I have a problem with a model and its table in Django. It is possible that for some installed applications I use one type of model and for another I use another model, since when I change the table it gives me this error: (1146, "Table 'dsa_dj.lab_sampletests' doesn't exist") I change the table again, this error goes away, but if I do another action it throws me the following: (1146, "Table 'dsa_dj.lab_sample_tests' doesn't exist") How can I solve this problem between Models? From already thank you very much -
Architecture suggestions - How to implement autoscaled async tasks
We have a large application, which uses django as an ORM, and celery as a task running infrastructure. We run complex pipelines triggered by events (user driven or automatic), which look something like this: def pipeline_a: # all lines are synchronous, so second line must happen after first is finished successfully first_res = a1() all_results = in_parallel.do(a2, a3, a4) a5(first_res, all_results) We wish to run a1, a2, ... on different machines (each task may need different resources), and the number of parallel running pipelines is always changing. Today we use celery which is super convenient for implementing the above - but isn't suitable for auto-scaling (we hacked it to work with kubernetes, but it doesn't have native support with it). Mainly the issues I want to solve are: How to "run the next pipeline step" only after all previous ones are done (I may not know in advance which steps will be run - it depends on the results of previous steps, so the steps are dynamic in nature) Today we try and use kubernetes (EKS) to autoscale some of the tasks (SQS queue size is the hpa metric). How to make kubernetes not try and terminate currently running tasks, … -
Django select options value getting empty value with original values
how can i define select option in html using django tags for loops. i am getting empty values with for loop values. how can i solve this bug? create.html <select class="form-control" name="books" required="" id="id_books"> {% for book in form.books %} <option value="{{ book.id }}">{{ book }}</option> {% endfor %} </select> output.html <select class="form-control" name="books" required="" id="id_books"> <option value=""></option> <option value="1">django</option> <option value=""></option> <option value="2">python</option> <option value=""></option> <option value="3">java</option> <option value=""></option> <option value="4">reactjs</option> </select> -
Avoiding N+1 Queries When Serializing Model With Property Referencing Reverse Foreign Key Relationship
I currently have an issue where neither Django's prefetch_related() nor prefetch_related_objects() are sufficient in optimizing a Django Rest Framework serialization and I'm curious if anyone here has some ideas! To visualize the situation I'm in, suppose I have three models, linked as such: class VotableObjectExampleParent(models.Model): #several other fields redacted here# class VotableObjectExample(models.Model): #several other fields redacted here# votableobjectexampleparent = models.ForeignKey('VotableObjectExampleParent', on_delete=models.CASCADE, related_name = 'votableobjectexamples') @property def total_votes(self): return self.votableobjectexample_votes.aggregate(sum = Sum("vote"))["sum"] or 0 class VotableObjectExample_Vote(models.Model): #several other fields redacted here# votablebjectexample = models.ForeignKey('VotableObjectExample', on_delete=models.CASCADE, related_name = 'votablebjectexample_votes') vote = models.IntegerField(choices = [(-1, "down"), (1, "up")]) I then have appropriate (and functional!) DRF serializers such as the ones shown: class VotableObjectExampleParent_Serializer(serializers.ModelSerializer): related_votableobjectexamples = Idea_Proposal_Serializer(source = "votableobjectexamples", many=True, read_only=True) class Meta: model = VotableObjectExampleParent fields = ['related_votableobjectexamples'] #other fields would normally be in this array read_only_fields = fields class VotableObjectExample_Serializer(serializers.ModelSerializer): class Meta: model = VotableObjectExample fields = ['total_votes'] #other fields would normally be in this array read_only_fields = fields At first, I would simply call the parent serializer (VotableObjectExampleParent_Serializer) in the view: #assume a variable I already have called this_pk is correct and available for use serializer = VotableObjectExampleParent_Serializer(VotableObjectExampleParent.objects.get(pk = this_pk), many = True) JSONRenderer().render(serializer.data) This produces 100% correct JSON for my … -
virtualenv or venv? which one should be used?
I am a windows 10 user. Usually I use $-- python -m venv venv_name to create a virtual environment and activate it by venv_name\Scripts\activate.bat. But today when I did the same, I saw there wasn't any Scripts folder rather a bin folder. So I tried this commands -> $-- venv_name\bin\activate.bat $-- venv_name\bin\activate $-- venv_name\bin\activate.ps1 $-- source venv_name\bin\activate but none of them worked. What was wrong actually and why there wasn't any Scripts folder? -
Date on which maximum number of tasks were completed in a single day django
I have 2 models like this. one user can have multiple tasks class User(models.Model): userCreated_at=models.DateTimeField(blank=True) class Tasks(models.Model): owner=models.ForeignKey(User , on_delete=models.CASCADE) title = models.CharField(max_length=100,null=True,blank=True) completion_date_time = models.DateTimeField(blank=True) So I want to calculate . Since time of account creation of user , on what date, maximum number of tasks were completed in a single day . Any help would be highly appericiated -
How to link "Searchbar" to Search view Django
I create a post_searchview : def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] search_vector = SearchVector('title', 'body') search_query = SearchQuery(query) results = Post.published.annotate( search=search_vector, rank=SearchRank(search_vector, search_query), ).filter(search=search_query).order_by('-rank') context = {'form': form, 'query': query, 'results': results} return render(request, 'blog/post/search.html', context) And i want to link that to my base.html where i have located an html code for the searchbar (look in the bottom of the file): <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="{% url 'blog:post_list' %}"> My Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span></button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto"> <li class="nav-item mr-2"> <input class="form-control" type="text" placeholder="Search" aria-label="Search"> </li> Also, now i have a search.html file to make the searchs, idk if i should delete it : {% extends "blog/base.html" %} {% block title %}Search{% endblock %} {% block content %} {% if query %} <h1>Posts containing "{{ query }}"</h1> <h3> {% with results.count as total_results %} Found {{ total_results }} result{{ total_results|pluralize }} {% endwith %} </h3> {% for post in results %} <h4><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h4> {{ post.body|safe|truncatewords_html:5 }} {% empty %} <p>There … -
I am new to django , my code is working fine in local server , but when deployed on heroku , its showing the following error
Exception Type: ProgrammingError at / Exception Value: relation "main_tutorial" does not exist LINE 1: ...ntent", "main_tutorial"."tutorial_published" FROM "main_tuto. -
How to handle external API tokens after logout
This is a higher level conceptual question. I use token authentication on my django - react app and I handle the token by saving, retrieving it, and removing it from local storage as necessary. The flow is sort of like this: user registers- generate token and save it to local storage user logs in - same thing user logs out - token is destroyed and removed from local storage The external API I use also uses token authentication, however I would like to treat it differently as to enhance the user experience. I do not want (aka it is not correct) to generate a new token for the external api every time the user logs in. Upon logging in I would like to retrieve the previously generated token from somewhere, preferably local storage. Saving a token like this in local storage when the user is not logged in is also bad practice. Where is a good place to save this token? Right away I think my django server. However, I feel like it is overkill to generate a whole model for it, or even to create a new attribute for my user, since I would have to create a custom …