Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'ProgrammingError: relation "contacts_vendor" does not exist' for existing table
Background: I am upgrading an app from Django 1.4.22 to Django 1.7.11 as the first in several stepping stones to bring the implementation of the app out of the stone age and up to Django 1.10+. The first step to 1.7 was chosen because that is when the migrations infrastructure was implemented into the Django core (previously migrations were done with hand-written SQL and syncdb, plus some voodoo written before my time). This app has been in use for a long time and has a pre-existing User model under an app named 'users'. This has been updated to be listed as our AUTH_USER_MODEL with all the necessary changes to be compatible with that functionality. Another portion of the application is a 'contacts' app which contains a Vendor model (important parts copied below) that links to the User model as a record of who last updated the Vendor object. class Vendor(models.Model): title = models.CharField(max_length=64) address_1 = models.CharField(max_length=128, null=True, blank=True) address_2 = models.CharField(max_length=128, null=True, blank=True) city = models.CharField(max_length=64, null=True, blank=True) created = models.DateTimeField(default=datetime.now) updated = models.DateTimeField(null=True, blank=True) updated_by = models.ForeignKey('users.User', related_name='vendors') class Meta: app_label = 'contacts' There is an AppConfig for this 'contacts' app, as well as the 'users' app, and both … -
Django: view arguments after POST?
I call my "editFamily" view via an HttpResponseRedirect from somewhere else: return HttpResponseRedirect(reverse('editFamily', kwargs={'pk': family_id})) The corresponding url pattern looks like this: url(r'^editFamily/(?P<pk>[0-9]+)/$', views.editFamily, name='editFamily') And then finally there's my view: def editFamily(request, pk_): obj = models.Family.objects.all().filter(pk=pk_) if request.method == 'POST': form = forms.FamilyForm(request.POST, instance=obj) if form.is_valid(): form.save() else: form = forms.FamilyForm(instance=obj) return render(request, 'editFamily.html', {'form': form}) It takes the pk_, ends up in the else branch and serves my edit-html. But what happens after the viewer submits his data with respect to the argument pk_? Is pk_ missing when I'm coming from POST? Do I somehow have to make sure to pass that argument in my template? -
Python 3.5.2 error UndefinedValueError
My application is configured for use mysql, but when i try to run ./manage.py migrate this error ocours root@renato-VirtualBox:/home/renato/unb-alerta# ./manage.py migrate Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/renato/unb-alerta/venv/lib/python3.5/site- packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/renato/unb-alerta/venv/lib/python3.5/site- packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/home/renato/unb-alerta/venv/lib/python3.5/site- packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/renato/unb-alerta/venv/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/renato/unb-alerta/venv/lib/python3.5/site- packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/renato/unb- alerta/venv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/renato/unb-alerta/unb_alerta/settings.py", line 139, in <module> cast=db_url, File "/home/renato/unb-alerta/venv/lib/python3.5/site- packages/decouple.py", line 197, in __call__ return self.config(*args, **kwargs) File "/home/renato/unb-alerta/venv/lib/python3.5/site- packages/decouple.py", line 77, in __call__ return self.get(*args, **kwargs) File "/home/renato/unb-alerta/venv/lib/python3.5/site- packages/decouple.py", line 64, in get raise UndefinedValueError('%s option not found and default value was not defined.' % option) decouple.UndefinedValueError: DATABASE_URL option not found and default value was not defined. My .env have DATABASE_URL end my settings.py has this configuration DATABASES = { … -
Django: Unit test on-memory compiled code
I am working on a Django project that requires to save and execute fragments of python code. I just wondering how can I add some "unit tests" to that code, in order to check that it is working as we expect. Is there some library or methodology that I can implement to achieve this? Thanks. -
Django no module named http
,Hi guys I downloaded mod_wsgi-4.5.17 and tried to install it using ./configure --with-apxs=/usr/bin/apxs --with-python=/usr/bin/python3.4 sudo LD_RUN_PATH=/usr/lib64 make sudo make install In terminal > python > import django from django.http import HttpResponse and I get no error, but when I run it as a script > python djangoexample.py I get this: No module named http When I use this command: >>>>ldd /usr/lib64/httpd/modules/mod_wsgi.so linux-vdso.so.1 => (0x00007ffd5d916000) libpython3.4m.so.1.0 => /usr/lib64/libpython3.4m.so.1.0 (0x00007f044a067000) libpthread.so.0 => /usr/lib64/libpthread.so.0 (0x00007f0449e4a000) libdl.so.2 => /usr/lib64/libdl.so.2 (0x00007f0449c46000) libutil.so.1 => /usr/lib64/libutil.so.1 (0x00007f0449a43000) libm.so.6 => /usr/lib64/libm.so.6 (0x00007f0449741000) libc.so.6 => /usr/lib64/libc.so.6 (0x00007f044937f000) /lib64/ld-linux-x86-64.so.2 (0x00007f044a736000) But: >>>> ldd mod_wsgi.so ldd: ./mod_wsgi.so: No such file or directory Any suggestion? -
Django admindocs, strange behaviour
I've enabled the django admin docs, as reported from the official django documentation: HERE And there is my url structure: list_url_auth_patterns = [ url(r'^(?i)login_user/$', authentication.login_user, name="login_user"), url(r'^(?i)login/$', TemplateView.as_view(template_name='login.html'), name="login"), url(r'^(?i)logout_user/$', authentication.logout_user, name="logout_user"), url(r'^(?i)render_template_esempio/$', vista_esempio.render_template_esempio, name='render_template_esempio'), url(r'^(?i)signup_user/$', authentication.signup_user, name="signup_user"), url(r'^(?i)signup/$', TemplateView.as_view(template_name='signup.html'), name="signup"), ] # List url for insert/manage orders list_url_order_manager = [ #Generic urls url(r'^(?i)insert_order/(?P<order_id>\d+)/', orders.render_order_manager, name='render_order_manager'), url(r'^(?i)insert_order/$', orders.render_order_manager, name='render_order_manager'), ] But when i'll go to the Django documentation page, in the views, i see: Empty namespace (why? how i can set the namespace of my app?) ImportError pages where they have into the description below the view name (as you can see in photo...in fact: the first link does not work and shows the ImportError of a custom decorator that it's not a package, but the remaining two links works properly) Why? how i can fix that? Thanks -
HTTP 405 Method Not Allowed Error in Django
I have a file called calculator.py in which there is a function called calc() which has a method called calculate:calculator.py class calc(): @classmethod def calculate(request_data): # start = time.time() results = {} a = 1 return a I need to give a POST request in the view,py and should display the variable a(i.e 1) from the calculator.py in the POST request. Below is the screenshot of my views.py from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.clickjacking import xframe_options_exempt from rest_framework.decorators import api_view from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from calculator import calc import json # local variables debug = True @xframe_options_exempt @csrf_exempt @api_view(['POST']) def calculated(request): report_table = calc.calculate(data=request.data) return JsonResponse(report_table.data, status=status.HTTP_201_CREATED) #return JsonResponse({"data":report_table.data}) But when I run this program and check the API end point for the POST request, it is showing the following error..! API End point result GET /api/calculated HTTP 405 Method Not Allowed Allow: OPTIONS, POST Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } Can someone help me, why am I getting this error. Is there anything wrong with this code..? I want the value '1', i.e being returned in calculate.py to be displayed in the … -
Listing a ChoiceField in django
Is there a way for me to change the way ChoiceFields are represented in django from a drop down list to something like buttons with each having a different choice ? -
Django won't import values to database - sqlite3
I am trying to put values to my django database. My app_name/models.py looks like: from django.db import models # Create your models here. class Language(models.Model): id = models.AutoField(primary_key=True) code = models.TextField(max_length=14) I ran this commands: python3 manage.py makemigrations app_name python3 manage.py migrate app_name After that I starting importing values to my database. So I run this command: python3 manage.py shell and put this code to the shell: from app_name.models import * with open('lang.txt', 'r') as file: for i in file: a = Language.objects.create(code=i.strip()) File lang.txt contains 309 lines with language codes. The file looks like: en fr af de ... When I run this code in the manage.py shell Django created 309 Language objects. But when I try type random id in the shell -> Language(id=1).code it return only empty string - ''. I tried use save() method too but still same problem. from definitions.models import * with open('lang.txt', 'r') as file: for i in file: a = Language(code=i.strip()) a.save() Django version 1.10.1 So my question is where can be a problem? -
How did Django implement its lazy-loaded QuerySets?
I am curious about how do they determine when QuerySet is being iterated or sliced to evaluate database query? -
Django FileField not working with german "Umlaut" (ä, ö, ü)
I use django, nginx and gunicorn. In my models i have a FileField which is not working with german "Umlaute" in production. When i try to upload a file (select file and push "save") in /admin with an "Umlaut": UnicodeEncodeError: 'ascii' codec can't encode character '\xe4' in position 27: ordinal not in range(128) models.py class wiki(models.Model): headline = models.CharField(max_length=255) file = models.FileField(null=True, blank=True) def __str__(self): return self.headline On the development Web server on the local machine (./manage runserver) it is working fine, so i thought it has something to do with gunicorn or nginx and did the following changes without success: /etc/systemd/system/gunicorn.service: (added --env LANG=de_DE.UTF-8) [Unit] Description=gunicorn daemon After=network.target [Service] User=django Group=www-data WorkingDirectory=/opt/django/project ExecStart=/opt/django/bin/python3 /opt/django/bin/gunicorn --env LANG=de_DE.UTF-8 --workers 3 --bind unix:/opt/django/gunicorn.sock uhd.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/domain server { charset UTF-8; } Here are some information which i think might be useful: $ locale LANG=C.UTF-8 LANGUAGE= LC_CTYPE="de_DE.utf8" LC_NUMERIC="de_DE.utf8" LC_TIME="de_DE.utf8" LC_COLLATE="de_DE.utf8" LC_MONETARY="de_DE.utf8" LC_MESSAGES="de_DE.utf8" LC_PAPER="de_DE.utf8" LC_NAME="de_DE.utf8" LC_ADDRESS="de_DE.utf8" LC_TELEPHONE="de_DE.utf8" LC_MEASUREMENT="de_DE.utf8" LC_IDENTIFICATION="de_DE.utf8" LC_ALL=de_DE.utf8 cat /etc/*-release PRETTY_NAME="Debian GNU/Linux 8 (jessie)" NAME="Debian GNU/Linux" VERSION_ID="8" VERSION="8 (jessie)" ID=debian HOME_URL="http://www.debian.org/" SUPPORT_URL="http://www.debian.org/support" BUG_REPORT_URL="https://bugs.debian.org/" i appreciate any help. If more informations are needed, please let me know. -
Django-autocomplete-light multiple selection
I am using Django-autocomplete-light 3.2.9 and Django_filters together. Skills = django_filters.ModelMultipleChoiceFilter(name='persontoskills__SkillsID', queryset=Skills.objects.all().order_by('Name').distinct(), widget=autocomplete.ModelSelect2Multiple(url='RSR:Skills-autocomplete')) For example, I have a filter called 'Skills', which allows a user to select multiple skills using autocomplete. Right now, if I choose 'Python' and 'Java', the filter will return people who know python or Java. How can I change the current code so that the filter will return people who know python and Java? Or let the users to choose which way they want to filter. Thanks -
How to automatically generate a new Template when a Model is added
I'm building an application in Django, I have a Model called User and a View called profile. When I add an User object, I want to automatically generate a new template username-profile.html correspondent to the new User object. Is possible to do that or I'll have to manually create a new template for each User object? models.py: from django.db import models class User(models.Model): name = models.CharField(max_length=220) views.py: class Profile(View): def get(self, request, *args, **kwargs): return render(request, 'profile.html') -
Django Multiple Forms Handling
I am new to Django and tried making a view that holds a list of forms and handles them. I am familiar with the FormView provided by django's generic views however it only holds one form in it. The idea is that the main form I have is split into a few forms, and then the "mini-forms" are held in a list ("forms"). Since I'm splitting the form into parts and saving a list of forms (for reasons like re-usability and such), the template looks something like this (which does the trick): ... <form ...> {% for form in forms %} {{ form.as_p }} {% endfor %} <input type="submit"...> </form> ... I have been messing around with the view that should handle the forms, validate them and will get the data from them. Since I feel like Im making it more complicated than it should really be, I'd like to ask you to give an example of a simple view for that, that Ill develop further (get -
django filter by manytomany or no record
I have models class Product(models.Model): title = models.CharField(...) class PropertyType(models.Model): title = models.CharField(...) class Property(models.Model): property_type = models.ForeignKey(PropertyType) product = models.ForeignKey(Product, related_name='properties') value = models.CharField(...) So, how can i filter Products for properties with some value and property_type and include products, which have no property with same property_type Something like this properties = Property.objects.filter(property_type__pk=12, value='anyValue') products = Product.objects.filter(Q(properties__in=properties)| Q(NO PROPERTY RECORD WITH PROPERTYTYPE__ID=12 FOR PRODUCT)) -
ImportError: No module named task.control
I'm attempting to import the revoke method in Celery, to cancel a task with: from celery.task.control import revoke but this throws the error: ImportError: No module named task.control Why am I getting this error? I can't find any documentation on Celery removing or refactoring this method. I'm using celery==3.1.18 and I can't upgrade it because I'm using an older version of Django which depends on it. -
How to include a field from the joining table in the queryset?
We have Django Rest Framework at work, however I'm a front-end developer who's decided to do a little bit of DRF for his next open-source project. I don't wish to copy-paste a lot of code, as you can see all of my serializers, models, etc... on GitHub. I've asked the developers at work. One said I should override to_representation which seems bad, as we're building the serialized model from scratch. Whereas the other Django developer at work suggested I look into custom relation fields. Essentially given the following serializer, how would I include the "type" (badly named) column from my joining table in my queryset: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'countries') In pseudo-code I'm looking for something like the following, so when you get a user, you also get associated countries, which is working just fine via the many-to-many relationship, as well as the "type" from the joining table: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'countries', 'pinned.type') I'd expect a JSON response of something like the following: { "username": "wildhoney", "countries": [ { "country_id": 4, "type": 1 }, { "country_id": 5, "type": 2 }, { "country_id": 6, "type": 3 … -
Integrating Django (Rest Framework) with ReactJS
Let's say I want to join Django Rest Framework with React. I've read some questions but couldn't understand how to do it. Can I just make Django listen to another port with Apache, redirect port 80 to my React index.html and make the API calls using Django's port? Or do I need separate servers? Help would be appreciated. Thanks! -
ListView for Django not Working but function based view is working
When I am using function based view using the following code: from django.views import View from django.views.generic import TemplateView, ListView from .models import Restaurant def restaurant_listview(request): template = 'restaurants/restaurants_list.html' context = { "queryset" : Restaurant.objects.order_by('-updated') } return render (request, template, context) it is working with the url file kept as follows: from django.conf.urls import url from django.contrib import admin from restaurants import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^restaurants/$', views.restaurant_listview), ] But when I am trying to do the same thing with class based views it is not working only the following portion doesn't seem to work: <ul> {% for obj in queryset %} <li>{{obj.name}}, {{obj.location}}, {{obj.category}}, {{obj.timestamp}}</li> {% endfor %} </ul> the following part works fine: {% extends 'base.html' %} {% block title %} Restaurants List {{ block.super }} {% endblock %} {% block content %} <h1>Restaurants</h1> for class based view my views.py is: class RestaurantListView(ListView): queryset = Restaurant.objects.all() template_name = 'restaurants/restaurants_list.html' and urls.py is: url(r'^restaurants$', RestaurantListView.as_view(), name='Home') P.S. I am following this guide : https://www.youtube.com/watch?v=yDv5FIAeyoY&t=25471s -
Render encode64 image in django template
I receive an encode64 image from front end and I want to insert the data into html template and render it as image so I can convert the html into pdf later. {{imagedata}} will only show the all those encoded data in pdf. -
Can't display model of review of product in html in django
I have created a model for products' review with rating in my e-commerce site. My model is correct but I cant understand how to make function in views.py and how to create template for that in html. I have added my function of views.py but i don't know what to write in the template. I am using python 2.7 and django 1.8. models.py(not all shown) class Product(models.Model): title = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=20) active = models.BooleanField(default=True) categories = models.ManyToManyField('Category', blank=True) default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True) objects = ProductManager() class Meta: ordering = ["-title"] def __unicode__(self): #def __str__(self): return self.title def get_absolute_url(self): return reverse("product_detail", kwargs={"pk": self.pk}) def get_image_url(self): img = self.productimage_set.first() if img: return img.image.url return img #None def average_rating(self): all_rating = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_rating) class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2,'2'), (3,'3'), (4,'4'), (5,'5'), ) product = models.ForeignKey(Product) pub_date = models.DateTimeField('date published') user_name = models.CharField(max_length=100) comment = models.CharField(max_length=200) rating = models.IntegerField(choices=RATING_CHOICES) My views.py(not all shown) class ProductListView(FilterMixin, ListView): model = Product queryset = Product.objects.all() filter_class = ProductFilter def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) context["now"] = timezone.now() context["query"] = self.request.GET.get("q") #None context["filter_form"] = ProductFilterForm(data=self.request.GET or None) return context … -
How to add caption using django-tables2
ive been trying to get the model name "Cars" on top of my html table, cant according to bootstrap i can use a tag called "caption" but i how to create my own tag. ive tried adding it via attrs but its not where it should be -
Django Filefield path depends on folder. Weird bug?
When I run shell from project's root category I get the following result: >>> from generations.models import * >>> Generation.objects.all().first().file.path '/Users/marijus/workspace/preeti/media/data/58/input/IRIS.csv' Which is good and what I want. However when I run shell or any other script with django context from other directory I get the following result: ─$ cd scripts ╰─$ python ../manage.py shell >>> from generations.models import * >>> Generation.objects.all().first().file.path '/Users/marijus/workspace/preeti/scripts/media/data/58/input/IRIS.csv' notice scripts appended before /media which results in an error when I try to access the file from scripts directory. my models: def get_upload_path(instance, filename): return "media/data/%s/input/%s" % (instance.id, filename) class Generation(models.Model): file = models.FileField(upload_to=get_upload_path, blank=True, null=True) Is this some kind of bug or is FileField's path supposed to depend on folder from which I'm trying to access it. -
What are visual characteristics of a website made from Flask, Django, Pyramid, etc in python and by this how can I distinguish it without code access?
Clarification of the title: Assuming a website is not complex and has not undergone major customization that makes things indistinguishable, (assume it is a simple platform) What are visual/in-browser characteristics of these websites (it is sure that the sites are made from python but I don't have access to the codes and I do not know the framework) and what do I have to look upon to distinguish the web framework module they are made of? (Take it simple, just the 3 major frameworks and assume the only thing I have access is the F12 button of a browser or view-source: in Chrome) -
Web application for creating Excel like environment using React or Angular
I am a student working a temp job at one of my university's department. I am trying to automate a process where I have ~40 students (users) who fill out their internship hours in multiple sheets in Excel while exactly similar sheets are filled out by someone from the department (admin). We then use Windows SpreadsheetCompare to compare the two sheets and tell the students which fields they entered wrong, which leads to a barrage of emails and manual effort which takes up a lot of man hours. Ideally, I wish to create a web application with login where the users and the admin can enter hours separately in multiple sheets/tabs and each data field can be compared and color coded green when the entries match and red when they don't match. And obviously, the admin can see all the sheets and the each user can only see their hours. I am thinking of making a Django app where I can use something like Angular or React to create an Excel like interface, which can then be used to enter the data. I can also use jinja2 instead. The issue is that I am new to front end programming so …