Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: set the foreign key field of model which is related with User [duplicate]
This question already has an answer here: Using request.user with Django ModelForm 2 answers My model Resume has a user field as foreign key: class Resume(models.Model): name = models.CharField(max_length=25) base_info = models.TextField() created_at = models.DateTimeField(auto_now_add=True) User = get_user_model() superuser = User.objects.get(username=<superuser_username>) user = models.ForeignKey(User, on_delete=models.CASCADE, default=superuser.id) (Set default as superuser since I added that after some migrations and it is working right.) I want to set the user field automatically login user where the new ResumeForm saved. I think saving the user in view is better than in template but following doesn't work: def resume_form(request): if request.method == 'POST': form = ResumeForm(request.POST, request.FILES) form.user = request.user if form.is_valid(): resume = form.save() return redirect('resume:list') else: form = ResumeForm() return render(request, 'resume/index.html', { 'form': form, }) How can I do that? +) Where is the proper part to save(set) user, in view or template? (or any other can access to user context?) -
How to display records belonging to exacly one category
I've create something like this In the label 'Monitoring www' the records now are displaying correctly. If the user is logged, they can add Websites, and after that the user can add keywords.Now I want to display the websites and the keywords belonging to the website record. In view.py I have: @login_required def website_list(request): website_list_user = Website.objects.filter(user=request.user).order_by('-user') context = {'website_list_user': website_list_user} return render(request, 'konto/dashboard.html', context=context) @login_required def keyword_list(request): keyword_list_user = Keyword.objects.filter(keyword=request.keyword).order_by('-keyword') context = {'keyword_list_user': keyword_list_user} return render(request, 'konto/dashboard.html', context=context) in forms.py class KeywordForm(forms.ModelForm): class Meta: model = Keyword fields = ('www', 'keyword') def __init__(self, user, *args, **kwargs): super(KeywordForm, self).__init__(*args, **kwargs) self.fields['www'].queryset = user.website_set.all() self.user = user def save(self, commit=True): instance = super(KeywordForm, self).save(commit=False) instance.user = self.user if commit: instance.save() return instance and my template : {% if request.user.is_authenticated %} <b>Monitoring www:</b><br> {% for website in website_list_user %} {{website.website}}<br> {% endfor %} <b>Słowa kluczowe:</b><br> {% for keyword in keyword_list %} {{keyword.keyword}}<br> {% endfor %} {% endif %} EDIT: my urls.py from django.urls import path from django.contrib.auth import views as auth_views from .views import dashboard, register, settings, del_user, website_list, keyword_list, new_website, new_keyword, main_page urlpatterns =[ path('', main_page, name='main_page'), path('login/', auth_views.login, name='login'), path('logout/', auth_views.logout, name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), path('password-change/', auth_views.password_change, name='password_change'), path('password-change-done/', auth_views.password_change_done, … -
Django DRF - serializing foreign key relationship in a linear form
I am using DRF to power up my Django REST api. Consider the following model: class Author(models.Model): name = CharField(...) class Book(models.Model) author = ForeignKey(Ablum) title = CharField(...) My desired output should be a linear JSON looking like this: [ { "name": "Jack London", "title": "White fang" } { "name": "Jack London", "title": "Martin Iden" } { "name": "Charles Dickens", "title": "David Coperfield" } { "name": "Charles Dickens", "title": "Oliver Twist" } ] I accomplished the result using the corresponding serializers class BookSerializer(serializers.ModelSerializer): author = serializers.CharField(source='album.author') class Meta: model = Book depth = 1 fields = ('author', 'title ') ...but the problem is that this solution is very dirty in terms of DRYness. Every time I add new field to Author, I would like it to appear in Book as well. Is there any way to tell Django to include all fields of the related model ? Or I also tried the following approach: class BookSerializer(serializers.ModelSerializer): author = CalendarEventSerializer(read_only = True) class Meta: model = Book depth = 1 fields = ('author', 'title ') but with this I ended up with nested JSON structure like this: [ { "name": "Jack London", "author": {...} }, ... ] which does not meet … -
How to programmatically generate the CREATE TABLE SQL statement for a given model in Django?
I need to programmatically generate the CREATE TABLE statement for a given model in my Django app. The ./manage.py sql command was useful for this purpose but it has been removed in Django 1.8 Do you know about any alternatives? -
rq-scheduler does not pass the job to "worker"(django / redis)
I'm trying to figure out the work of the scheduler "rq-scheduler". There is a scheduler.py: from redis import Redis from rq_scheduler import Scheduler from datetime import datetime from task import save_exchange_rates redis_conn = Redis() scheduler = Scheduler(connection=redis_conn) scheduler.schedule( datetime.utcnow(), save_exchange_rates, interval=10, repeat=None, ) it's a script that writes data to the database, if I run it manually, it works. task.py: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'market_capitalizations.settings' import django django.setup() import requests from exchange_rates.models import Currency def save_exchange_rates(): url = 'https://api.coinmarketcap.com/v1/ticker/' repositories = requests.get(url).json() for exchange in repositories: Currency.objects.create(name=exchange['name'], price_usd=exchange['price_usd'], last_updated=exchange['last_updated'],) if __name__ == '__main__': save_exchange_rates() I installed the modules: rq, rq-shcheduler, redis. enter image description here But the scheduler "rq-scheduler" does not transfer the task to "worker". Tell me, please, what am I doing wrong and what is the cause of the problem? -
How do I fetch url parameters of the current page in Django?
Sample URL: https://www.samplewebsite.com/search?query=my+site+is How do I fetch the query parameters in Django? Required: variable = "my site is" -
Django Form errors not displaying in template (custom forms)
I'm using Django 1.11. I have a model with regex validators. Unfortunately validation errors not displaying in my template. Everythink works fine on standard forms, but on custom forms in template it doesnt work. Whats wrong with that? template.html: {% for form in answers_formset %} <tr> <input type="hidden" name="answer-{{forloop.counter0}}-id" value="{% if form.instance.id %}{{ form.instance.id }}{% endif %}" /> <td class="place_in_td"> <p class="forloop-counter">{{forloop.counter}}</p><input type="hidden" name="answer-{{forloop.counter0}}-place_in_sequence" value="{% if form.place_in_sequence.value %}{{ form.place_in_sequence.value }}{% else %}{{ forloop.counter }}{% endif %}"> </td> <td> <input type="text" class="form-control" name="answer-{{forloop.counter0}}-command" id="id_answer-{{forloop.counter0}}-command" placeholder="{% trans 'command' %}" value="{{ form.command.value | default_if_none:'' }}"/> {{ form.command.errors }} </td> <td> <input type="text" class="form-control" name="answer-{{forloop.counter0}}-answer" id="id_answer-{{forloop.counter0}}-answer" placeholder="{% trans 'answer' %}" value="{{ form.answer.value | default_if_none:'' }}"/> {{ form.answer.errors }} </td> <td> {{ form.is_correct }} </td> <td><button type="button" class="remove-row pull-right btn btn-danger btn-sm"><span class="fa fa-minus-circle"></span></button></td> </tr> {% endfor %} views.py(a part of) for form in self.answer_formset: form.is_valid() if form.cleaned_data: answer = form.save(commit=False) answer.question = question try: answer.save() except IntegrityError: formset_errors.append(answer.command) else: submitted_answers_ids.append(answer.id) -
Datetime.time error django
I'm trying to import data from an excel file into my database in Django. Unfortunately, I'm getting this error when trying to import a time. AttributeError at /datavisual/upload/ 'datetime.time' object has no attribute 'total_seconds' Models.py CallRecord(models.Model): timeOfCall = models.TimeField() and in my Excel logic py file: class ExcelParser(): def read_excel(Document): wb2 = load_workbook('Sheet1.xlsx',guess_types=True) for row in wb2.active.iter_rows(range_string=wb2.active.calculate_dimension()): newRecord = CallRecord.objects.create(timeOfCall = row[1].value) newRecord.save() So far, the rest of the fields are saving as expected but I'm not sure what is causing this issue. Full error report: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/datavisual/upload/ Django Version: 2.0.1 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'datavisual.apps.DatavisualConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Michael\callcentre\callcentre\datavisual\views.py" in model_form_upload 29. ExcelParser.read_excel(request.FILES['file']) File "C:\Michael\callcentre\callcentre\datavisual\ExcelParser.py" in read_excel 21. invoiceNumber = row[19].value) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\db\models\query.py" in create 417. obj.save(force_insert=True, using=self.db) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\db\models\base.py" in save 729. force_update=force_update, update_fields=update_fields) File "C:\Users\d_aqu\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\db\models\base.py" in save_base 759. updated = self._save_table(raw, cls, force_insert, force_update, … -
background image in css style from static files with django
I used this template to create a home page in a django project, however I can't have the background image displayed correctly (bg.jpg) The background image is used as foollows in the css file : .wrapper.style3 { background-color: #000; color: #bfbfbf; background-image: url(/media/usr/path_to_project/project_name/home/static/images/bg.jpg); background-size: cover; background-attachment: fixed; background-position: center; position: relative; } I read these topics How to add background image in css? How to use background image in CSS? use static image in css, django How do I put a background image on the body in css with django using static? and tried all of the solutions but non of them seems to work. My project tree is like project_name - home - static --home ---style.css --images ---bg.jpg - templates -- home ---base.html ---home_template.html in the style.css file I tried the following background-image: url(/media/usr/path_to_project/project_name/home/static/images/bg.jpg); background-image: url("/media/usr/path_to_project/project_name/home/static/images/bg.jpg"); background-image: url(../images/bg.jpg); background-image: url("../images/bg.jpg"); background-image: url("{% static 'images.bg.jpg' %}); in my base.html template I have : {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'home/style.css' %}"/> and in my home_template.html I have {% block body %} {% load staticfiles %} <section id="two" class="wrapper style3"> <div class="inner"> <header class="align-center"> <p>Nam vel ante sit amet libero scelerisque facilisis eleifend vitae urna</p> <h2>Morbi maximus justo</h2> … -
How to add conditional intermediary page in Django admin
I have a model: class Survey(BaseModel): name = models.CharField(max_length=500, help_text='name') user = models.ForeignKey('User') json = JSONField(default=dict) status = models.CharField( max_length=50, default=INCOMPLETE, choices=STATUS_CHOICES) I override the save() method inside that models class and run some other pre save operations there. In that logic you can see where I want to do the confirmation: def save(self, *args, **kwargs): if self.status == self._status: # Status was unchanged. self.skip_history_when_saving = True else: self._status = self.status if self.status == 'live': # DO INTERMEDIARY CHECK HERE super(Survey, self).save(*args, **kwargs) What I'm trying to do I want like to add an intermediary page (see the delete confirmation) only if the status is going from incomplete to live, for example. I've been trying to trigger it with a function in my admin.py but not been able to do it. Here's my intermediary template method which right now is in admin.py SurveyAdmin class. I understand how it works, but I don't know how to link it in the the save() method I'm using to check in my models.py: @csrf_protect_m @transaction.atomic def conditional_status_confirm(self, request, object_id=None, form_url='', extra_context=None): survey = Survey.objects.get(pk=object_id) if request.method == 'POST': survey.status = Survey.LIVE survey.save() msg = _('Survey updated successfully.') messages.success(request, msg) return HttpResponseRedirect(reverse('admin:survey_change', args=(survey.pk,))) else: context … -
Django 1.11 admin list_filter to include fields in another model
I have a Django Admin class that displays all registered Users. I want to add a column next to each user that displays their latest Response (it's a survey app). What I've tried so far is: Response Model class Response(models.Model): """ A Response object is a collection of questions and answers with a unique interview uuid. """ created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) survey = models.ForeignKey(Survey, related_name="responses") user = models.ForeignKey(User, null=True, blank=True) interview_uuid = models.CharField(_(u"Interview unique identifier"), max_length=36) class Meta(object): verbose_name = _('response') verbose_name_plural = _('responses') def Quarter(self): msg = u"Q%d %d" %(((self.created.month-1)//3)+1, self.created.year) return msg Admin.py class ResponseAdmin(admin.ModelAdmin): list_display = ('survey', 'created', 'user', 'Quarter') **works here class UserAdmin(admin.ModelAdmin): list_display = ('username', 'latest_response') list_filter = ('is_staff', 'latest_response') def latest_response(self, obj): (return "Quarter" from Response Model) **how do I get it to work here too? admin.site.register(Response, ResponseAdmin) admin.site.register(User, UserAdmin) A few of my attempts resulted in the following error: FieldError: Cannot resolve keyword 'Quarter' into field. Choices are: answers, created, id, interview_uuid, survey, survey_id, updated, user, user_id So I can see the issue is that UserAdmin isn't getting the Quarter field from the Response Model for some reason. When I change def Quarter(self) to __str__(self), it displays as I want in … -
Django import export: skip_unchanged = True doesn't skip older records and also imports unchanged values
@admin.register(Hospital) class HospitalAdmin(ImportExportModelAdmin): pass class HospitalResource(resources.ModelResource): model = Hospital skip_unchanged = True report_skipped = False I have also tried using other available mixins, but somehow cannot get this working. I want unchanged records/values to be skipped during the import. -
How do I pass Javascript variables from my html template page to a Django views function?
I am working on a Django environment. I have created a form in my html page which contains a textbox for input for a label like "Enter your name" . I have a submit button below the textbox. I need to pass the inputted name to the button as a value and then this button value is to be passed to a python function in views.py. Can anyone help me with this ? -
Django UpdateView, get the current object being edit id?
I am trying to get the current record being edited's id, but am failing thus far. my view is as per the below: views.py class EditSite(UpdateView): model = SiteData form_class = SiteForm template_name = "sites/site_form.html" @method_decorator(user_passes_test(lambda u: u.has_perm('config.edit_subnet'))) def dispatch(self, *args, **kwargs): self.site_id = self.object.pk return super(EditSite, self).dispatch(*args, **kwargs) def get_success_url(self, **kwargs): return reverse_lazy("sites:site_overview", args=(self.site_id,)) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs() return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['SiteID']=self.site_id context['SiteName']=self.location context['FormType']='Edit' return context and the error: File "/itapp/itapp/sites/views.py" in dispatch 890. self.site_id = self.object.pk Exception Type: AttributeError at /sites/site/edit/7 Exception Value: 'EditSite' object has no attribute 'object' ive tried: self.object.pk object.pk self.pk -
Using values_list in the templates
I wanted to know if there is some way other than creating a custom template filter to get the values_list in Django templates. Like we use User.objects.all().values_list('first_name') to get the first_name of all the users in the form of a list. How can we do a similar thing in the template? -
Is this appropriate technology stack to make SPA with Python
I'm going to build a simple project and I wonder, if a technology stack which I've choosen is appropriate with this kind of tasks. About project: Single-page application where I could make basic analysis with stock markets data. Main goals is to get ticker quotes, display real-time chart which would automaticly update, portfolio section and some news feed. This should be main shape of this app. If this would work I'll update it with some other features. Back-end: Python 3.6 with Django Framework (ver. 2.0) Django REST Framework AlphaVantage API Front-end: HTML, CSS, plain JS D3.js Bootstrap Is this suitable or I miss something? The 'path' I've imagined is like that: Get quotes and data (AlphaVantage API) => Django + REST framework would manage all and push it as JSON to users client => D3.js would display charts Is this possible to make it the way I mentioned? If not what I have to change? (not Python, I really want to make this app using it). My purpose: This will be my first bigger project with everything stacked together. In past I've made some data analytics and visualisation with Python (anaconda package), very simple blog backend with django and some … -
Django: Not able to access prefetch_related values in template
First website. Firs time using Django. I am using this Query right now in view: visitingQuerySet = ClinicDoctor.objects.filter(doctor_id = doctor_id).prefetch_related('clinicDoctor_dayShift').all() Then in template I want to have something like this: {% for vis in visitinghours %} <tr> <td> {{ vis.doctor.full_name }} </td> <td> {{ vis.clinic.name }} </td> <td> {{ vis.clinicdoctordayshift.id }} </td> </tr> I can get first two `<td>` but not others if I try to get values from other models. My models are: class User(AbstractUser): full_name = models.CharField(max_length=200) clinics = models.ManyToManyField(Clinic, through='ClinicDoctor', related_name='doctors') class ClinicDoctor(models.Model): doctor = models.ForeignKey('User', related_name='doctorsF') clinic = models.ForeignKey(Clinic, related_name='clinicsF') class Day(models.Model): day = models.CharField(max_length=20) class Shift(models.Model): shift = models.CharField(max_length=20) days = models.ManyToManyField(Day, through='DayShift', related_name='day_shift') class DayShift(models.Model): time = models.TimeField() day = models.ForeignKey(Day, related_name='to_day') shift = models.ForeignKey(Shift, related_name='to_shift') clinics_doctors = models.ManyToManyField(ClinicDoctor, through='ClinicDoctorDayShift', related_name='clinicDoctor_dayShift') class ClinicDoctorDayShift(models.Model): clinic_doctor = models.ForeignKey(ClinicDoctor, related_name='to_clinicDoctor') day_shift = models.ForeignKey(DayShift, related_name='to_dayShift') I want to be able to be able to get Day.day, Shift.shift and DayShift.time as well. Is my prefetch_related wrong? Is it Ok to have this in view after that prefetch_related: if visitingQuerySet: I mean will this cause any extra DB hits or this will be the first point where it will be actually evaluated? Currently I can see these two queries being … -
How to be able to edit field in Django admin panel
I do not see edit icon in django admin panel in the detail page of my model. It looks like this: Thus normally it should have add icon and edit icon, something like this: But the edit icon is missing. My model is as follows: class BusinessUnit(models.Model): name = models.CharField(max_length=255) brands = models.ManyToManyField(to=Brand) site_picture = models.ImageField(upload_to=settings.MEDIA_ROOT, blank=True, null=True) address = models.ForeignKey(to=Address) def __unicode__(self): return self.name And in admin.py i have the code as follows: class BusinessUnitAdmin(admin.ModelAdmin): search_fields = ('name',) list_display = ('name', 'address', ) admin.site.register(BusinessUnit, BusinessUnitAdmin) Any ideas what is wrong? -
Can I get cookies value or session value inside the has_permission method of django rest framework?
I am working on a project where i have to check the user whether they belong the company or not.i am already put check while login user. how i can use company id inside the has_permission() method? class IsCompanyEmployee(permissions.BasePermission): message = 'You are unauthorized to perform any action on this company.' def has_permission(self, request, view): if request.user.is_authenticated(): if request.user.is_superuser: return True else: #company_id = request.COOKIES["company_id"] #or #company_id = request.session["company_id"] return request.user.companyemployee_set.filter(company__id=company_id).exists() else: return False -
Django forms - looping through form choice fields, how to assign the ID?
I am looping through some form choice fields in my template, but when I post, the form is not valid as it is missing required field "subnets" however I have manually created the subnet checkboxes. The reason I believe it is failing is because the manually created objects do not have an id, is this right? and how do I assign the id? template: {% for value, text in form.subnets.field.choices %} <div class="checkbox"> <label> <input type="checkbox" id="subnets" value="{{ value }}" />{{ text }} </label> </div> {% if forloop.counter|divisibleby:4 %} </div> <div class="col-xs-3"> {% endif %} {% endfor %} error: subnets This field is required. -
How to retrieve Json meta-data from endpoint using django-rest-framework
I'm using Django rest framework to retrieve data from server. Now I create a view: class Snipped(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.AllowAny,) #@ensure_csrf_cookie def get(self, request, format=None): request.session["active"] = True snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) def post(self, request, format=None): serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) the model is this: # Create your models here. class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() def __str__(self): return self.title so at this point I'd like to know metadata of data passed to this endpoint, I 've found http://www.django-rest-framework.org/api-guide/metadata/ but if a send OPTION I don't obtain informations about data but only this json answer { "name": "Snipped", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], } without (see list at http://www.django-rest-framework.org/api-guide/metadata/) "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "note": { "type": "string", "required": false, "read_only": false, "label": "title", "max_length": 100 } } } any idea how can achieve above results with an APIView ? -
Django: how to find out that the request to update rows in the database was completed
The essence of the problem is that while I'm not able to execute my select need update in the postgres for the time being, for example, the update does not happen, but the view is already in progress, ie I make an update request, it went into the database for execution, and my form is executed further, so long as it really refreshes my rows in DB, I did not continue my view. Thanks! -
Django Models - insert foreign key values using Shell
I am trying to save values for my Models through Django Shell . I am beginner in Django. I have crated three models. I inserted values in models one by one.i created Dept first and inserted all Dept Values.Created Student and inserted all student related values. Now i am trying to insert values in course which contains two foreign key studentId and dept id . How to insert values for Student model using Django Shell. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. from django.db import models from django.utils import timezone class Student(models.Model): studentId = models.AutoField(primary_key=True) firstname = models.CharField(max_length=50) middlename = models.CharField(max_length=1) lastname = models.CharField(max_length=50) city = models.CharField(max_length=200) registe_dt = models.DateTimeField(default=timezone.now()) def __str__(self): return '%s %s %s' % (self.studentId, self.firstname,self.city) class Dept(models.Model): deptId = models.AutoField(primary_key=True) deptName = models.CharField(max_length=200) def __str__(self): return '%s %s' % (self.deptId, self.deptName) class Course(models.Model): courseId=models.AutoField(primary_key=True) courseName=models.CharField(max_length=100) student = models.ManyToManyField(Student) dept = models.ForeignKey(Dept,on_delete=models.CASCADE) def __str__(self): return '%s %s %s %s' % (self.courseId, self.courseName,self.student.primary_key,self.dept.primary_key) Thank you for helping Jordan -
Django api performance improvement
I have a Django API which is fetching records( on an avg 30000 records) from MSSQL database using stored procedures. This API is consumed in an Angular4 web app which is used for downloading in excel format. It is taking an average of 10 seconds for the procedure to execute and approximately 47 seconds for API to fetch it. Let me know the areas where performance can be improved. -
Django url slash matching
my url pattern in apps like: urlpatterns = [ url(r'^show/(?P<arg1>[\w\d_\.]+)$', views.view_1), url(r'^show/(?P<arg1>[\w\d_\.]+)/(?P<arg2>[\w\d_\.]+)$', views.view_2), url(r'^show/(?P<arg1>[\w\d_\.]+)/(?P<arg2>[\w\d_\.]+)/(?P<arg3>[\w\d_\.]+)$', views.view_3), ] the url : /show/in_arg1/in_arg2%2F_this_is_arg2 match to view_3 but I want to let the url match view_2 I try to change urlpatterns like urlpatterns = [ url(r'^show/(?P<arg1>[\w\d_\.]+)$', views.view_1), url(r'^show/(?P<arg1>[\w\d_\.]+)/(?P<arg2>[\w\d_\.\/]+)$', views.view_2), url(r'^show/(?P<arg1>[\w\d_\.]+)/(?P<arg2>[\w\d_\.\/]+)/(?P<arg3>[\w\d_\.]+)$', views.view_3), ] the url : /show/in_arg1/in_arg2%2F_this_is_arg2 works well but the url /show/in_arg1/in_arg2/in_arg3 will match to view_2, not what I want It seems django decode %2F to / before url matching Can I let django do url matching without decode %2F ? Or some way to solve my problem thanks