Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checking conditions with a function django views
I am trying to make my code more readable and less verbose. I have this long view, where I have some if and elif statement to check some conditions. What I am trying to do is to write this function into another file (utils.py) and use this function in the views. The view is something like that: views.py if float(ata_tacho) <= float(etd_tacho): messages.error(request, "ATA Tachometer cannot be greater or equal to ETD Tachometer") return HttpResponseRedirect(reverse('flight:add_new_flight')) elif ata <= etd: messages.error(request, "ATA cannot be greater or equal to ETD!") return HttpResponseRedirect(reverse('flight:add_new_flight')) elif function_type_obj.name == 'Dual Command' and not instructor: messages.error(request, "Instructor must be on Board!") return HttpResponseRedirect(reverse('flight:add_new_flight')) More code to run only if conditions above are satisfied These are some conditions I need to check to continue running the code. So far, so good. If I try to write this function in a more general one in utils.py file like below: utils.py def flight_validator(request, ata_tacho, etd_tacho, ata, etd, function_type, instructor): if float(ata_tacho) <= float(etd_tacho): messages.error(request, "ATA Tachometer cannot be greater or equal to ETD Tachometer") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) elif ata <= etd: messages.error(request, "ATA cannot be greater or equal to ETD!") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) elif function_type == 'Dual Command' and not instructor: messages.error(request, … -
who viewed my profile - list ( python - Django) Algorithm
Am currently working on Matrimonial site using django framework. In that site,I want to show the list of users who viewed my profile.Let's say I am user 'x' , if user 'y' and user 'z' viewed my profile . I want to show user 'y' and user 'z' viewed your profile in the my visitors page of user'x'. How to find out who viewed my profile?. -
Django i try to use reverse function and i got NoReverseMatch
i am a new at Django framework. and i follow of some guide on udemy and do step by step but something go wrong. i open startapp call 'accounts', and then i have file call urls.py here is what i have. from django.urls import path from . import views urlpatterns = [ path("<int:month>", views.monthly_num), path("<str:month>", views.monthly_str, name='monthly-acc'), ] and in views.py file i want to do reverse and to do redirect. from django.shortcuts import render from django.http import HttpResponseNotFound from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse # Create your views here. months = { "january": "Hello january", "febuary": "Hello febuary", "march": "Hello march", "april": "Hello april", } def monthly_str(request, month): try: text_month = months[month] return HttpResponse("<h1>"+text_month+"</h1>") except: return HttpResponseNotFound("THIS NOT A MONTH!") def monthly_num(request, month): monthly = list(months.keys()) if month > len(monthly) or month <= 0: return HttpResponseNotFound("<h1>NO GOOD</h1>") redirect_month = monthly[month-1] redirect_path = reverse('monthly-acc', args=[redirect_month]) # HERE I GOT THE ERROR. return HttpResponseRedirect(redirect_path) so what i try to do i have the local url for example: http://mypro:9000/acc/1 i want to redirect to http://mypro:9000/acc/january and i got this page error. -
Django migrating to new database, should I apply migrations before moving data?
My Django app uses an encrypted Amazon AWS RDS database. The encryption causes some annoyances/complexities and costs a small amount of extra money, so I'd like to do away with it. Encryption can't be removed so I've created a new RDS instance with new database. The old database also use PostGres 12.8 whereas the new one uses 14.2. Should I apply migrations to the new database and then move the data into the tables created by the migrations? Or can I just use a data migration service such as AWS DMS or DBeaver which will create the tables for me? I ask because I wonder if there are any intricate differences in how migrations provision the database vs how a data migration tool might do it, causing me issues down the line. -
Deployment of a React app with Django backend
As in the title I use React.js at the frontend and Django at the backend. I basically remade a website for my father's enterprise and we got cPanel on our hosting service (prevoius website was made in Django alone). The problem is I use cross origin in the new app. It is easy for me to just open up 2 command prompts and start 2 different localhosts for Django and React, but I have no idea how to do it on the server side. I had some ideas before like: "Should I buy a second server and host just React there?" or "Should I somehow merge backend and frontend together?", but still I have no idea which solution would fit the most. I would be grateful for any advice, tutorials, links that would help me solve this problem. If needed I can paste a github link to a project aswell. -
Django related models also need a generic relation: how to work around unresolved reference?
Here is the two models: class Circuit(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) service_order_item = models.ForeignKey(ServiceOrderItem, on_delete=models.RESTRICT) location_a = models.ForeignKey(Location, on_delete=models.SET_NULL, blank=True, null=True) location_z = models.ForeignKey(Location, on_delete=models.SET_NULL, blank=True, null=True) class CircuitItem(models.Model): circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE) index = models.IntegerField(default=0) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() CircuitItems are list of things in a circuit the problem is CircuitItems can be Circuits themselves (as well as some other models) Is it possible to do something like: circuit_link = GenericRelation("CircuitItem") to avoid the unresolved reference, or is there no way to do this with only two tables and a third will be required? -
Cant save image to "media" folder when the ImageField UPDATES
I am using ajax to send image file through formdata() Javascript code: $("#change-default-img").change(function () { let category = $($("#category-buttons-row").find('button[aria-label="ACTIVE"]')).attr("id") // Change preview in the UI if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#imagePreviewDefault").css('background-image', 'url(' + e.target.result + ')'); } reader.readAsDataURL(this.files[0]); } var fileData = new FormData(); fileData.append("file", this.files[0]) fileData.append("csrfmiddlewaretoken", "{{ csrf_token }}") fileData.append("category", category) $.ajax({ method: "POST", url: "{% url 'set-default-image' %}", processData: false, contentType: false, mimeType: "multipart/form-data", data: fileData, success: function (response) { data = $.parseJSON(response); if (data.status == "Done") { console.log("Default image updated for " + category); } } }) }) This is my view for updating the ImageField if request.method == 'POST': category = request.POST['category'] image = request.FILES.get('file') image = f'default_images/{image}' if category == 'category-logo': DefaultImages.objects.filter(app_name='payup').update(app_logo=image) elif category == 'category-property': DefaultImages.objects.filter(app_name='payup').update(property_card=image) elif category == 'category-owner': DefaultImages.objects.filter(app_name='payup').update(owner_profile=image) elif category == 'category-renter': DefaultImages.objects.filter(app_name='payup').update(renter_profile=image) return JsonResponse({'status': 'Done'}) This is my models.py class DefaultImages(models.Model): app_name = models.CharField(max_length=5, default='payup') app_logo = models.ImageField(upload_to="default_images/", null=True) property_card = models.ImageField(upload_to="default_images/", null=True) owner_profile = models.ImageField(upload_to="default_images/", null=True) renter_profile = models.ImageField(upload_to="default_images/", null=True) def __str__(self): return self.app_name This is how the directory looks like : media ---- backup_images ---- profile_images ---- prop_images When I am changing the image from the UI, the … -
Tripple Join with sum in django fails
How can I fetch such a query especially Mark is not attached to stream but the child's ClassInformation is the one that has the stream has_all_marks = Mark.objects.filter(marks_class=marks_class, year=year, term=term, exam_set=exam_set, child__classinformation__stream__id=stream).values('child').annotate( mtotal=Sum('marks')).order_by('-mtotal') Right now the result I get is wrong. I get multiples for some mtotal -
Next.js or Django for a small website with dynamic content with a firebase backend?
I am to develop a website for a design firm to showcase their work. The website only has a few pages, with text and images that can be dynamically changed from a firebase backend. The priority is on a neat UI that loads fast, and the timeline for development is short. Should I use Next.js as the framework or would Django be a better option? Please let me know why I should pick one framework over the other. -
How to serialize abstract base models and sub-models in Django REST framework
I have a model Complaint which can have many Evidences. An Evidence can be an Attachment or a Link. Evidence is an abstract base model. from django.db import models class Complaint(models.Model): text = models.TextField() class Evidence(models.Model): complaint = models.ForeignKey( Complaint, related_name='%(class)s_evidences', on_delete=models.CASCADE ) is_attached = models.BooleanField() class Meta: abstract = True class Attachment(Evidence): file = models.FileField(upload_to='attachments') class Link(Evidence): url = models.URLField() I want to be able take input of a Complaint and and all its Evidences from a single view like so: { "text": "Lorem ipsum", "evidences": [ { "description": "dolor sit amet", "is_attached": false, "url": "https://example.com" }, { "description": "consectetur adipisicing elit", "is_attached": true, "file": "http://localhost:8000/media/attachments/filename" } ] } This is what I have in my serializers.py thus far: from rest_framework import serializers from .models import Complaint, Evidence, Attachment, Link class EvidenceSerializer(serializers.Serializer): class Meta: abstract = True model = Evidence fields = ['id', 'is_attached'] class AttachmentSerializer(EvidenceSerializer, serializers.ModelSerializer): class Meta: model = Attachment fields = EvidenceSerializer.Meta.fields + ['file'] class LinkSerializer(EvidenceSerializer, serializers.ModelSerializer): class Meta: model = Link fields = EvidenceSerializer.Meta.fields + ['url'] class ComplaintSerializer(serializers.ModelSerializer): evidences = EvidenceSerializer(many=True) class Meta: model = Complaint fields = ['id', 'text', 'evidences'] This gives the following error when requesting to the complaint POST view (/lodge): TypeError … -
Can't get model in template through related_name
I create a project had 2 app( group & posts) and just found out that you can use: from django import template register = template.Library() To allow link from post to group through related_name. Now I want to show group member in and all group. But when I try to show GroupMember in template post_list through related_name = user_groups it doesn't show data (same with all group). Seem like I miss something, can u check it for me. Thank! App groups models.py from django import template register = template.Library() class Group(models.Model): name = models.CharField(max_length=235, unique=True) slug = models.SlugField(allow_unicode=True,unique=True) descripsion = models.TextField(blank=True,default='') descripsion_html = models.TextField(editable=False,default='',blank=True) member = models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args, **kwargs): self.slug =slugify(self.name) self.descripsion_html = misaka.html(self.descripsion) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups',on_delete=models.CASCADE) def __str__(self): return self.user.username In template post_list.html <h5 class='title'> Your Groups</h5> <ul class='list-unstyled'> {% for member_group in get_user_groups %} <li class='group li-with-bullet'> <a href="{% url 'groups:single' slug=member_group.group.slug %}">{{ member_group.group.name }}</a> </li> {% endfor %} <h5 class='title'> All groups</h5> <ul class='list-unstyled'> {% for other_group in get_other_groups %} <li class='group li-with-bullet'> <a href="{% url 'groups:single' slug=other_group.slug %}"></a> </li> {% endfor %} -
Django Html - make dropdown menu from navigation bar [duplicate]
I would like to create a dropdown menu from the logged-in user account. currently, the top-right button in the navigation bar is either "Login" or "Logout" based on if user is logged in. I would hope to create a dropdown menu when user is logged in, which contains more options such as account, myorder, and logout. So I can save space in the navigation bar by avoiding having too many buttons. Some desired examples like below: The dropdown menu can contain two options (MyOrder and Logout). Please do not provide the external stylesheet as it will conflict/mess up my current page. CSS <style> .block [for=s1]{ width: 400px; display: block; margin:5px 0; } .block [for=s2]{ width: 800px; display: block; margin:5px 0; } .center [for=s1]{ text-align: center; } .center [for=s2]{ text-align: center; } label[for=s1]{ display: inline-block; width: 100px; text-align: right; } label[for=s2]{ display: inline-block; width: 70px; text-align: left; } input,textarea [for=s1]{ vertical-align: top; } input,textarea [for=s2]{ vertical-align: left; } .page-header { //background-color: #5E5A80; background-color: #454545; margin-top: 0; //padding: 20px 20px 20px 40px; padding: 5px 5px 5px 5px; } .page-header h1, .page-header h1 a, .page-header h1 a:visited, .page-header h1 a:active { color: #ffffff; font-size: 25pt; text-decoration: none; } input:focus{ border-color: #66afe9; outline: 0; … -
Django website fails to load after request
I have two Django websites on the same server using Apache (windows 10) with mod_wsgi. My first Django website runs fine, it is a lot simpler, my second one, however, does not. Once I connect to it, it loads very slowly, however, I can't connect to it again (it just remains in the connecting phase with no errors). I've had this problem for quite a while, here are my other posts for context. Only the first Django site to be loaded works Django infinite loading after multiple requests on apache using mod_wsgi Django websites not loading Only quite recently have I pinpointed the problem to this specific Django project, I will provide most of my code below. Hopefully, someone can show me what I have done wrong. Contact me if this isn't enough information, thank you. Base urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("accounts/", include("accounts.urls")), path('', include('mainfront.urls')), path('about/', include('mainfront.urls')), path('contact/', include('mainfront.urls')), path('home/', include('mainfront.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ] Base WSGI import os from django.core.wsgi import get_wsgi_application import sys sys.path.append('C:/xampp/htdocs/neostorm') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'neostorm.settings') application = get_wsgi_application() Mainfront (front app) views.py from django.shortcuts import render import threading from mcstatus import JavaServer from .models import Article #Query … -
Import multiple models with only one csv file django import export
I'm using django import export package. I have two models called Vineyard and VineyardUser. I also have a csv file that contains all the data for both the Vineyard and VineyardUser models (separated by one blank column). Here is my model (which has been simplified): class Vineyard(models.Model): name = models.CharField(max_length=255, blank=True) text = RichTextUploadingField(blank=True) class VineyardUser(models.Model): vineyard = models.OneToOneField(Vineyard, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=True) I want to click import on the Vineyard model in admin, and then it also created the VineyardUser object. How can I do that? Now it only creates Vineyard objects even though there is a VineyardUser data in that csv file. I think we can use before_save_instance or after_save_instance but I'm not sure how to do that. Also one thing to note is that they may also have two fields with the same name. Any suggestion or solution to solve this problem? -
right way to deploy a django-rq worker
maybe it's a silly question, but I didn't found much while googling around. So I'm on the way to transform my development environment to a deploy environment. I connected django and nginx using uwsgi, put both in docker containers... so far no problem. But I'm using django-rq, so I need a Worker process. In all these nice examples about deploying django I didn't found much about deploying django-rq. All I found was "create a docker container and use the manage.py " like this: CMD python manage.py rqworker [queue1] [queue2] Really? Should I just start the worker like this? I think manage.py is just for testing!? -
Django forms 'str' object has no attribute 'get'
the error is with the following: registerform = UserCreationForm(request.POST) Error here!if registerform.is_valid(): class UserCreationForm(forms.ModelForm): error_messages = { 'password_mismatch': ("The two password fields didn't match."), "email_missing": ("Please enter email."), "name_missing": ("Please enter name."), } password1 = forms.CharField(label=("Password"), widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) password2 = forms.CharField(label=("Password confirmation"), widget=forms.PasswordInput(attrs={'placeholder': 'Repeat Password'}), help_text=("Enter the same password as above, for verification.")) first_name = forms.CharField(label=("First Name"), widget=forms.TextInput(attrs={'placeholder': 'First name'})) last_name = forms.CharField(label=("Last Name"), widget=forms.TextInput(attrs={'placeholder': 'Last name'})) username = forms.CharField(label=("Username"), widget=forms.TextInput(attrs={'placeholder': 'Username'})) email = forms.EmailField(label=("Email"), widget=forms.TextInput(attrs={'placeholder': 'Email'}),help_text=('Security is of upmost importance for Glocal. We require email address verification in order to prevent trolling and fake accounts. Please enter your email address below and click on "verify" in the email that we will send you, in order to activate your account.')) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) # remove username self.fields.pop('username') class Meta: model = User fields = ("username", "email",) field_order = ['first_name', 'last_name', 'password1', 'password2', 'email'] def clean(self): cleaned_data = super(UserCreationForm, self).clean() password1 = cleaned_data["password1"] password2 = cleaned_data["password2"] email = cleaned_data["email"] username = cleaned_data['first_name'] + "." + cleaned_data['last_name'] first_name = cleaned_data['first_name'] last_name = cleaned_data['last_name'] if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch', ) if not email: raise forms.ValidationError( self.error_messages['email_missing'], code="email_missing") if not first_name or not … -
How to loop thru JSON list and save data in Django
I am trying loop thru JSON list data and save into the variable 'nfts'. Exception Value: string indices must be integers Traceback: nft_data_id = item['nfts'][item]['nft_data_id'], ... JSON response: {"result":{"page_count":3041,"nfts":[{"nft_id":"#-#-#-#","nft_data_id":"#-#-#-#", ... views.py Code: def market_data(request): URL = '...' response = requests.get(URL).json() nfts = response['result'] for item in nfts: nft_data = NFT_attributes( nft_data_id = item['nfts'][item]['nft_data_id'], ... -
How can I save a user's selected choice on refresh Django
I'm trying to save a user's choice which but on refresh or navigating to another page, the submission had been removed. How can I save the user's submission so it won't reset/change unless the user chooses to? I.e. if someone chooses AUD, that choice will remain submitted on refresh/navigation/login/logout. FORM class CurrencyForm(forms.Form): currency = forms.ChoiceField(initial=('USD', 'USD'), choices=['USD', 'AUD', 'GBP' 'CAD'], label='Choose Currency:') VIEW class MyDashboardView(TemplateView): template_name = 'coinprices/my-dashboard.html' def get(self, request, **kwargs): form_c = CurrencyForm(prefix='form_c') return render(request, self.template_name, { 'form_c': form_c, }) def post(self, request): currency = 'USD' form_c = CurrencyForm(request.POST, prefix='form_c') if request.method == 'POST': if form_c.is_valid(): currency = form_c.cleaned_data['currency'] rates = {'USD': 1.0, 'AUD': 1.321, 'GBP': 0.764, 'CAD': 1.249} deposit = 10000 / rates[currency] context = { 'deposit': deposit } return render(request, 'coinprices/my-dashboard.html', context) HTML <span> <form method="post"> {% csrf_token %} {{ form_c.as_p }} <button class="btn btn-outline-success btn-sm">Submit</button> </form> </span> <span class="text-xl">${{ deposit }}</span> -
Why does django continues naming my app as the previous name?
thanks for reading. When I run "py manage.py makemigrations" I get the following message: "ModuleNotFoundError: No module named 'transformaTe'" This is the apps.py code: from django.apps import AppConfig class TransformateConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'transformate' The name is updated there and in my INSTALLED_APPS: INSTALLED_APPS = [ 'transformate', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Where else should I look to change the name of the app? This is the simplified structure of the app: \my-app \transformate admin.py apps.py models.py urls.py views.py \my-app asgi.py settigs.py urls.py wsgi.py All this happened when I rename the app because I had a problem creating a table called transformaTe_myuser so I though all could be caused by the capitalized letter use. Is there a better way of renaming an existing app in Django? I followed this steps, except for the migration part (Because I deleted the db and the migrations folder): https://odwyer.software/blog/how-to-rename-an-existing-django-application Thanks for your help. -
Secure webapp with Django and React
I'm experimenting with these 2 technologies to make a secure web app [Currently learning React (60%) and Django (<50%). This is intended to be like a medical database, so doctors and nurses enters their patients' information. They need to login obviously. I wanted to implement React-based UI (And not using the classic method to create views from django), so I've found many tutorials just like this one: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react It basically turns Django into a restAPI, and then the React frontend uses axios to retrieve data from the endpoint. Sounds not bad at all (comparing to the native method of rendering data in a webpage from Django), but the problem is that I have no idea on how to make this secure, you know, Django provides an auth system, which is pretty good and secure, I have to say, but in a project with this structure, the auth needs to be done in React, so there many questions appear: To start with, is it a good idea to make a project of this structure? (If no, then what could be a good one) If it's a yes, how can I protect the API so only logged in users can interact with … -
Django: How to display the voting options that correspond to the logged-in user
Working through my first Django project. I'm trying to display the Result model record that has been pre-created specifically for the logged-in user and wherein that user/decision-maker can see the decision that they've been assigned to vote on, as well as the corresponding choices from which they must select one. The code further below "works"---but there are 2 problems related to the forms.py line: result_instance = Result.objects.create(decision_id=22) First problem is that I'm inadvertently creating a new record in the model Result by using the property "create"---when I just want to update an existing Result record (i.e., the logged-in user's record containing their assigned decision/choices, which in turn are foreign-keyed from the model Decision). Second problem is that the option, "decision_id"=22, obviously has a static value and needs to be changed to dynamically refer to the decision that has been pre-assigned to the logged-in user in their "personal" Result record. I think I need to pass the logged user's assigned decision from views.py to forms.py---but not sure how to do that. Hoping there is a solution that fixes both issues. Thanks! models.py class Decision(models.Model): custom_user = models.ForeignKey(CustomUser, default=None, null=True, on_delete=models.SET_NULL) summary = models.CharField(default="", verbose_name="Decision") option1 = models.CharField(default="") option2 = models.CharField(default="") class … -
How to filter products by category in Django?
There is a product page. I need to display only those products that belong to the same category.I tried to use get_queryset(), but got an error Unsupported lookup 'slug' for SlugField or join on the field not permitted.. How can I solve this? My code: model.py class Category(models.Model): name = models.CharField(max_length=50, verbose_name="Ім'я категорії") slug = models.SlugField(unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("category_detail",kwargs={'slug': self.slug}) class Product(models.Model): category = models.ForeignKey(Category, verbose_name='Категорія', on_delete=models.CASCADE) title = models.CharField(max_length=150, verbose_name='Ім\'я продукта') slug = models.SlugField(unique=True) product_code = models.IntegerField(default='0003001', verbose_name='Код продукту', blank=True, null=False) img = models.ImageField(verbose_name='Фотокартка') qty_product = models.IntegerField(default=1, verbose_name='Кількість товару') price = models.DecimalField(max_digits=5, decimal_places=0, verbose_name='Ціна') description = models.CharField(max_length=3000, verbose_name='Опис') def __str__(self): return self.title def get_absolute_url(self): return reverse('product_detail', kwargs={'slug': self.slug}) views.py class CategoryDetailView(DetailView): model = Category queryset = Category.objects.all() template_name = "mainapp/product-category.html" slug_url_kwarg = 'slug' context_object_name = 'products' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) category = self.get_object() context['categories'] = self.model.objects.all() context['products'] = Product.objects.all() context['category_products'] = category.product_set.all() return context def get_queryset(self): return Product.objects.filter(slug__slug=self.kwargs['slug']) -
Is there any way of solving a django static problem
directory: website static website images balloons.gif error: GET /static/website/images/balloons.gif HTTP/1.1" 404 1840 -
Storing datetime objects in django session?
I am storing a nested dictionary in a Django session variable. One of these fields that is pretty important is a DateTimeField. emp_list = [] employees = Employee.objects.filter(**filter here) for employee in employees: context = {} created = employee.created.strftime( "%Y-%m-%d %H:%M:%S" ) context["created"] = datetime.strptime(created, "%Y-%m-%d %H:%M" ) emp_list.append(employee) if I return a simple emp_list all works fine... return emp_list But if I return a... return request.session["emp_list"] = emp_list I get the common error TypeError: Object of type datetime is not JSON serializable So if I just want to just return the emp_list everything is fine, but trying to store inside of a session, I get the error. Is there any way around this to store datetimes inside of the sessions framework? Thanks in advance! -
How to run python commands in a new shell
I am learning django. I am stuck with this problem. So basically, I have designed a form (template) in HTML that takes a text file as input and generates a voiceover of that text file. I am using espeak for it in the backend. So, when a user uploads a file, this command - espeak -ven+m1 -f", uploaded_file.name where uploaded_file.name is the name of the uploaded file should run in a new terminal window. In order to achieve this, I wrote a print statement like this- print("espeak -ven+m1 -f", uploaded_file.name) in views.py but the problem with this is that it runs in the same shell but I want this print statement to execute in a different shell. So basically, my problem boils down to, I want to run a print command in a new shell but I am unable to figure out how. As I already said I am new to django and some help will be appreciated.