Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reading and Writing to PDFs stored in Django Models.py
I apologize if this question seems silly, I am still learning Django. My goal is to Have PDF's stored in Models.py Have User input data Transfer Data to string type Print strings on PDF Store new PDF in user account. Can I store PDFs in Django Models.py under ImageField? Documentation doesn't seem to mention PDFs much. I'm thinking of trying something along the lines of: from django.db import models class Model(models.Model): text = models.CharField(max_length=30, unique=False) pdf = models.ImageField(upload_to='media/pdfs') with a form.py structured like this: from django import forms from model.models import Model class textForm(forms.ModelForm): class Meta: model = Model fields = ('text',) With a Views.py structured like this: def user_view(request): text = form.cleaned_data.get('text') can.drawString(10, 100, Model.text) existing_pdf = PdfFileReader(open("media/01.pdf", "rb")) page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) PdfFileWriter().addPage(page) return render(request, "app/fill_form.html", context) Any help or advice would be much appreciated. Thank you. -
not able to create a ForeignKey in the django models
I am creating quiz app in which each user can store there choices to question and I want Choice model as ForeignKey of model Question but getting error while makemigrations models : class Choice(models.CharField): ans = models.CharField(max_length=50) def __str__(self): return self.ans class Meta: ordering = ['ans'] class Question(models.Model): que = models.CharField(max_length=200) choice = models.ForeignKey(Choice,on_delete=models.CASCADE) def __str__(self): return self.que class Meta: ordering = ['que'] error : (venv) bhupesh@Laptop:/home/mydata/challenges$ python manage.py makemigrations Traceback (most recent call last): File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 786, in __init__ to._meta.model_name AttributeError: type object 'Choice' has no attribute '_meta' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/mydata/challenges/venv/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed … -
Problem reading file with pandas uploaded to a django view
I'm uploading some excel and csv files to a django view using axios, then i pass those files to a function that uses pandas read_csv and read_excel functions to process them, the first problem i had was with some excel files that had some non utf-8 characters that pandas was unable to read, the only solution i found was to set "engine = 'python'" when reading the file (changing the encoding to utf-8-sig or utf-16 didn't work). This works when i'm testing the script from my terminal, but when i use the same script on a view i get the following error: ValueError("The 'python' engine cannot iterate through this file buffer.") This is the code i'm using: try: data = pandas.read_csv(request.FILES['file'], engine="python") except: print("Oops!",sys.exc_info(),"occured.") trying the same function through the terminal works fine pandas.read_csv("file.csv", engine="python") -
Levels of Authorization depending on Authentication method - Django
Using Django, I am trying to figure out how to limit a users permissions depending on the method used to login. In my specific case, a user will scan a QR code, (or let's say he went to a less secure login page)then he will only have basic permissions. If he went to the website and logged in fully, he would have fully authenticated permissions. How would I go about implementing this using Django? -
Django-simple-history to display logs on webpage other than admin website
I have been successful to register Django-simple-history with admin page. I have now been trying to get audit (CRUD) logs to display on a webpage other than the admin site. The page currently displays blank. Here is my attempt to get this working - views.py file def audit_trail(request, id): if request.method == "GET": obj = My_Model.history.all(pk=id) return render(request, 'audit_trail.html', context={'object': obj}) audit_trail.html file {%extends "did/base.html" %} {% block content %} {% for h in object%} {{ h.id }} {{ h.carrier }} {% endfor %} {% endblock content %} url pattern path('audit_trail/', views.audit_trail, name='audit_page'), ** Model File ** from django.db import models from django.utils import timezone from django.contrib.auth.models import User from simple_history.models import HistoricalRecords class My_Model(models.Model): field1 = models.CharField(max_length=100) field2 = models.DateTimeField(default=timezone.now) field3 = models.CharField(max_length=100) history = HistoricalRecords() -
Easiest way to run a Python script on a website
I want to run a script on a website that just takes one input does some web scraping and then prints some data on the website. I know very little about websites (just some about the html and css) and I'm wondering what the easiest approach is for me. Is it to use Django or Flask somehow on a XAMPP server or is there an easier way? All help is greatly appreciated! -
Combining fields for a historic overview of equity portfolio performance
I'm trying to create an equity portfolio app but are having trouble creating an overview of the historic performance of a portfolio. I have four models on my django site: One for Company details class CompanyDetail(models.Model): ticker = models.CharField(max_length=100) name = models.CharField(max_length=250) description = models.TextField() def __str__(self): return self.ticker One for historic prices for each company: class EquityEOD(models.Model): equity = models.ForeignKey( 'asset_details.CompanyDetail', on_delete=models.CASCADE, ) date = models.DateField(default=date.today) close = models.DecimalField(decimal_places=4, max_digits=15, default=0) def __str__(self): return self.equity.ticker One for the portfolio information: class Portfolio(models.Model): portfolio_name = models.CharField(max_length=200) def __str__(self): return self.portfolio_name And then finally a model for each trade class Trade(models.Model): portfolio = models.ForeignKey( Portfolio, on_delete=models.CASCADE, ) equity = models.ForeignKey( 'asset_details.CompanyDetail', on_delete=models.CASCADE, ) trade_date = models.DateField(default=date.today) amount = models.IntegerField(default=0) buy_price = models.DecimalField(decimal_places=2, max_digits=15, default=0) def totalcost (self): totalcost = self.buy_price*self.amount return totalcost def lastEOD (self): lastEOD = EquityEOD.objects.filter(equity=self.equity).order_by('-date')[0] return lastEOD def holdingvalue(self): holdingvalue = self.lastEOD().close*self.amount return holdingvalue def __str__(self): return self.equity What I'm trying to do now is to take the last years EquityEOD (equity end of day closing price) for each portfolio holding and adding them together to get an overview of how the entire portfolio have performed during the year. But I'm completely stuck on how to solve this. -
One to One Field throwing error "This field must be unique." django rest framework
I am stuck on this error when i send a post request to my django server it only seems to return "user": [ "This field must be unique." ] } and i have done a bit of debugging and found its related to the fact i am using a one to one field here is my: models.py from django.contrib.auth.models import User class EventPost(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) event_name = models.CharField(max_length=50 ) event_time = models.CharField(max_length = 50, default = '') event_date = models.CharField(max_length = 50, default = '') def __str__(self): return self.event_time serializers.py from rest_framework import serializers from .models import EventPost from django import forms from django.contrib.auth.validators import UnicodeUsernameValidator class EventPostSerializer(serializers.ModelSerializer): class Meta: model = EventPost fields = ( 'user', 'event_name', 'event_time', 'event_date', ) and my views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView from .models import EventPost from .serializers import EventPostSerializer from rest_framework.permissions import IsAuthenticated # Create your views here. class PostViews(APIView): permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): data = { 'GET':'True', } return Response(data) def post(self, request,*args, **kwargs): serializer = EventPostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) I am quite new to django rest framework so please excuse me. Also … -
How can I auto run a python script in my django app deployed on heroku
I deployed my first Django app on Heroku, but I need to periodically execute the scraper I put in to update the data on the site. Right now I'm doing it manually, running the management command I created through the Heroku CLI. How can I set up an auto run for the scraper to start every hour? -
Creating Model for Django
After following this Tutorial https://docs.djangoproject.com/en/3.0/intro/tutorial02/ i encountered a problem. When i came to create my very first Model Django would refuse to do it. I have done it all. Django.setup() manage migrate make migrate and INSTALLED APPS. My init is empty and settings is vanilla as it gets except with the extra entry for installed app. This is my Project Structure. Picture data.py > from django.db import models > > > class bill_table(models.Model): > number = models.CharField(primary_key=True) > name = models.CharField() > adres = models.CharField() > status = models.CharField() > money = models.IntegerField() > > > class offer_table(models.Model): > number = models.CharField(primary_key=True) > name = models.CharField() > adres = models.CharField() > status = models.CharField() > money = models.IntegerField() settings.py > # Application definition INSTALLED_APPS = [ > 'django.contrib.admin', > 'django.contrib.auth', > 'django.contrib.contenttypes', > 'django.contrib.sessions', > 'django.contrib.messages', > 'django.contrib.staticfiles', > 'data', ] view.py > import data > > > def home(request): > return render(request, 'home.html', {'APP': render_to_string('dashboard.html')}) > > > def bill(request): > bills = data.bill_table.objects.all() > return render( > request, 'home.html', > {'APP': render_to_string( > 'app/bill.html', {'title': 'Offerte', > 'status': 'status', > 'rows': bills} > )}) i am done with this framework if it makes it so hard to do … -
Putting Break Points in Comments in Python (Django)
This is how my site is rendering - I tried putting <br> and </br> in a few places and I have not seen any impact. Does anyone have any ideas? <article class="media content-section"> <!-- comments --> <h3>{{ comments.count }} Comments</h3> <br><br/> {% for comment in comments %} <div class="media-body "> <a class="mr-2" href="#">{{ comment.name }}</a> <small class="text-muted">{{ comment.created_on|date:"F d, Y" }}</small> </div> <br><br/> <h2 class="article-title">{{ post.title }}</h2> <p class="article-content">{{ comment.body }}</p> <br><br/> {% endfor %} </article> -
Pass the data calculated by js to the database
I want to pass the values calculated by js to the database. I try to use ajax but it didn't work. could you give me some suggestions? <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script> <script> window.onload= function score() { var value = sessionStorage.getItem("key"); var score = 0; if (value > 160) { score = 9; } else if (value < 161 && value > 140) { score = 8; } else if (value < 141 && value > 120) { score = 7; } else if (value < 121 && value > 100) { score = 6; } else if (value < 101 && value > 80) { score = 5; } else if (value < 81 && value > 60) { score = 4; } else if (value < 61 && value > 40) { score = 3; } else if (value < 41 && value > 20) { score = 2; } else if (value < 21 && value > 0) { score = 1; } else { score = 1; } document.getElementById("score").innerText = "Score: " + score; $.ajax({ url: "/score/", data: {score: score}, type: 'POST', }); } </script> I want to pass the score and view: if request.method == 'POST': score = … -
Couldn't find that process type (web) error on heroku
I'm trying to deploy a Django application to heroku, but i keep getting the following error when trying to scale my application: heroku ps:scale web=1 Error: Scaling dynos... ! ! Couldn't find that process type (web). I don't understand what am i doing wrong here, my file is called Procfile, it is located at the root of my project, here is how i defined it: Procfile web: gunicorn myproject.wsgi --log-file - -
Please help me to solve this issue
File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 260, in watched_files yield from iter_all_python_module_files() File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 105, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 141, in iter_modules_and_files resolved_path = path.resolve(strict=True).absolute() File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 1172, in resolve s = self._flavour.resolve(self, strict=strict) File "C:\Users\Hazrat\AppData\Local\Programs\Python\Python38-32\lib\pathlib.py", line 200, in resolve return self._ext_to_normal(_getfinalpathname(s)) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' PS D:\pr\blog> -
object has no attribute 'title'
def __str__(self): """ String for representing the Model object """ return '%s (%s)' % (self.id,self.book.title) . class Book(models.Model): """ Model representing a book (but not a specific copy of a book). """ title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) # Foreign Key used because book can only have one author, but authors can have multiple books # Author as a string rather than object because it hasn't been declared yet in the file. summary = models.Text Field(max_length=1000, help_text="Enter a brief description of the book") is bn = models.Char Field('ISBN',max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>') genre = models.Many To Many Field('Genre', help_text="Select a genre for this book") # Many To Many Field used because genre can contain many books. Books can cover many genres. # Genre class has already been defined so we can specify the object above. def __str__(self): """ String for representing the Model object. """ return self.title i`m working on Django framework part Admin and when i want to enter part Book instances it shows this Error : 'None Type' object has no attribute 'title' , Can someone tell me why this happened? -
save() prohibited to prevent data loss due to unsaved related object on inherited object
I have following models structure: class Parent(models.Model): fieldA = models.TextField() fieldB = models.TextField() class Child(Parent): fieldC = models.CharField() I noticed some unexpected behavior in following code snippet: child = Child(fieldA = 'Text fieldA', fieldB = 'Text fieldB', fieldC = 'Text fieldC') child.full_clean() child.save() self.assertEqual(Child.objects.count(), 1) child.delete() self.assertEqual(Child.objects.count(), 0) child.full_clean() child.save() Not getting into why I add the second child.save(), assertions are passed, but when I want to save it with this second error it is failing with ValueError: ValueError: save() prohibited to prevent data loss due to unsaved related object 'parent_ptr' At the same time I don't see any such error with following code: parent = Parent(fieldA = 'Text fieldA', fieldB = 'Text fieldB') parent.full_clean() parent.save() self.assertEqual(Parent.objects.count(), 1) parent.delete() self.assertEqual(Parent.objects.count(), 0) parent.full_clean() parent.save() Why is that happening? Is someone able to tell me how I am supposed to fix the first snippet? -
Customize dashboard catalogue forms in Django Oscar doesn't work
I have followed the main documentations for django oscar. and i am trying to add a new field to product named video_url. first i add the new field to product models and it worked fine. catalogue/models.py from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): video_url = models.URLField(null=True, blank=True) from oscar.apps.catalogue.models import * and and then i continue to customize the catalogue dashboard but it seems like i didn't change any thing there's no error or anythin. dashboard/caralogue/forms.py from oscar.apps.dashboard.catalogue.forms import ProductForm as CoreProductForm class ProductForm(CoreProductForm): class Meta(CoreProductForm.Meta): fields = ['title', 'upc', 'description', 'is_public', 'is_discountable', 'structure', 'video_url'] myproject/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'dashboard.catalogue', # Oscar 'django.contrib.sites', 'django.contrib.flatpages', 'oscar', 'oscar.apps.analytics', 'oscar.apps.checkout', 'oscar.apps.address', 'oscar.apps.shipping', # My Catalogue 'catalogue.apps.CatalogueConfig', # 'oscar.apps.catalogue', 'oscar.apps.catalogue.reviews', 'oscar.apps.partner', 'oscar.apps.basket', 'oscar.apps.payment', 'oscar.apps.offer', 'oscar.apps.order', 'oscar.apps.customer', 'oscar.apps.search', 'oscar.apps.voucher', 'oscar.apps.wishlists', 'oscar.apps.dashboard', 'oscar.apps.dashboard.reports', 'oscar.apps.dashboard.users', 'oscar.apps.dashboard.orders', # My Catalogue dashboard 'dashboard.catalogue.apps.CatalogueDashboardConfig', # 'oscar.apps.dashboard.catalogue', 'oscar.apps.dashboard.offers', 'oscar.apps.dashboard.partners', 'oscar.apps.dashboard.pages', 'oscar.apps.dashboard.ranges', 'oscar.apps.dashboard.reviews', 'oscar.apps.dashboard.vouchers', 'oscar.apps.dashboard.communications', 'oscar.apps.dashboard.shipping', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', ] -
React SPA with initial state/route, served from Django
I am facing an unusual use-case with React and Django. My process starts with a POST request initiated by an app running on user's system to my Django server(The response is displayed on the browser). The POST request contains the data required for authenticating the user. Once authenticated, the server returns a simple HTML page customized for that user, including the details necessary to authenticate subsequent requests(like form submissions). Now I need to replace that simple HTML page with a react application. The problem is how can I embed the user specific info into the react app when returning the react app from server, so that I don't have to ask user to provide authentication information again once application loads on browser. Is this even possible while using react? -
Django DateTimeField query last hour
I'm trying to query the data from the last hour form a postgreSQL database, this is the table model in Django: class data(models.Model): fecha = models.TextField(db_column='Fecha', blank=True, null=True) # Field name made lowercase. hora = models.TextField(db_column='Hora', blank=True, null=True) # Field name made lowercase. lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) tipo = models.BigIntegerField(db_column='Tipo', blank=True, null=True) # Field name made lowercase. ka = models.FloatField(db_column='kA', blank=True, null=True) # Field name made lowercase. error = models.FloatField(blank=True, null=True) tiempo = models.DateTimeField(db_column='Tiempo',primary_key=True, blank=True, null=False) # Field name made lowercase. geom = models.PointField(blank=True, null=True) and this is what I have in my views file: from datetime import datetime, timedelta time = datetime.now() - timedelta(hours=1) def last_hour(request): hour = serialize('geojson',data.objects.filter(tiempo__lt=time)) return HttpResponse(hour, content_type='json') I haven been luckly with the information of other posts. My Django version is 3.0.5 and the timezone data in postgreSQL is utc-5 -
In Django REST Framework, how to filter list based on user?
I have two models, User and Book. Users own books and can only be seen by their owners. NOTE: the book model is handled in a separate database, so I can't use a foreign key on Book pointing to User. Not sure if this matters. If I'm authenticated, and send a GET /books request, I want only the books owned by the user to be shown. If I'm not authenticated, I should get a 403 error. Where should I implement this logic? I could do it in the View, with something like this: class BookView(APIView): """ Get books """ permission_classes = (IsAuthenticated, IsBookOwner,) queryset = Book.objects.all() serializer_class = BookSerializer def post(self, request): # create a book def get(self, request): books = Book.objects.filter(owner_id=request.user.owner_id) serializer = self.serializer_class(books, many=True) return Response(serializer.data) class IsBookOwner(permissions.BasePermission): """ Object-level permission to only allow seeing his own books """ def has_object_permission(self, request, view, obj): # obj here is a Book instance return obj.owner_id == request.user.owner_id Is this the correct way to do it? Also, is the IsBookOwner permission doing anything here? -
how can I run celery task only once in django?
from __future__ import absolute_import, unicode_literals from celery import shared_task from celery.task import periodic_task from celery.schedules import crontab from datetime import timedelta @periodic_task(run_every=(crontab(minute='*/1')), name='greeting_task') def greeting_task(): print('hello Dias!') Can I create a function that runs only once at certain time with crontab? PLEASE, HELP!!! thanks in advance! -
Hide a button when another is clicked with ajax
I'm currently triying to implement a voting system similar to the one in Hackernews. When the votearrow is clicked, the nuber of votes should update and the unvote button should appear. Since I don't want to reload the wholepage, I am using ajax to handle the votes requests. I'm struggling with the voting system (showing unvote and hiding votearrow when votearrow is clicked and vicecersa). With the current implementation when i clicked the votearrow, it hides as expected but does not show the unvote button (I need to reload) and the same happens with the unvote button, It hides but does not show the vote button... I have the following html template: ... {% for contribution in contribution_list %} ... {% if not user.is_authenticated %} <button onclick="location.href = 'http://127.0.0.1:8000/login/google-oauth2/?next=/';" id="myButton" class="votearrow"></button> {% elif contribution.id_contribution not in voted %} <button class="votearrow" id="vote{{ contribution.id_contribution }}" likehref='{{ contribution.get_api_like_url }}' userlike='{{ user.pk }}' contid='{{ contribution.id_contribution }}'></button> {% endif %} ... <span class="score">{{contribution.points.count}} point</span> by <a> {{contribution.author}} </a> <span class="age"> {{contribution.whenpublished}} </a> </span> {% if user.is_authenticated %} {% if contribution.id_contribution in voted %} <button class="unvote" id="unvote{{ contribution.id_contribution }}" likehref='{{ contribution.get_api_like_url }}' userlike='{{ user.pk }}' contid='{{ contribution.id_contribution }}'>Unvote</button> {% endif %} {% endif %} ... And … -
How do I view the first name of a user in Django?
I have set up my blog so that when a user clicks on the displayed name, it will go to that user's blogs (filtered that so only that person's blogs will show up). I used {{ view.kwargs.username }} to show the person's username, but I'd rather show the first name. What can I change to accomplish this? blog/templates/blog/user_post.html: {% extends 'blog/base.html' %} {% block content %} <h1 class="mb-3">Posts by {{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1> {% for post in posts %} <article class="media content-section"> <img class="rounded article-img mt-2" src="{{ post.author.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author.profile.user.first_name }} {{ post.author.profile.user.last_name }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %} <a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% … -
Django - extract filtered data
I have a django-filter (OrderFilter) to display a filtered table, now I want to extract to excel the same filtered table. My code works but the get return blank. Can you help please ? Views.py def Order(request): filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date') """ Don't work Category_query = request.GET.get('Category') qs = Order.objects.filter(Category= Category_query) """ if request.GET.get('Export') == 'Export': response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xlsx"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows=qs.values_list('Date', 'Category', 'Item') for row, rowdata in enumerate(rows): row_num += 1 for col, val in enumerate(rowdata): if isinstance(val,datetime.date): val = val.strftime('%d/%m/%Y') ws.write(row_num, col, val, font_style) wb.save(response) return response return render(request, 'template.html',{'orders':orders,'filter': filter}) template.html <form method="get"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <form method="GET" > <button class="btn btn-warning" type="submit" value="Export" name="Export"> Export</button> </form> -
POST requests do not go through Google Cloud Endpoints? (Django REST)
My iOS app makes POST requests to Google Cloud Run container which hosts my Django Rest Framework Project. To add a layer of security I've set up public ESP (Extensible Service Proxy - Cloud Endpoints) to serve as a gateway for private Cloud Run Container. Basically, ESP does authentication before routing the request to private Cloud Run container. Django urls All GET requests to ESP work fine: they successfully get routed to Cloud Run Container (for example when I request non existent /hello at www.mysite.com/hello, I get Django Debug 404) However, for some reason, POST requests are not routed by ESP (for example I'm trying to access existing /upload at www.mysite.com/upload I get standard 404) I've tried disabling csrf, setting APPEND_SLASH to false, nothing seems to work. All POST requests result in 404. Am I doing something wrong in Django? All testing done with Postman. All POST requests work fine if sent directly to Cloud Run Container