Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PdfFileReader.getFields() returns {} | django
I'm trying to read a pdf form with django. The point is that in another view of my views.py I've succeed into do it by using PyPDF2 and its PdfFileReader.getFields() method. Now the problem is that the reading is not working properly: I've checked with adobe acrobat and the file still is a form with actually fields, so I don't really have any idea of what could be the problem. I'm attaching here the relevant portion of the code: if request.method == "POST": form = Form(request.POST, request.FILES) # the form refer to a model called 'New Request' if form.is_valid(): form.save() File = request.FILES['File'].name full_filename = os.path.join(BASE_DIR, 'media/media', File) f = PdfFileReader(full_filename) fields = f.getFields() fdfinfo = dict((k, v.get('/V', '')) for k, v in fields.items()) k = creare_from_pdf2(request, fdfinfo, pk) # this is a custom function nr = NewRequest.objects.all() #I'm deleting the object uploaded because it won't be useful anymore nr.delete() os.remove(full_filename) If I display print(fdfinfo) it actually shows {}. This of course is leading to error when fdfinfo passes into the 'create_from_pdf_2' function. I don't really know what the problem could be, also because in another view I made exactly the same and it works: if request.method=='POST': form = Form(request.POST, … -
How to sort and count values when they are selected?
I send a request to the site https://swapi.dev/ the received data needs to be sorted: Provide the functionality to count the occurrences of values (combination of values) for columns. For example when selecting the columns date and homeworld the table should show the counts as follows: my code is not very good because I write something like this for the first time: import requests from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from rest_framework import status from rest_framework.response import Response from datetime import datetime from rest_framework import filters from rest_framework.pagination import PageNumberPagination from rest_framework.decorators import action # class StarWarsAPIListPagination(PageNumberPagination): # page_size = 4 # page_size_query_param = 'page_size' # max_page_size = 20 class StarView(APIView): # pagination_class = StarWarsAPIListPagination # filter_backends = (filters.OrderingFilter) # ordering_fields = ('name',) def get(self, request): date = datetime.today() page = request.query_params.get('page', 1) url = f'https://swapi.dev/api/people/?page={page}' response = requests.get(url, date).json() return Response(response, status=status.HTTP_200_OK) class StartDateView(APIView): def get(self, request): date = datetime.today() page = request.query_params.get('page', 1) url = f'https://swapi.dev/api/people/?page={page}' response = requests.get(url).json() a = response['results'][0]['name'] # a = response['results'] # for i in range(len(a)): # if a[i]["name"] == "R2-D2": # return Response(a[i]['name'], status=status.HTTP_200_OK) -
why does the csrf token get added to the database in django?
html <form action='order' method='post'> <label for="order">Choose storage size:</label> <!--{% csrf_token %}--> <select name="size" id="size" form="order" required> <option value=4>-</option> <option value=1>Small</option> <option value=2>Medium</option> <option value=3>Large</option> </select> </form> views.py def order(request): price = 0 if request.method == 'POST': size = request.POST;{'size'} duration = request.POST;{'duration'} username = request.POST;{'username'} if size=='1': print('aa') else: storage = Storage.objects.create(size=size, duration=duration, price=price, username=username) storage.save() print('order created') return redirect('/') else: return render(request, 'order.html') class Storage(models.Model): size=models.CharField(max_length=100) duration=models.CharField(max_length=100) price=models.CharField(max_length=100) username=models.CharField(max_length=100) location=models.CharField(max_length=2) whenever i submit the form, the csrf token gets added to all the fields in my database the valeu that gets added is "<QueryDict: {'csrfmiddlewaretoken': ['(series of numbers and letters)']}>" -
Can I get the values from the "GET" parameters as array?
I can get data from url like this. http://127.0.0.1:8000/page/?key=003 I show output as Json. This is view.py def page(request): key = request.GET['key'] data=Device.objects.get(key=key) print(key) data = { "open": data.open, "close": data.close, } return JsonResponse(data, safe=False) I try to get many value in same time like this http://127.0.0.1:8000/page/?key=003&key=004 In terminal it show output like this. [22/Mar/2022 15:19:22] "GET /page/?key=003&key004 HTTP/1.1" 200 64 003 The output show 003 only. Can I get the values from the "GET" parameters as array? -
Joining more than 2 tables for reports in django and extract all the fields from the joined table
I am joining the ClientDetails, AssignmentTable and CallDetails table to get a view as to which telecaller a particular client has been assigned to and get the latest call details as well. However I am unable to accomplish that using django ORM. ISSUE: I am trying to access the fields inside the assignment table and call table but I am getting only the ids and not the other fields. Question: How do I extract all the columns from the assignment and call details table which has the client id as 1? This is the SQL Query that I am trying to come up with: SELECT t1.uid, t1.phone_number, t1.client_name, t1.base, t1.location, t2.assigner, t2.bpo_agent, t2.cro_agent, t3.bpo_status_id, t3.cro_status_id, t3.agent_id_id FROM public.bpo_app_clientdetails t1 LEFT JOIN public.bpo_app_assignmentdetails t2 ON t1.uid = t2.client_id_id LEFT JOIN public.bpo_app_calldetails t3 ON t1.uid = t3.client_id_id; Below is the model file: class ClientDetails(models.Model): uid = models.AutoField(primary_key=True) phone_number = PhoneNumberField(unique=True) client_name = models.CharField(max_length=50, blank=True, null=True) base = models.CharField(max_length=50, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) class Meta: verbose_name_plural = "Client Contact Detail Table" def __str__(self): return f"{self.phone_number}, {self.client_name}" class AssignmentDetails(models.Model): uid = models.AutoField(primary_key=True) client_id = models.ForeignKey( ClientDetails, on_delete=models.PROTECT, related_name='assignment_details' ) date_and_time = models.DateTimeField(auto_now_add=True, blank=True) assigner = models.ForeignKey( User,on_delete=models.PROTECT, related_name='AssignerAgent', db_column='assigner', ) bpo_agent … -
Djnago model instance only update after calling objects.get() again (DRF Test case)
I have an APIView (DRF), where I set the user is_active field to False instead of deleting him, everything works as expected, but I have a wired behavior when I try to make a test case for the view, I try to test if the field 'is_active' is False after calling the ApiView but it remains 'True' if change the code a little bit and call user.objects.get() with the same user email after calling the ApiView, the new instance field is_active is False. I've never encountered this behavior, can someone explain the reason behind it? thanks! this test passes: def test_delete_account(self): self.authentication() # create user and log him in user = User.objects.get(email=self.sample_user['email']) self.assertEqual(user.is_active, True) response = self.client.post(reverse('delete-account')) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) user = User.objects.get(email=self.sample_user['email']) self.assertEqual(user.is_active,False) this test fails: def test_delete_account(self): self.authentication() # create user and log him in user = User.objects.get(email=self.sample_user['email']) self.assertEqual(user.is_active, True) response = self.client.post(reverse('delete-account')) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) self.assertEqual(user.is_active,False) # FAILS HERE delete account ApiView: class DeleteAccountAPIView(GenericAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request): user = self.request.user user.is_active = False user.save() return Response(status=status.HTTP_204_NO_CONTENT) -
Failed Python and Django Request
This code refused to work after many attempts and I really need help to get this rectified. check my code below def recharge (request): form = RechargeForm (request.POST or None) if request.method == "POST": url = "https://www.example.com/api/topup/" form = RechargeForm (request.POST or None ) if form.is_valid(): mobile_number = form.cleaned_data['mobile_number'] Ported_number = form.cleaned_data['ported_number'] network_id = form.cleaned_data['idnetwork'] plan_id = form.cleaned_data['idplan'] payload = { "network": network_id.network_id, "mobile_number": mobile_number, "plan":plan_id.plan_id, "Ported_number":True } headers = {'Authorization': 'Token eyeghegge7373c891fe9e7bbe3f9a0a8742d','Content- Type': 'application/json'} response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) info = response.json() info['mobile_number'] = mobile_number info['network_id'] = network_id info['plan'] = plan_id info['Ported_number'] = True i got the below error JSONDecodeError at /file/recharge Expecting value: line 1 column 1 (char 0) I now changes the code to something like this code so i can parse the json but still fails with open("response.json", "r") as write_file: info = json.load(write_file) but didn't work still I did also but still faailes info = json.loads(response) PORTED NUMBER is a boolenfield and i formatted it in this question like this for clarity. can someone help me out ? -
Security Scanning of files other than source code
I have some files that I need to download and then upload to a specific location during execution of code. These files are other than source code files but required by the source code(.yaml, .xml, some .zip folders etc.) I need to scan these files for any security vulnerabilities. Most available approaches look at source code and not at external files. What are some tool(s)/approach(es) that can be used for this? -
How to integrate moment.js into django? [closed]
I know a package by the name of "flask-moment" exists that provides a way to use the moment.js library with flask. Is there anything like that for django? If yes, then how do i use it? -
Advanced Python Scheduler running multiple times in production (Django on DigitalOcean)
I have a simple use of Advanced Python Scheduler to run some django code overnight everyday. The code itself works fine, and locally using manage.py runserver with the --noreload flag everything is spot on. My problem is in production where the APS code is being executed three times; as an example, I receive a status update by email at the end of the process each night, and this email is delivered 3 times within a 10 second period. Where should I be looking to replicate the protections of the --noreload flag in a production set up? -
How to apply different permission classes for different http requests
I have a UserViewSetthat supports get, post, patch, and delete HTTP requests. I have admins with different roles, some of them can delete users, and others cannot. I want to edit my UserViewSet to support this feature. I tried to do something like this: class UserViewSet(ModelViewSet): queryset = User.objects.all() http_method_names = ['get', 'post', 'patch', 'delete'] def get_serializer_class(self): if self.request.method == 'PATCH': self.permission_classes = [CanEdit] return UpdateUserSerializer elif self.request.method == 'DELETE': self.permission_classes = [CanDelete] return UserSerializer I am not sure if this is the best practice to do this. -
Page Not Found for urls - openwisp-radius
I'm new to Django, I am following this guide to setup openwisp-radius https://openwisp-radius.readthedocs.io/en/latest/developer/setup.html#setup-integrate-in-an-existing-django-project When I go to the browser for any path from urlpatterns besides admin/ I get Page not found (404). When I go to admin/ I get: ModuleNotFoundError: No module named 'openwisp_users.backends' My django version is 3.0, os is Ubuntu 20.04, I installed openwisp-radius-0.2.1 I created a new django project with django-admin startproject testapp, and added code from the guide to settings.py and urls.py this is my settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$_u-k638-9hprxb8lhx96+q+yo97be1uriik_86*t3my(s8ux3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', # openwisp admin theme 'openwisp_utils.admin_theme', # all-auth 'django.contrib.sites', 'allauth', 'allauth.account', # admin 'django.contrib.admin', # rest framework 'rest_framework', 'django_filters', # registration 'rest_framework.authtoken', 'dj_rest_auth', 'dj_rest_auth.registration', # openwisp radius 'openwisp_radius', 'openwisp_users', 'private_storage', 'drf_yasg', ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') PRIVATE_STORAGE_ROOT = os.path.join(MEDIA_ROOT, 'private') AUTH_USER_MODEL = 'openwisp_users.User' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'openwisp_users.backends.UsersAuthenticationBackend', ) OPENWISP_RADIUS_FREERADIUS_ALLOWED_HOSTS … -
Navbar sliding to the right
<nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <div class="container-fluid"> <span class="navspacing"></span> <a class="navitems hover" href="{% url 'home' %}">Home</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar"> <span style="margin:5px;" class="navbar-toggler-icon"></span> </button> <div class=" collapse navbar-collapse topnav" id="collapsibleNavbar"> <ul class="navbar-nav" > {% if user.is_authenticated %} <li class="nav-item navitems"> <a class="nav-link hovering" href="{% url 'light_novel:characters_page' %}">Characters</a> </li> <li class="nav-item navitems"> <a class="nav-link " href="{% url 'light_novel:moves_page' %}">Moves</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:chapters_page' %}">Chapters</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:outfits_page' %}">Outfits</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:sights_page' %}">Sight</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:timelines_page' %}">Timeline</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:scratchpads_page' %}">Scratchpad</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:statistics' %}">Statistics</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'logout' %}">Logout</a> </li> {% else %} <li class="nav-item navitems"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> {% endif %} </ul> </div> </div> </nav> When I click on burger icon in navbar the Home button along with the burger icon slides to right side of the screen which I don't want it to do. I tried several solutions but the button keeps sliding no matter what I tried. Can anyone help me with this? -
Django Docker media files save and restore
Hi there I am trying to deploy a project in docker with django and django rest framework. According to the documentation I successfully able to deploy it and it is working fine with media files. I am able to upload media files (images) and it also shows the right file at the right side. But the problem is for some changes I need to re-build the container with new code ... after re-deploying It can not able to found out the previously uploaded media files(images). I badly need help on it.enter image description here this is my docker-compose file. enter image description here and dockerfile -
Overriding is_valid in Nested serializer to be able to process child model with same information during update()
I'm trying to make my nested serializer to be able to process updating when I'm only updating for the parent model. The default action in drf is that the serializer cant tell if ur child model is trying to updating or create, there's a solution where you just turn off the validation, which I don't think is ideal for the database and iots implication. I've scour about this topic for like 2 days and I think the ideal approach to this is to override the is_valid method to be able to just return the object. Idea from : Django REST Framework ModelSerializer get_or_create functionality from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned class MyModelSerializer(serializers.ModelSerializer): def is_valid(self, raise_exception=False): if hasattr(self, 'initial_data'): # If we are instantiating with data={something} try: # Try to get the object in question obj = Security.objects.get(**self.initial_data) except (ObjectDoesNotExist, MultipleObjectsReturned): # Except not finding the object or the data being ambiguous # for defining it. Then validate the data as usual return super().is_valid(raise_exception) else: # If the object is found add it to the serializer. Then # validate the data as usual self.instance = obj return super().is_valid(raise_exception) else: # If the Serializer was instantiated with just an object, and no # … -
table app_shop_boughtitem has no column named buyer_id Django
Can you explain me, why I have this error? I think migration should solve this problem, but it doesn't. How can I solve this problem? My model: class BoughtItem(models.Model): name = models.CharField(max_length=100, verbose_name='Название товара или акции', blank=True) price = models.IntegerField(verbose_name='Цена', blank=True) created_at = models.DateTimeField(auto_now_add=True) buyer = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Покупатель') This migration: class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('app_shop', '0002_item'), ] operations = [ migrations.CreateModel( name='BoughtItem', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=100, verbose_name='Название товара или акции')), ('price', models.IntegerField(blank=True, verbose_name='Цена')), ('created_at', models.DateTimeField(auto_now_add=True)), ('buyer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Покупатель')), ], ), ] -
Django orm latest data
reference class Board(model.Model): master = models.ForeignKey(User, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) status = models.PositiveIntegerField(default=0) class MSG(models.Model): Board= models.ForeignKey(Board, on_delete=models.CASCADE) writer = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=True) How can I get the following values from this relationship? i'm using PostgreSQL response = { master="USER1", member="USER2", status=0, master_latest_MSG="master last_msg" master_latest_date="2020.03.21", member_latest_MSG="member last_msg" member_latest_date="2020.03.22", } Is there any better way instead of subquery? -
Reduce the time consumed by api in Django Rest Framework
These are the models that I created i.e. Video, Tag, Category, Exercise and Package_Exercise respectively. and i want to fetch data based on the object in package exercise and fetch all the data from the Exercise i.e. video url, tag and category of each exercise. I wrote the code but its taking too much time how do I reduce the time taken by the code? What should be the best approach to handle these kind of situations? What would be the best approach based on the time complexity. class Video(models.Model): video = models.FileField(upload_to='videos_uploaded',null=False,validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])]) name = models.CharField(max_length=100) thumbnail = models.ImageField(upload_to="video_thumbnails",null=False) description = models.TextField(max_length=200) created_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='videos_created_by') updated_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='videos_updated_by') def __str__(self): return self.name class Tag(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): title=models.CharField(max_length=200) created_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='catagoery_created_by') updated_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='catagoery_exercise_updated_by') def __str__(self): return self.title class Exercise(models.Model): name=models.CharField(max_length=100,null=False) description=models.TextField(max_length=300,null=False) video=models.ForeignKey(Video,on_delete=models.CASCADE,null=False) category=models.ForeignKey(Category,on_delete=models.CASCADE,null=False) tag=models.ManyToManyField(Tag,null=False) created_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='exercise_created_by', null=False) updated_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='exercise_updated_by', null=False) def __str__(self): return self.name class Package_Exercise(models.Model): package = models.ForeignKey(Package,on_delete=models.CASCADE,related_name='package') exercise = models.ForeignKey(Exercise,on_delete=models.CASCADE) repetition = models.IntegerField() number_of_sets = models.IntegerField() rest_time = models.IntegerField() created_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='packages_exercise_created_by') updated_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='packages_exercise_updated_by') Here is the serializer takes 2.3s for ~30 objects of … -
Django retain order of product when displayed
Suppose I want the order of my products in my Django webshop to be displayed in a certain order. How can I achieve that? I have simplified the below example to show the problems that I am experiencing. In my webshop models I have the below 2 models. class TakeawayWebshop(models.Model): name = models.CharField(max_length = 255, help_text = 'name of takeaway restaurant') products = models.ManyToManyField(Product) class Product(models.Model): name = models.CharField(max_length = 50, unique=True) description = models.TextField() price = models.DecimalField(max_digits=9, decimal_places=0, default=0.00) class Meta: ordering = ['-created_at'] In the admin.py I have class TakeawayWebshopAdmin(admin.ModelAdmin): form = TakeawayWebshopAdminForm list_display = ['name'] ordering = ['name'] filter_horizontal = ('products',) admin.site.register(TakeawayWebshop, TakeawayWebshopAdmin) Now from the admin, I am adding 3 products in the exact product A, product B and product C to the webshop using the filter_horizontal. . Upon saving the TakeawayWebshop model object, the products in the filter_horizontal box automatically rearanged, so the order becomes product C, product B and product A. When from the views.py if I get a list of all the products I have added to the webshop such as webshop = TakeawayWebshop.objects.filter(name = 'my webshop name')[0] products = webshop.products.all() The queryset returned is <QuerySet [<Product: Product C>, <Product: Product B>, <Product: … -
How to collect data from google form and store in jsonfield in django?
How to collect data from google form and store in JsonField in Django? I am expecting to collect all the responses and save them in my database in JsonField Any help would be appreciated. Thanks in advance :) -
Redirect http url to https for django application served by Apache without virtualHost
I have a django application running on http://localhost:8081 I want to redirect it to https://localhost:8081 I have following in my settings.py: SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True httpd.conf file has been modified to: WSGIScriptAlias / /path/to/django/application/wsgi.py #WSGIPythonHome /python3.9 WSGIPythonPath /path/to/django/application:/python3.9/lib/python3.9/site-packages <Directory /path/to/django/application> <Files wsgi.py> Require all granted </Files> </Directory> When I am trying to execute my django application with command: /python3.9/bin/python3 manage.py runserver 8081 it gives this error on webpage: This site can’t provide a secure connection localhost sent an invalid response. ERR_SSL_PROTOCOL_ERROR I have not configured virtual environment and have default python2.7. Installed python3.9 at different location on machine to serve django. Any thoughts what I'm missing to make it work. -
How do you pass multiple kwargs to reverse_lazy in django?
I could pass one kwargs for reverse_lazy as follows, but I don't know how to do 2 or 3 kwargs. return reverse_lazy('next-url', kwargs={'pk': variable}) Is there a way I can easily do this? Is the following line of code functional? return reverse_lazy('next-url', kwargs={'pk': variable, 'pk2': variable_two}) -
Django check if time is in an object's timefield range
How do I check if a time is in the range of two timefields? #appointmentApp.models Appointment #Appointments class Appointment(models.Model): ... date_selected = models.DateField(blank=True, default='2001-12-1') time_start = models.TimeField(blank=True) total_time = models.IntegerField(blank=False, null=False, default=0) end_time = models.TimeField(blank=True, null=True) appointment_accepted = models.BooleanField(blank=False, default=False) Total_time and end_time are calculated after the object is created because it requires an attribute from a many to many field In my views where I want to check if there is an object that exists #appointmentApp.views def appointment_view def appointment_view(request): ... #form is submitted else: form = AppointmentForm(request.POST) if form.is_valid(): cd = form.cleaned_data date = cd.get('date_selected') #this is a datetime field start = cd.get('time_start') #appointments = Appointment.objects.filter(date_selected=date, start_time__range=()) #form needs to save first because total time and end time don't have values until after the object is saved form.save() new_appointment = Appointment.objects.filter(date_selected=date, time_start=start, appointment_accepted=False) for apps in new_appointment: new_app_starttime = apps.time_start new_app_endtime = apps.end_time appointments = Appointment.objects.filter(date_selected=date, appointment_accepted=True) #if the start time #my question is here for app in appointments: if app.time_start__range(new_app_starttime, new_app_endtime): print('another appointment begins/ends during this time slot!') return render(request, 'home.html') How can it check if its time falls in between two timefields? -
How to call two urls with one submit button to get form data
I am trying to perform two different functions with single submit button, the below script shows the example of what I am trying to get. Thank you for helping me. Expected solution --> when I click on submit button file has to upload along with map2 has redirect to mapRedirect url. from flask import flask, render_template, flash, request, redirect,url_for @app.route('/map2') def map_2(): return render_template('map2.html') @app.route('/mapRedirect', methods = ['POST', 'GET']) def onMap(): if request.method == 'POST': name = request.form['nm'] return redirect(f"map2") @app.route('/proc') def upload_file(): ## file upload script return render_template('proc.html') map2.html <iframe name = "Ifrmp", id='mp', src="map2" > proc.html <form method="post" enctype="multipart/form-data" target="Ifrmp"> <input type="submit" id='btn' name="nm" value="submit> -
How to reduce the time for this code in django rest framework
class Category: title = models.CharField(max_length=50) class Tag: name = models.CharField(max_length=50) class Video: video = models.FileField(upload_to='xxx/') class Exercise: name = models.CharField(max_length=50) video = models.ForeignKey(Video) description = models.CharField(max_length=250) category = models.ForeignKey(Category, on_delete=models.CASCADE) tag = models.ManyToManyField(tag, on_delete=models.CASCADE) class Data: relation = models.ForeignKey(Relation, on_delete=models.CASCADE) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE) The code for getting data accordingly this is taking too much time how do I reduce this or what are the ways to handle these kind of situations for each in Data: sam.append( { "name": each.exercise.name, "url": each.exercise.video.video.url, "description": each.exercise.description, "category": each.exercise.category.title, "tag": each.exercise.tag.name } )