Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django Queryset with Latest of Foreignkey
I have 3 linked Django models. models.py Assessment(models.Model): finalized = models.BooleanField(default=False) finalized_date = models.DateTimeField(default=blank, blank=True) class Meta: get_latest_by = "finalized_date" Workstation(models.Model): assessment = models.ForeignKey(Assessment, null=True, blank=True, on_delete=models.SET_NULL) Answer(models.Model): score = models.IntegerField(default=0) assessment = models.ForeignKey(Assessment, null=True, blank=True, on_delete=models.SET_NULL) Here is my 1st problem: I need a queryset that returns all the assessments that are the latest (L). For example where (L) is latest: Workstation 1 | Workstation 2 | Workstation 3 ------------------------------------------------------ Assessment 1 (L) | Assessment 12 | Assessment 4 Assessment 2 | Assessment 41 | Assessment 15 (L) Assessment 3 | Assessment 99 (L) | Assessment 9 So the query set should return: Assessment 1, Assessment 99 and Assessment 15 I thought about doing a queryset of Workstations and then doing a for loop but that is too costly and spawns a LOT of queries. Second Problem (related to the first): I actually need a queryset of all the Answers associated with the latest assessments by workstation. I thought that I could break it down into several querysets in order to get it to work, but if there is a way to do this from one queryset please educate me! So once I have that queryset of Assessments from … -
Invalid Object Name django_migrations Using django-pyodbc-azure
I have a django project (myProject) with one django app (myApp). This project is run on a conda environment that includes django-pyodbc-azure to connect to SQL Server. The only changes made from the default setup are the following: Added myApp.apps.MyAppConfig to INSTALLED_APPS Changed DATABASES to this: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'hostname', 'NAME': 'databasename', 'USER': 'username', 'PASSWORD': 'password', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0' }, }, } When I attempt to run python manage.py runserver, the following error occurs: Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\pathtodjangoproject\myProject>activate myApp (myApp) C:\pathtodjangoproject\myProject>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000000000422A378> Traceback (most recent call last): File "C:\pathtoanaconda\anaconda\envs\myApp\lib\site-packages\django\db \backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\pathtoanaconda\anaconda\envs\myApp\lib\site-packages\sql_serve r\pyodbc\base.py", line 545, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42S02', "[42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'django_migrations'. (208) (SQLExecDirectW )") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\pathtoanaconda\anaconda\envs\myApp\lib\site-packages\django\ut ils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\pathtoanaconda\anaconda\envs\myApp\lib\site-packages\django\co re\management\commands\runserver.py", line 128, in inner_run self.check_migrations() File "C:\pathtoanaconda\anaconda\envs\myApp\lib\site-packages\django\co re\management\base.py", line 422, … -
How to join tables with multiple foreign keys and get filtered data in Django?
I have two models like this: class Question(models.Model): ques_id = models.IntegerField() test_id = models.ForeignKey('exam.Test') ques = models.TextField() class UserAnswer(models.Model): user = models.ForeignKey('exam.User') test_id = models.ForeignKey('exam.Test') ques_id=models.ForeignKey('exam.Question') user_ans = models.TextField() I need to execute this query to get the correct 'ques' field values. SELECT A.ques_id, B.ques, A.user_ans FROM useranswer A inner join question B on B.ques_id= A.ques_id and B.test_id =A.test_id WHERE A.user_id=1 and B.test_id='101' So far what I have done: UserAnswer.objects.filter(test_id=test_id, user_id=user_id).values('ques_id', 'ques_id__ques','user_ans') But it doesn't returning the right 'ques' field values because it doesn't considering the B.test_id =A.test_id section. How to retrieve it??? -
Data wrangling in Django
I am new to Django framework, but have managed to put together a website with views, models, templates and connecting it to my database (Postgresql) through Django REST framework. I am retrieving data from the database, but some of this data needs to be transformed (e.g. if positive = 1, if null = 0, or multiply all numbers by 100, and so forth). My question is, where can I do this in Django? Should this be done somehow in model.py, view.py or serializer.py? Apologies for the perhaps basic question, but I am struggling to figure this out. My model.py from django.db import models # Create your models here. class Test(models.Model): index = models.BigIntegerField(blank=True, null=True) hash_id = models.BigIntegerField(primary_key=True, blank=True) locality = models.TextField(blank=True, null=True) page = models.BigIntegerField(blank=True, null=True) latitude = models.FloatField(blank=True, null=True) longitude = models.FloatField(blank=True, null=True) ... serializer.py from rest_framework import serializers from rentlistings.models import Test class coordinatesSerializer(serializers.ModelSerializer): class Meta: model = Test fields = ('latitude', 'longitude') class propertiesSerializer(serializers.ModelSerializer): class Meta: model = Test fields = ('price', 'price', 'yields', 'num_floor', 'num_rooms', 'elevator', 'garage', 'balcony_size', 'garden_area', 'parking', 'terass', 'loggia', 'cellar', 'hash_id') class TestSerializer(serializers.Serializer): coordinates = coordinatesSerializer(many=True, read_only=True) properties = propertiesSerializer(many=True, read_only=True) class Meta: model = Test fields = ('coordinates', 'properties') views.py from rentlistings.models … -
Django tutorial 8 pip install Errno 1
Hello I am following the Django tutorial 8 but then i reach the point where i must pip install --user django-polls/dist/django-polls-0.1.tar.gz I get the error Command "python setup.py egg_info" failed with error code 1 in C:\Users\Name\AppData\Local\Temp\pip-simuco8v-build\ I have tried to update pip, setuptools, easyinstall but nothing is working i still get the error. Any help will be greatly appreciated. Thanks! -
Let desktop app based on Django, connect to remote DB is secure?
I have a desktop app that is built on top of Django framework and frozen to .exe using PyInstaller. The idea behind it, that an application should connect to remote database(PostgreSQL) on VPS. That VPS is serving static files for this application too. So here is the question - is that option secure? Can potential hackers connect to my database and make a mess in it or replace original DB with the fake one? If they can, how should I fix that?