Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ckeditor - Django
I am trying to figure out how to customize the Ckeditor text box in my form. I have installed CKeditor locally and it works fine when I run it locally. When I try to run it from the CDN, I can't figure out how to customize my textarea. It will display fine using the CDN, but it's only the text area, no functions for the text area. I've spent the last two days looking for an answer but nothing seems to work. My HTML form looks like this: <div class="spacer1"> <label class="label6">Roster</label> <textarea class="bushes"> {{ form.procedure }} </textarea> When I run my app, it is just showing me the django-ckeditor-widget HTML in the textarea. As shown below: <div class="django-ckeditor-widget" data-field-id="id_procedure" style="display: inline-block;"> <textarea cols="40" id="id_procedure" maxlength="2000" name="procedure" rows="10" required data-processed="0" data-config="{"skin": "moono-lisa", "toolbar_Basic": [["Source", "-", "Bold", "Italic"]], "toolbar_Full": [["Styles", "Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker", "Undo", "Redo"], ["Link", "Unlink", "Anchor"], ["Image", "Flash", "Table", "HorizontalRule"], ["TextColor", "BGColor"], ["Smiley", "SpecialChar"], ["Source"]], "toolbar": "Full", "height": 291, "width": 835, "filebrowserWindowWidth": 940, "filebrowserWindowHeight": 725, "language": "en-us"}" data-external-plugin-resources="[]" data-id="id_procedure" data-type="ckeditortype"> If I try to display the form in my HTML as form.as_p, it works fine, when I try to customize this portion of my django form, … -
How can I connect models.py to .html file to store emails in database?
I'm making a practice website using Django and I love it, especially the sqlite database that's built into it. In my simple program, I'm trying to make a text field appear, which it does, so that the upon the user typing in their email address and hitting submit, that email address goes directly into the database. I know how to operate the database, I just need to know how to connect them together so I can see their email address in the database when they hit Submit. Here's basic.html file: {% extends "personal/header.html" %} {% block content %} <style type="text/css"> h1 { color: #2e6da4; font-family: Chalkboard; } .text { text-align: center; } </style> {% for c in content %} <h1>{{c}}</h1> <div class="form-group"> <label for="email" class="text">Email address:</label> <input type="email" class="form-control" id="email"> <button type="submit" class="btn btn-default">Submit</button> </div> {% endfor %} {% endblock %} Here's models.py: from django.db import models class Email(models.Model): email = models.CharField(max_length=140) def __str__(self): return self.email -
Why am I getting this Exception Value in Django's csrf.py file?
I have a Django application whose purpose is to take user input and use it to update a database of drug compounds. A particular function of this application is fixing the names of compounds. One of my requests seems to be having an error. Why am I getting this error, and what should I do so I don't have this problem? I'm using Django 1.11.2. Traceback: File "/Users/davidmaness/development/fim_db/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Users/davidmaness/development/fim_db/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/davidmaness/development/fim_db/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/davidmaness/development/fim_db/env/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Users/davidmaness/development/fim_db/env/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/davidmaness/development/fim_db/fim_app/api.py" in handle_request 406. new_compound_name File "/Users/davidmaness/development/fim_db/env/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 145. result = middleware.process_view(request, view_func, args, kwargs) File "/Users/davidmaness/development/fim_db/env/lib/python3.6/site-packages/django/middleware/csrf.py" in process_view 168. cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME] Exception Type: AttributeError at /update_compound_name/ Exception Value: 'int' object has no attribute 'COOKIES' Request information: USER: b3llydrum GET: No GET data POST: csrfmiddlewaretoken = 'bTdZkcrKRGzdxEwoTucilzykEIqhC7HUVnTG9p5uHSqqzAcwxwN2Wcwj79GEEWVy' compound_id = '5' new_name = "'diabetes education / management' test" status_id = '1' add_status = 'true' FILES: No FILES data COOKIES: _ga = 'GA1.1.2108053191.1485202736' username-localhost-8888 = '2|1:0|10:1499796651|23:username-localhost-8888|44:YzNkNjk4YTk4ZDVkNDc2NDkzNTZkZmZkODIxZjI2Yzk=|8c0a537caca3f335d9000c281ffb35dd3cb28d0b8b412e4d37736e6a98c42900' sessionid = '11iju6gzkx3zgrjadmy8tybh8al9nw0s' csrftoken = 'bTdZkcrKRGzdxEwoTucilzykEIqhC7HUVnTG9p5uHSqqzAcwxwN2Wcwj79GEEWVy' Here's what's causing the error. … -
Can I get or set django extends templates in middleware?
So I have a template like this {% extends "exemple.html" %} In django middleware I have any params in process_template_response(), but I do know if this params has in this response, I want get and set this string in middleware "example.html" I want get to check before set, I searched but not get anything about this. Can I get this params? thanks. -
Pgbouncer closing connections
I recently set up pgbouncer for connection pooling. My pgbouncer.ini file contains [databases] mydb = host=localhost port=5432 user=user dbname=mydb [pgbouncer] auth_type = any auth_file = /etc/pgbouncer/users.txt listen_addr = 127.0.0.1 listen_port = 6432 pool_mode = session server_reset_query = DISCARD ALL ; total number of clients that can connect max_client_conn = 100 default_pool_size = 20 I use Django to hit pgbouncer with the following config DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '6432', }, } when I run the app everything seems to work fine. But in the pgbouncer logging I get the following logs, which happen repeatedly and often. 2017-08-08 14:36:25.626 1215 WARNING tune_socket(11) failed: Invalid argument 2017-08-08 14:36:25.626 1215 LOG C-0x7ff2d081b590: (nodb)/(nouser)@unix:6432 closing because: client unexpected eof (age=0) I have no idea what this refers to. Could this be anything insidious? Have I messed up something in the config? -
How does Django understand the difference between slug and id in view functions?
I'm new to Django framework and have some troubles with its view functions and the arguments it accepts. For example, consider the following view function: def product-list(request, category_slug=None): categories = Category.objects.all() products = Product.objects.filter(not-finished=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) My problem is that: 1. How does Django understand that category_slug which is passed to this function is a slug and not an id? 2. If the function had 3 arguments like def product-list(request, id, category_slug): how would it know that the second argument is id and the last one is the slug. Thank you very much. -
Django media file path is incorrect, missing a directory
Currently using Django 1.9. Image files in my model are uploading properly to project\media\FILEPATH.jpg However, images are attempting to be displayed using the filepath without \media. For example, when I go to my localhost http://127.0.0.1:8000/media/FILEPATH.jpg in my browser, I get a 404 because Django's get request is looking for: project\FILEPATH.jpg How do I get django to serve my media files properly with \media\? More information if it may be of any use: settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.dirname(os.path.join(BASE_DIR, 'media')) model: image = models.ImageField(upload_to='media', blank='true') project urls.py I have the following after urlpatterns as per the documentation: static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thank you for any help! -
Django won't display textfield from model
I have a login system where you need to be logged in to submit a new post. My "New Post" page/form work fine and the content the user submits is properly posted in the database, how when it comes to displaying that content on the home page only the title and subtitle are shown (which are Charfields) and no the body text of the post (which is a text field). inde.html {% extends "blog/base.html" %} {% block body_block %} <div class="left"> {% if userposts %} {% for posts in userposts %} <div class="front-post"> <h2 class="post-title">{{ posts.post_title }}</h2> <h3 class="post-sub-title">{{ posts.post_sub_title }}</h3> <p class="post-author">{{ post.post_author }}</p> <p class="post-date">{{ post.post_date }}</p> <p class="post-body">{{ post.post_body }}</p> </div> {% endfor %} {% endif %} </div> <div class="right"> <p>SIDE BAR</p> </div> {% endblock %} views.py from django.shortcuts import render from blog.forms import UserForm,UserProfileInfoForm,AddPost from blog.models import UserPosts from django.contrib.auth import authenticate,login,logout from django.http import HttpResponseRedirect,HttpResponse from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required # Create your views here. def index(request): post_list = UserPosts.objects.order_by('post_date') post_dict = {'userposts':post_list} return render(request, 'blog/index.html',context=post_dict) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics',blank='True') def … -
How to read from txt file to display a chart
Hello i have this html to display chart but i don't know how to use it to display data from txt file. Please i need your help . <html> <div id="chart_div" style="width: 100%; height: 500px;"></div> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["corechart"]}); google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Date', 'Y1', 'Y2'], ['2004', 1000, 400], ['2005', 1170, 460], ['2006', 660, 1120], ['2007', 1030, 540] ]); var options = { colors: ['#000000', '#00FF00'] }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </html> My txt file is very big similar to : 20160413,100000.0,100000.0 20160414,100017.287579,98685.5322684 20160415,99918.8444214,99054.1977814 20160418,100572.410945,100190.134483 20160419,100882.626944,101014.591377 20160420,100959.460628,100361.830561.... And i need to show the coordinates when i click on each point on the graph. Your help is much appreciated. -
How to add a comment form in a DetailView in Django?
I'm trying to add a comment form in a DetailView in Django and I don't know how to approach it. I've been able to do it with a function based view but I don't know how to start using a class based view. My views.py for the DetailView: class BusinesDetaiView(DetailView): queryset = Business.objects.all() Any suggestions? Thanks! -
Django, image upload error with aws s3 bucket
I have configured a django app to elasticbeanstalk and s3 bucket. But when I added an image with file field, server throws server error-500. So I changed the file field to image field and installed pillow, this time the error is failed to deploy application and error log shows File "/tmp/pip-build-8q5oqqgj/Pillow/setup.py", line 566, in build_extensions raise RequiredDependencyException(f) main.RequiredDependencyException: jpeg How I can solve this? Thanks.. -
Display google recpatcha at the end of the form django-allauth app
I am creating a signup form using django(1.10) allauth app. I have installed django-recaptcha app from - https://github.com/praekelt/django-recaptcha The captcha is working but it is showing after the field 'Organisation' as I am calling the module after 'Organisation' field. Is there any way so that the field displays at the end after password field. Forms.py from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Div, Field from ajax_select.fields import AutoCompleteSelectField, AutoCompleteField from phonenumber_field.formfields import PhoneNumberField from . import models from captcha.fields import ReCaptchaField class SignUpForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) phone_number = PhoneNumberField(label=_("Phone (Please state your country code eg. +44)")) organisation = forms.CharField(max_length=50) captcha = ReCaptchaField(attrs={'theme' : 'clean'}) Screenshot -- The captcha needs to put after 'password again' field. Do I need to create sub class or something like that? Any help is highly appreciated. -
What is the best storage data type in python for a request response cycle? Lists ,Dicts or something else?
I know that using a data type depends on the situation. But just for informational purposes which do you consider the best storage data type in python, especially during a web request. Please explain based on the response time as well as usability and environment. -
Django formset validation
Even though the fields are set to empty_permitted as False. But even if valid data is entered in the fields still getting error message in formset.errors as "This field is required". Following are the code snippets for forms, formset, and view methods. class QuestionUploadModelForm(forms.ModelForm): class Meta: model = Question exclude = ('question_module', 'difficulty') class RequiredFormSet(BaseFormSet): def clean(self): if any(self.errors): return def total_form_count(self): """Returns the total number of forms in this FormSet.""" if self.data or self.files: return self.management_form.cleaned_data[TOTAL_FORM_COUNT] else: if self.initial_form_count() > 0: total_forms = self.initial_form_count() else: total_forms = self.initial_form_count() + self.extra if total_forms > self.max_num > 0: total_forms = self.max_num return total_forms def __init__(self, *args, **kwargs): self.prefix = "question" super(RequiredFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False class ChoicesForm(forms.Form): choice = forms.CharField(max_length="100") choice_form_set = formset_factory(ChoicesForm, max_num=6,validate_max=True, formset=RequiredFormSet, extra=2) def render_page_form_formset(request, form, formset, prefix, page_title, template_name, parameters=None): if parameters is None: parameters = {} parameters['form'] = form(request.GET) parameters['formset'] = formset(prefix=prefix) parameters['page_title'] = page_title return render( request, template_name, parameters ) class AddSingleQuestionView(VerificationRequiredMixin, View): template_name = "question_addition/add_single.html" form = QuestionUploadModelForm formset = choice_form_set prefix = "choice" page_title = "Add Single Choice Question" def get(self, request, qb_id): print("get qb add view form") try: qb = QuestionBank.objects.get(id=qb_id) except QuestionBank.DoesNotExist: raise Http404("Question Bank doesn't … -
Django URLs ignore first path element
Say I have a URL: http://Localhost/ctp/ The part that reads ctp will be used to identify what version of a site someone wants to look at and I want Django to essentially ignore it and treat this as the base URL. However there could be any number of these identifiers so I can't just add ^ctp/ to the start of all of the URL patterns. Ideas appreciated on how to implement this. -
Setting up SQS with Celery (multiple queues)
Can anyone give me a very thorough walkthrough of setting up django (1.11) celery (4.0) to work with SQS? A lot of the info I found is outdated (from 2011 etc.) and most of it isn't cohesive. I didn't find a guide for setting up multiple queues / workers with SQS. My questions on below code: Are my queues setup right from using Broadcast etc in celery.py Why is json set for the content / serializers in the guide I used in settings.py There's a discord between the "default queue name" for SQS_QUEUE_NAME and the queues I want to make in celery.py. How do I rectify this? Essentially I want the two queues listed below in celery.py for separate workers / servers which will be processing intensive web scraping tasks. One is periodic (every week upwards of thousands of things to process) the other isn't and would be processed as forms are submitted by users. Here's what I've got so far.... celery.py from celery import Celery from kombu.common import Broadcast from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my app name.settings') app = Celery('my celery app name') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.task_queues = ( Broadcast('first queue'), Broadcast('second queue') ) app.conf.task_routes = { 'my first … -
Django: Two types of users logged in at same time
I have two applications in Django (one for admin and one for regular users). I want to allow the admin user to login in admin panel and also login in the home page as regular user (two different users with different credentials). I know that the session is saved as a cookie, so my best guess is that I have to use a different SESSION_COOKIE_NAME in each app, but I don't know if this is the best approach. How can I set different login sessions for each app?. -
Django REGEX --How To Replace %20 In URL?
I'm trying to create some nice looking permalinks for my DJANGO site. Specifically for a product page, i want it to appear in browswer as product/product-title so if I have a product with the title of "Free $20 Coupon With Purchase" the permalink would show as product/free-$20-coupon-with-purchase my url is as follows: url(r'^(?P<slug>.*)/$', product_by_detail, name='product_detail') but in the browser the URL is appearing as product/free%20$20%20Salad%20Coupon%20With%20Purchase i know the %20 represents the space, but is there something i can do in the regex to replace the %20 with a '-' character? -
How to use two frameworks for a single project?
I want to crawl the web contents from Scrapy framework and display that data with django. How can I do that? -
Django export ForeignKey
I have the following models: #models.py class Authors(models.Model): name = models.CharField(max_length=50) ... class Stories(models.Model): author = models.ForeignKey(Authors) ... class Book(models.Model): story = models.ForeignKey(Stories) ... Every Book has Stories and every story has an Author. I want to export the Book model, with an Author row using django-import-export. From the documentation, I saw that I can use the ForeignKeyWidget, so I should have something like this as a resource: class BookResource(resources.ModelResource): stories_author = fields.Field(column_name=_('Stories Author'),attribute='stories',widget=widgets.ForeignKeyWidget(Stories, 'author')) The problem with this is that I would be trying to export a noniterable object and after going through the whole documentation, I did not end up finding a solution to this. -
django models field factory
I am trying to do something like this: class User(models.Model): @staticmethod def NameField(): return models.CharField(max_length=30, null=True) name = NameField.__get__(None, object) And when I create instance of User, passing some name to the constructor python throws an error: TypeError: 'name' is an invalid keyword argument for this function What is going on? How I can make factories for model fields? -
django-cors-headers stop working for Django 1.6.11
I'm currently using Angular4 with django-nonrel as the backend. Got the CORS error at the beginning and installed django-cors-headers to give django support for CORS. I had to install version 1.1.0 because django-nonrel supports up to django 1.6.11. Everything was working perfectly so far for several weeks, but after I turned off my laptop today I started getting the CORS error again. Django ConnectionFailure: [Errno 10061] No connection could be made because the target machine actively refused it Angular XMLHttpRequest cannot load http://127.0.0.1:8000/pgla/project_list. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:4200' is therefore not allowed access. The response had HTTP status code 500 I verify the installing instructions for the django-cors-headers module and everything is correct. Here are my settings: MIDDLEWARE_CLASSES = ( ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ) CORS_ORIGIN_ALLOW_ALL = True And here is the hearder paremeter for Angular: new Headers({'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'}), Any help will be much appreciated. Thanks in advanced. -
How to display objects in a drop down list (django)?
python=2.7, django=1.11.13 In my html I am not able to display my condition choices from my models.py When filling the form, the user is not able to choose a condition because they are not displayed. models.py class Books(models.Model): book_name = models.CharField(max_length=100) book_condition = models.ForeignKey('Condition') def __unicode__(self): return self.book_name class Condition(models.Model): NEW = 'new' USED = 'used' COLLECTIBLE = 'collectible' CONDITION_CHOICES = ( (NEW, 'New'), (USED, 'Used'), (COLLECTIBLE, 'collectible'), ) book = models.ForeignKey(Books) condition = models.CharField(max_length=10, choices=CONDITION_CHOICES) def __unicode__(self): return self.condition views.py def add_book(request): if request.method == 'GET': context = { 'form': BookForm() } if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): form.save() context = { 'form': form, } return render(request, 'add_book_form.html', context=context) add_book_form.html {% extends 'base.html' %} {% block body %} <h3>Add Book </h3> <form action="" method="post"> {% csrf_token %} {{ form}} <br/> <input class="button" type="submit" value="Submit"/> </form> {% endblock %} -
Authenticating against OpenID in Django 1.9
I installed django-openid-auth and used the suggested configuration. INSTALLED_APPS = ( ... 'django_openid_auth', ) AUTHENTICATION_BACKENDS = ( # 'django_auth_ldap.backend.LDAPBackend', 'django_openid_auth.auth.OpenIDBackend', 'django.contrib.auth.backends.ModelBackend', ) OPENID_CREATE_USERS = True OPENID_UPDATE_DETAILS_FROM_SREG = True SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' OPENID_VALID_VERIFICATION_SCHEMES = { None: (), } OPENID_SSO_SERVER_URL = 'https://some_wso2_server:443/' I am not sure whether I missed something in the configuration, but I get the following error: OpenID failed OpenID discovery error: Error fetching XRDS document: (60, 'SSL certificate problem: unable to get local issuer certificate') Googling the error didn't turn up much. By someone's suggestion I grabbed a certificate from the server and installed it in the browser (Chrome) and also in Windows (probably shouldn't have), but I still get the same error. The server has ClientId and ClientSecret, but I have no clue as to how I could pass those with OpenId. With other plugins from django-social-auth, for example, these can be set in settings.py, but OpenId doesn't seem to support them. Any suggestions? (bear in mind I have almost ZERO experience with SSL, so details are welcome) -
Send email to any receiver django
I used data from class Create_order and I would like to send email to the customer . He write his email address and get the message with his Name and Surname . views.py class Create_order (CreateView): template_name ='games/create.html' model= Order fields = ['person_name','person_surname','street','city','email_order'] def post(self, request, pk): form = self.get_form() if form.is_valid(): order = form.save() order.game_id = int(pk) order.save() send_mail( 'Zamówienie {}'.format(order.pk), 'Witaj {}'.format (order.person_name,order.person_surname), 'luke.rudzinski@gmail.com', ['email_order'], ) settings.py ALLOWED_HOSTS = [] EMAIL_HOST ='smtp.gmail.com' EMAIL_HOST_USER ='luke.rudzinski@gmail.com' EMAIL_HOST_PASSWORD = '*****' EMAIL_PORT = 587 EMAIL_USE_TLS = True I my form can't send email to any receiver Image with error