Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make a post request and get the radio button values in django
I'm doing a website in django but this is the first time i use this framework so i'm not so used to it. I need to save some information on a DB, and i need to take these information from some radio buttons. I tryied so many ways to get the data but nothing worked. So i'd like to ask how to get these data in models.py from a template.html. This is the code in views.py: def question1(request): form = CHOICES(request.POST) if request.method == 'POST': form = CHOICES(request.POST) if form.is_valid(): selected = form.cleaned_data.get("NUMS") return render(request, 'q1.html', {'form': form}) This is the template question1.html: <form class="form-inline" method='POST' action="" enctype='multipart/form-data'>{% csrf_token %} {% csrf_token %} {{form.path}} </form> Then there is the form in forms.py: NUMS = [ ('one', 'one'), ('two', 'two'), ('three', 'three'), ('four', 'four'), ('five', 'fives'), ] class CHOICES(forms.Form): NUMS = forms.ChoiceField(choices=NUMS, widget=forms.RadioSelect) I checked and I think that the problem could be the request.method that is GET insted of POST. So how can I make a POST request? Thank you -
Update a Python variable that is interrogating JIRA API that is subsequently presented on a template page
I have a variable that is being written from a JIRA call using the JIRA Python Library - when restarting the development server, the values in the variable are updated of course as the connection to JIRA is re-established. I am trying to understand the best way to update the value in the variables - either on a timed basis, or on each refresh/visit to the Dashboard. My views.py file below: views.py # Emergency Changes Query jira_emergency_changes = jira.search_issues('labels = change-audit AND resolution = Unresolved').total class Dashboard(LoginRequiredMixin,View): def get(self, request): greeting = {} greeting['heading'] = "Dashboard" greeting['pageview'] = "Tooling" greeting['jira_emergency_changes_render'] = jira_emergency_changes return render(request, 'hub/dashboard.html',greeting) Thanks in advance :) -
Facing Internal Server Error With Django Requests When Adding A Product
ISSUE: I ran my project and tried adding a product through Django's Jet Dashboard, but it's giving me errors. Project Repository: https://github.com/Bilal815/ecommerce_storee My Redis giving warning: enter image description here My Logging Messages: enter image description here POST request's response: enter image description here Question: What do I do here? Is it an SSL issue or an elasticsearch issue? I've tried disabling elasticsearch but to no avail and also tried adding product via MySQL and it worked! Thank you for any help! -
Why i cant get the prefetched related object in DJANGO?
I want to get the midia with the thumbnail = True for every galeria using the prefetch related. class Midia(Base): galeria = models.ForeignKey(Galeria, on_delete=models.CASCADE, related_name= "midias") thumbnail = models.BooleanField('Thumbnail ', default=False) video_thumbnail = models.URLField(blank = True) imagem = StdImageField(upload_to='midias/', blank=True, delete_orphans=True) class Galeria(Base): titulo = models.CharField('Título', max_length=100) descricao = models.TextField('Descrição', blank= True) I did it using this code in the view: galerias = Galeria.objects.prefetch_related(Prefetch('midias', queryset= Midia.objects.filter(thumbnail = True))).all() And this in the HTML: {% for galeria in galerias %} {% with thumbnail=galeria.midias.first %} {% if thumbnail %} {% if thumbnail.imagem %} <img src="{{ thumbnail.imagem.url }}" alt="" > {% else %} <img src="{{ thumbnail.video_thumbnail }}" alt=""> {% endif %} {% else %} <img src="generic image" alt="" > {% endif %} {% endwith %} But why when i try to do this: {% with thumbnail=galeria.midias %} It returns None. Checking the sqls hits in the database the galeria.midias.first does not appear. Why when i use galeria.midias it returns None? -
Django - How to import csv data with a model that has a foreign key to an instance of the same model?
I'm trying to import data from a CSV file on a model Category that looks something like this: class Categories(BaseModel): shop_id = models.SmallIntegerField(default=1, blank=True) parent_id = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) name_en = models.CharField(max_length=255) name_fr = models.CharField(max_length=255, null=True, blank=True) I am working on a script to load the csv and read the data to create a model instance, but how can I get the Categories instance related to parent_id when it has not been created yet. -
What platform would be best to host my Ecommerce site?
I currently have a Shopify website but I have now learned Python and Django and I am building out my own ecommerce site. It's a relatively small website with 1 current product, some images and a blog with a number of articles. Can anyone please recommend a platform that would work best for hosting my page and domain? Shopify is currently 30euros and I would hope that I could reduce this with AWS or GCP although I am new to web dev and may be incorrect. Any advice is highly appreciated. -
django debug toolbar unit testing version change
I'm updating a legacy Django (version 2.2.27) running on Python 3.7.7 to use an upgraded version of django-debug-toolbar (version 2.2.1) because of a Dependabot alert. The alert was about possible SQL injection. Is it possible to write unit tests to determine if the version update does what it's supposed to? Any resources, links or suggestions are welcome. -
Password Reset Confirm did'nt work Django
I'm trying to Reset password with Django but after sending email to write new password it renders me to django adminstration page enter image description here from django.urls import path from . import views from django.contrib.auth import views as auth_views from django.contrib.auth.views import LoginView,LogoutView from .forms import UserLoginForm urlpatterns = [ path('login/',LoginView.as_view( template_name='registration/login.html', authentication_form=UserLoginForm),name='login'), path('logout/',LogoutView.as_view(),name='logout'), path('signup/',views.UserCreateView.as_view(),name='signup'), path('user_profile/<int:pk>/', views.UserProfileView.as_view(),name='user-profile'), path('user/<int:pk>/update', views.UpdateUserProfileView.as_view(),name='update-profile'), path('user/password/', views.ChangePasswordView.as_view(),name='password-change'), # Process of reset the passwords path('reset_password/', auth_views.PasswordResetView.as_view( template_name='registration/reset_password.html'), name='reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view( template_name='registration/password_reset_sent.html'), name='password_reset_done'), path('reset/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view( template_name='registration/password_reset_form.html'), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view( template_name='registration/password_reset_done.html'), name='password_reset_complete'), ] and password_reset_form.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} {% if validlink %} <h3>Change password</h3> <form method="post"> {% csrf_token %} {{ form|crispy}} <button type="submit">Change password</button> </form> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} {% endblock %} -
Django CreateView: ModelForm not saving to db;
My modelform is not saving data to the database and using a CustomUser Model and a Profile model too. Here is my CustomUser model class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True, null=True) # Personal details first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) dob = models.DateField() gender = models.CharField(max_length=100, choices=SEX) profile_pic = models.ImageField(upload_to='images',null=True) Here is my Profile Model class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) # Education school_name = models.CharField(max_length=200) school_address = models.CharField(max_length=200) lga = models.CharField(max_length=100) school_state = models.CharField(max_length=200) course = models.CharField(max_length=100) level_of_study = models.PositiveIntegerField() When the user clicks on the student registration link, it loads the CustomUser Fields and the Additional fields in the Student Class. I need a proper way of saving these data to the database so that when under the CustomUser Model i will see the user's details and also when i check the Student Model i will see the user's details who are students too. -
wagtail: How to dynamically limit the number of Parent Key objects in the admin panel (page model)?
Here is my model: class Store(Page): ..... panels=[InlinePanel(pr)] class pr(orderable): .... store = ParentalKey(Store,...) I want each user to have a different limit on the number of PRs.and raise ValidationError if exceeds the limit I try to use WagtailAdminPageForm and override clean() to detect the number of PRs, but I have a problem. delete button not really delete item, it's just "display:none". so, I can't use attribute of self.data "store_pr-TOTAL_FORMS" to detect the number of PRs and raise ValidationError. When the user exceeds the limit, this form cannot be saved, even if the PR is deleted on the form, because the length of the PR sent to the server will only increase and will not decrease -
Return inital value in admin change/add form field
I need return only current user on add/change admin model field: In my admin/model the field fk user, return a list of users, independent if the current user is_admin or not: How put initial value only current user, and nothing more. admin.py class AdminProductModel(admin.ModelAdmin): inlines = [AdminProductImages,AdminProductFeatures] model = Product def formfield_for_dbfield(self, db_field, request, **kwargs): formfield = super(AdminProductModel, self).formfield_for_dbfield( db_field, request, **kwargs) if db_field.name == 'user': formfield.widget.can_add_related = False formfield.widget.can_change_related = False return formfield def product_thumb(self, obj): # return HTML link that will not be escaped return mark_safe( '<img src="%s" style="width:30px;height:30px;">' % (ProductImages.objects.filter(product=obj).first().image_file_w200_png.url) ) product_thumb.short_description = 'Preview' list_display = ['product_thumb','user','slug','created_at'] list_display_links = ('slug','product_thumb') exclude = ['slug','product_title_seo'] def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(user_id=request.user) models.py class Product(models.Model): user = models.ForeignKey(User,verbose_name = u'usuário', on_delete=models.CASCADE) #...otherfields -
How to put api in Django?
I have just started learning Django. I am a beginner. I have a project related to cryptocurrency, and it is supposed that the white paper we import through the API will get the price and volume from the desired site (example: coinmarketcap.com), but no matter how much I search, I do not know how to implement this piece.Can you help me? -
How to keep sidebar remain open when page reload in django?
Can you guys help me? I badly need help, this problem is taking forever and really consumed a lot of the allotted time. There's a project that I currently working on where there's a sidebar on the admin panel. I wanted to keep the sidebar remain open or keep its state whenever the page reloads to other link. Whenever I click the submenu item or an active link on the sidebar header like the "Access" on the Dashboard, the sidebar closed and getting back to the way it was. I've searching for possible solutions but nothing solved my problem. Here's my base.html: <body> <div class="wrapper"> <!-- Sidebar --> <nav id="sidebar" class="menu"> <div class="sidebar-header"> <a href="/"> <img src="{%static 'img/w1_yellow.png'%}"> </a> </div> <ul class="list-unstyled components pre-scrollable nav-menu" id="nav-menu"> <!--Dashboard--> <li class="main-list active"> <a href="#homeSubmenu" role="button" data-toggle="collapse" data-parent="#nav-menu" aria-expanded="false" class="dropdown-toggle"> <i class="fas fa-tachometer-alt mr-2"></i>Dashboard</a> <ul class="collapse list-unstyled sub-menu" id="homeSubmenu"> <li {% block nav_dash-access%}{% endblock %}> <a href="/attendance/access" >Access</a> </li> <li {% block nav_dash-activity%}{% endblock %}> <a href="/activity/dashboard">Activity</a> </li> <li {% block nav_dash-facility%}{% endblock %}> <a href="/booking/admin">Facility</a> </li> <li {% block nav_dash-mentors%}{% endblock %}> <a href="/account/dashboardmentors">Mentor</a> </li> </ul> </li> <li class="main-list"> <a href="#pageSubmenu" data-widget="pushmenu" role="button" data-toggle="collapse" data-parent="#nav-menu" aria-expanded="false" class="collapse-toggle"> <i class="fas fa-bookmark mr-2"></i>Booking</a> <ul … -
Create a python object with a date field 3 months from now
I'm learning python, hence this is probably an obvious solution for some, but I am trying to create a class that, whenever created, has a test field with a date value of three months from now. My class is as follows: class Something(models.Model): test = models.DateTimeField(default=self.get_date()) def get_date(self): today = datetime.date.today() return today + relativedelta(months=1) I thought that I could define it as a function and then call it to set the date. Can someone advise what's wrong here? Any links to relevant documentation would also be appreciated, thank you. -
Django not show checkbox after submit form
I create control_form.html for show and edit status of checkbox like this code. control_form.html {% for device in device %} <!-- Rounded switch --> <form action="addStatus" method="post"> {% csrf_token %} <label class="switch"> <input type="checkbox" name="status" onChange="this.form.submit()" {% if device.status %} checked{% endif %}> <span class="slider round"></span> </label> </form> {% endfor %} When form submit it will send data to addStatus() for update database. After that, it will back to control_form.html with data update. views.py def controlForm(request): status = 0 data=Device.objects.all().filter(api_key='003') device = {'device':data} return render(request,'control_form.html', device) def addStatus(request): status =request.POST.get('status') if status == "on": device_item = Device.objects.get(api_key='003') device_item.status = 1 device_item.save() else: device_item = Device.objects.get(api_key='003') device_item.status = 0 device_item.save() return render(request, 'control_form.html') The problem is after update database in addStatus(). The control_form.html not show checkbox. How to fix it? -
DRF SearchFilter in ListAPIViews
I'm working on Django==3.2.7, djangorestframework==3.12.4 and django-filter==21.1. and React for the frontend What I would like to do: Return Job Offer objects that contains words from search (Search fields job_title and localistation) Remove useless words like ('in', 'a', 'an', 'the', 'at', 'for', 'to') in search here an example of the url: {{URL}}/api/v1/job-offers/jobs/?search=Chef in Texas allowed_methods = ['GET'] What I've done so far in my (ListAPIView): class JobOfferListAPIView(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] queryset = JobOffer.objects.all() serializer_class = JobOfferSerializer filter_backends = [filters.SearchFilter, filters.OrderingFilter, DjangoFilterBackend] search_fields = ['job_title', 'localisation'] ordering_fields = ['user', 'is_active'] filterset_fields = ['user', 'is_active', 'job_title', 'type_of_job', 'start_date', 'salary', 'localisation'] def get_queryset(self, *args, **kwargs): exclude_words = ['in', 'a', 'an', 'the', 'at', 'for', 'to'] keywords = self.request.GET.get('search').split(' ') keywords = [keyword for keyword in keywords if keyword not in exclude_words] if keywords: for keyword in keywords: queryset = queryset.filter( Q(job_title__icontains=keyword) | Q(localisation__icontains=keyword) ) print(queryset) return queryset Problème: When i'm printing queryset i can see filtered Job Offers in terminal but not return in Postman. Terminal Screen: Postman Screen -
ORM query using REGEX in ORM [closed]
I want to write a query using regex. Ex. Id Name 1 Edelweiss Banking and PSU Debt Fund - Regular Plan Growth 2 Edelweiss Small Cap Fund - Direct Plan Growth I have above to recodes in my MF table. we have to get query using name column for Name = edelweiss banking - and PSU Debt Fund - Regular Plan-Growth I thought, have using MF.objects.get(name__regex=r'____') -
Python/Django - radiobutton with submit button instead of buttons
I have a Django application where I want to have a setting: if the email is sent automatically or manually. What I have works, but not in the style that I want it. At the moment I have 2 buttons where you can click them and the setting is set to what you want. But what I would want is radio buttons, that are also already checked or unchecked, depending on the setting. What I have now is: model.py class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") forms.py CHOICES = [('manual', 'MANUAL'), ('auto', 'AUTO')] class SendMailSetting(ModelForm): class Meta: model = AutoSendMail fields = ['auto', 'manual', 'type'] widgets = { "manual": forms.RadioSelect(attrs={'class': 'form-control'}), "auto": forms.RadioSelect(attrs={'class': 'form-control'}), 'type': forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) } views.py class AutoSendView(generic.TemplateView): template_name = 'core/mailbox/autoSendMail.html' context_object_name = 'autosend' extra_context = {"mailbox_page": "active"} form_class = SendMailSetting def post(self, request, *args, **kwargs): if request.POST.get('manual'): logger.info("Set to: manual email send") AutoSendMail.objects.filter(pk=1).update(auto=True, manual=False, type="manual") elif request.POST.get('auto'): logger.info("Set to auto email send") AutoSendMail.objects.filter(pk=1).update(auto=True, manual=False, type="auto") return HttpResponseRedirect(self.request.path_info) autoSendMail.html <form class="card" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <h3 class="card-title">Update Mail Settings</h3> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label class="form-label">Send E-mail</label> <button … -
Django many to many filter out itself but other field
I have a UserProfile model as follows: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_ips = models.ManyToManyField(IpAddress, related_name="ip_user_ips", blank=True) and an IpAddress Model as follows: class IpAddress(models.Model): ip = models.CharField(max_length=69) Admin.py: class UserProfileAdmin(admin.ModelAdmin): form = UserProfileForm fieldsets = ( (None, { 'fields': ('user', 'user_ips', 'shared_users',), }), ) list_display = ['user', ] filter_horizontal = ['user_ips',] Forms.py class UserProfileForm(forms.ModelForm): class Meta: fields = '__all__' model = UserProfile shared_users = forms.MultipleChoiceField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['shared_users'].queryset = # Display Shared Users By The Same IP of all IPs this user have accessed with As of now, "user_ips" displays all ip addresses by a particular user in Admin, I want to filter out and display the username of All users shared by the same ip address of all ip addresses by that user in Admin, Preferably without having to actually create an additional field or model in the database. -
Posting http request after enabeling TLS/SSL
I have a website using Angular for the frontend, Django for the backend and they are being served using Apache. It was working properly until I enabled TLS/SSL using letsencrypt. Since then I was still able to access the website using https, but all my http request to the backend give errors. The error message is: Http failure response for http://backend.IP:8080/api/load_data/: 0 Unknown Error If I call the API function from the browser like this: http://backend.IP:8080/api/load_data/ It works well and returns the expected data from the backend, but when posting http request from the code it gives the previous error. Here is apache configurations for the frontend.conf: <VirtualHost *:80> DocumentRoot "/home/ubuntu/myproject/static/" # Other directives here DirectoryIndex index.php index.htm index.html <Directory "/home/ubuntu/myproject/static"> AllowOverride All Require all granted </Directory> # Logs ErrorLog /var/log/apache2/frontend_error.log CustomLog /var/log/apache2/frontend_access.log combined RewriteEngine on RewriteCond %{SERVER_NAME} =test.myproject.org RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> Here is the frontend-le-ssl.conf: <IfModule mod_ssl.c> SSLStaplingCache shmcb:/var/run/apache2/stapling_cache(128000) <VirtualHost *:443> DocumentRoot "/home/ubuntu/myproject/static/" # Other directives here DirectoryIndex index.php index.htm index.html <Directory "/home/ubuntu/myproject/static"> AllowOverride All Require all granted </Directory> # Logs ErrorLog /var/log/apache2/frontend_error.log CustomLog /var/log/apache2/frontend_access.log combined ServerName test.myproject.org SSLCertificateFile /etc/letsencrypt/live/test.myproject.org/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/test.myproject.org/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf Header always set Strict-Transport-Security "max-age=31536000" SSLUseStapling on Header always set Content-Security-Policy upgrade-insecure-requests </VirtualHost> … -
Unable to set formset fields in view
I have try to make inlineformsets and it works but I need to set field that are not displayed in formset in the corresponding view. Model Antecedent is linked to Inclusion models with a one-to-many (FK) field (inc). I've tried to do it in is_valid() method but it dosen't work. I manage to set 'parent' (Inclusion) form sai_log field but not related 'childrens' (Antecedent) formsets sai_log fields. I know that Antecedent.objects.filter(inc__pat=self.kwargs["pk"]).update(sai_log=self.request.user.username) is a correct instruction but data is not saved in database. models.py class Inclusion(models.Model): pat = models.ForeignKey('Patient',on_delete = models.CASCADE, related_name='inclusion_patient', db_column='pat') sai_log = models.CharField('Login de l\'utilisateur ayant fait la saisie (AUTO)', max_length=50, null=True, blank=True) class Antecedent(models.Model): ide = models.AutoField(primary_key=True) inc = models.ForeignKey('Inclusion',on_delete = models.CASCADE, related_name='antecedent_inclusion', db_column='inc') sai_log = models.CharField('Login de l\'utilisateur ayant fait la saisie (AUTO)', max_length=50, null=True, blank=True) views.py def form_valid(self, form): context = self.get_context_data() antecedents = context['antecedents'] self.object = form.save(commit=False) if antecedents.is_valid(): self.object.sai_log = self.request.user.username # sai_log set in 'parent' form works self.object.save() # self.kwargs["pk"] => pk of patient Antecedent.objects.filter(inc__pat=self.kwargs["pk"]).update(sai_log=self.request.user.username) # sai_log set in 'childrens' formsets doesn't works antecedents.instance = self.object antecedents.save() else: return render(self.request, self.template_name, context) return super(InclusionCreate, self).form_valid(form) -
django.urls.exceptions.NoReverseMatch: Reverse for 'like_qa' with arguments '('',)' not found
I have a Django app with a like button that I implemented based on that tutorial. The URL differs in my app because I don't put 'id' in my URL but only slug. When clicking on the like button it adds likes to the counter, however, it doesn't show the updated counter until the page is refreshed. I get the following error every time I click on the like button: Traceback (most recent call last): ... django.urls.exceptions.NoReverseMatch: Reverse for 'like_qa' with arguments '('',)' not found. 1 pattern(s) tried: ['like_qa/(?P<slug>[-a-zA-Z0-9_]+)/$'] [17/Mar/2022 12:44:49] "POST /like_qa/how-to-add-products-to-the-catalog/ HTTP/1.1" 500 149900 views.py @login_required def LikeQA(request, slug): article = get_object_or_404(QA, slug=slug) liked = False if article.likes.filter(id=request.user.id).exists(): article.likes.remove(request.user) liked = False else: article.likes.add(request.user) liked = True context = { 'like': article, 'liked': liked, 'total_likes_qa': article.total_likes_qa(), } if request.is_ajax(): html = render_to_string('components/like_section_ajax.html', context, request=request) return JsonResponse({'form': html}) urls.py path('like_qa/<slug:slug>/', views.LikeQA, name='like_qa'), like_section_ajax.html {% if request.user.is_authenticated %} <form action="{% url 'like_qa' qa.slug %}" method="POST"> {% csrf_token %} {% if liked %} <button type="submit" id="like" name="qa_slug", value="{{qa.slug}}" class="btn btn-clicked"><i class='bx bxs-like'></i></button> {% else %} <button type="submit" id="like" name="qa_slug", value="{{qa.slug}}" class="btn btn-to-be-clicked"><i class='bx bx-like'></i></button> {% endif %} {{ total_likes_qa }} like{{ total_likes_qa|pluralize }} </form> {% endif%} QADetail.html <script type="text/javascript"> $(document).ready(function(event){ $(document).on('click', … -
Django How to link a foreign key to many tables
I have n classes and each class contains a column called key like this (where n==3) class class1(models.Model): Id1 = models.AutoField(primary_key=True) key = models.CharField(max_length = 16, blank=True) class class2(models.Model): Id2 = models.AutoField(primary_key=True) key = models.CharField(max_length = 16, blank=True) class class3(models.Model): Id3 = models.AutoField(primary_key=True) key = models.CharField(max_length = 16, blank=True) I want to make the column key as Foreign key between all the n classes? I know how make a foreign key between 2 classes but I want to do that with many classes because I have about 40 classes and some classes has some commun columns -
What are some useful resources to learn model serializers provided by Django Rest Framework?
I am a beginner in learning Django Rest Framework. What are some useful resources to learn model serializers provided by Django Rest Framework? I am learning from some course videos on Youtube, Udemy and Coursera. But most of the videos use templates in views.py file and I want to use DRF with APIView. -
Allow Users to Specify SESSION_COOKIE_AGE in Django at Runtime
I'm specifying a default SESSION_COOKIE_AGE in the main settings.py file; however, I'd like admin users to be able to overwrite this value. This value should persist across server restarts. My initial reaction was to store this in a single-row in a DB table and then write some middleware that would adjust the user's expiry date on each request to match the user-supplied SESSION_COOKIE_AGE; however, that seems like a lot of redundant db queries. Then I went down a signals rabbit hole and am considering creating two signals (post_save and connection_created) to handle: user updates to the user-supplied SESSION_COOKIE_AGE value stored in the DB as well as ensuring SESSION_COOKIE_AGE is updated upon the server starting. And finally I see all of these projects like django-constance, etc. to dynamically update settings constants at runtime. Any suggestions on the most reliable / least error-prone architecture for this?