Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin List Filter Error: Value of List Does not Refer to a Field
Adding a Django Admin List Filter for a property on a mixin that is read only gives the following error: (admin.E116) The value of 'list_filter[2]' refers to 'deleted', which does not refer to a Field. Why? Below is an example of what I'm doing, edited for brevity, Admin: list_filter = ('deleted') readonly_fields = ('deleted_at', 'deleted') Model: class User(AbstractBaseUser, SoftDeleteMixin): name = models.CharField(max_length=80, null=True, blank=True) etc class SoftDeleteMixin(models.Model): deleted_at = models.DateTimeField(blank=True, null=True, default=None) deleted = property(get_deleted, set_deleted) Django==1.9.9 Python 3.4 -
AngularJS routing behavior not as expected, no errors whatsoever
Fellow coders of SO, I seem to have encountered a perculiar issue with my code, i'm relatively new to angularJS so this might be an error on my behalf, yet I cannot seem to figure it out. The use case is as follows, I have a simple django rest_framework application that works 100% (tested with the swagger UI). I'm fairly certain there is no issue whatsoever in the Django app. I wish to control the front-end using angularJS. For some odd reason I cannot figure out, the routing in angularJS refuses to do its job. this is my app.routes.js (function () { 'use strict'; angular .module('inventaris.routes') .config(config); config.$inject = ['$routeProvider']; function config($routeProvider) { $routeProvider.when('/register', { controller: 'RegisterController', controllerAs: 'vm', templateUrl: '/static/templates/authentication/register.html' }).otherwise('/'); } })(); The following code block is my app.js (function () { 'use strict'; angular .module('inventaris', [ 'inventaris.routes', 'inventaris.config', 'inventaris.authentication' ]); angular .module('inventaris.routes', ['ngRoute']); angular .module('inventaris.config', []); angular .module('inventaris') .run(run); run.$inject = ['$http']; function run($http) { $http.defaults.xsrfHeaderName = 'X-CSRFToken'; $http.defaults.xsrfCookieName = 'csrftoken'; } })(); Following image is an screenshot from the chrome browser with debugger open, as you can see there are no errors So I lack the 10 reputation required to post images, here is a direct … -
How to let Django fill an html template, then let the user download it without showing it in browser?
I have an HTML template, and I want django to fill it with some data, but rather than redirect the user to a view that uses this template, I want Django to send the filled-template to the user as a download file. Any suggestions? -
Associating users with models django
I have a lot of models in model.py - class Portfolio(models.Model): company = models.TextField(null=True) volume = models.IntegerField(blank=True) date = models.DateField(null=True) isin = models.TextField(null=True) class Endday(models.Model): company = models.TextField(null=True) isin = models.TextField(null=True) eop = models.TextField(max_length=100000) class Results(models.Model): companies = models.TextField(default=0) dates = models.DateField(auto_now_add=False) eodp = models.FloatField(null=True) volume = models.IntegerField(null=True) class Sectors(models.Model): sector_mc = models.TextField(null=True) class Insector(models.Model): foundation = models.ForeignKey(Sectors, null=True) name = models.TextField(null=True) value = models.FloatField(default=0) class AreaLineChart(models.Model): foundation = models.ForeignKey(CompanyForLineCharts, null=True) date = models.DateField(auto_now_add=False) price = models.FloatField(null=True) class Meta: ordering = ['date'] I have more such models but as you can see from this snippet, they are not in any way related to any user. Now I want to related them to a particular user. In the views too, I was not classifying data per user in any way. I make users from django admin with username and password and also generate a token for those users from admin. I can authenticate via username and password but from there I know I'd need to use permissions but how is what I do not know. Also, I have serializers that are associated to these models, I know I'd have to use permissions there too but again, I don't know how to. … -
Django url list problems
Working with book "Tango with Django".Have a problem with url patterns.My url patterns you can see below.Can connet to the only one category called "Python"(slug = 'python').Others like "Django","Other categories","Myown" links dont working, showing me error 404 like below. If some other info or code is needed please write. P.S.New to Stackoverflow.If question design is bad just tell me. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/rango/category/myown Using the URLconf defined in tang_w_djang.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='index'] ^rango/ ^$ [name='index'] ^rango/ ^about/$ [name='about'] ^rango/ ^add_category/$ [name='add_category'] ^rango/ ^category/(?P<category_name_slug>[\w\-]+)/$ [name='show_category'] ^rango/ ^category/(?P<category_name_slug>[\w\-]+)/add_page/$ [name='add_page'] The current URL, rango/category/myown, didn't match any of these. -
Django formsets: creating multiple model instances in single form
These are my models class Campaign(models.Model): campaign_name= models.CharField(max_length=30) campaign_desc= models.CharField(max_length=400) cer_date = models.DateTimeField('date created') class CampaignForm(ModelForm): class Meta: model = Campaign fields = ['campaign_name', 'campaign_desc' class Item(models.Model): campaign=models.ForeignKey(Campaign) item_name=models.CharField(max_length=70) item_ID=models.PositiveIntegerField() item_url=models.URLField(max_length=400) I need a single form to create 1 campaign with 3 items with the campaign as one of the fields. How can it be done? There is help in displaying multiple model instances in sigle form but not for creating new ones. View.py def createcampaignform(request) : if request.method == 'POST': form = CampaignForm(request.POST, request.FILES) campaign = form.save(commit=False) #to change attributes if(not campaign.cer_date): campaign.cer_date=timezone.now() if form.is_valid(): campaign.save() return redirect('/campaign') else: print "form is not valid" else: form = CampaignForm() return render(request, 'campaign/test/newCampaign_Raw.html', {'form': form}) template: newcampaign_Raw.html <form action="{% url 'campaign:createcampaign' %}" method="post" enctype="multipart/form-data"> <span>Campaign name</span> <input type="text" size="20" name="campaign_name" value="Name"/> <input type="text" size="20" name="campaign_desc" value="Description"/> <input type="submit" value="Save"> </form> -
Gaining information from the form data in form_valid
I have to get some information from the form that has just been submitted. The form is a to put an event on a calendar. I need to get the "Category" field, this is basically a name of the person the event includes. From there i need to split the name into last and first and get their email from the user table. From there i will send them a email telling them they have been added to the calendar. This is my form_valid function now: def form_valid(self, form): Event = form.save(commit=False) Event.created_by = self.request.user Event.save() send_mail( 'test', 'Is this really working?', 'from@example.com', ['blah@gmail.com'], fail_silently=False, ) return HttpResponseRedirect('/calendar/') How do i get information that has just been submitted in the form? is that even possible? -
Angular2 + Django deployment
I'm developing a project with DRF as a backend and Angular2 (using angular-cli) as a frontend. Locally I serve my Django at http://localhost:8000/, so all request within Angular2 services are pointing to URLs like http://localhost:8000/api/users, etc. However, my production address for the backend is http://example.com/project_api/ while the address for frontend is http://example.com/project/. Is it possible to separate addresses for dev and prod environments? Or maybe the approach should be different? -
Django form: restore predefined field value in clean method
In my Django form I need to perform different field values comparisons (+ some additional checks). If all of these conditions are met I want to raise error and inform user that he can't perform this operation. Right now I'm doing it in clean method and code looks like these: if self.instance.foo != cleaned_data['foo'] and \ Bar.objects.filter(baz=self.instance.id).count(): cleaned_data['foo'] = self.instance.foo raise forms.ValidationError("You can't change it") That's working fine, but I'd also like to reject the change and restore previous value (before the update). The assignment cleaned_data['foo'] = self.instance.foo obviously is not working because cleaned_data is not being returned due to raising ValidationError. How can I achieve this? -
post data to remote host, wrong value
I have json like: {'singleQuesResponses': {'28': '', '14': '', '27': '', '26': ''}, 'org_apache_struts_taglib_html_TOKEN': 'a1553f25303435076412b5ca7299b936', 'quesResponses': {'some': 'data'}} when i post it like: page = requests.post('http://localhost/chilivery/index.php', data=data, cookies=bcookies) then value that post is something like this: array(3) { ["quesResponses"]=> string(4) "some" ["singleQuesResponses"]=> string(2) "14" ["org_apache_struts_taglib_html_TOKEN"]=> string(32) "a1553f25303435076412b5ca7299b936" } but i expect: array(3) { ["quesResponses"]=> array["some"=>'data'] ["singleQuesResponses"]=> string(2) "14" ["org_apache_struts_taglib_html_TOKEN"]=> string(32) "a1553f25303435076412b5ca7299b936" } I mean why 'some' is not sent by value as array and the only first key of it send as a string ? -
How much efficient is django cms with Dynamo Db
Hi all i am new to Django CMS & i am using it for my ongoing project so i have few query related with Django CMS & i am hoping to get a good guidance, so while starting the project i didn't used Aldryn client for Django CMS because i don't want to depend on third party & also i want to try from my own so i went through few tutorials document of Django CMS which were effective and Helpful with the help of that somehow i manage to build a project but now i need to implement Dynamo DB as a backend for Data Store and i tried to find tutorials for that but it wasn't quite effective so i wanted to know how much effective is Dynamo Db with Django CMS, is it fine to use Dynamo DB as a Backend or i have to lookout for some other alternative like postgres or mysql. -
serializer class to get user name with the user id
I have a model like this class ProjectTemplate(models.Model): project_template_id = models.AutoField(primary_key=True) name = models.CharField(max_length=64) description = models.TextField(max_length=255) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) created_by = models.IntegerField(blank=True, null=True) modified_by = models.IntegerField(blank=True, null=True) activated = models.BooleanField(default=False) org_id = models.IntegerField(blank=False,null=False) class Meta: db_table = 'project_template' def __str__(self): return self.name and a serializer class like this class NeProjectTemplateSerializer(serializers.ModelSerializer): class Meta: model = NeProjectTemplate in the created_by field i am storing the user id in the db, when listing the project templates, basically i'll get user id's for create_by field, how to change my serializer class to get a dict like this {"user_id":id,"user_name":name} for created_by field -
upload multiple files in django
I am new to django, I am trying to upload more thgan one file from the browser and store them somewhere in computer but I am not storing them successfully with this code please help me out to find my mistake or improvements that I can do. Thanks in advance for help. views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def Form(request): return render(request, "index/form.html", {}) def Upload(request): for count, x in enumerate(request.FILES.getlist("files")): def process(f): with open('/Users/benq/djangogirls/upload/media/file_' + str(count), 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) process(x) return HttpResponse("File(s) uploaded!") app/urls.py from django.conf.urls import url from index import views urlpatterns = [ url(r'^form/$', views.Form), url(r'^upload/$', views.Upload) ] form.html <form method="post" action="../upload/" entype="multipart/form-data"> {% csrf_token %} <input type="file" name="files" multiple /> <input type="submit" value="Upload" /> -
How to use/import PyCrypto in Django?
I am trying to use PyCrypto with Django. I import it like this: from Crypto.Cipher import AES But it says: ImportError: No module named 'Crypto' But when I try it using the Command Prompt, it is working. Other details (if it can help): I am using Eclipse Luna with PyDev installed. My OS is Windows7 32 bit. -
Django Redis cache values
I have set the value to Redis server externally using python script. r = redis.StrictRedis(host='localhost', port=6379, db=1) r.set('foo', 'bar') And tried to get the value from web request using django cache inside views.py. from django.core.cache import cache val = cache.get("foo") It is returning None. But when I tries to get it form from django_redis import get_redis_connection con = get_redis_connection("default") val = con.get("foo") It is returning the correct value 'bar'. How cache and direct connections are working ? -
django-mptt show "no such column"
I used MPTT to implement a forum which allow posts to latest news.I can't solve this error: "no such column: news_comment.lft" The app name is news.This is models.py: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class News(models.Model): .... class Comment(MPTTModel): .... news = models.ForeignKey(News,related_name='news', null=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class MPTTMeta: order_insertion_by = ['created'] this is views.py def show_news(request,request_id): news = News.objects.get(id=request_id) comments = Comment.objects.filter(news=news) return render( request, 'news.html', {'news': news, 'comments': comments,}) This is part of news.html,the error is in line11 {% block title %}{{news.title}}{% endblock title %} {% block content %} <div id='news_info'> <h1>{{ news.title }}</h1> <p>{{ news.created}}</p> <p>{{ news.content}}</p> </div> <div id="comment_list"> <h2>Comments</h2> **{% for comment in comments %} -- error here** {% if comment.replyto == null %} <div class="comment_info"> .... -
Import value from a button in a Modal to another button in another Modal
I have a Modal opened on clicking a button. The modal has values which should be posted on to the button on selection. Any idea how to do this? -
How to save custom field with Django all-auth
I'd like to save custom field in django allauth. I create models and forms to make separate table and I can save the user_id in that table. But I can't save the actual custom field in that table. myApp_userprofile table have a school, user_id. When I save the form it save only user_id without any errors but school field is empty. Could you please let me know what I miss? And Yes, I'm a supper newbie in python ㅡㅡ) models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import * class UserProfile(models.Model): # user = models.OneToOneField(User, related_name='profile') # A required line - links a UserProfile to User. user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') # The additional attributes we wish to include. school = models.CharField(max_length=128, blank=False) def __unicode__(self): # __str__ return unicode(self.user.username) def create_user_profile(sender, instance=None, created=False, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) forms.py from django import forms from .models import UserProfile SCHOOL = ( ('', 'Select your school...'), ('ucla.edu', 'UCLA'), ('berkeley.edu', 'Berkeley'), ('gmail.com', 'Test Gmail'), ) class SignupForm(forms.Form): school = forms.ChoiceField(choices=SCHOOL, required=True) def signup(self, request, user): # user.school = self.cleaned_data['school', 'email', 'password1', 'password2'] #user.school = self.cleaned_data['school'] #user.save() profile = UserProfile() profile.school = self.cleaned_data['school'] #profile.save(profile, update_fields=['school']) profile.create_user_profile(profile) Thanks … -
Python django removes #anchor in urls
I've got a url set up like in python django 1.9 url(r'^faq/?$', views.faq, name="faq"), However, if I go to a url with #anchors in them, it keeps removing the #anchor part in all browsers. So, localhost:5000/faq#12 always goes to localhost:5000/faq. How do I get django to keep the #anchor section? -
django sub query filter using value from field in paret query
I have following models: class Domain(models.Model): name = models.CharField(...) plan = models.ForeignKey(Plan, ....) class Plan(models.Model): name = models.CharField(...) num_ex_accounts = models.IntegerField(...) class PlanDetails(models.Model): accounts = models.IntegerField() plan = models.ForeignKey(Plan, ....) class Mailbox(models.Model): domain = models.ForeignKey(Domain, ...) Any domain has a plan, any plan has N plan details which has accounts value for create mailboxes using a domain, I want to get in a queryset domains which exceed the accounts value, using raw sql the sql is like: SELECT domain FROM domain, plan WHERE plan.id = domain.plan_id AND ( SELECT SUM(accounts) FROM plandetails WHERE plandetails.plan_id=plan.id ) <= ( SELECT COUNT(*) FROM mailbox WHERE mailbox.domain_id=domain.id ) I tried in django something like this: domains = Domain.objects.filter( Q( PlainDetails.objects.filter(plan = Domain.plan).aggregate(Sum('accounts')) <= Mailbox.objects.filter(domain = Domain).count() ) ) But doesn't works, it throws an error about the Domain.plan, is there a way to reference that field value from parent query in the sub-query? is this queryset valid or is there another (better) approach? or I should use simply raw sql, what is the best option in this case? -
Run celery task without workers
How to run all celery tasks without workers, I mean call directly? I can call task with TaskName.run(), but I want to write this in configurations, so how to make it? -
Django Cookiecutter: gaierror [Errno 8] nodename nor servname provided, or not known
I'm starting with a Django Cookiecutter project and trying to test local email through Mailgun. When I submit a user registration, it kicks off an email to verify the user's email address. In sending that email, this error pops up when I try to use Mailgun. In trying to debug this, I was able to get an email to render in the terminal using: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' I've set my Mailgun settings in my local settings file: DJANGO_MAILGUN_API_KEY=key-XXXXXXXXXXXX DJANGO_SERVER_EMAIL=postmaster@sandbox.....mailgun.org The error I get: Environment: Request Method: POST Request URL: http://localhost:5000/accounts/signup/ Django Version: 1.9.9 Python Version: 2.7.10 Installed Applications: (u'django.contrib.auth', u'django.contrib.contenttypes', u'django.contrib.sessions', u'django.contrib.sites', u'django.contrib.messages', u'django.contrib.staticfiles', u'django.contrib.admin', u'crispy_forms', u'allauth', u'allauth.account', u'allauth.socialaccount', u’test_proj.users.apps.UsersConfig', u'test_proj.books’, u’test_proj.taskapp.celery.CeleryConfig', u'kombu.transport.django', u'compressor', 'debug_toolbar', 'django_extensions') Installed Middleware: (u'django.middleware.security.SecurityMiddleware', u'django.contrib.sessions.middleware.SessionMiddleware', u'django.middleware.common.CommonMiddleware', u'django.middleware.csrf.CsrfViewMiddleware', u'django.contrib.auth.middleware.AuthenticationMiddleware', u'django.contrib.messages.middleware.MessageMiddleware', u'django.middleware.clickjacking.XFrameOptionsMiddleware', u'whitenoise.middleware.WhiteNoiseMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware') Traceback: File "/test_proj/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/test_proj/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/test_proj/lib/python2.7/site-packages/django/utils/decorators.py" in inner 184. return func(*args, **kwargs) File "/test_proj/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/test_proj/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/test_proj/lib/python2.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/test_proj/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/test_proj/lib/python2.7/site-packages/allauth/account/views.py" in dispatch 177. return super(SignupView, self).dispatch(request, *args, **kwargs) … -
Django - ImportError: No module named apps
I am trying out the Django tutorial on the djangoproject.com website, but when I reach the part where I do the first "makemigrations polls" I keep getting this error: ImportError: No module named apps Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/Library/Python/2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Python/2.7/site-packages/django/apps/config.py", line 112, in create mod = import_module(mod_path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) How can I resolve this error? -
Django load resources on startup
How can I load resources from mysql database when Django starts up and put it in memory (Redis) to use by all the applications. I have seen this [https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready] class MyAppConfig(AppConfig): def ready(self): But they mention not use db connections inside ready function. How can do it when my Website starts.? -
NOT NULL constraint failed: Adm_profile.user_id (using Allauth)
my problem is that when I try to register a new user jumps me the following error: http://i.stack.imgur.com/sMrS3.png I read that this error may be that this dejango the field user_id of Adm_profile null, but this field does not receive null values. I found a solution , which is put on the line OneToOneField accept null values (null = True) , only in this way the system works, but it does not work well , because I need the relationship of the table is made "auth_user" with that of " Adm_profile " to obtain user data that this logged at that time. Adm_profile table (My custom Model) I added an ID, but was added manually (10) My forms.py class SignupForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'last_name', 'Matricula') #Saving user data def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.Matricula = self.cleaned_data['Matricula'] user.save() ##Save profile profile = Profile() Profile.user = user profile.Matricula = self.cleaned_data['Matricula'] profile.save() My models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) Matricula = models.CharField(max_length=25) My views.py @login_required def profile(request): return render(request, 'Profile/Profile.html') if I change, null=True, my system works user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) I do not need …