Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allauth custom signup form error: 'Institution' object is not iterable
I'm probably missing something obvious here, but I'm getting the following error: 'Institution' object is not iterable It doesn't like this line in the code: user.institution = institution Here's the full SignupForm class for Django allauth: class SignupForm(forms.Form): first_name = forms.CharField( max_length=255, label="Your First Name", ) last_name = forms.CharField( max_length=255, label="Your Last Name", ) institution = forms.ModelChoiceField( label="Your Institution", queryset=Institution.objects.all(), empty_label="Other Institution Not Listed", ) def signup(self, request, user): from pprint import pprint user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.institution = self.cleaned_data['institution'] user.save() I've checked self.cleaned_data and it appears to be passing the institution correctly: {'email': 'blah@blah', 'first_name': 'John', 'institution': <Institution: Blah College>, 'last_name': 'Doe'} I'm using a custom user model and institution is a many-to-many: institution = models.ManyToManyField(Institution, db_index=True) Any ideas? What am I doing wrong here? -
Django - Multivalue Foreign Key
I have models as follows. The FormResponses model is used to create form. I want to store list of all the members who were missing in the event. Is something like models.ForeignKeyListField possible? There can be zero or more members missing class Member(models.Model): name = models.CharField("Name", max_length=200) ... class FormResponses(model.Model): missing_members = # array of members missing ... -
Django 1.10: login required middleware redirect loop
I'm writing a bit of middleware to effectively make @login_required on all pages. Unfortunately what I've got results in a redirect loop. The implementation is using "old" style middleware with 1.10 via MiddlewareMixin and process_request() hook in attempt to redirect to login page whenever the user is not authenticated. First, I'm using the default auth urls django.contrib.auth.urls. The docs say: This will include the following URL patterns: ^login/$ [name='login']... # main URLConf urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('django.contrib.auth.urls')), # https://docs.djangoproject.com/en/1.10/topics/auth/default/#module-django.contrib.auth.views ] Then here's the middleware (yes it's added to MIDDLEWARE in settings.py): from django.http import HttpResponseRedirect from django.utils.deprecation import MiddlewareMixin class LoginRequiredMiddleware(MiddlewareMixin): def process_request(self, request): if not request.user.is_authenticated(): return HttpResponseRedirect('/login/') The login page/functionality works fine when the my middleware isn't included, while including it results in every url causing ERR_TOO_MANY_REDIRECTS. What am I missing? Thanks. -
Django filtering with nested queries
I have a Django model that looks roughly like this class Equipment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100) class Tag(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True) tag_type = models.ForeignKey(TagType) equipment = models.ForeignKey(Equipment) name = models.CharField(max_length=100) class TagType(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) name = models.CharField(max_length=100, unique=True) class Meta: db_table = "tag_type" ordering = ["name"] TagTypes have names such as "Equipment" and "Load" "Equipment" tags can be "HVAC" or "Lighting" "Load" tags can be "Variable" or "Weather" I want to be able to filter to equipment that have a certain tag_type with a tag name. If I want equipment that have an HVAC tag with tag_type Equipment the following works: Equipment.objects.filter(tag__tag_type__name="Equipment", tag__name="HVAC") However, I believe that in this case the tag_type name and the tag aren't necessarily from the same tag. AKA tag__tag_type__name="Equipment" and tag__name="HVAC" might not be referring with the right values. Since there can be many different types of tags with diverse names, I want to make sure I'm filtering to the right one. Is there a way I can manage this? -
Django-hosts redirect form non-www to www
The site generates different URLs that all look like http://example.com/'somepath'. What I want to do is to redirect users from http://example.com/'somepath' to http://www.example.com/'somepath'. As I found out it's possible to do with django-hosts. As it's said in instructions I have the following in settings.py: ALLOWED_HOSTS = ['www.example.com', 'example.com'] INSTALLED_APPS = [ ..., 'django_hosts', ] MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', ... 'django_hosts.middleware.HostsResponseMiddleware', ] ROOT_URLCONF = 'appname.urls' ROOT_HOSTCONF = 'appname.hosts' DEFAULT_HOST = 'www' DEFAULT_REDIRECT_URL = "http://www.example.com" PARENT_HOST = "example.com" In hostsconf/urls: from django.conf.urls import url from .views import wildcard_redirect urlpatterns = [ url(r'^(?P<path>.*)', wildcard_redirect), ] In hostsconf/views: from django.conf import settings from django.http import HttpResponseRedirect DEFAULT_REDIRECT_URL = getattr(settings, "DEFAULT_REDIRECT_URL", "http://www.example.com") def wildcard_redirect(request, path=None): new_url = DEFAULT_REDIRECT_URL if path is not None: new_url = DEFAULT_REDIRECT_URL + "/" + path return HttpResponseRedirect(new_url) But looks like it doesn't work because if I go to http://example.com/'somepath' it returns "400 Bad Request" and http://www.example.com/'somepath' points to the correct destination. What am I doing wrong? -
Django AllAuth Warning
I'm new to Django and installed the AllAuth package and every seems to work fine. I followed different tutorials but each time I execute the command python manage.py runserver I receive a warning: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_CONTEXT_PROCESSORS. Here a part of my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'sekizai.context_processors.sekizai', ], }, }, ] TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.request", "django.contrib.auth.context_processors.auth", "allauth.account.context_processors.account", "allauth.socialaccount.context_processors.socialaccount", ) AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) Any help is appreciated. Regards -
How to get data from database without models in django?
I have been crawling around its doc but mostly it uses database with model. The problem is my database is too large and I don't want to create any models since it's legacy one, and I will have to call different tables dynamically, so I just want to pull data from it. Is that possible in django? -
Django: 'NoneType' object has no attribute 'score'
I'm having some trouble with an application I'm building, in that Django has been crashing consistently while I'm trying to compute an average score for items in a group. I have a model called Tree, a model called Species, and a model called Condition. I would like to show the average condition per species. The models are fairly basic and look like this: class Condition(models.Model): name = models.CharField(max_length=256) score = models.IntegerField() class Species(models.Model): name = models.CharField(max_length=256) class Tree(models.Model): species = models.ForeignKey(Species, related_name='trees_of_species') condition = models.ForeignKey(TreeCondition, related_name='trees_of_condition') then in my Views, I'm calling all the species, and send them to my template: def species_view(request): species_list = Species.objects.all() for species in species_list: species_condition_score = 0 for tree in species.trees_of_species.all(): species_condition_score += tree.condition.score species.average_condition = species_condition_score / species.trees_of_species.count() I'm getting the error ''NoneType' object has no attribute 'score'' However, in my template I have this: {% for species in species_list %} {% for tree in species.trees_of_species.all %} {% tree.condition.score %} {% endfor %} {% endfor %} And that prints out the list perfectly. If I change my views to this: def species_view(request): species_list = Species.objects.all() for species in species_list: species_condition_score = 0 for tree in species.trees_of_species.all(): if tree.condition: species_condition_score += tree.condition.score species.average_condition = … -
Error when using jinja2 as django template engine: cannot import name 'Environment'
I followed the recommendations in the django docs for enabling jinja2 as my template engine: https://docs.djangoproject.com/en/1.9/topics/templates/#django.template.backends.jinja2.Jinja2 But then I was getting an intermittent error from django: cannot import name 'Environment' I'm running on Windows 10, django 1.9 -
How to render a TemplateResponse in a Django unittest
I'm attempting to check the body of a response inside a Django unittest for sepcific text, by doing: response = client.post('/path/to/form', form_data) self.assertTrue('some text' in unicode(response, 'utf-8', 'ignore')) However, I get the error: TypeError: coercing to Unicode: need string or buffer, TemplateResponse found If I replace unicode() with str() it works fine, but that prevents me from looking for Unicode text. Why can't a TemplateResponse be casted to unicode like it can be for str? -
Django Registration form Verification Email
I originally started out by using django-registration to implement registration email verification. I've implemented a custom login/registration form to my django app to allow users to login with a unique email address. However, doing so, overrode my django-registration workflow. Ideally i would like to send the user a verification email after the user registers - instead of redirecting them to the login page. I'm not sure if this has something to do with the settings.py file or not. models.py class AccountUserManager(UserManager): def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields): """ Creates and saves a User with the given username, email and password. """ now = timezone.now() if not email: raise ValueError('The given username must be set') email = self.normalize_email(email) user = self.model(username=email, email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractUser): # now that we've abstracted this class we can add any # number of custom attribute to our user class # in later units we'll be adding things like payment details! objects = AccountUserManager() forms.py class UserRegistrationForm(UserCreationForm): email = forms.EmailField( label='', widget=forms.EmailInput(attrs={'placeholder': 'Email Address'}) ) password1 = forms.CharField( label='', widget=forms.PasswordInput(attrs={'placeholder': 'Password'}) ) password2 = forms.CharField( label='', widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}) ) class Meta: model = User fields … -
Django REST: custom styling
Got attuned to work on Django project that used Django Rest Framework. Current GUI uses default styling. I would like to re-style it. There is an article describing re-styling: http://www.django-rest-framework.org/topics/browsable-api/ However I don't understand where to add rest_framework folder with the api.html. My existing project doesn't contain any folder related to REST. "To customize the default style, create a template called rest_framework/api.html that extends from rest_framework/base.html" Where to put rest_framework? -
Django- how to copy elements from one view to another?
I have a Django project, and on one of the pages, I am displaying a report about some of the information in a database. The element in which I am displaying the report has a number of tabs- each one displaying a 'PDF-style' report about different elements in the database. I want to add the information that's being displayed on one of the tabs to another tab, but I'm not too sure how I'd do this. The view for the tab that has the information I want to copy to the other tab is defined with: def report_ccis(request, project_id): """ CCI items styled for pdf """ project = Project.objects.get(id=project_id) budget = get_current_budget(project_id) cci_total_exc = budget.cci_total_exc_vat_final cci_grouped_items = budget.cci_items.all().order_by('project_room', 'name') context = { 'project': project, 'cci_total_exc': cci_total_exc, 'cci_grouped_items': cci_grouped_items, 'webview': 1, } try: context['current_budget'] = project.budget_versions.get(current_marker=1) #For option name/date on top of pdfs except ObjectDoesNotExist: pass if request.GET.get('stage') == 'pd': """ Render post deposit homepage """ context['html'] = render_to_string('costing/report2_ccis.html', context) context['active_tab'] = '4' return render(request, 'costing/reports_post_deposit.html', context) else: """ Render pre deposit homepage """ context['html'] = render_to_string('costing/report_ccis.html', context) context['active_tab'] = '5' return render(request, 'costing/reports_pre_deposit.html', context) and the view for the tab on which I want to display this information is defined … -
Ontology creation and twitter monitoring django site
I have been researching many articles and many pages in the internet on how could this be possible, but basically i want to create a django site that gathers data from twitter, and output this in a form of a website. Difference is my site will have a search box and i wanted it to filter specific words, to handle such big data, i was hoping if owl (ontologies can help to categorize the data that i get and only return relevant tweets). for example: if i search a tweet 'eagle' specific to a bird, it will only return results that is relevant to a bird (eagle) and wont refer this with any other term. Can ontologies actually help ? i imagine i have to used sqllite to store the tweets, can owl ontologies be stored in SQL relational databases so i can query relevant words? Apologies, im new to this thing, and its something for a semantic web project. -
How to retrieve related name of Django model
Given models like: class Author(models.Model): name=models.CharField(max_length=30) class Article(models.Model): writer=models.ForeignKey(Author) How would you do: >>> get_related_name(Author, Article) 'article_set' -
Should nginx be packed into the same container as Django when deploying with Docker Swarm?
We are looking to move our current Nginx/Gunicorn/Django stack into Docker, and deploy it for high availability using Docker Swarm. One of the decisions we have been struggling with is whether or not to place Nginx in the same container as Gunicorn/Django. Here are the scenarios and how we view them: Scenario 1: Place Nginx in the app's container. This goes against the "each service has its own container" methodology, but it allows Nginx to communicate with Gunicorn directly through a unix socket instead of a port. This obviously isn't huge but it's worth mentioning. The main advantages are listed below. A potential disadvantage here is having extra overhead from too many Nginx instances (please weigh in on this). Scenario 2: Place Nginx in its own container. Though this follows the aforementioned methodology, it seems more flawed. In a Docker Swarm scenario, the distribution of Nginx and App containers will likely not be uniform. Some nodes may end up with more Nginx containers, while others have more app containers (and possibly even 0 Nginx containers). This means that Nginx would end up reverse-proxying an app container on a different host entirely. Now I'm sure Docker Swarm supports special configurations that … -
The image in Django app not working
I created a Python-Django web application.I set an album_logo field in models.py file and I tried to upload an image url through python shell using the code >>>from music.models import Album, Song >>>Album.objects.all() [] >>>a = Album(artist="Taylor Swift", album_title="Red", genre=" Country", album_logo="http://carywebdesigns.com/wp-content/uploads/2015/02/www2.jpg") >>>a.save() >>>a.artist 'Taylor Swift' >>>a.album_title 'Red' >>>a.id 1 >>>a.pk 1 Models.py from django.db import models # Create your models here. class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) def __str__(self): return self.album_title + ' - ' + self.artist And I run this codes using python manage.py runserver,I got the correct answer.But the image was not loaded.How can I solve this problem.Please help me.Thanks in advance.. -
Where to put Textming function in Django and Show it's output.as Html File?
I am beginner in django, i am trying to make a django app which will take a pdf file as input from the user through file uploader in frontend, make it a file object, I have a python text mining code in python with will use this file object and print some output I want to show this out put as a web page output I am able to do 1st 3 steps I am having problem where to put the text mining python code in django and take it's output and show as a html output my python textmining code import sys sys.path.append('D:\Python\pdfminer') sys.path.append('D:\Python\chardet') import pdfminer import chardet from io import StringIO sys.path.append('D:\Python\pdfplumber-master') import pdfplumber import os os.getcwd() os.chdir('D:/') with pdfplumber.open("UP-048215-0051_Data_cisco_60_1.pdf") as pdf: first_page = pdf.pages[0] print(first_page.chars[0]) table_crop = first_page.crop((30, 240, 556, 660)) //to print as text table = table_crop.extract_text(x_tolerance=2) print(table) //to print as table table = table_crop.extract_table(v="gutters",h="gutters",x_tolerance=1) for row in table[:15]: print(row) Model.py from django.db import models class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=500, blank=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(Picture, … -
Python Django обрезает ответ [on hold]
Создал простенькое приложение на Django на Ubuntu, views.py from django.shortcuts import render import json import psycopg2 import csv from django.http import HttpResponse from ratelimit.decorators import ratelimit def create_connection(): return psycopg2.connect(database="data",user="ag",host="localhost",port=5432,password='пароль') def execute_query(query, parameters): with create_connection() as connection: result = [] cursor = connection.cursor() cursor.execute(query, parameters) for row in cursor: result.append(row) for i in range(len(result)): result[i] = list(result[i]) for j in range(len(result[i])): result[i][j] = result[i][j] if result[i][j] else "" return result @ratelimit(key='ip', rate='10/m') def to_csv(request): j_body = json.loads(request.GET.get('data', '')) query = j_body['query'] print(query) print("****************************************************************") parameters = j_body['params'] headers = j_body['headers'] rows = execute_query(query, parameters) response = HttpResponse(content_type='text_csv') response['Content-Disposition'] = 'attachment; filename="result.csv"' writer = csv.writer(response) writer.writerow(headers) writer.writerows(rows) return response В общем цель данного приложения - получать откуда-то sql запрос и отвечать csv. Csv может быть на несколько сотен тысяч строк и весить более 200 мб. Проблема в том, что мой csv в ответе обрезается до 696 кб (вообще вне зависимости от запроса и данных в нём). Хотя на другом хостинге (heroku) из того же скл получается большой файл. Да и так видно, что csv обрезанный В чем может быть проблема? -
How can I add dynamic variable in the URL which being used inside requests.get()?
I would like to add dynamic variable in the below URL- book_id = 33327 resp_data = requests.get('http://example.com/book_id') How can achieve this in Django 1.9.6 (Python 2.7)? Thanks in advance! -
Linking a django docker container to a mysql container
I am trying to build a Docker container for a Django app that uses Mysql as database. From what I have read, the easiest way to do this, is by using docker-compose.yml to link 2 containers. I am assuming that my dockerfile for the django app works, because I tested it with sqlite3 and it worked. The issue that I am having is when I try to use mysql as the database. After starting up the 2 containers with the docker-compose up command (for the Mysql container I am using a ready image from the dockerhub, which is image: mysql/mysql-server:5.7 and under environment I have declared the database name, user name & password), I get 0 errors, however, as soon as I try to enter 127.0.0.1 and log as the superuser I get a 504 Timed-Out error. After a decent amount of time, I found out that the django app is not connecting to the mysql container. I entered the mysql container and after using the command SHOW DATABASES;, I saw that the database is there, however, after typing SELECT USER();, I did not end up seeing my username in the table. After trying to create it, I received the … -
Django CharField with no max length
I have a frontend that will be sending bas64 images, I will put those very large strings on a variable and send it to a form. What kind of FormField can I use? The regular CharFields need a max_length. Since it is a very large string, I don't know the length it could have. -
How to remove a default value function in Django
In a comment to this question answer I asked how to remove a field with a default value function. To sum up, the example code is: def get_deadline(): return datetime.today() + timedelta(days=20) class Bill(models.Model): name = models.CharField(max_length=50) customer = models.ForeignKey(User, related_name='bills') date = models.DateField(default=datetime.today) deadline = models.DateField(default=get_deadline) and my question to the code is: How do you remove the deadline field again while also deleting the get_deadline function? I have removed a field with a function for a default value, but now Django crashes on startup after removing the function. I could manually edit the migration, which would be ok in this case, but what if you simply changed the default function, and wanted to remove the old function? I ended up removing the default part of the migration that referred to it, but how do you remove it nicely? The only way I can think of is to squash the migrations, such that the migration using the function disappears, but that is not always an option. -
limit choices of manytomanyfield to a foreginkey
let's say i have these classes : models.py class Parent(models.Model): title = models.CharField(max_length=250) class Child(models.Model): parent = models.ForeignKey(Parent) title = models.CharField(max_length=250) class Family(models.Model): title = models.CharField(max_length=250) parent = models.ForeignKey(Parent) child = models.ManyToManyField(Child) the problem with this code the family form shows all the "Child" objects. I need to show "Child" objects only if the Child is related to "Parent" objects in the family form. if there's a way not to use manytomanyfield i am open to that too.. any idea? -
Django and Celery - key error at checking if GroupResult ready
I want to check if my task group is ready. If I do it inside celery task, it works fine: from time import sleep from celery import task, group from celery.result import GroupResult @task def a(): sleep(10) @task def b(): c = group(a.si())() c.save() saved_result = GroupResult.restore(c.id) print saved_result.ready() b.apply_async() However, it doesn't work inside my Django view. task_result = GroupResult.restore(my_hash) print type(task_result) if task_result.ready(): # this throws an error print 'ready!' Error: if task_result.ready(): File "/home/kam/project1_env/local/lib/python2.7/site-packages/celery/result.py", line 259, in ready return self.state in self.backend.READY_STATES File "/home/kam/project1_env/local/lib/python2.7/site-packages/celery/result.py", line 396, in state return self._get_task_meta()['status'] File "/home/kam/project1_env/local/lib/python2.7/site-packages/celery/result.py", line 341, in _get_task_meta return self._maybe_set_cache(self.backend.get_task_meta(self.id)) File "/home/kam/project1_env/local/lib/python2.7/site-packages/celery/result.py", line 332, in _maybe_set_cache state = meta['status'] KeyError: 'status' I'm using Redis as backend. My celery settings: BROKER_URL = 'redis://127.0.0.1:6379/1' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/1' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json'