Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send request from chrome extension to django
I am developing a chrome extension having three links login,registration,Sign out. This is my html page in chrome extension <form name="form1" method="POST"> <p><a href="https://localhost:8000/login.html class="login" id="Login">Login!</a></p> <p><a href="#" class="text" id="Registration">Registration!</a></p> <p><a class="text" id="Signout">SignOut!</a></p> </form> Manifest file: "background": { "scripts": ["popup.js"], "persistent": false }, "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html" }, "externally_connectable": { "matches": ["*://localhost:*/"] }, "permissions": [ "http://localhost:8000/", "tabs", "contextMenus", "<all_urls>", "storage" ] Popup.js: function login() { chrome.tabs.executeScript({ file: 'contentscript.js' }); } document.getElementById('login').addEventListener('click', login); where i have developed login and registration pages in Django frame work and i have successfully registered and login in local host Django .But when I click a registration button in chrome extension i have to open Django registration page which is in local server. For this how to send request from chrome extension to Django and how to get request from chrome extension in Django. -
Django MsSQL FreeTDS - Nvarchar(max) Auto Truncates
I'm using Django that is connected to AWS' RDS MSSQL. So I'm to input very long texts, but they are generally longer than 4000 characters. In Django, this specific field is using TextField and the data type in MSSQL is nvarchar(max). So my question now is how can I configure and increase its max length. I've got the assumption that it's supposed to be infinite (of course it's not). Help is desperately needed. I've read about it briefly here: How to get entire VARCHAR(MAX) column with Python pypyodbc. However, I'm using RDS and I have no idea in doing this as at all. Thank you all in advanced! -
How I should set up my Django project tree in production
I've moved my Django repo from development onto my remote DigitalOcean server ready for production. My question is - where do I put my apps, manage.py etc? My current tree looks like this: path: /home/zorgan/project and the contents of the directory is: env manage.py static app So I imported app, which is my repo, from Bitbucket. This contains my code including manage.py etc. Do I use this manage.py or do I use the manage.py in the outer folder? Do I remove the app directory altogethor and simply put it's contents (all my apps) inside /home/zorgan/project next to env, static etc? Feedback appreciated. -
change value of selected RadioSelect field in django
How can i change the value of the selected choice rendered as RadioSelect field in django? ....... ---newbie Thanks... template <div class="row"><div class="boxed_content">Classification of Research<br> {% for rdo in form.classif_res %} <div class="form-check form-check-inline"> {{ rdo }} </div> {% endfor %} <input class="form-control" type="text" name="classif_other" id="res_classifcation" /> </div></div> the model field is a TextField with one of the choices named as "Others." what i want to do is whenever the user selects "Others" the data that will be saved is the value from the textbox in the template.... -
How to pass form value to view django 2
I need to pass form value to view to make fiter result by id. Here is my form <form class="form-horizontal rating-form" action="{% url 'stories:rating' %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="hidden" name="rating_value" id="rating_value" /> <input type="hidden" name="story" id="story_id" value="{{ story.story_id}}" /> </div> </form> In my urls.py I have, path('ratings', views.RatingView.as_view(), name='rating'), And in my views.py file I have, class RatingView(generic.ListView): template_name = 'stories/rating.html' context_object_name = 'rating_count'; def get_queryset(self): return Rating.objects.get(story_id=id).values('rating_value').annotate(total=Count('rating_value')) fields = ['rating_value', 'story'] I need to perform where story_id = id ( {{story.story_id}}) in query. How to get the post value inside get_queryset function? -
datetime.datetime(2017, 4, 6, 1, 44, 44, tzinfo=<UTC>) django
When i create my Model serializer with django-rest-framework and try to get from URL i got the next error 'unicode' object has no attribute 'tzinfo' But when i execute the shell of django a = Model.objects.all()[0:1] a[0].upload_date This is printed in shell datetime.datetime(2017, 4, 6, 1, 44, 44, tzinfo=) The field in the model upload_date = models.DateTimeField(blank=True, null=True) The serializer class ReportSerializer(serializers.ModelSerializer): class Meta: model = Reports fields = '__all__' I don't know how serialize this field -
Is possible handle a fail queue with django-rq
Im working with google´s api , sometimes this fail and throw a 500 (backenderror), but in django settings , im calling RQ_EXCEPTION_HANDLERS = ['path.to.my.handler'] as say RQ documentation, but they dont talk about how to requeue , like a try_catch if worker or job return an error. -
How To validate Formsets in Django?
I am new to Django FormSet, let say I have the form like follow. class PillarForm(ModelForm): class Meta: model = Pillar exclude = ("created_at", "updated_at", "is_active", "owner") PillarFormSet = formset_factory(PillarForm, validate_min=True) and my pillar model looks like follow class Pillar(models.Model): name = models.CharField(max_length=255) description = models.TextField(null=True) order = models.IntegerField() #SYSTEM FIELDS created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) report = models.ForeignKey(Report, on_delete=models.CASCADE) when my views look like follow def pillars_create(request, report_id): context = {} report = Report.objects.get(pk=report_id, is_active=True) form = PillarFormSet() if request.POST: form = PillarFormSet(request.POST) print(form.errors) return render(request, os.path.join(TEMPLATE_FOLDER, "create/index.html"), { 'report' : report, 'formset' : form }) but form doesn't showing the error messages for example name, order are required fields but it doesn't shows the error messages and form.is_valid is True, what mistake i made here. but if I create formset with fields max_fields, min_fields, 'validate_max' like it shows the message. PillarFormSet = formset_factory(PillarForm, max_num=5, min_num=4, validate_max=True, validate_min=True) -
Django Apache django.wsgi adjusting system path
I am having trouble determining why my django project is throwing an error when launched through apache. Everything runs fine however I am getting an import error for a library I have created. within django.wsgi I attempt the following. import sys sys.path.append('path/to/some/directory') This is added because I am trying to use source code from a library on my system that is not directly located within my django project. In my code, I try to import the library I added to my system path within django.wsgi. However, within my apache error.log, I am getting an import error for this above added module. What am I doing wrong? -
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_]+)\\/$']