Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GeoDjango + Postgis missing functions
So I've been using a Postgres database with the extension Postgis installed, and then using a Django setup to draw spatial data on a Leaflet OpenStreetMap. It has been a bit difficult translating my sql queries to the database functionality that Django is using whenever you're communicating with your database. Often I seem to be missing Postgis functions such as ST_LineCrossingDirection or ST_FrechetDistance. How do I get to use those functions along with .annotate and .filter from Django without having to write custom sql queries and executing those? I've tried to look into F() and Func() from Django as well, but I don't think that solves my issue as it seem to be using built in aggregate functions. I also tried to execute RawSQL in an annotate function to perform the function ST_LineCrossingDirection but it would require me to write a WHERE clause and the condition is something I'm not aware of until I get to the filter() call where I'm using intersects() between two geometries. Anyway .. If anyone knows how to use what I assume is missing Postgis functions please let me know. Because my code is getting quite messy and ineffective. Thanks, and all help is appreciated! -
Connect fields from 2 models with a primary key
I'm working on an already built project. There are 2 different model, product and stock. Products model has field which is sub_category and stock has main_category. Stock has a product_id which is a foreign key to the Product. I also need to get information from Product which is product_sub_category with product_category_id in a serializer. class Product(BaseModel): product_id = models.CharField(default=randomword(5), null=False, blank=True, max_length=100, unique=True) product_sub_category_id = models.ForeignKey(Product_sub_category, on_delete=models.SET_NULL, null=True, blank=True) class Vendor_Stock(BaseModel): vendor_id = models.ForeignKey(Vendor_management, on_delete=models.SET_NULL, null=True, blank=True) product_id = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True) product_category_id = models.ForeignKey(Product_category, on_delete=models.SET_NULL, null=True, blank=True) What would a serializer look like for this? -
Upload python script and load/use it in runtime in django
I need to upload user created python script and load/use it in runtime in django. I tried several approaches like using importlib and other django module like SourceFileLoader. But it seems like the import is failed with 'Permission error'. Ideally, I would like to store the uploaded file in a folder which is at the level of my django project. What's the correct approach for this functionality, particularly the module loading part? -
How to handle editing conflicts in Django forms?
Imagine the following situation: Two users, Alice and Bob, are using a Django form to edit the same object simultaneously. For the purpose of this example, let's use the following model: class Book(models.Model): title = models.TextField() description = models.TextField() Alice edits the book to change its title. Meanwhile, Bob edits the book to change its description. Now, if Bob is the last one to click the "Save" button, his form will "win" and only the description of the book will have been changed. Otherwise, if Alice is the last one to save, only the title will have been changed. Ideally, however, after both forms have been saved, the database should contain the title from Alice, and the description from Bob. I can think of a few possible solutions to prevent this from happening: Locking the form. As soon as Alice requests the book edit form, she acquires a lock that is released after she clicks "Save". When Bob tries to request the same form, he could get an error or warning message that Alice is already editing the same book. The problem here is if course dealing with stale locks. Checksumming the data being edited. The form could contain a … -
Django: maintain sessions across multiple domains with different backend
I have two websites hosted on the same server (aws instance), let's say: web1.domain.com and web2.domain.com Every time a user access one website or another, they will have to log in. If a user accesses from web1 (already logged in) to web2, I want to avoid the user having to log in again. The backend is different: web1 (Python, django) web2 (PHP, mediawiki) Both websites use Mysql and Apache server. I have found this but it does not solve my question completely: Django: maintain sessions across multiple domains I would like to know if there is any way to achieve it. For now, options such as SSO via SAML are ruled out due to complexity. -
Auto printing orders from sql using django/laravel
Is there any possibility to create app (django, laravel) - that would get data from database, table called orders and would automatically create pdf with data and download it? Let's say, i've got 5 new orders, each for different address and different goods. App should automatically create pdf and download for each of those 5 orders. It could also be a react app getting orders from API. Is this possible? Thanks in advance. -
Problem about making correctly link a URL with a webpage
models.py from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator #from django.contrib.postgres.fields import ArrayField # Create your models here. class locationData (models.Model): locationID = models.AutoField (primary_key = True) name = models.CharField (max_length = 64) population = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) apiEndpoint = models.URLField (max_length = 256) resourceURL = models.URLField (max_length = 256) class dateData (models.Model): entryID = models.AutoField (primary_key = True) name = models.CharField (max_length = 64) date = models.DateField (auto_now = False, auto_now_add = False) confirmedCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) deathCase = models.IntegerField (default = 0, validators = [MinValueValidator(0)]) views.py from django.shortcuts import render from django.views.generic import TemplateView, ListView, DetailView from database.models import locationData, dateData # Create your views here. class viewLocationData (DetailView): template_name = "locationData.html" model = locationData def get_context_data (self,**kwargs): location = self.kwargs['location'] context = super().get_context_data (**kwargs) context ['location'] = locationData.objects.get (pk = location) return context app/urls.py from django.urls import path from database import views urlpatterns = [ path ('location_data/<int:location>', views.viewLocationData.as_view(), name = 'location-data') ] config/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path ('database/', include ('database.urls')) ] locationData.html <h1>Location Data</h1> <table> <tr> <td>Location Name</td> <td>{{location.name}}</td> </tr> <tr> <td>Current Estimated Population</td> <td>{{location.population}}</td> </tr> … -
Issue Installing Locustio(0.7.5) Package
macOS == 10.15.7 || Django Project || Python 3.6.7 When I'm trying to install locustio version 0.7.5 package from pip it is giving error.I have tried fix mentioned in all versions of answer that were similar to this everywhere but no progress. When I run the following command :- pip install locustio==0.7.5 Collecting locustio==0.7.5 Using cached locustio-0.7.5-py3-none-any.whl Requirement already satisfied: requests>=2.9.1 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from locustio==0.7.5) (2.25.1) Collecting flask>=0.10.1 Using cached Flask-1.1.2-py2.py3-none-any.whl (94 kB) Requirement already satisfied: msgpack-python>=0.4.2 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from locustio==0.7.5) (0.5.6) Collecting gevent==1.1.1 Using cached gevent-1.1.1.tar.gz (2.0 MB) Requirement already satisfied: greenlet>=0.4.9 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from gevent==1.1.1->locustio==0.7.5) (1.0.0) Requirement already satisfied: Werkzeug>=0.15 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from flask>=0.10.1->locustio==0.7.5) (1.0.1) Requirement already satisfied: click>=5.1 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from flask>=0.10.1->locustio==0.7.5) (7.1.2) Requirement already satisfied: itsdangerous>=0.24 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from flask>=0.10.1->locustio==0.7.5) (1.1.0) Requirement already satisfied: Jinja2>=2.10.1 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from flask>=0.10.1->locustio==0.7.5) (2.11.3) Requirement already satisfied: MarkupSafe>=0.23 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from Jinja2>=2.10.1->flask>=0.10.1->locustio==0.7.5) (1.1.1) Requirement already satisfied: certifi>=2017.4.17 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from requests>=2.9.1->locustio==0.7.5) (2020.12.5) Requirement already satisfied: urllib3<1.27,>=1.21.1 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from requests>=2.9.1->locustio==0.7.5) (1.26.4) Requirement already satisfied: idna<3,>=2.5 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from requests>=2.9.1->locustio==0.7.5) (2.10) Requirement already satisfied: chardet<5,>=3.0.2 in /Users/anantkrishanjoshi/.virtualenvs/envdoconpy/lib/python3.9/site-packages (from requests>=2.9.1->locustio==0.7.5) (4.0.0) Building wheels for collected packages: gevent Building wheel for gevent (setup.py) ... error ERROR: Command errored out with exit status 1: … -
Request not sending file in django test
I want to test a view that is suppose to receive files attached with the request. my django test: TEST_DIR = "myapp/tests/test_data/" file_name = "some_resume.pdf" email_data = { # ... } api = APIClient() with open(FILE_DIR + file_name, "rb") as fp: response = api.post( "/api/v1.0/emails/receive/", data=email_data, files={"resume": fp}, # pass file handler open with byte mode format="multipart", # use multipart format ) # test some stuff but when I print the files attached to the request in the View I get nothing: print(request.FILES) # <MultiValueDict: {}> I checked everywhere and the format for my api request looks file. Also, my view works fine when I test with shell sending request with with python requests library. Am I missing anything? Could id be somehow related to my test environment or some obscure middlewares? -
Images slider with Django, Bootstrap, Javascript doesn't work properly
I am trying to use the static slider(javascript snippet) for dynamic data. From ListView I am getting to the image. I am sure, the loop in the template and javascript is wrongly built. Any suggestions? models.py class Gallery(models.Model): name = models.CharField(max_length=250) new_image = models.ImageField(upload_to='gallery_folder') day_publish = models.DateField() def save(self, *args, **kwargs): super().save(self, *args, **kwargs) img = Image.open(self.new_image.path) if img.height > 940 or img.width > 788: output_size = (820,720) img.thumbnail(output_size) img.save(self.new_image.path) def get_absolute_url(self): return reverse('detail-slug', kwargs={'pk': self.pk}) def __str__(self): return self.name views.py def slide_show_view(request, *args, **kwargs): all_images = Gallery.objects.all() choosen_image = Gallery.objects.get(**kwargs) context = { 'all_images': all_images, 'choosen_image': choosen_image } return render(request, "gallery/gallery_slide.html", context) urls.py urlpatterns = [ path('slug/<int:pk>/', views.slide_show_view, name="detail-slug"), ] I try with if statement for span(i don't know is correct or not) still not working. gallery_slide.html <div class="container"> <div class="carouselContainer"> <div class="carouselMainImage"> <img src="{{ choosen_image.new_image.url }}"> </div> {% for image in all_images %} <div class="carouselImgs"> <img src="{{ image.new_image.url }}"> </div> {% endfor %} <span class="prev" id="prev"> < </span> <span class="next" id="next"> > </span> </div> </div> <script src="{% static 'js/slideshow.js' %}"></script> slideshow.js var currentSlide = document.getElementsByClassName('carouselMainImage'); function showSlide(slideIndex) { const slides = document.getElementsByClassName('carouselImgs'); console.log(slides); if (slideIndex > slides.length) { currentSlide = 1 } if (slideIndex < 1) { currentSlide … -
step to save image file to server using django api
I am new in python and django, right now I would like to upload an image from postman (content type: form-data) and then save it in server. So far I have doing this @csrf_exempt def detector(request): data = {"success": False} if request.method == "POST": print("oke0") # check to see if an image was uploaded if request.FILES.get("image", None) is not None: ...# here I would like to save the image else: return JsonResponse(data) return JsonResponse(data) so the flow is: upload image from postman and then directory 'media' will be created and the image will be stored there so far I have been following this https://www.geeksforgeeks.org/python-uploading-images-in-django/ but I don't know how to try it in postman, anyone knows step by step to save image file to server in django? -
Error code H10 and H13 deploy django app to Heroku
this is my first time deploying a website and im new to Python, so i dont know how to fix this. I follow CoreyMS tutorial on YouTube, but I am stuck. I keep getting these H10, H13 and sometimes H14 errors. Im on a windows and im not sure if i got it pushed correctely, since Coreys commandline reads master and my commandline stays the same throughout. Note: I have already pip install gunicorn Here is my commandline: (djangoenv) C:\Users\aston\OneDrive\Skrivebord\mydjangoapp\django_project>heroku logs 2021-03-18T07:54:27.389903+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-03-18T07:54:27.389903+00:00 app[web.1]: django.setup(set_prefix=False) 2021-03-18T07:54:27.389904+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 19, in setup 2021-03-18T07:54:27.389904+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2021-03-18T07:54:27.389904+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__ 2021-03-18T07:54:27.389905+00:00 app[web.1]: self._setup(name) 2021-03-18T07:54:27.389905+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup 2021-03-18T07:54:27.389905+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2021-03-18T07:54:27.389906+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__ 2021-03-18T07:54:27.389906+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2021-03-18T07:54:27.389906+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2021-03-18T07:54:27.389907+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-03-18T07:54:27.389907+00:00 app[web.1]: File "/app/django_project/settings.py", line 123, in <module> 2021-03-18T07:54:27.389908+00:00 app[web.1]: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') 2021-03-18T07:54:27.393425+00:00 app[web.1]: NameError: name 'os' is not defined 2021-03-18T07:54:27.394367+00:00 app[web.1]: [2021-03-18 07:54:27 +0000] [10] [INFO] Worker exiting (pid: 10) 2021-03-18T07:54:27.399214+00:00 app[web.1]: [2021-03-18 07:54:27 +0000] [9] [ERROR] Exception in worker process 2021-03-18T07:54:27.399216+00:00 … -
django.db.utils.ProgrammingError: relation " - " does not exist
(New to Django) - I am looking to create two model with a foreign key. The first model is called Portfolio, and each Portfolio has many member through the second model Portfoliomember. It currently looks like this: class Portfolio(models.Model): portfolio_name = models.CharField(max_length=30, blank=True, null=True) def __str__(self): return self.portfolio_name class Meta: db_table = "portfolio" class PortfolioMember(models.Model): portfolio = models.ForeignKey(Portfolio, related_name = "portfoliomember", on_delete=models.CASCADE) quality = models.FloatField(blank=True, null=True) def __str__(self): return self.portfolio class Meta: db_table = "portfoliomember" Later i aim at using formset in a form. but for now, when i try to create the migration, i get the following : django.db.utils.ProgrammingError: relation "portfoliomember" does not exist Is there an obvious reason why this would not work ? -
Nginx error while using django-channels, nginx and daphne for websocket connection
#This is my nginx config location /order_history/ { proxy_http_version 1.1; proxy_pass http://0.0.0.0:8001; proxy_buffer_size 64k; proxy_buffers 16 32k; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } nginx error: upstream prematurely closed connection while reading response header from upstream -
Get logged user ip by models.py and Generic Cass Views in Django
i'd get the ip address all the time user do login. Please Help. my models.py user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ip_address = models.GenericIPAddressField() def __str__(self): return self.ip_address -
Error while building a simple project. Writes could not find the specified file
./project /site_ts /web Dockerfile requirements.txt docker-compose.yml my docker-compose.yml: version: '3' services: web: build: ./web command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/site_ts ports: - '8000:8000' my Dockerfile: FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN mkdir /site_ts WORKDIR /site_ts COPY requirements.txt /site_ts/ RUN pip install --upgrade pip && pip install -r requirements.txt ADD . /site_ts/ i write docker-compose up and take this Error: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose\cli\main.py", line 67, in main File "compose\cli\main.py", line 123, in perform_command File "compose\cli\command.py", line 69, in project_from_options File "compose\cli\command.py", line 132, in get_project File "compose\cli\docker_client.py", line 43, in get_client File "compose\cli\docker_client.py", line 170, in docker_client File "site-packages\docker\api\client.py", line 188, in __init__ File "site-packages\docker\api\client.py", line 213, in _retrieve_server_version docker.errors.DockerException: Error while fetching server API version: (2, 'CreateFile', 'The specified file cannot be found.') [9356] Failed to execute script docker-compose -
Getting a particular value from QuerySet in django
how can I get to print "Mathematics" from this QuerySet? <QuerySet [<Schedule: Thursday - Class 1/2/3 Section A - Mathematics>]> -
How to solve this error in Django rest framework?
#My Model from django.db import models class Tutorial(models.Model): title = models.CharField(max_length=100, blank=False, default=''), description = models.CharField(max_length=250, blank=False, default=''), published = models.BooleanField(default=False) #my 0001.py migration file from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Tutorial', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('published', models.BooleanField(default=False)), ], ), ] Why is the model neglecting the title, description fields even I mentioned them clearly??? I deleted the init0001.py file re run the migrations again but not resolved -
drf- discord like role permissions checking
relevant discussion is here. So I am building an api with architecture inspired by discord. I have objects called Boxes and these boxes have their own set of Roles. The role object looks like this. class Role(CoreModel): class Meta: ordering = ('position', 'box') permission_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', 'MANAGE_UPLOADS', 'MANAGE_ROLES', 'MANAGE_BOX', 'MANAGE_INVITES', 'KICK_MEMBERS', 'BAN_MEMBERS' ) default_flags = ( 'ADD_STARS', 'DOWNLOAD_FILES', 'SEND_UPLOADS', ) color = ColorField( verbose_name=_('color'), help_text=_("role's hex color code"), default='#969696' ) hoist = models.BooleanField( verbose_name=_('hoist'), help_text=_("whether the role can be pinned"), default=False ) is_default = models.BooleanField( verbose_name=_('default'), help_text=_("whether the role is default"), default=False ) position = PositionField( verbose_name=_('position'), help_text=_("position for the role"), collection=('box', 'is_default') ) box = models.ForeignKey( to='uploads.Box', verbose_name=_('box'), on_delete=models.CASCADE ) name = models.CharField( verbose_name=_('name'), help_text=_("role name"), default='new role', max_length=100, validators=[ MinLengthValidator(2) ] ) permissions = BitField( verbose_name=_('permissions'), help_text=_("permission bit set"), flags=permission_flags, default=default_flags ) REQUIRED_FIELDS = (name, box) I am using the bitfield extension provided by disqus here. Roles have a set of predefined permissions which can be allowed or denied for a specific role, like MANAGE_ROLES # allows to manage box roles MANAGE_BOX # allows to manage and edit the box Now, users can be a part of the box, through a model called member, and … -
how to use inlineformset with js to add extra fields
i want to use inlineformset factory for my project ! i have write my own js to add more fields , but it only save the last form in child form ! i dont want to use jquery.formset.js this is my models.py class Main(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) company = models.ForeignKey(Companies,on_delete=models.CASCADE) items = models.ManyToManyField(Item,through='Child') invoice_number = models.IntegerField() class Child(models.Model): main = models.ForeignKey(Main,on_delete=models.CASCADE) item = models.ForeignKey(Item,on_delete=models.CASCADE) quantity = models.IntegerField() and this is my views.py , i have used class based view class CreateMainInlineFormset(LoginRequiredMixin,SuccessMessageMixin,CreateView): model = Main form_class = MainForm template_name = 'main/create.html' def get_context_data(self, *args,**kwargs): data = super().get_context_data(*args,**kwargs) if self.request.POST: data['items'] = ChildInlineFormSet(self.request.POST) data['items'].full_clean() else: data['items'] = ChildInlineFormSet() return data def form_valid(self, form): context = self.get_context_data() items = context['items'] with transaction.atomic(): self.object = form.save(commit=False) form.instance.admin = self.request.user if items.is_valid() and form.is_valid() and items.cleaned_data!={}: items.instance = self.object form.save(commit=True) items.save() else: return render(self.request,self.template_name,context) return super().form_valid(form) def get_success_url(self): return reverse_lazy('maininfo:list-item') and this is my template html + js script ,i think the problem is here , i dont know how increase child forms in a right way ! $("#addRow").click(function () { var html = $("#relInputs").clone(); $('#relatiedInput').append(html); }); $(document).on('click', '#removeRow', function () { if ($("#relatiedInput> #relInputs").length != 1) $(this).closest('#relInputs').remove(); }); <div class="mt-1 text-right mx-auto" style="direction: rtl;"> … -
Django Channels - Mark user as online and offline
How can we use django channels to mark user as online and offline? Means using websocket is it possible to mark user as offline or online? If not, what all are the other possible ways to mark user as online and offline, like how it is done in facebook, instagram and all? In frontend, I want to show green ball in case user is online and red ball in case user is offline. -
Django to modify value in body and return it
class LocationRetrieveSerializer(serializers.ModelSerializer): class Meta: model = UserAttributes fields = '__all__' def create(self, validated_data): logger.info(self.context["request"].user.aerosimple_user) if UserAttributes.objects.filter(user_id=self.context["request"].data['user']).exists(): raise serializers.ValidationError("User Already exists.") user_attributes = UserAttributes.objects.create(**validated_data) return user_attributes i want to change the value in the body and should return it with the changed value in the body -
What is the difference between the types of CORS settings?
I searched to solve the cross domain that occurs when deploying django to the google cloud app engine and found three solutions. The cross domain problem has not been solved yet, but I have a question. GCP storage CORS setting https://cloud.google.com/storage/docs/cross-origin?hl=en GCP app.yaml setting https://cloud.google.com/appengine/docs/standard/python3/config/appref?hl=en django-cors-headers https://pypi.org/project/django-cors-headers/ Are there any differences between the three? -
Chartjs not parsing JsonResponse (Django and Chartjs)
I'm trying to get a pie chart (Chart.js) rendered from my django model; however, instead I'm getting my Json data rendered to my localhost (see picture). here's my code for reference (also, the JsonReponse is a class because I'm using Django 1.6.11 and JsonReponse was only formally added to django >= 1.7) views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from django.contrib import messages from django.utils import simplejson from django.middleware.csrf import get_token from django.db.models import Count from .models import Member, Driver, Order, Distance import json class JsonResponse(HttpResponse): # Code for JSONResponse - not in Django 1.6.11 def __init__(self, content, mimetype='application/json', status=None, content_type=None): super(JsonResponse, self).__init__( content=simplejson.dumps(content), mimetype=mimetype, status=status, content_type=content_type, ) def homepage(request): # pie chart for payment type queryset = Order.objects.order_by('payment').values('payment').annotate(payment_type=Count('payment')) data = list(queryset.values_list('payment_type', flat=True)) labels = list(queryset.values_list('payment', flat=True)) return JsonResponse({ 'labels' : labels, 'data' : data, }) urls.py from django.conf.urls import patterns, include, url from django.contrib import admin from mysite import views urlpatterns = patterns('', url(r'^$', 'mysite.views.homepage', name='payment-chart'), ) base.html <div class="payment_chart"> <canvas id="payment_chart" data-url="{% url 'payment-chart' %}"> </canvas> </div> <script> $(function () { var $paymentChart = $("#payment-chart"); $.ajax({ url: $paymentChart.data("url"), success: function(data) { var ctx = $paymentChart.getContext("2d"); new Chart(ctx, { type: 'pie', data: { labels: labels, … -
How to Router Redirect After Login in Django
from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import redirect def auth_middleware(get_response): def middleware(request): #print(request.session.get('customer')) returnUrl = request.META.get('PATH_INFO') #print(request.build_absolute_uri()) if not request.session.get('customer'): return HttpResponseRedirect(reverse(f'store:login?return_url={returnUrl}')) print('middleware') response = get_response(request) return response return middleware