Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django templates with css file
I am learning about templates for my project(i am creating a web app with the Django framework.. of course with HTML and Css) However i have hit a snag. I did try to link the css file to the base html file (which is the parent template that my other templates inherits from) and my css updates aren't reflecting on the home page to my browser. Is there a problem with the link? The indentations are okay and there are no errors on my code. I have also tried to rerun my server and nothing. The main.css file is in the static sub directory which is inside the blog directory and my app is called Brenda's Blog. The code in my base.html file is below, inclusive of the link linking the main.css file. My css file : blog/static/main.css {% load static %} <!-- will load css file from static directory --> <!DOCTYPE html> {% load static %} <!-- will load css file from static directory --> <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if … -
The only page I see in my Django project is "migrations." I'm new to Django and the command line and am trying to create a "Hello World" page
I'm totally new to Django and the command line.. so please bear with me :) I started a Django project in virtualenv - but the "tree" doesn't show much at all. According to the tutorial I'm using (https://djangoforbeginners.com/hello-world/), after typing $ django-admin startproject helloworld_project . and entering $ tree I should have seen: ├── Pipfile ├── Pipfile.lock ├── helloworld_project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py However, I only got: C:. └── helloworld_project I see these files in the directory when I open the folder with the Windows explorer, though. How do I see the whole tree? I'm trying to create a "Hello World" page in Django using this tutorial: https://djangoforbeginners.com/hello-world/ ... Thank you!!!! -
Django 'CSRFCheck' object has no attribute 'process_request'
It was all ok till suddenly I got the above error while implementing DjangoObjectPermissions on my APIs. Before this It was working ok even my production environment it is working fine. I am seeing this error on my local environment only. according to this answer, the error would go away, but I need to know why? Please let me know what information should I add to this post. -
Request POST to Django views.py using JQuery AJAX
I want to filter users lat lon location coordinates to show other nearby users using a radius view function in my Django app. Currently the app can retrieve and save the users lat lon coordinates to the Location model in models.py I can't figure out how to write the radius view function using Ajax / JQuery which should request POST to the radius view. After a user locates themselves and saves their coordinates, there is a 3rd button that they should be able to press that will refresh the results based on the query set in the radius view function. urls.py urlpatterns = [ path('', connect_views.connect_home_view, name='connect_home'), path('insert', connect_views.insert, name='insert'), path('radius', connect_views.radius, name='radius'), views.py @login_required def connect_home_view(request): context = { 'users': User.objects.exclude(username=request.user), } return render(request, 'connect/home.html', context) def insert(request): location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user) location.save() return JsonResponse({'message': 'success'}) def radius(request): radius_km = request.data.get('radius', 0) queryset = User.objects.annotate( radius_sqr=pow(models.F('loc__latitude') - request.user.loc.latitude, 2) + pow(models.F('loc__longitude') - request.user.loc.longitude, 2) ).filter( radius_sqr__lte=pow(radius_km / 9, 2) ) context = dict(location=queryset) return render_to_response('connect/home.html', context) models.py class Location(models.Model): latitude = models.DecimalField(max_digits=19, decimal_places=16) longitude = models.DecimalField(max_digits=19, decimal_places=16) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='loc') def __str__(self): return f'{self.user}\'s location' connect.html <!-- Get IP Address and send to Location … -
does django have lots of clash if not isolated
I'm very new to django and web dev in general. I'm following tutorial https://www.youtube.com/watch?v=n-FTlQ7Djqc&index=1&list=PL4cUxeGkcC9ib4HsrXEYpQnTOTZE1x0uc create a blog by 'The Net Ninja'. His django version is 1.x but I'm using 2.1 I have completed it and have successfully emulate it on my own by following along. But I wanted to make another on my own. After I created it the files in my static files(the pictures for background) are clashing with my previous project. Now background photo of my new project shows in previous project (both projects have static files in similar named folder ) So am I supposed to use virtualenv and is this kind of clash normal??? please help -
Django getstream one activity many variants
getstream works perfect, but i need activity on model change. I have model "Goal" and users can joined to goal. I try to add activity on template - "activity/goal.html" like django getstream documentation say and then use: {% if activity.joined %} # Code displaying activity {% endif %} But sadly this don't work. It's possible to simple create other activity? After joined by user to Goal? -
Laravel oline building tool like Canva.com or Wix.com
I am currently looking examples of how to do online building tool like https://www.canva.com or even https://www.wix.com. What will be the best solution to achieve that. I have good experience with PHP Laravel framework and even Django Python. My main problem is the how to store all elements data like text boxes text, position, fonts etc without hitting too many times my DB with huge requests that will slow down the site. Have you ever done somethinking like this. I am open to suggestions as the site can have thousands of active users in future so i am looking for the best performance possible. Does anyone knows how Canva or Wix are achieving that. Thanks :) -
How to access data from django models?
This is a very easy question. I have this django model, and after populating this model with random data, I want to print the data like bio, location, birth_date using django template. I want to ask that how should I pass this data to template and print it? class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) And the template is as follows {% if user.is_authenticated %} <p>Hi{{ user.username }}</p> <!––Here I want to print data like bio, location, birth_date of the logged in user I thought {{ user.bio }} will print the data--> {% else %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign up</button> </form> {% endif %} I know that this is a very elementry question but I cannot find the solution. -
how to import excel file with django import-export and fix KeyError: > 'id'
i need to import excel files (xlsx) as data into the sqlite3 database in django for that i am using import_export package. excel file includes 2 columns: id (empty values) name (contains values ) when i try to import the file the system display this below error : Line number: 1 - 'id' None, smugling Traceback (most recent call last): File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 492, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 269, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 263, in get_instance return instance_loader.get_instance(row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\instance_loaders.py", line 31, in get_instance field = self.resource.fields[key] KeyError: 'id' Line number: 2 - 'id' None, kill Traceback (most recent call last): File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 492, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 269, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\resources.py", line 263, in get_instance return instance_loader.get_instance(row) File "C:\Users\LTGM~1\Desktop\TEHLIL~2\TEHLIL~1\lib\site-packages\import_export\instance_loaders.py", line 31, in get_instance field = self.resource.fields[key] KeyError: 'id' i followed the tutorial of import_export package and how it run. these are the steps: create a class in the models.py create resources.py file create admin.py file create a function in views.py file create an import html file. models.py from django.db import models class criminal_type(models.Model): criminal_typeID = models.AutoField(primary_key=True) … -
execute python code on html button click in Django
I have a code(function) written in python which I need to execute when a Button on HTML is clicked. I'd prefer not to use a form. Is there any way other than using forms by which I can execute code on HTML Button click. -
Django ValueError at /admin/, even after flush
I'm setting up an Django application with react, redux and the django-rest-framework. After adding a "Customer" model within Django, I got an ValueError when accessing the admin interface. The error keeps returning even after removing all the models from the admin interface by removing the line: admin.site.register(model). Even when I flush the database, the error keeps returning. I use the django User model with a knox token to log into the django application. This is an local django installation within a pipenv. error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 2.1.5 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'leads', 'rest_framework', 'frontend', 'knox', 'accounts', 'customer'] 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 "/home/[NAME]/.local/share/virtualenvs/lead_manager-2CdCcx2v/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/[NAME]/.local/share/virtualenvs/lead_manager-2CdCcx2v/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/[NAME]/.local/share/virtualenvs/lead_manager-2CdCcx2v/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/[NAME]/.local/share/virtualenvs/lead_manager-2CdCcx2v/lib/python3.5/site-packages/django/contrib/admin/sites.py" in wrapper 241. return self.admin_view(view, cacheable)(*args, **kwargs) File "/home/[NAME]/.local/share/virtualenvs/lead_manager-2CdCcx2v/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/[NAME]/.local/share/virtualenvs/lead_manager-2CdCcx2v/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/[NAME]/.local/share/virtualenvs/lead_manager-2CdCcx2v/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner 213. if request.path == reverse('admin:logout', current_app=self.name): File "/home/[NAME]/.local/share/virtualenvs/lead_manager-2CdCcx2v/lib/python3.5/site-packages/django/urls/base.py" in reverse 58. app_list = resolver.app_dict[ns] File "/home/[NAME]/.local/share/virtualenvs/lead_manager-2CdCcx2v/lib/python3.5/site-packages/django/urls/resolvers.py" in app_dict 477. self._populate() … -
Django NameError: 'version' not defined (runserver error)
I am trying to use the runserver command just like the django tutorial says. i'm using pipenv enviromment but i also tried using on anaconda and on virtualenv. When i type "py manage.py runserver" on my project folder i get this error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000003FE2840> Traceback (most recent call last): File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\db\models\base.py", line 101, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\DOCUMENTOS\.virtualenvs\DOCUMENTOS-A1FIg8A2\lib\site-packages\django\db\models\base.py", … -
How to display all the users created by a particular user in django?
For example: if a user creates n number of users . I want to display the n number of users created by that particular user alone in django . I can't come up with a solution. Do i have to create a model like profile with OnetoOnemodel of user? -
how to create an User via django-allauth social login
I have problems making actual User instance when using django-allauth. I let users to login with other SNS account, and then It creates sociall accounts, not User instance on server. and this 'all-auth' is also a problem. I read many lines of official docs and code but I can't even guess how it works. {% load socialaccount %} <ul> {% for provider in providers %} <li> {% if provider.social_app %} <a href="{% provider_login_url provider.id %}">{{provider.name}}</a> {% else %} <a>Provider {{ provider.name }} is not ready yet</a> {% endif %} </li> {% endfor %} </ul> it's all I typed.(beside starting setups). I click that provider_login_url, it goes to social login, my social account is authorized and I get logged in to may service. I wanna know how it works internally. and how to make User instance that I can see and manage on my admin page. -
Django Localhost is giving an error for my csv file when using it with d3.js
In my Django application I'm creating a csv file. When I try to use that file with a D3.js boilerplate it can't find the csv file? I've tried moving where the csv file is to the root and into it's own folder but it doesn't do anything different {% extends "lm_test/base.html" %} {% block content %} <meta charset="utf-8"> <style> svg { font: 10px sans-serif; } .y.axis path { display: none; } .y.axis line { stroke: #fff; stroke-opacity: .2; shape-rendering: crispEdges; } .y.axis .zero line { stroke: #000; stroke-opacity: 1; } .title { font: 300 78px Helvetica Neue; fill: #666; } .birthyear, .age { text-anchor: middle; } .birthyear { fill: #fff; } rect { fill-opacity: .6; fill: #e377c2; } rect:first-child { fill: #1f77b4; } </style> <body> <script src="https://d3js.org/d3.v3.min.js"></script> <script> var margin = {top: 20, right: 40, bottom: 30, left: 20}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom, barWidth = Math.floor(width / 19) - 1; var x = d3.scale.linear() .range([barWidth / 2, width - barWidth / 2]); var y = d3.scale.linear() .range([height, 0]); var yAxis = d3.svg.axis() .scale(y) .orient("right") .tickSize(-width) .tickFormat(function(d) { return Math.round(d / 1e6) + "M"; }); // An SVG element with a … -
Make a change to a string in django template?
I have a queryset in Django that contains a string field. This is a filename, something like images/photo.jpg or images/photo.20.19.22.jpg. I need to rewrite them in one particular view so that ".thumbnail" is inserted before the extension. The previous names should become images/photo.thumbnail.jpg and images/photo.20.19.22.thumbnail.jpg. What is the best way to do this? This is part of a queryset so it will look like: {% for record in list %} {{ record.image }} {% endfor %} Now of course I would love to do this outside of my template. However, I don't see a way in which I can do that. After all, this needs to be done for every record inside my queryset. To complicate things, this record does not come directly from a modal. This record is coming from a subquery, so I don't see a way for me to change the modal itself. Should I use templatetags for this? Any other recommendations? FYI the subquery is something like this: >>> from django.db.models import OuterRef, Subquery >>> newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at') >>> Post.objects.annotate(image=Subquery(newest.values('image')[:1])) -
Cannot send JSON data from Django to javascript
I need to send some data from html file to django for some processing and return it back using ajax But the response goes to the error callback in the ajax call with status=0 This is the ajax code, I've tried both commented URLs function snapshot() { ctx.drawImage(video, 0,0, canvas.width, canvas.height); imageData = ctx.getImageData(0, 0, canvas.width, canvas.height) console.log(imageData) //url:"{% url 'blind:getcaption' %}", $.ajax({ type: 'GET', url: 'http://127.0.0.1:8000/blind/ajax/getcaption/', //url: /ajax/getcaption/ data: { 'img': imageData }, dataType: 'json', success: function (data) { console.log(data); }, error: function(request, status, error){ console.log(request, " " ,status, " ", error) } }); } This is views.py def getcaption(request): img = request.GET.get('img', None) data = {'caption': "This caption for test"} return JsonResponse(data) And urls.py app_name = 'blind' urlpatterns = [ path('', views.index, name='index'), url(r'^ajax/getcaption/$', views.getcaption, name='getcaption'), ] But when I type in the url tap url:'http://127.0.0.1:8000/blind/ajax/getcaption/ I get the json object back viewed in chrome -
Best way to check crawler status
I have been crawling almost 20 websites and I want to be informed if one of my scripts does not work. What is the best solution for this? One way is that I write a script to check the count of stores in my database every day and alert me if they are not equal to 20. another way is that I run a script to notify me by email at the end of crawler script if it does not go well. Do these sound good? Do you have any other solution? Thanks in advance. -
My webservice with oauth2client don't work on remote server,
The django app runs on the local server, but does not work on the remote. The server does not have a GUI and does not provide the user with a link to authorization. The server outputs link to the console. from __future__ import print_function from apiclient import discovery from httplib2 import Http from oauth2client import file, client, tools import datetime import os import json SCOPES = 'https://www.googleapis.com/auth/calendar' from .models import Aim try: import argparse flags = tools.argparser.parse_args([]) except ImportError: flags = None def calendar_authorization(username): store = open('app/static/secret_data/' + username +'.json', 'w') store.close() store = file.Storage('app/static/secret_data/' + username +'.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('app/client_secret.json', SCOPES) flags.noauth_local_webserver = True print("________flow_______") print(flow.__dict__) creds = tools.run_flow(flow, store, flags) print("________creds_______") print(creds.__dict__) In the local version, I use client_secret.json, obtained from OAuth 2.0 client IDs. I suspect that I may have the wrong settings for this. I found the information to use the Service account keys(I don't use it now). But I didn’t find a good setup guide for this. How to set it up and paste in the code for authorization( I did not understand how the access service key is used in the code?)? What could be wrong? -
How to dynamically re-render template?
Currently I am trying to create a dynamic filter for listing model objects in a template. Here is the django view: def view_data(request): text = request.GET.get('text') persons = None if text: try: persons = models.Person.objects.get(code__regex=text) except models.Person.DoesNotExist: pass return render(request, 'view_data.html', {'persons': persons if not isinstance(persons, models.Person) else [persons]}) The related part from the template: <div class="jumbotron row"> <form> <label>Alanyok szűrése</label> <input id="filter" type="text" placeholder="Keresett alany"> </form> </div> <div class="row"> <div class="col-4"> <div class="list-group" id="list-tab" role="tablist"> {% for person in persons %} <a class="list-group-item list-group-item-action" id="list-{{person.code}}" data-toggle="list" href="#" role="tab" aria-controls="{{person.code}}">{{person.code}}</a> {% endfor %} </div> </div> <div class="col-8"> <div class="visualisation content"> <div class="canvas_div"> <canvas id="Canvas1" width="540" height="250" style="border:1px solid #202020;"> </canvas> </div> </div> </div> </div> The input field with filter id has a callback on keyup event which sends a request to django with the content of the input field which is used in the view for query. Here is the callback: $( "#filter" ).keyup(function() { $.get("", {text: $('#filter').val()}); }); When I checked it with Pycharm debugger, the render returns the correct html but on the client side the html doesn't change. How to re-render with the new object list? -
Django Template Loaders fail to load templates of my app installed via pip
I need help. I have a Django app which I have uploaded to test.pypi.org so that I can install it in my virtualenv via pip. However, the template loaders fail to look into my app even though it is on my INSTALLED_APPS giving me a TemplateDoesNotExist error message in debug mode. It looks inside django's template directory and on other installed apps, but skips my app. I do not know what else I am missing. I have looked and searched for a solution, however results return problems related to the django apps, which they are working on locally and not installed on virtualenv via pip like me. Thanks in advance. -
how to fix unique constraint in OnetoOneField in migrate step
I am not getting why the unique constraint is failed every time. #models.py from django.db import models # Create your models here. class usersclass(models.Model): user = models.OneToOneField( 'auth.User', default = False, on_delete = models.CASCADE, related_name = 'profiles', ) I am using Meta class for including Fields #forms.py from django import forms from .models import usersclass from django.contrib.auth.models import User class usersclassForm(forms.ModelForm): """Form definition for userclass.""" class Meta: """Meta definition for userclassform.""" model = usersclass fields = ('name_full','address','Gender','timestamp','Mobile_num','landline_number') Authentication is done properly but i am unable to migrate my models #veiws.py def post(self,request,*args,**kwargs): form = LoginForm(request.POST) if form.is_valid(): user = authenticate( username = form.cleaned_data['Name'], password = form.cleaned_data['password'], ) if user is not None: login(request,user) return HttpResponse() -
Django many to many relationsip update field
I have two models many to many relationships, I am trying to update a field by subtraction two values from the two models and save the changes to the db. class LeaveBalance(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True,) Leave_current_balance= models.FloatField(null=True, blank=True, default=None) Year=models.CharField(max_length=100,default='') def __unicode__(self): return self.Year class NewLeave(models.Model): user=models.ForeignKey(User,default='',on_delete=models.CASCADE) leave_balance=models.ManyToManyField(Leave_Balance) Leave_type=models.CharField(max_length=100,blank=False,default='') Total_working_days=models.FloatField(null=True, blank=False) def __unicode__(self): return self.Leave_type in my views I have tried but I get the error 'CombinedExpression' object has no attribute 'leave_balance' file = Leave_Balance() balance = NewLeave.objects.get(id=id) balance= F('Leave_current_balance') -balance.Total_working_days balance=balance.leave_balance.add(file) balance.save() -
How to access a special field in a subquery?
I have an image field in Django, but I'm using an StdImage field: class Photo(TimestampedModel): image = StdImageField(upload_to='photos', variations={'thumbnail': (200, 200), 'large': (1024, 1024)}) Normally, in a template I can use the following to access a 'variation': <img alt="" src="{{ object.myimage.thumbnail.url }}"/> However, I am using a subquery to retrieve the latest photo for an article (there could be many photos, or none) and I have no other way than to retrieve the image as a single value (as I can't retrieve multiple values in a subquery). newest_photo = Photo.objects.filter(industry__type=OuterRef('pk')).order_by('-date') list = Article.objects.filter(published=True).annotate(image=Subquery(newest_photo.values('image')[:1])) This all works well. Except for one thing. I am only able to retrieve the regular image, not the variation (which I would normally access by object.image.thumbnail.url). Any idea how to access this variation? -
Sending 1gb data as a response to POST request
I am running a django web app where I have one form which accepts text area input. I am sending that text to my view by POST request. After processing that input at server my generated output is of 1GB. Now the question is how can I send that data back to browser. I want that whole data at client side. How can I do it.