Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django log work strange, no record?
I am using django's logging app to log my server about the order and payment. It's very strange that I found sometimes a order is placed but there is no log in my system, and the payment is success but my system didn't get the result, while most of the orders works normal and has right log infomation. It make me confused!!! Anybody have the same experience and found the answer??? -
'list' object has no attribute 'encode' when passing string to recipients list
I am having an issue with a Django app where I am attempting to perform send_mail using a Class Based View. Everytime I submit the form, I get this error: AttributeError at /contact/ 'list' object has no attribute 'encode'. Not sure what to do. views.py from django.shortcuts import render from django.http import HttpResponse from django.views.generic.edit import FormView from django.core.mail import send_mail from django.http import request from .forms import ContactForm def index(request): return render(request, "main/index.html") def about(request): return render(request, "main/about.html") def thanks(request): return render(request, "main/thanks.html") class ContactView(FormView): template_name = "main/contact.html" form_class = ContactForm success_url = '/thanks/' def form_valid(self, form): form.send_email() return super(ContactView, self).form_valid(form) Here is my ContactForm forms.py from django import forms from django.core.mail import send_mail class ContactForm(forms.Form): subject = forms.CharField(max_length=75) message = forms.CharField(widget=forms.Textarea) sender = forms.EmailField() def send_email(self): # Write some code for sending an email # pass mar = [] x = "email@icloud.com" mar.append(x.encode('ascii')) print(type(x)) send_mail( self.cleaned_data['subject'], self.cleaned_data['message'], self.cleaned_data.get('sender', 'to@mail.com' ), mar, fail_silently=False, ) -
Running Django in docker-compose
I have a problem starting a django project inside a docker container. My Dockerfile looks as follows: FROM python:2.7 ADD . /code WORKDIR /code RUN pip install -r requirements.txt EXPOSE 8000 The requirements.txt consists of the single line Django which install django successfully. My docker-compose.yml has the following content: version: '2' services: web: build: ./web command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" volumes: - ./web:/code To create a project I am calling: docker-compose run web python django-admin.py startproject web . which crashes with the following message: python: can't open file 'django-admin.py': [Errno 2] No such file or directory Also this docker-compose run web django-admin.py startproject web . crashes with ERROR: Cannot start service web: oci runtime error: container_linux.go:247: starting container process caused "exec: \"django-admin.py\": executable file not found in $PATH" It seems to me that there is an error in the $PATH when executing the container like this. When I use the interactive mode -it, I am able to call the django-admin from this folder. Is the PATH not set correctly or am I doing something else wrong here? The Dockerfile is in the directory web. -
Display all id for an object
Django automatically creates an id field as primary key. Now I need all id for a certain class. I thought I could use class.objects.all(id), but it is not working. Could anyone be able to tell me how to display all id for a certain class? -
There are errors when I install django by git?
I install django through 1.git clone git://github.com/django/django.git 2.pip install -e django/ I use ubuntu16.04. But some errors occur: Obtaining file:///home/leo/django Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/home/leo/django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 60, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /home/leo/django/ How to fix this? Thank you. -
Is Heroku blocking my local git commands?
So i've run a heroku create command on my django repo, and currently it is living on Heroku. What I didnt do prior was create my own local git repo. I run git init, create a .gitignore to filter out my pycharm ide files, all the fun stuff. I go to run git add . to add everything to the initial commit. Odd...it returns: [1] 4270 killed git add. So i run git add . again and get back this: fatal: Unable to create /Users/Panebianco/mjpanebianco/helloweb/.git/index.lock': File exists. "Another git process seems to be running in this repository, e.g. an editor opened by 'git commit'. Please make sure all processes are terminated then try again. If it still fails, a git process may have crashed in this repository earlier: remove the file manually to continue." So I go and destroy the file, run it again; same error. Removed the whole repo, repeated the process, still got the same message. Is Heroku running in the background where ps can't see it? -
Django filter - search with string with symbols
I used icontains for filtering data which equivalents to 'LIKE'. But it won't trigger filter for strings with other ASCII characters e.g. / , ' , & , etc. -
Django Registration Registration_form
I'm using Django Registration_redux templates for user registrations. I am wondering how does Django know where to go when user submits his registration when action is action="." ? {% extends "registration/registration_base.html" %} {% load i18n %} {% block title %}{% trans "Register for an account" %}{% endblock %} {% block content %} <form method="post" action=""> {% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans 'Submit' %}" /> </form> {% endblock %} {% comment %} **registration/registration_form.html** Used to show the form users will fill out to register. By default, has the following context: ``form`` The registration form. This will be an instance of some subclass of ``django.forms.Form``; consult `Django's forms documentation <http://docs.djangoproject.com/en/dev/topics/forms/>`_ for information on how to display this in a template. {% endcomment %} -
How can I apply I18N to the labels of a CheckboxSelectMultiple in Django?
Considering a Django application, I have to apply I18N to the values stored in "Area" table. The values of the field i18n_code points to msgid entries in my locale/en_US/LC_MESSAGES/django.po. As you can see in my code, Startup model has a ManyToMany field of Area. In my form, area is a CheckboxSelectMultiple widget. How can I, inside my form01.html (template) get the i18n_code, pass to {% trans area.i18n_code %} so I can get options rendered in proper language? I checked many questions relative to this subject... but I did not got some clean solution. Checkout the codes: models.py: @python_2_unicode_compatible class Area (models.Model): name = models.CharField(max_length = 200) i18n_code = models.CharField(max_length = 200) def __str__(self): return self.name @python_2_unicode_compatible class Startup (models.Model): name = models.CharField(max_length = 200) # ... areas = models.ManyToManyField(Area, verbose_name = 'Areas') def __str__(self): return self.name form01.html <div class="row linhaForm"> <div class="col-lg-4 legenda"> <b>{% trans 'FORM_1_LABEL_AREA' %}</b> <p>{% trans 'FORM_1_LABEL_AREA_DESCRIPTION' %}</p> </div> <div class="col-lg-8"> {% for area in form.areas %} <div class="checkbox"> {{area}} <-------------------- Here is my problem! </div> {% endfor %} </div> </div> forms.py from django.utils.translation import ugettext_lazy as _ class Step1Form(forms.ModelForm): class Meta: model = models.Startup fields = ['name', 'areas'] widgets = { 'areas': forms.CheckboxSelectMultiple(attrs={'onclick':'onAreaCheckHandler()'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), … -
Data always resets to original state on heroku free account after some time
I have deployed my django app into heroku free account.(first time) In my working environment I use SQLLite on Heroku I assume POstgres should work. However I am confused whats going on. So first of all the app is up and running the data that was in my SQLlite database is currently shows at my deployed app. Is it because my SQLLite DB was copied to heroku and this is what I actually see? Another issue that indicates somthing is wron with DB is that if I create superuser via terminal I cant log with it to my app. Another issue is that it looks data constantly restores to its original state after some time . I followed the instructions and this is what I have in my settings for DB DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) -
IPython.embed() didn't work in a TestCase class
Why import IPython IPython.embed() doesn't work in a TestCase class? Is there a way to bypass that 'rule'? Thanks! -
Deliver images in Django from a different path than from its ImageField.url property
I'm porting a web app from PHP (Codeigniter) to Python (powered by Django.) I already migrated the database and am now using Django models. I populated the database with images using Django's ImageField field and the images are in its proper folders under MEDIA_ROOT. I'm in development so I'm using Django's server to test the web app as I go and I can serve the images through image.url. image.url serves the image from: MEDIA_ROOT/folder/subfolder/numberImage_folder_subfolder.jpg But I need it to be served from MEDIA_ROOT/numberImage_folder_subfolder.jpg. In production I know I can serve the image using nginx's XSendFile or something like that. Django's server (runserver command) is very easy to use and gives me what I need at the moment. While in development, how can I deliver the image from the URL I require? Preferably using Django's server... Any help will be so much appreciated. -
django-libsass requires me to restart server
I setup django-libsass and after I save my sass changes and refresh browser page my changes are not reflected. After I restart the local server though I'm able to see the change. When I use plain css and javascript with django compressor, I'm able to see changes without restarting the server. Please advise how I can resolve this so no server restart is required. -
Django AttributeError: form object has no attribute x
I see many people have already encountered this error, but what I'm trying to do is specific and the answers to those other questions don't help me. I'm new to Django and I'm trying to make a form with first name, last name, email and password fields, and after the form is submitted, I want all of those to be written in a file. I do not have a User object, and I'm not actually trying to make a sign-in page, I just want to see how I can write stuff to a txt file. So, I did this, in urls.py: url(r'^file/$', views.employee, name='employee') Then in views.py: def employee(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): with open('employee.txt', 'w') as f: myfile = File(f) myfile.write('%s ... %s ... %s ... %s ' % form.first_name % form.last_name % form.email % form.password) return render(request, 'blog/employee_thanks.html') else: form = EmployeeForm return render(request, 'blog/employee.html', {'form': form}) so then I have an EmployeeForm in forms.py: class EmployeeForm(forms.Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput()) and the relevant html files are: employee.html: {% extends 'blog/base.html' %} {% block content %} <h1>Employee Sign-in</h1> <h3>Please sign in with your Credentials</h3> <form … -
Generating visual maps in web applications
For a component of my web application I need to generate visual maps somewhat similar to this http://i.imgur.com/FPBz5sB.jpg . I was wondering I could use in order to do this? Bit of background info, I'm using django and bootstrap. -
Pagination in a function-based view that employs a POST request
In a Django app I'm developing, I needed to gate off a certain feature based on time. This entailed users being able to write special messages for others to read, but only at the designated time. To manage its gating, I made the feature accessible via a POST request. Thus, when I needed it active, it'd only be available behind the visual element (button) tied to the form that made the said POST request. But once the button's hidden, the feature is effectively hidden with it, even if users hit the URL with a GET request. This feature's generated a lot of interest on my site. My problem is that I now need to paginate all the messages generated on the page. Everything is programmed behind if request.method == 'POST':. I'm dealing with a function-based view here. If I create pages via the Paginator class, I get to flip pages via GET requests - which wouldn't work in my case. I think I need to change the overall pattern I'm using to gate users. Can anyone suggest an alternative way to effectively gate off a feature from users from time to time? Or a tweak to my current method? Would … -
The shell didn't show up
In a Django project, I've created the tests.py file : from django.test import TestCase from .models import Cust from loanwolf.users.models import User from loanwolf.loans.utils import compute class ProductTestCase(TestCase): def calculationtest(self): user = User.objects.get(pk=200) loan = compute(user, {product_id: 1}) import IPython IPython.embed() self.assertEqual(Cust.product_type, 'Normal') self.assertEqual(Cust.amort, Decimal('440,00')) My problem is located when I'm trying to restart the server. It is supposed to show the shell, but nothing happened. Could anyone be able to help me at this point? -
Using nltk inside Django app
I am trying to use NLTK within a Django app that I'm creating and don't know how to go about achieving this. I have functions written in .py files, and want to use them inside my web app. How exactly can this be done? Thanks -
Django if else template tag queryset not right
I want to display follow button when the user is not following the project, and update the button once the user follows it. I tried using the following template tags but it was always returning true. Here is the model for projects people can follow, following includes a list of followers that currently following this project. class Team(models.Model): ... following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True) These are the template tags I tried, but it always return 'Follow'. {% if not request.user in user.followers.all %} <div class="progress-stats"> <a href="{% url 'teams:follow' team.id %}">Follow </a> </div> {% endif %} {% if request.user in user.followers.all %} <div class="progress-stats"> <a href="{% url 'teams:unfollow' team.id %}">Unfollow </a> </div> {% endif %} -
GEOSGeometry error creating polygon
I'm trying to create a polygon from coords but throws the next error: Error encountered checking Geometry returned from GEOS C function "GEOSWKTReader_read_r". its not works poly = GEOSGeometry('POLYGON((4.8371311 4.8371311, 4.8371311 4.8371311, 4.6857419 4.6857419, 4.6857419 4.6857419))') but it works poly = GEOSGeometry('POLYGON((4 4, 4 4, 4 4, 4 4))') ¿Some idea? -
Form uploads image to 'media' folder when it should upload to 'static'
In my model, I've specified the upload_to directory class Event(models.Model): image = models.ImageField(upload_to='event_image') and I was expecting the Form that is linked to the model to upload it to the same location, but it is uploaded to media. Here is my form: class EventForm(forms.ModelForm): image = forms.ImageField(label="Event Image", required=True) class Meta: model = Event Here are my setting for media and static roots: STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [STATIC_DIR, ] MEDIA_DIR = os.path.join(BASE_DIR, 'media') MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' How can I have the image in the form uploaded to 'static/event_image'? Thank you. -
Joining two querysets in Django based on common field
Imagine I have two querysets queryset 1: [ {'field_a': 12, 'field_b': 23}, {'field_a': 24, 'field_b': 35}, ] and queryset 2: [ {'field_a': 12, 'field_c': 32}, {'field_a': 24, 'field_c': 43}, ] My goal is to get the left join of these two querysets based on the common field (that is, field_a) so that the result looks like this: [ {'field_a': 12, 'field_b': 23, 'field_c': 32}, ] I googled it for 30 minutes, and now I am even in doubt that it's possible in Django. -
Redirect after login django registration redux
settings.py LOGIN_REDIRECT_URL = '/profile/create/' views.py def has_no_profile(user): # Receives the request.user object from user_passes_test # Note that you need to filter using model_field=value # Returns true if the user has no profile, false otherwise return not Profile.objects.filter(user=user).exists() @method_decorator(user_passes_test(has_no_profile, redirect_field_name=None), name='dispatch') class NewProfile(LoginRequiredMixin, CreateView): form_class = ProfileForm model = Profile queryset = Profile.objects.all() template_name = 'profile/profile_create.html' def get_form_kwargs(self): kwargs = super(NewProfile, self).get_form_kwargs() kwargs.update({'user': self.request.user}) kwargs.update({'slug': self.request.user.username}) return kwargs Code Explanation: i am using LOGIN_REDIRECT_URL to redirect the user to "/profile/create/" page. if the user does not have a profile associated to the user he will be able to create a profile. if the user has been already associated with a profile he will not be able to access "profile/create" page so the user should be directed to the page "/profile/view/" My Question is - now i am able to create only one profile for a user but if the user logs in for the second time the user should be automatically be redirected to "profile/view" what am i doing wrong? -
Django channels static files issue
I was trying my hands on this example for websockets in Django, https://github.com/jacobian/channels-example as I have intention to use it my production application as well which is hosted in Heroku, and using Whitenoise there. So, after cloning the above mentioned example, I did some tweaks using whitenoise, but now on first visit to the application through any browser (chrome or FF) the static files doesnt load and when I refresh again it loads static files, and in third load it again goes off and so on. Here is my settings file: import os import random import string import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) SECRET_KEY = os.environ.get("SECRET_KEY", "".join(random.choice(string.printable) for i in range(40))) DEBUG = os.environ.get("DEBUG", False) # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'chat', ) MIDDLEWARE_CLASSES = ( 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'chat.urls' TEMPLATES = ( { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'debug': DEBUG, }, }, ) # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': dj_database_url.config(default="postgres:///channels-example", conn_max_age=500) } AUTH_PASSWORD_VALIDATORS = ( { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { … -
Create dictionary from 2 lists, use in django template
I have 2 lists: year_month_day_list = ['2017-02-12', '2017-02-11', '2017-02-10', '2017-02-09'] filename_prefix_list = ['2017-02-12_11-45-59', '2017-02-12_11-35-05', '2017-02-10_11-00-52', '2017-02-11_10-59-23', '2017-02-09_09-12-09'] If I can grab all of the filenames that match their associated ymd: def filter_files(file_list, filter_param): return [f for f in file_list if f.startswith(filter_param)] for unique_day in year_month_day_list: files_for_day = sorted(filter_files( filename_prefix_list, unique_day), reverse=True) How can I create a dictionary that uses the unique_day as the key and the associated filenames for that day as the values? Output should be something like: dict = {'2017-02-12': ['2017-02-12_11-45-59', '2017-02-12_11-35-05'], '2017-02-10': ['2017-02-10_11-00-52']} Then, how can I use those in my template? Something like: <div class="thumbnail-row" id="thumbnail_row"> <div class="row-date"> <span>{{ unique_day }}</span> </div> <div class=""> <form action="{{ filename_prefix }}/video/" method="post"> {% csrf_token %} <input type="image" name="filename_prefix" value="{{ filename_prefix }}" src="{{ MEDIA_URL}}thumbnails/2017/02/{{ filename_prefix }}.jpg"> </form> </div> </div>