Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do a Django subquery
I have two examples of code which accomplish the same thing. One is using python, the other is in SQL. Exhibit A (Python): surveys = Survey.objects.all() consumer = Consumer.objects.get(pk=24) for ballot in consumer.ballot_set.all() consumer_ballot_list.append(ballot.question_id) for survey in surveys: if survey.id not in consumer_ballot_list: consumer_survey_list.append(survey.id) Exhibit B (SQL): SELECT * FROM clients_survey WHERE id NOT IN (SELECT question_id FROM consumers_ballot WHERE consumer_id=24) ORDER BY id; I want to know how I can make exhibit A much cleaner and more efficient using Django's ORM and subqueries. In this example: I have ballots which contain a question_id that refers to the survey which a consumer has answered. I want to find all of the surveys that the consumer hasn't answered. So I need to check each question_id(survey.id) in the consumer's set of ballots against the survey model's id's and make sure that only the surveys that the consumer does NOT have a ballot of are returned. -
Django-Autocomplete-Light Admin InLine for Many to many fields
I'm trying to get Django Autocomplete Light to work of a specific project. I've been struggling with using it in the admin for InLine Many2Many relations. #models.py class Person(models.Model): name = models.CharField() class Country(models.Model): country_name = models.CharField() persons = models.ManyToManyField(Person) #forms.py class CountryInlineForm(forms.ModelForm): class Meta: model = Country fields = ('__all__') widgets = { 'country_person': autocomplete.ModelSelect2(url='countries-autocomplete') } #admin.py class CountryInLine(admin.TabularInline): model = Country form = CountryInlineForm extra = 2 class PersonAdmin(admin.ModelAdmin): inlines = CountryInline, admin.site.register(Person,PersonAdmin) There are a couple of questions dealing with Django-Autocomplete-Light and InLines that recommend to use ListSelect2 instead of ModelSelect2, but it's still not working. This is probably not the best example, since I should have the M2M at the Person Model, but in my project I need it to work as an InLine. Thanks! -
How To Display Multiple Progress Bars In Django Template Using JS?
Here is my code, which displays the bar based on votes for just first option. {% extends 'polls/base.html' %} {% block main_content %} <head> <style> ....//all css styling </style> </head> <div id="Results"> <h1>{{question.question_text}}</h1> {% for choice in question.choice_set.all %} <div id="votes"><img style="border-radius: 2px; border-width: 2px; border-style: none solid solid none; border-color: darkblue;" src='{{choice.image2.url}}'/> <div style=" float: right; width: 88%;"> <b>{{choice.choice_text}}</b> <div id="myProgress"> <div id="myBar">{{choice.votes}} vote{{choice.votes|pluralize}} <script> move() function move(){ var elem = document.getElementById("myBar"); var width = 1; var id = setInterval(frame, 10); function frame(){ if (width >= {{choice.votes}}){ clearInterval(id); } else { width++; elem.style.width = width + '%'; } } } </script></div> </div> </div> </div> {% endfor %} </ul> <p id="info">Your Vote Has Been Stored!!</p> <br> </div> {% endblock %} Following is what it displays. I need to modify a code so that i could display all bars based on votes. Question and choice are the models. Javascript modification is encouraged. Please help. results.html image -
Django Rest Framework for commercial use
The question is: can I use Django Rest Framework for commercial use? The reason why I'm asking this is because in their website, they talk about "signing up for a paid plan". -
404 on slug in django
I am following a tutorial where they do something like this: <a href="{ % url 'films:add_comment' slug=film.slug %}">Leave a comment</a> They use slug. I have not been doing that, but have been referencing an ID. The parts of my code which I think are important to this are: films/urls.py: app_name = 'films' urlpatterns = [ url(r'^films/<int:film_id>/comment/', views.add_comment, name='add_comment'), ] films/views.py def add_comment(request, film_id): film = get_object_or_404(Film, pk=film_id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit = False) comment.post = post comment.save() return redirect('film:detail',film) else: form = CommentForm() template = 'films/add_comment.html' context = {'form':form} return render (request,template,context) add_comment.html: {% extends 'base_layout.html' %} {% block content %} <div class="create-comment"> <h2>Add Comment</h2> </div> {% endblock %} If I click the link I made which is: <a href="{ % url 'films:add_comment' film.id %}">Leave a comment</a> I get this: And if I manually alter the url to http://127.0.0.1:8000/films/2/comment/ I get this: But it looks like url 3 in that list matches what I typed? -
can we split django server log?
I just got django server log setup and I found there's this problem, the file gets TOO big in just a day if there are lots of traffics. I am wondering if it is possible to split the files in a certain time or when the file reaches a size? Thanks in advance for any advices -
ModuleNotFoundError: No module named 'django_tables2'
I am trying to use Django-tables2, but my project can't find this module. Firstly, I installed it without a problem. (acct) C:\Users\tsjee_000\dev\acct\src>pip install django-tables2 Requirement already satisfied: django-tables2 in c:\users\tsjee_000\dev\acct\lib\site-packages Requirement already satisfied: Django>=1.11 in c:\users\tsjee_000\dev\acct\lib\site-packages (from django-tables2) Requirement already satisfied: pytz in c:\users\tsjee_000\dev\acct\lib\site-packages (from Django>=1.11->django-tables2) Secondly, I added this to 'INSTALLED_APPS' in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_tables2', 'clients', 'companies', 'report', ] Thirdly, views.py and html templates are updated according to the tutorial. But when I run my project it doesn't work because of the error, ModuleNotFoundError: No module named 'django_tables2' I think this error happens in settings.py. FYR, 'django_tables2'module can be imported correctly in the shell mode. Thanks for your help in advance! -
Django: multiple forms on different pages
I'm making a website but I'm having some problems. On the first page you start by uploading a file with a form, it then does some processing to the file and takes you to the second page where there is another input form with a dropdown menu. But I can't work out how to pass the variables from the second form to the back end so I can do something else with them. Can someone help? This is what my "views.py" looks like. from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from django.utils.safestring import mark_safe from django.template import Template from .y14 import convert_image_to_instructions, generate_html def simple_upload(request): accepted = ['bmp', 'gif', 'jpeg', 'jpg', 'png', 'tif', 'tiff'] if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] name = myfile.name point = name.rfind('.') ext = name[point+1:].lower() if ext in accepted: fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) instructions, image_colours, n_colours = convert_image_to_instructions(filename) html_1, html_2 = generate_html(instructions, image_colours, n_colours) return render(request, 'core/preview.html', {'html_1': mark_safe(html_1), 'html_2': mark_safe(html_2)}) return render(request, 'core/simple_upload.html') -
Create comment on details page in django
I have an index page which lists films, and clicking on each film link takes you to a details page which displays comments related to the film selected. I wish to include an "add comment" form at the bottom of the details page. Currently I have: index.py: {% if latest_film_list %} <ul> {% for film in latest_film_list %} <li><a href="{% url 'films:detail' film.id %}">{{ film.title }}</a></li> {% endfor %} </ul> {% else %} <p>No films are available.</p> {% endif %} detail.py: <h1>{{ film.title }}</h1> <table id="myTable"> <tr> <th>Comment</th> <th>User</th> <th>Update</th> <th>Delete</th> {% for comment in film.comment_set.all %} <tr> <td>{{ comment.body }}</td> <td>{{ comment.user }}</td> {% if request.user == comment.user %} <td><a href="/">Update</a></td> <td><a href="/">Delete</a></td> {% endif %} {% endfor %} </tr> </table> {% if user.is_authenticated %} <h2>Comment</h2> #form to go here {% endif %} films/views.py: def index(request): latest_film_list = Film.objects.order_by('-pub_date')[:5] context = {'latest_film_list': latest_film_list} return render(request, 'films/index.html', context) def detail(request, film_id): film = get_object_or_404(Film, pk=film_id) return render(request, 'films/detail.html', {'film': film}) forms.py: from django import forms from . import models class CreateComment(forms.ModelForm) class Meta: model = models.Comment fields = ['body'] models: class Film(models.Model): title = models.CharField(max_length=200) director = models.CharField(max_length=200) description = models.CharField(max_length=200) pub_date = models.DateField('date published') class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, … -
Where to put Django OAuth Toolkit middleware in Django 2?
I'm trying to follow a tutorial on the Django OAuth Toolkit: https://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_03.html. The instructions say to update de MIDDLEWARE as follows: MIDDLEWARE = ( '...', # If you use SessionAuthenticationMiddleware, be sure it appears before OAuth2TokenMiddleware. # SessionAuthenticationMiddleware is NOT required for using django-oauth-toolkit. 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', '...', ) In my current project generated using startproject in Django 2.0.1, however, I see both SessionMiddleware and AuthenticationMiddleware, but no SessionAuthenticationMiddleware: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Where should I put the OAuth2TokenMiddleware? After AuthenticationMiddleware as in the commented-out line? -
Django - aggregate and annotate for simple operations
I see in the docs the aggregate and annotate functions can be used to create a new column in the query, so if I write something like: my_object = ...objects.filter(something).annotate(extra_column=Avg(value)) the inner query will give an extra column , AVG(value) AS "extra_column" ... Now, it seems to me that it can be used only will functions like count, avg, max, and min... can I do something as a simple +/- certain number? I'm trying .annotate(extra_column=another_column+1) or .annotate(extra_column='another_column'+1) but it doesn't work. What am I doing wrong? Sorry for the silly question. -
CSRF verification failed when in chrome incognito
I recently upgraded my application from Django 1.11 to Django 2.0. I am facing an issue when trying to logging in while in the incognito mode of Google Chrome, only the first time I get: Forbidden (403) CSRF verification failed. Request aborted.. If I resend the login post, I still getting error. But, if I go to the login page again, it works normally. I think it is something related to cookies. My middlewares are the following: 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] I assumed everything is configured correctly since this problem happens only at this scenario. Does anybody knows what is going on? -
Does Django Rest Framework tests use a "mock" database?
I am trying to come up with the best way to test a POST only endpoint, which takes a payload and creates 6 different objects from that data. I am trying to send the payload and then assert that all the objects that should have been created, are created. The last block (after the new lines), is trying to repost the same load and ensure that no duplicates were created. My question is if I run this test, is this using the existing database? Or is it setting up a "mock" database and tearing it down after the test runs? I don't want any of this data dirting up my db. class APITests(APITestCase): def test_job_start(self): url = '/api/v1/job_start/' response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(Platform.objects.count(), 1) self.assertEqual(Platform.objects.get().name, 'andr') self.assertEqual(CdTool.objects.count(), 1) self.assertEqual(CdTool.objects.get().name, 'https://jenkins-andr.test.com') self.assertEqual(Job.objects.count(), 1) self.assertEqual(Job.objects.get().name, 'ANDR_master_CI') self.assertEqual(JobExecution.objects.count(), 1) self.assertEqual(JobExecution.objects.get().build_id, '3500') # Send the same payload, make sure no duplicate records are created response = self.client.post(url, data, format='json') self.assertEqual(Platform.objects.count(), 1) self.assertEqual(CdTool.objects.count(), 1) self.assertEqual(Job.objects.count(), 1) self.assertEqual(JobExecution.objects.count(), 1) -
How to show queryset from one app in another app with Django
I have a little problem. I have the main app(cartoons) and I created the another app(Settings). The "Settings" app must be responsible for settings in <head> like: changing the title, description and footer text.But I dont know how to include models as querysets from "Settings" App to "Cartoons" App? My files are: Settings/models.py # -*- coding: utf-8 -*- from django.db import models class Ustawienia(models.Model): title = models.CharField(max_length=75, verbose_name="Tytuł strony(title)") description = models.TextField(max_length=280, verbose_name="Opis META(description)") logo = models.CharField(max_length=150, verbose_name="Nazwa LOGO") footer = models.TextField(verbose_name="Opis stopki") class Meta: verbose_name = "Ustawienia Strony" verbose_name_plural = "Ustawienia Strony" def __str__(self): return self.title Project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('bajki.urls')), path('', include('kontakt.urls')), path('tinymce/', include('tinymce.urls')), path('', include('ustawienia.urls')), ] Cartoons/views.py from ustawienia.models import Ustawienia def ustawienia(request): ustawienia = Ustawienia.objects.all() context ={'ustawienia': ustawienia,} return render(request, '', context=context) and Settings/urls.py from django.urls import path from bajki import views urlpatterns = [ path('', views.ustawienia, name="ustawienia"), ] The section is : <head> {% for ustaw in ustawienia %} <title>{{ustaw.title}}</title> {% endfor %} .... Where is the problem in my code? Anybody know? -
Python: How to convert a MagicMock object response to regular JSON?
I have a method similar to this def method(request, id): obj = Object.objects.get(id=id) return response_json(Response.SUCCESS, obj.toDict()) And I am trying to write a test using the mock library, with MagicMock as a mock request with the following code: class test_method(): def test_get_job_exist(self): obj = Object expected_response = {"data":data} request_mock=mock.MagicMock(method='GET') with mock.patch('Object') as mock_obj: mock_obj.objects.get.return_values = obj response = method(request_mock, 1) self.assert_equals(response.content, expected_response) I would expect that response.content to return the expected_response but got this instead: {"data": "<MagicMock name=\'Object.objects.get().__getitem__()\' id=\'1232344\'>"}" I am using Django and Object is a Django model object. I've tried this and ran mock_job.return_value.objects.return_value.get.return_value= job and mock.MagicMock(method='GET').return_value but that did not work. Any help is appreciated -
How do I pass two captured values to a Django url?
I'm creating a job request system in Django 2.0 and I need to pass two captured values to a template. This all works if I hardcode in a url that goes to an existing brand slug and category slug urls.py: path('request/<slug:brand_slug>/<slug:category_slug>/', views.job_request_step_two, name="job_request_step_two") My attempted, but failed try at setting that url dynamically in a template: {% url 'form_step_two' brand.slug category.slug %} Running this, I get this error: NoReverseMatch at /jobs/request/ Reverse for 'job_request_step_two' with arguments '('', '')' not found. 1 pattern(s) tried: ['jobs\\/request\\/(?P<brand_slug>[-a-zA-Z0-9_]+)\\/(?P<category_slug>[-a-zA-Z0-9_]+)\\/$'] -
Django redis cache rebuild
We have an application for which the daily data needs to be updated in the cache. So if we flush out the data is there any easy way of rebuilding the cache without visiting all the pages and combinations. Is there any way to automate this. -
Django Asset Pipeline - javascript template compiling & testing
I have got handlebars templates compiling with django-pipeline and it's great. I notice it compiles my templates in the html like so.... <script type="text/javascript"> Handlebars.templates = Handlebars.templates || {}; Handlebars.templates['index'] = Handlebars.compile('< div >hi world< /div >'); </script> So cool I'll create a javascript object that uses this new template function MyObject(){}; MyObject.prototype.init = function(){ var html = Handlebars.templates['index'](); } Now I want to write a test with jasmine for this javascript object.... But it doesn't know what Handlebars.templates['index']. Is there a way to get the compiled templates into my jasmine tests? -
ImportError pin pycharm
My pycharm worked right with django until I uninstalled django to use virtual environment and now I can't import django, I however can run my django projects in d virtual env but not pycharm anymore,please help -
Django: Custom 404 template for specific ListView
I am using a Django ListView, to serve a web page. class MySpecificListView(ListView): pass All 404 errors of the website, use the 404.html template. Is it possible to call another template (for example MySpecificListView404.html) when a 404 error raises from this view? -
django posts receive CSRF verification failed after switching to load balancer
I have a working login template that does a post and looks like: <form action="" method="post"> {% csrf_token %} <br> {{form.email}} <div class="text-center"> <button type="submit">Login</i></button> </div> </form> I made two changes. I switched to an aws ec2 elastic load balancer and from https to http. Now I am getting an error: Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. Does anyone know why this is occurring? -
How to create and save object in bulk for dictionary in Django
I want to create object in bulk for my models. My models is class Fees(models.Model): city = models.CharField(max_length=200, blank=True) contact = models.CharField(max_length=200, blank=True) class = models.CharField(max_length=200, blank=True) veg = models.BooleanField(default=False) rollno = models.CharField(max_length=200, blank=True) and my dictionary values are - response = { 'A101': { 'VEG': True, 'CONTACT': '12345', 'CLASS': 'SIX', 'ROLLNO': 'A101', 'CITY': 'CHANDI', }, 'A102': { 'VEG': True, 'CONTACT': '54321', 'CLASS': 'SEVEN', 'ROLLNO': 'A102', 'CITY': 'GANGTOK', }, } Currently I am doing like as follow- def create_obj(response): for key, value in response.items(): fee_obj, _ = Fees.objects.get_or_create( rollno=key, defaults={ **change_value }) yield fee_obj So how can i create object in bulk. Any help would be appreciated. -
Which python web framework is most suitable for building a data repository site?
First of all, I have used only php till now and the reason for choosing python now is that I also need to do dynamic ploting of graphs on webpage from the data in the repository and I have already started using python mpld3 for it. Currently, I am calling the python script from my php code which works well. But I think it would be better if I use python only. For data repository sites, I have experience with fedora commons for data archiving and retrieving and solr for indexing and search functionality. But as it has dependency on java and as I found it extremely hard to setup, I don't want to use that. Also fedora commons uses a complex backend storage layout by default, where it splits the file data into multiple small files and I need to use more extensions for normal filesystem storage layout. I don't need this complexity, as my dataset size is small and usually they are txt, csv or png files. However, the number of datasets can grow to thousands in distance future. So for faster search and retrieval of data, my idea is to setup a MySQL database and manage the … -
Import the OAuth Toolkit's support layer for the Django REST framework
I'm trying to follow the minimal setup instructions on http://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html#step-4-get-your-token-and-use-your-api to set the following DEFAULT_AUTHENTICATION_CLASSES for the REST_FRAMEWORK setting: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.ext.rest_framework.OAuth2Authentication', ) } However, this is leading to an ImportError because it can't find the oauth2_provider.ext module. I've reproduced this in the Django shell: (venv) Kurts-MacBook-Pro:lucy-web kurtpeek$ python manage.py shell Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: import oauth2_provider In [2]: oauth2_provider.__version__ Out[2]: '1.0.0' In [3]: import oauth2_provider.ext --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-3-863d7f96a2d0> in <module>() ----> 1 import oauth2_provider.ext ModuleNotFoundError: No module named 'oauth2_provider.ext' From what I can tell from https://pypi.python.org/pypi/django-oauth-toolkit, 1.0.0 is the most recent version of the Django OAuth Toolkit, so the instructions should apply. Any idea why this is not working? -
Read String Array in Django API
I have EmberJS front-end which calls Django REST API. I am passing string array from front-end to the API as shown below: Back-end Request http://localhost:8000/api/v1/User/search/?active=true&city%5B%5D=newyork&city%5B%5D=chicago&city%5B%5D=boston HTML Decoded http://localhost:8000/api/v1/User/search/?active=true&city[]=newyork&city[]=chicago&city[]=boston Some how I am not able to get rid of the extra %5B%5D (which is square brackets) from this request as EmberJS automatically adds that as the parameter is passed as string array. I searched over several forums but did not get a solution for it. How to read the string array (City parameter) in Django API and get all passed values from EmberJS front-end?