Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Property destructuring pattern expected.javascript
How to fix this ',' expected.javascript Property destructuring pattern expected.javascript var map_{{ forloop.counter }} = new google.maps.Map(document.getElementById('map_{{ forloop.counter }}'), { zoom: 8, center: {lat: {{ image.lat }}, lng: {{ image.lon }}} }); var marker_{{ forloop.counter }} = new google.maps.Marker({ position: {lat: {{ image.lat }}, lng: {{ image.lon }}}, map: map_{{ forloop.counter }} }); -
Django on Ubuntu giving libpq version 10 error
I am trying to setup a Django website on linux ubuntu with postgresql, gunicorn and nginx. However every time I try to start the development server I get this following error: Traceback (most recent call last): File "/home/ubuntu/personalserver/manage.py", line 22, in <module> main() File "/home/ubuntu/personalserver/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations if self.has_table(): File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 323, in cursor return self._cursor() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 299, in _cursor self.ensure_connection() File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 281, in ensure_connection with self.wrap_database_errors: File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/ubuntu/personalserver/myprojectenv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 282, … -
Can´t find a way to change the initial value of the primary key id, and make start from it on my models
I really apreciate somebody's help.... I am working on django, so I created my table on my models.py.... by default when I start registering data, the id, set as primary key, begins with the initial value #1 and counting on each time I do a new register. But, I have loaded some data in my table, so the final id right now is 185. I runserver and try to add a new register, but I get an error about id duplicity..... django is trying to save in id # 1 the actual register.... but I want it to continue saving the register from id #186 and counting on... I have tried doing this on my models: class MyModel(models.Model): id = models.AutoField(primary_key=True, initial=123) but it does not recognizes the kwarg 'initial' So I am stuck right now.... -
How to creating Image with matplotlib and instaly displaying it? Django + Python
I want my program to display map created with matplotlib that uses .csv file and display that map alongside with JSON data. Map alone actually works, but I want it to open on next page with JSON data. Now I can only go to next page that contains JSON data after I close the map window which opens on home page. On next page I get "Failed to load resource: the server responded with a status of 404 (Not Found)" from DevTools. And other problem is after a while it doesn't even open, just keeps loading with no error. Closing terminal and putting again virtual env and python manage.py runserver works but then it happens again. And if you leave JSON alone, it works perfectly so I guess map is the problem. This is the main page. So you gotta click X on map window then it proceed to next page This is the next page, you can even go back and forth when map is minimalized from django.shortcuts import render import json import urllib import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import numpy as np import pandas as pd def Last1Hour(request): # this is for reading … -
How to setup django-anymail with mailgun?
I've installed django-anymail and add it in the settings.py: # settings.py ... if not DEBUG: INSTALLED_APPS += [ "anymail", ... ] ... ...and configure as described in the quickstart docs: # settings.py ... # Mail configuration # https://anymail.dev/en/stable/quickstart/ ANYMAIL = { "MAILGUN_API_KEY": env("MAILGUN_API_KEY"), "MAILGUN_WEBHOOK_SIGNING_KEY": env("MAILGUN_WEBHOOK_SIGNING_KEY"), "MAILGUN_SENDER_DOMAIN": env("MAILGUN_SENDER_DOMAIN"), } EMAIL_BACKEND = ( "django.core.mail.backends.console.EmailBackend" if DEBUG else "anymail.backends.mailgun.EmailBackend" ) # DEFAULT_FROM_EMAIL = f"from@{env('MAILGUN_SENDER_DOMAIN')}" DEFAULT_FROM_EMAIL = "from@mysandboxdomain.mailgun.org" # SERVER_EMAIL = f"server@{env('MAILGUN_SENDER_DOMAIN')}" SERVER_EMAIL = "server@mysandboxdomain.mailgun.org" ... I also use dj-rest-auth for authentication. Which sends email after successful registration, tested with django.core.mail.backends.console.EmailBackend. But when I runserver and register a new account with DEBUG=False to test anymail.backends.mailgun.EmailBackend, it throws Server Error (500) and nothing else. Please help me, what I am doing wrong? -
Group by month based on DateTime Field
I have a model for hotel reservations: class PaymentRequest(SoftDeleteModel): class Meta: verbose_name_plural = "PaymentRequests" user = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, blank=False, null=False, default=None) customer_first_name = models.TextField(blank=False, null=False) customer_last_name = models.TextField(blank=False, null=False) arrival_date = models.DateTimeField(blank=True, null=True) What I'd like to do is make a queryset to group my reservations by month and get a count of it. i.e {'jan' : 10, 'feb' : 11, etc..} I've seen some answers like this but does not work quite right, maybe since it was answered 10 years ago. Appreciate any help. -
this is the code for my manage.py script i would like someone to explain each line please i barely understand it
import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bookr.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() the code works i just do not understand why -
How to convert a queryset quickly?
Through an ajax request I request data from the database that has 70 thousand lines. The query is very fast, it lasts 0.2 seconds but I can't return it because I can't return queryset by JsonResponse, so I have to convert it to json but that's the problem. How to convert as fast as possible? I tried using the following code, but it still takes like 6 seconds. queryset = Users.objects.all() list = [] [list.append({"id": query.id, "name": query.name}) for query in queryset] return JSONResponse(list, safe=False) -
How Do I properly create a three column responsive grid
I'm having a little difficulty implementing a three column grid in Django. I'm trying to create a page where my blog post are displayed in columns of three. I'm using bootstrap to do this and I just cant seem to figure out how to get this right. I implemented a for loop in order to display a grid of three. I'm either getting three of the same articles. Which is not what i'm trying to accomplish. Please let me know if you have any idea of how I accomplish fix this. Below you can find my code. {% for post in object_list %} <div class="row "> <div class="column" style="background-color:#grey" > <div class="card h-100 " style="max-width: 24rem; max-height: 28.5rem; "> <img src="{{ post.header_image.url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"><a href="{% url 'article-detail' post.pk post.slug %}">{{ post.title }}</a></h5> <p class="card-text">{{ post.snippet }}</p> </div> <div class="card-footer"> <small class="text-muted">By: {{ post.author.first_name }} {{ post.author.last_name }} - {{ post.post_date }} - </small> <a href="{% url 'category' post.category|slugify %}" style=text-transform:uppercase;">{{ post.category }}</a> </div></div></div></div> {% endfor %} -
Unable to install mysqlclient using virtualenv (Fedora 37)
I am developing an app using Django 4 and have set up a virtual environment using venv. THe problem I have is I cannot get the mysqlclient package installed using pip in order to allow my django app to connect to an existing MariaDB hosted on the same server. I am using Fedora 37, Python 3.11.1 . Everytime I try to install mysqlclient via pip within my virtual environment I the the below error: (venv) $ pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [18 lines of output] /bin/sh: line 1: mysql_config: command not found /bin/sh: line 1: mariadb_config: command not found /bin/sh: line 1: mysql_config: command not found Traceback (most recent call last): File "", line 2, in File "", line 34, in File "/tmp/pip-install-fuegkdx1/mysqlclient_d3182534a7ce4d10ae4bceac47107c54/setup.py", line 15, in metadata, options = get_config() ^^^^^^^^^^^^ File "/tmp/pip-install-fuegkdx1/mysqlclient_d3182534a7ce4d10ae4bceac47107c54/setup_posix.py", line 70, in get_config libs = mysql_config("libs") ^^^^^^^^^^^^^^^^^^^^ File "/tmp/pip-install-fuegkdx1/mysqlclient_d3182534a7ce4d10ae4bceac47107c54/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs [end of output] note: This error originates from a subprocess, and is likely not … -
Django many-to-many: I want to query the bootcamps the user has signed up for
#This is my Model.py from django.db import models from django.contrib.auth.models import User class Tipo_Categoria(models.Model): nombre = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now_add=True) class Bootcamp(models.Model): titulo = models.CharField(max_length=50) contenido = models.CharField(max_length=500) imagen = models.ImageField(upload_to='bootcamps') requisito1 = models.CharField(max_length=100) autor = models.ForeignKey(User, on_delete=models.CASCADE) categoria = models.ManyToManyField(Tipo_Categoria) fecha_inicio = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now_add=True) class ProgramasAcademico(models.Model): codigo = models.BigIntegerField(null=False, unique=True, primary_key=True) nombre = models.CharField(max_length=100) status = models.BooleanField(default=True) class BootcampInscripcion(models.Model): cedula = models.IntegerField(blank=True, null=True) nombre = models.CharField(max_length=100) apellido = models.CharField(max_length=100) usuario = models.ForeignKey(User, on_delete=models.CASCADE) carrera = models.ManyToManyField(ProgramasAcademico) email = models.EmailField(max_length=254) direccion = models.CharField(max_length=100) telefono = models.CharField(max_length=10) bootcamp = models.ManyToManyField(Bootcamp) created = models.DateTimeField(auto_now_add=True) update = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) #This is my Views.py from django.shortcuts import render from bootcamps.models import * from django.contrib.auth.models import User def mis_bootcamp(request,id): try: bootcampBd = BootcampInscripcion.objects.filter(usuario=id) except BootcampInscripcion.DoesNotExist: print("no tiene cursos") else: cursos = Bootcamp.objects.filter() #Bootcamps return render(request, "campus/mis_bootcamp.html",{"bootcampBd":bootcampBd,"cursos":cursos}) Each user has signed up for a bootcamp or several. I want you to help me is in which It would be the query or the way to filter only the bootcamps to which the user signed up. user and thus publish (title, image) of the bootcamp in the html. I appreciate your help. -
Django DJStripe access fields from foreign key in template
I have a user model with a foreign key that points to Subscription which is imported from DJ Stripe. class User(PermissionsMixin, AbstractBaseUser): ... subscription = models.ForeignKey(Subscription, on_delete=models.SET_NULL) ... The Subscription table in djstripe has a subscription field and a created field which I am trying to access through my template like this: {{ user.subscription.subscription }} or {{ user.subscription.created }} I have tried several variations with double underscores or subscription_set.get but I am really just scratching my head. Is there a simple way to access those fields in my template? -
django if elif statement fails: IndentationError
In Django i have two forms. In my code i wanna check which form is filled with a value by the user. I use this to check which form is used: def test(context): if request.method == 'GET' and 'q' in request.GET: --do_something-- elif request.method == 'GET' and 'y' in request.GET: --do_something_else-- <form action="/my_page"> <label for="lblq">find something:</label><br> <input type="text" id="lblq" name="q"><br> <input type="submit" value="find q"> </form> <form action="/my_page"> <label for="lbly">find something else</label><br> <input type="text" id="lbly" name="y"><br> <input type="submit" value="find y"> </form> But i get an error: elif 'q' in request.GET: ^ IndentationError: expected an indented block after 'if' statement on line 12 Don't see the problem, am i missing something? Thnx in advanced. -
I can't get metadata from stripe session in django
I'm doing a course in udemy and there's a stripe payment lesson in django. And the problem is that today's stripe docs are different from docs from the lesson and I can't do a one thing: get an order_id from the order to make my function work correct (function change order status, save order in 'basket_history' dict and delete an actual basket). There are code from the video and my one: views.py Similar code: class OrderCreateView(TitleMixin, CreateView): title = 'Store - Оформление заказа' template_name = 'orders/order-create.html' form_class = OrderForm success_url = reverse_lazy('orders:order_create') def post(self, request, *args, **kwargs): super().post(request, *args, **kwargs) baskets = Basket.objects.filter(user=self.request.user) checkout_session = stripe.checkout.Session.create( line_items = baskets.stripe_products(), metadata = {'order_id': self.object.id}, mode='payment', success_url='{}{}'.format(settings.DOMAIN_NAME, reverse('orders:order_success')), cancel_url='{}{}'.format(settings.DOMAIN_NAME, reverse('orders:order_canceled')), ) return HttpResponseRedirect(checkout_session.url, status = HTTPStatus.SEE_OTHER) def form_valid(self, form): form.instance.initiator = self.request.user return super(OrderCreateView, self).form_valid(form) @csrf_exempt def my_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, settings.STRIPE_WEBHOOK_SECRET ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) Then the difference My code: # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': # Retrieve the session. If you require line items in the response, you may include … -
How to get a queryset from many to many field
I have this model and i want to retrieve all the "members" as queryset class Team(models.Model): name = models.CharField(max_length=120) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner') members = models.ManyToManyField(User, related_name='members') # <--- I tried this but its not working Team.objects.all()['members'] # and Team.members.all() -
How to fetch related model in django_tables2 to avoid a lot of queries?
I might be missing something simple here. And I simply lack the knowledge or some how-to. I got two models, one is site, the other one is siteField and the most important one - siteFieldValue. My idea is to create a django table (for site) that uses the values from siteFieldValue as a number in a row, for a specific site, under certain header. The problem is - each site can have 50s of them. That * number of columns specified by def render_ functions * number of sites equals to a lot of queries and I want to avoid that. My question is - is it possible to, for example, prefetch all the values for each site (SiteFieldValue.objects.filter(site=record).first() somewhere in the SiteListTable class), put them into an array and then use them in the def render_ functions by simply checking the value assigned to a key (id of the field). Models: class Site(models.Model): name = models.CharField(max_length=100) class SiteField(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.name class SiteFieldValue(models.Model): site = models.ForeignKey(Site, on_delete=models.CASCADE) field = models.ForeignKey(SiteField, on_delete=models.CASCADE) value = models.CharField(max_length=500) Table view class SiteListTable(tables.Table): name = tables.Column() importance = tables.Column(verbose_name='Importance',empty_values=()) vertical = tables.Column(verbose_name='Vertical',empty_values=()) #... and many … -
Django many-to-many: Quiero consultar los bootcamps a los que el usuario se haya inscrito
#Model.py from django.db import models from django.contrib.auth.models import User Cada usuario se ha inscrito a un bootcamp o a varios. Quiero que me ayuden es en cual sería el query o la forma de filtrar sólo los bootcamps a los que se inscribió el usuario y asi publicar(titulo,imagen) de los bootcamp en el html. Les agradezco su ayuda. -
Unable to login and redirect in django
I am unable to login and redirect to home page using the custom login view (user_login) and AuthenticationForm. However, if i login using the admin page (http://127.0.0.1:8000/admin) and then reopen login page it automaticaly redirects to home page. There is some issue related to authentication which is not getting done from my custom login page/view .I am unable to fix this or identify resolution based on answers provided online. There is another issue regarding the URL it is showing as http://127.0.0.1:8000/login/?csrfmiddlewaretoken=FhHQjhGGgFDwcikpH9kl3OwQMcZisjWS2zvMHFGBU6KxGNWbamgago7FhtSs8MeN&username=admin&password=admin However, Password and Username should not be showing in the URL if form method is post. URL urlpatterns = [ path("", views.index, name="index"), path("signup/", views.user_signup, name="signup"), path("login/", views.user_login, name="login"), path("home/", views.homepage, name="home"),] Views def user_login(request): if request.user.is_authenticated: return redirect("/home") else: if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("home") else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render( request=request, template_name="socialapp/login.html", context={"login_form": form}, ) def homepage(request): return render(request=request, template_name="socialapp/home.html") Login HTML <form action="{% url 'login' %}" id="login-form" method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"> {% csrf_token %} {{ login_form|crispy }} <button … -
Django class-based form with dropdowns populated with data from model / db
This my Django code: forms.py from django import forms class ReleaseForm(forms.Form): name = forms.CharField() location = forms.CharField() views.py class MyFormView(FormView): template_name = 'form.html' form_class = MyForm success_url = 'home' def get(self, request, *args, **kwargs): form = self.form_class return render(request, 'form.html', {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() return redirect('home') else: return render(request, self.template_name, {'form': form}) template form.html <form method="post" action="{% url 'form' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary btn-block py-2" value="OK"> </form> I want both two fields (name, location) to be drop-downs (combobox-es) not CharFields, and I want to populate their entries / values with data coming from db (django models). How can I do that? I am completely new to CBV idea. -
Django4.1 Как в настройках проекта urls ссылаться на другие приложения если их необходимо включить через одинаковый url ""
Столкнулся с проблемой. urls.py в проекте: urlpatterns = [ path('admin/', admin.site.urls), path('', include('catalog.urls')), path('', include('account.urls')), ] urls.py в приложении 1 urlpatterns = [ path('', views.main, name='home'), path('<slug:url>/', views.detail_category, name='detail_category'), ] urls.py в приложении 2 urlpatterns = [ path('register/', views.register_account, name='register'), path('login/', views.login_account, name='login'), path('logout/', views.logout_account, name='logout'), ] в представлении вывожу вот так: <a href="{% url 'app1:login' %}">LOGIN</a> <a href="{% url 'app1:register' %}">REGISTRATION</a> Как вариант в проекте сослаться на account/ тогда все будет работать. Например вот так все заработает: urlpatterns = [ path('admin/', admin.site.urls), path('', include('catalog.urls')), path('account/', include('account.urls')), ] Как вариант в проекте сослаться на account/ тогда все будет работать. Например вот так все заработает: urlpatterns = [ path('admin/', admin.site.urls), path('', include('catalog.urls')), path('account/', include('account.urls')), ] Какие есть еще варианты ? -
Django passing dynamic URL parameter into reverse function
I have just stated to learn Django. So far I pass dynamic URL parameters into reverse function inside the get_absolute_url() method in the following ways: # By using kwargs: def get_absolute_url(self): return reverse('book-detail', kwargs={'id':self.id}) # Or by using the args: def get_absolute_url(self): return reverse('book-detail', args=[self.id]) # But I found several examples of the following code: def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)] I have used the simple library app to pass id of the book into URL in order to get book details. All three variants work fine without any problem. Can somebody explain to me why and when we should use args=[str(self.id)]? -
Django model /w foreign keys transform to CreateView model or form problem
Good day everyone! I’ve made models with related objects, and now I’m stuck as I can’t manage CreateView class.. Let’s imagine that we have these abstract models: class NameValues(models.Model): name = models.CharField(…) value = models.CharField(…) group = models.ForeignKey(GroupOfValues, …) class GroupOfValues(models.Model): sheet = models.ForeignKey(ResultSheet, …) class ResultSheet(models.Model): date = models.DateField(…) name = models.CharField(…) class NameValues(models.Model): name = models.CharField(…) value = models.CharField(…) group = models.ForeignKey(GroupOfValues, …) class GroupOfValues(models.Model): sheet = models.ForeignKey(ResultSheet, …) class ResultSheet(models.Model): date = models.DateField(…) name = models.CharField(…) So is it possible to make a form for ResultSheet or CreateView class that can automatically generate all child forms from related objects? Form Date: 03.02.2023 Name: Some research Group of values: select option would be great [Parameters #1] Age: 32 Height: 180 Weight: 70 Really appreciate any help or advice -
How to port django application's code to python3?
I have a django project that has been developed in python2.7 version. Now I decided to port the code to python3. Porting python2 code to python3 is documented here. One way I chose to port my application is to use futurize tool. I am able to port python2 code to python3 using the futurize: futurize --stage1 -w filename.py and futurize --stage2 -w filename.py. My problem here is that it would become a huge task for me to run this command for each and every file on whole project. Is there any other way to run a command and port the whole django application code to python3? -
What does the thottle_user_ip when caching in django mean?
I implemented django cache like this in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'requests_cache_table', } } And added a simple caching mechanism around my subscription check as follows: stripe_subscription = cache.get(f'stripe-subscription-user:{user_id}') if stripe_subscription is None: stripe_subscription = stripe.Subscription.retrieve(subscription.subscription) cache.set(f'stripe-subscription-user:{user_id}', stripe_subscription, timeout=3600) This correctly works and I see user caches being added to my database. However, every time I login ip adresses are also cached. Even when I remove the caching functions described above. Why does this happen and what does this mean? -
Is serializing a field as FileField and JsonField possible?
My question is simple. In Django REST Framework, is it possible to serialize the same field as either FileField() or JsonField()? which means my serializer must be able to validate the user request provided as Json or csvfile for the same field. Is it possible? Can anyone tell me?