Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in psycopg2 install (django)
error in psycopg2 install in venv Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/psycopg2' Please help me on this . What am i doing wrong? thanks in advance -
Default permissions class for DRF
Django rest framework currently has IsAdminUseras a permissions class is there also a corresponding IsOwnerOrAdminUser? Something to that affect? It seems like there should be something that only allows an object to have CRUD functionality if the current user is the one that created it. I'm using DRF with djangorestframework-jwt -
Clean() method from custom Django form not being called
I need to validate a condition in my Experiment class that depends on more than one field. I specified a 'clean' method in my ExperimentForm, but the validation method is never raised. The model's validation errors are perfectly displayed. This is how the forms.py looks like: from django import forms from django.utils.translation import ugettext, ugettext_lazy as _ class ExperimentForm(forms.Form): name = forms.CharField(max_length=254) student_n = forms.IntegerField() expert_n = forms.IntegerField() student_cmd_n = forms.IntegerField() expert_cmd_n = forms.IntegerField() is_active = forms.BooleanField() error_messages = { 'insufficient_assignments': _("The total number of commands to be evaluated must be" "Greater than 28. Right now it's %(command_number)"), } def clean(self): cleaned_data = super(ExperimentForm, self).clean() s_n = cleaned_data.get("student_n") e_n = cleaned_data.get("expert_n") s_cmd_n = cleaned_data.get("student_cmd_n") e_cmd_n = cleaned_data.get("expert_cmd_n") command_number = s_n*s_cmd_n + e_n*e_cmd_n if command_number < 28: raise forms.ValidationError( self.error_messages['insufficient_assignments'], code='insufficient_assignments', params={'command_number': command_number}, ) return self.cleaned_data This is my views.py from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.core.urlresolvers import reverse_lazy from vacs.forms import ExperimentForm from django.views.generic import TemplateView,ListView from django.views.generic.edit import FormView, CreateView, UpdateView, DeleteView from django.views.generic.detail import DetailView from vacs.models import Experiment class ExperimentView(FormView): template_name = 'vacs/experiment.html' form_class = ExperimentForm success_url = '/vacs/experiments/' def form_valid(self, form): return super(ExperimentView, self).form_valid(form) class β¦ -
Object results in a NameError: name 'TransactionalData' is not defined
I'm creating a web app with django and currently working on a webhook that will receive and parse json. from django.db import models from django.utils import timezone from django_hstore import hstore class WebhookTransaction(models.Model): UNPROCESSED = 1 PROCESSED = 2 ERROR = 3 STATUSES = ( (UNPROCESSED, 'Unprocessed'), (PROCESSED, 'Processed'), (ERROR, 'Error'), ) date_generated = models.DateTimeField() date_received = models.DateTimeField(default=timezone.now) body = hstore.SerializedDictionaryField() request_meta = hstore.SerializedDictionaryField() status = models.CharField(max_length=250, choices=STATUSES, default=UNPROCESSED) objects = hstore.HStoreManager() def __unicode__(self): return u'{0}'.format(self.date_event_generated) class Message(TransactionalData): date_processed = models.DateTimeField(default=timezone.now) webhook_transaction = models.OneToOneField(WebhookTransaction) team_id = models.CharField(max_length=250) team_domain = models.CharField(max_length=250) channel_id = models.CharField(max_length=250) channel_name = models.CharField(max_length=250) user_id = models.CharField(max_length=250) user_name = models.CharField(max_length=250) text = models.TextField() trigger_word = models.CharField(max_length=250) def __unicode__(self): return u'{}'.format(self.username) When running in my local environment I'm getting an error that says: File "/Users/{myname}/summer-project/webhook/models.py", line 27, in <module> 21:16:16 web.1 | class Message(TransactionalData): 21:16:16 web.1 | NameError: name 'TransactionalData' is not defined What do I need to do to resolve this name error? I'm new to web apps so any help would be greatly appreciated! -
How to join two mysql tables in my Django application
I have two tables in my mysql database: First Table: For Subscribers (id, name, area, subscriberNumber, phoneNumber) Second Table: For Monthly Payment (id, subscriberNumber, month, year, amount, discount, fine, billNumber) I have a html page where the list of the Subscriber. Whenever the admin clicks on one of the subscriber the detail of the user is shown.But currently I can only show the user detail(from the first table). I want the page to show the list of payments he/she has done throughout the year(from the second table). I want to join the tables and show the details of both the table in one html page. This is the code to display the data of the first table in views.py @login_required def userDetail(request, id=None): instance = get_object_or_404(Subscribers.objects.using('db2'), id=id) context = { "Name": instance.name, "instance": instance, } return render(request, 'userDetail.html', context) How do I show the payments done by the user in the same page as their details are in. -
NameError: name 'hasattr' is not defined - Python3.6, Django1.11, Ubuntu16-17, Apache2.4, mod_wsgi
I've set up my Python/Django virtual environment, and mod_wsgi in daemon mode, and am pretty sure (done this before) it's "mostly correct" except I get the following error... [Thu Jul 06 00:35:26.986363 2017] [mpm_event:notice] [pid 11442:tid 140557758930432] AH00493: SIGUSR1 received. Doing graceful restart Exception ignored in: <object repr() failed> Traceback (most recent call last): File "/home/jamin/www/dev.tir.com/py361ve/lib/python3.6/site-packages/PIL/Image.py", line 572, in __del__ NameError: name 'hasattr' is not defined [Thu Jul 06 00:35:27.194483 2017] [mpm_event:notice] [pid 11442:tid 140557758930432] AH00489: Apache/2.4.25 (Ubuntu) mod_wsgi/4.5.15 Python/3.6 configured -- resuming normal operations [Thu Jul 06 00:35:27.194561 2017] [core:notice] [pid 11442:tid 140557758930432] AH00094: Command line: '/usr/sbin/apache2' My django app itself is loading fine through wsgi.py but it seems something to do with core python (error with my setup likely) is going wrong as per: NameError: name 'hasattr' is not defined In the browser - I get a plain "Server Error (500)" page and not the standard Apache "Internal Server Error" page. Leaving out my VirtualHost and steps beyond here are the basic steps I put together for myself if you can spot anything... (I've tried all the different python packages as well not just -venv) Install Python 3.6 and virtualenv sudo apt-get update sudo apt-get install python3.6-venv sudo β¦ -
Django migrate ImageFiles from one app to another
I have two django apps on heroku, app B is a copy of a section of app A. The A app has models with ImageFields, I'd like to copy these objects to the app B. The model I'd like to copy looks exactly the same. The images are stored in Amazon AWS. The django command dumpdata / loaddata gives me FK errors.. However, I could try to solve those FK errors but I'm not sure if loaddata can copy the images themselves, or am I missing something? Is there any other way to do this? -
Issue assigning form fields in the HTML template django
I have a model form and I wanted to know if it is possible to take a model form and assign the name of the specific field when it is running through a for loop within the template html file. Here is what i have in the current html template: {% extends "base.html" %} {% block content %} <h1>Add members to {{record.name}}</h1> {% if message %} <p>{{message}}</p> {% endif %} <form action="." method="POST"> {% csrf_token %} {% for trans in transactions %} {% if trans.record.id == record.id %} {{ trans.user.username }} {{ form.as_p }} {% endif %} {% endfor %} <p>Tax: <input type="text" name="tax" value=""></p> <p>Tip: <input type="text" name="tip" value=""></p> <input type="submit" name="submit" value="submit"> </form> {% endblock %} here is the current form model: class IndividualSplitTransactionForm(forms.ModelForm): class Meta: model = Transaction fields = ['amount', 'description'] currently the format is looking like this: omar amount description hani amount description assad amount description tax tip so when i process it and i want to grab the amount assigned to each of the specific users and update a record. I want it to look something like this for easier processing in the view. omar omaramount omardescription hani haniamount hanidescription assad assadamount assaddescription tax β¦ -
Django admin: increase width of visible Charfield
A picture of what I am going for Hi there, I feel like this probably has a simple answer but I've had trouble finding it as a lot of other problems sound similar but are for something different. I'd like to increase the visible width of the text input in my Django admin, the charfield maximum length is 500, I don't mind not seeing all of it, but its cut off far too soon. Does anyone know what I would need to add to my models.py or admin.py in order to change the cut off point of the text to be longer, like the Namefield? Thank you, Nick, in case it's relevant, I am also using mptt. -
AWS Elastic Beanstalk django app is not accepting AWS SES credentials
I am writing a simple Django app to send emails, and I am hosting on AWS' Elastic Beanstalk. Before I hosted on EB, the credentials worked (located in my ~/.aws/credentials). I am getting an AccessDenied error when I try to run the SES sendEmail function. I even put the AWS_ACCESS_KEY_ID and the AWS_SECRET_ACCESS_KEY in the settings.py file. I made sure my keys were correct, my email was verified with AWS, etc. -
Cant get ng-route's HTML5Mode to work with my Django app
I have a Django app that I want to convert to a single-paged Angularjs app. I started to incorporate ng-route and turned html5Mode on but whenever I go to one of the paths in my browser, Django throws a 404 error as if to bypass my angularjs routes. Furthermore if I go to a route with /#!/ prefixed, my browser goes to the route I want and then removes that prefix making it just /, but if I refresh I get the 404 again from django. I've run out of ideas for what should be a simple concept to implement. Thanks in advanced. main.js: saturdayBall.controller('TestController', function TestController($scope) { $scope.greeting = "hiya!" }); saturdayBall.config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) { $routeProvider .when('/add-plays', { template: '{{ greeting }}', controller: 'TestController' }) $locationProvider.html5Mode(true); }]); So if I go to 127.0.0.1:8000/#!/add-plays my browser will convert to 127.0.0.1:8000/add-plays and then when I refresh I get a 404. Also if I go to http://127.0.0.1:8000/#/add-plays the url gets converted to http://127.0.0.1:8000/#%2Fadd-plays -
Filtering Data using django - Python
Iβm new in django framework and i have question about filtering .. I have 2 tables , the first one is: Services: service_ID, service_name, description, department_id and the other table is: Departments: department_id, department_name, manager, coordinator how can i filter the services that appear on the web page depending on the user.. note that, each department has one coordinator, and the manager can manage more than one department.. I want the coordinator only view/edit the services of his department, and the manager can view/edit all the services for the departments he manages.. Thanks -
Why is Django not loading my CSS?
I am creating a website with Django and for some reason my CSS file is having no effect on the page. I have checked to make sure my STATIC_URL is defined but still no luck. My settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Inside of my blog app I have a static directory blog | static | css | blog.css My HTML doc: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <title>Medicare Supplemental info</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <!-- This is where I'm loading the CSS file --> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> I checked to make sure that I have the required app installed in the settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] I have also tried changing the way I load static files from: {% load staticfiles %} to: {% load static %} Still no luck. What is it I'm doing wrong? -
Cannot open or delete Django project folder on Windows 10 - Access Denied
I've created a Django project and now it seems I don't have permission to access it. I've run File Explorer as administrator, tried viewing the permissions tab, but it says I don't have permission. I cannot seem to touch this folder. Any ideas? -
Modifying django object model for better admin CRUD management
I am writing a blog app using django 1.10 This is a snippet of my object model: model.py class Attachment(models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='attachments') class FileAttachments(models.Model): title = models.CharField(max_length=50) attachments = models.ManyToManyField(Attachment) class Post(models.Model): title = models.CharField(max_length=200) text = models.CharField(max_length=2000) file_attachments = models.ForeignKey(FileAttachments, blank=True, null=True) slug = models.SlugField(max_length=40, default='', unique=True) author = models.ForeignKey(User, default=1) pub_date = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return "/blog/%s/%s/%s/%s/" % (self.pub_date.year, self.pub_date.month, self.pub_date.day, self.slug) def __unicode__(self): return self.title class Meta: verbose_name = "Blog Post" verbose_name_plural = "Blog Posts" ordering = ["-create_date"] permissions = ( ( "create", "Create Post" ), ( "modify", "Modify Post" ), ( "delete", "Delete Post" ), ) (simplified) admin.py: class PostAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} exclude = ('author',) def save_model(self, request, obj, form, change): obj.author = request.user obj.save() # Register your models here. admin.site.register(Post, PostAdmin) I have two problems in the admin view, when I try to access the Post object: In the list view, I only see 'Post object' - whereas I want to see the title of the post (and possibly, a few other attributes of the Post object) - how do I modify the admin view to achieve this? When creating/modifying a Post, I want to be able to β¦ -
Template error at line 0 django?
I have got an error on a django site that i am working on which is a zerodivision error.I couldnt find the source of the error which i am thinking that is because of likely mathfilter but still not sure.What i am asking here is that django gives that error with saying it occurs at line 0 which i dont know what that exactly mean.This is the begining of the template file: 1 {% extends "main.html" %} 2 {% include "ru.html" %} 3 {% load staticfiles %} 4 {% load mathfilters %} 5 {% load humanize %} Only thing that occurs to me when i see this (error at line 0) is that to look at the main.html file.But i couldnt find anything that might cause this zerodivison error.I am waiting for your answers on every aspect; How to debug? What might cause this error? What does error at line 0 means and which file should i debug then? Which filters might cause this? Any possible version problem? Anything. Thanks in advance! -
Django doesn't render the requested view
people. I'm a beginner Django developer so sorry if it's a basic question. I have a webpage that shows a list of movies and each movie has a details view, but for some reason, the details view is never rendered. #views.py def index(request): latest_movies = Movie.objects.order_by('-movie_id')[:5] template = loader.get_template('ytsmirror/index.html') context = { 'latest_movies' : latest_movies, } return HttpResponse(template.render(context, request)) def detail(request, movie_id): movie = Movie.objects.get(movie_id=movie_id) template = loader.get_template('ytsmirror/details.html') context = { 'movie' : movie, 'plot': 'Lorem impsum', } return HttpResponse(template.render(context, request)) And my urls.py #urls.py from django.conf.urls import url from . import views app_name = 'ytsmirror' urlpatterns = [ url(r'$', views.index, name='index'), url(r'^(?P<movie_id>\d{4})$', views.detail, name='detail'), ] When I try to reach /ytsmirror/4200/ for example, I don't get any error and Django apparently reaches the correct URL pattern but doesn't render the details view, it stays on the index view, without any change. What am I doing wrong? Thanks. -
How to select a MultipleChoice option based on text variable
I have a MultipleChoiceField and a variable my_choice = 'mystring' I want check the option relative to my_choice Here my html: ul id="id_layer_select"><li><label for="id_layer_select_0"><input checked="checked" id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li> <li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li> <li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul> here my javascript: var my_choice = 'mystring' var opt = $("#id_layer_select option"); opt.filter("[value=my_choice]").attr("selected", true); I can use jquery. Thank you PS: Off course mystring is an option Mychoice1 or Mychoice2 or etc. I don't want use the id_layer_select_x and I prefer to not add and attribute. -
When Django models field is empty, set value to the Default value
Whenever the user doesn't add a value, I need my Django models to replace the otherwise empty field with the value set in default. My models looks like this: not_before = models.TimeField(blank=True, null=True, default='00:00:00') max_num_per_day = models.IntegerField(blank=True, null=True, default=0) I tried every combination of null, blank and default but no matter what I do, the fields gets replaced by null instead of '00:00:00' and 0. Is there anyway I can force it to the default value whenever the field is empty? -
Django Queryset two problems
my queryset : Status.objects.filter(date__gte='2017-07-05', date__lt='2017-07-09', type='X').update(value=F('value') + 1) my database : date | value | value1 | value2 | type 2017-07-05 | 0 | 0 | 0 | X 2017-07-06 | 0 | 0 | 0 | X 2017-07-07 | 0 | 0 | 0 | X 2017-07-08 | 0 | 0 | 0 | X 2017-07-09 | 0 | 0 | 0 | X 2017-07-10 | 0 | 0 | 0 | X I have two question, but my above queryset don't work. 1 - How update field "value" in date range ? 2 - How to replace "value" with a variable ? update(value=F('value') + 1) I need to dynamically select field (value1, value2, valuse3) from the database to change value. -
Can't get url request to show, 404
I'm completely new to backend, working through the djangobook tutorial. If I'm missing any vital information, let me know. The first task is to get 'Hello World' to show up on your development server, and it keeps returning 404. The two files in question being the views.py (my hello world file) and urls.py this is the views.py: from django.http import HttpResponse def hello(request): return HttpResponse("Hello world") this is the urls.py: from django.conf.urls import url from django.contrib import admin from mysite.views import hello urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/$', hello), ] I feel like its not finding the views file correctly? This is how there set up, exactly as he said to do it in the tutorial -
Issue in migrating Django database
When I run this code by python manage.py migrate, I am getting indentation error in line 10. Can anyone find out what's the issue? (https://i.stack.imgur.com/nmJdw.jpg) -
How to use login_reuqired on Update/Create/Delete Views in Django
I am trying to use @login_reuqired decorator. For normal functions it is working fine, but when i try to use it in my UpdateView i am getting this error "AttributeError: 'function' object has no attribute 'as_view'" This is my view.py @login_required class RoomUpdate(UpdateView): model = Room fields = ['Name', 'RoomTypeID'] template_name='WebApp/room_form.html'` This is in my urls.py url(r'^roomList/updateRoom/(?P<pk>[0-9]+)/$', views.RoomUpdate.as_view(), name='room_update'), Any suggestions ? -
Dockerization and deploying on Heroku project with Angular 4 frontend with Django backend and postgresql database
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. Besides, I am going to deploy it on Heroku. At this moment my situation looks as shown below. I am note sure if this is done properly? Unfortunately it doesn't work. When i try docker-compose up I get: ERROR in Cannot determine the module for class OptionsListComponent in /usr/src/app/src/app/options-list/options-list.component.ts! ERROR in ./src/main.ts Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in '/usr/src/app/src' @ ./src/main.ts 3:0-74 @ multi ./src/main.ts ERROR: Service 'angular' failed to build: The command '/bin/sh -c node_modules/.bin/ng build -aot --target ${TARGET}' returned a non-zero code: 1 Structure of my files: βββ Backend β βββ AI β β βββ __init__.py β β βββ __pycache__ β β β βββ __init__.cpython-36.pyc β β β βββ settings.cpython-36.pyc β β β βββ urls.cpython-36.pyc β β β βββ wsgi.cpython-36.pyc β β βββ settings.py β β βββ urls.py β β βββ wsgi.py β βββ manage.py βββ Dockerfile βββ Frontend β βββ angularProject βββ Dockerfile β βββ all files in my angular project βββ docker-compose.yml βββ requirements.txt Dockerfile from frontend: FROM node:8.1.2-onbuild as builder ARG TARGET=production RUN npm install @angular/cli RUN node_modules/.bin/ng build -aot --target ${TARGET} FROM nginx:1.13-alpine COPY nginx.conf /etc/nginx/conf.d/ COPY --from=builder β¦ -
DJANGO REST API Filtering View Based on Preferences
Working on project where a user sets preferences (UserPref in model below) for dogs, and when shown a particular dog---the choose a 'STATUS' of liked or disliked for that dog. This STATUS is housed in my UserDog model. After rating a dog they are shown the next dog based on their preferences and based on whether or not they have rated the dog thus far. Having a tough time writing the API View for this I know what it needs to do, but having trouble writing the code. My Models class Dog(models.Model): name = models.CharField(max_length=255) image_filename = models.CharField(max_length=255, default='') breed = models.CharField(max_length=255, default='Unknown Breed') age = models.IntegerField() gender = models.CharField(choices=GENDER, max_length=1) size = models.CharField(choices=SIZE, max_length=2) @property def get_image_url(self): return self.image_filename.name def __str__(self): return self.name class UserDog(models.Model): user = models.ForeignKey(User) dog = models.ForeignKey(Dog, related_name='dogs') status = models.CharField(choices=STATUS, max_length=2) class Meta: unique_together = ('user', 'dog') def __str__(self): return '{} {} {}'.format(self.user, self.dog, self.get_status_display()) class UserPref(models.Model): user = models.OneToOneField(User) age = models.CharField(max_length=7, default='b,y,a,s') gender = models.CharField(max_length=3, default='m,f') size = models.CharField(max_length=8, default='s,m,l,xl') My Regex looks like this. So trying to define view for dog that would come 'next' after first dog matching preferences is shown url(r'^api/dog/(?P<pk>-?\d+)/(?P<dog_filter>liked|disliked|undecided)/next/$', DogFilterView.as_view(), name='dog-filter-detail'), I started like this and I β¦