Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NameError: name 'ModelSelect2MultipleField' is not defined
I'm getting an error when I run a program that says that ModelSelect2MultipleField is not defined. I use it here: from django import forms from django_select2 import * from django.db.models import Q from contacts.models import Contact from cards.models import JobCard from employee.models import * from django.core.exceptions import ValidationError def validate_fail_always(value): raise ValidationError(u'%s not valid. Infact nothing is valid!' % value) ########### Forms ##############] class GetContactSearchForm(forms.Form): clients = ModelSelect2MultipleField(queryset=Contact.objects, required=False) class GetEmployeeSearchForm(forms.Form): employees = ModelSelect2MultipleField(queryset=Employee.objects, required=False) My version of python is 2.7.10 and my django is 1.8; is there something I should replace that field with, or something else I need to install or put in my settings.py file? Thanks! -
django custom form clean() raising error from clean_field()
I have created a custom form and need to override both of the clean_field() method and clean() method. Here is my code: class MyForm(forms.Form): username=forms.RegexField(regex=r'^1[34578]\d{9}$') code = forms.RegexField(regex=r'^\d{4}$') def clean_username(self): u = User.objects.filter(username=username) if u: raise forms.ValidationError('username already exist') return username def clean(self): cleaned_data = super(MyForm, self).clean() # How can I raise the field error here? If I save this form twice, and the username will be already exist in the second time, the clean_username method will raise an error, however, the clean() method still run without interruption. So my question is, how can I stop calling clean() when error already raise by cleaned_xxx, if that is not possible, then how can I raised the error again which raised by clean_xxxx() in clean() method? -
Serializing custom related field in DRF
I am trying to make a serializer with a nested "many to many" relationship. The goal is to get a serialized JSON object contain an array of serialized related objects. The models look like this (names changed, structure preserved) from django.contrib.auth.models import User PizzaTopping(models.Model): name = models.CharField(max_length=255) inventor = models.ForeignKey(User) Pizza(models.Model): name = models.CharField(max_length=255) toppings = models.ManyToManyField(PizzaTopping) The incoming JSON looks like this { "name": "My Pizza", "toppings": [ {"name": "cheese", "inventor": "bob"}, {"name": "tomatoes", "inventor": "alice"} ] } My current serializer code looks like this class ToppingRelatedField(RelatedField): def get_queryset(self): return Topping.objects.all() def to_representation(self, instance): return {'name': instance.name, 'inventor': instance.inventor.username} def to_internal_value(self, data): name = data.get('name', None) inventor = data.get('inventor', None) try: user = User.objects.get(username=inventor) except Setting.DoesNotExist: raise serializers.ValidationError('bad inventor') return Topping(name=name, inventor=user) class PizzaSerializer(ModelSerializer): toppings = ToppingRelatedField(many=True) class Meta: model = Pizza fields = ('name', 'toppings') It seems that since I defined the to_internal_value() for the custom field, it should create/update the many-to-many field automatically. But when I try to create pizzas, I get "Cannot add "": the value for field "pizzatopping" is None" ValueError. It looks like somewhere deep inside, Django decided that the many to many field should be called by the model name. How do I … -
django default argument not working properly
Has anybody idea why model method: class SomeModel(models.Model): def get_some_result(related=set([])): (...) return somevalue sbd = SomeModel.objects.get(pk=1) value1 = sbd.get_some_result() value2 = sbd.get_some_result(set([])) gives different values??? value2 is working as expected, value1 is empty... -
CreateModelMixin does not insert one of the fields passed in the request
I'm building a Django web app and I use the CreateModelMixin in a CRUDGeneric class to abstract the CRUD operations. However, I've got a problem where one of the fields (the password) of POST /user request is not being saved into the database. I've checked the request up until the call for the create method and the request is correct. print request.data response = super(CRUDGeneric, self).create(request, args, kwargs) The output of request.data: {u'last_name': u'Last', u'first_name': u'First', u'vvuser': {u'mobile': u'1234', u'bio': u''}, u'is_active': True, u'password': u'password', u'email': u'email@email.com'} I've checked the implementation of CreateModelMixin.create and don't see how it could be failing to insert the password field?: class CreateModelMixin(object): """ Create a model instance. """ def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): try: return {'Location': data[api_settings.URL_FIELD_NAME]} except (TypeError, KeyError): return {} Anyone got any ideas? Maybe I'm looking at the wrong place, but this seems to be the place where the object is being saved into the DB. -
Pyvmomi get folders name
I'm new to Python and Django and I need to list all my VMs. I used pyvmomi and Django but I can't get the folders name from VSphere, it shows a strange line. VMware list 'vim.Folder:group-v207' 'vim.Folder:group-v3177' 'vim.Folder:group-v188' I have 3 folders on vSphere so I think my connection it's good but that's absolutely not their names. Here is my code : views.py from __future__ import print_function from django.shortcuts import render from pyVim.connect import SmartConnect, Disconnect import ssl def home(request): s = ssl.SSLContext(ssl.PROTOCOL_TLSv1) s.verify_mode = ssl.CERT_NONE try: connect = SmartConnect(...) except: connect = SmartConnect(...) datacenter = connect.content.rootFolder.childEntity[0] vmsFolders = datacenter.vmFolder.childEntity Disconnect(connect) return render(request, 'vmware/home.html', {'vmsFolders':vmsFolders}) home.html <h1>VMware list</h1> {% for vmFolder in vmsFolders %} <div> <h3>{{ vmFolder }}</h3> </div> {% endfor %} Can anybody help me to get the real names of my folders? -
Django-haystack search static content
My Django 1.10 app provides a search functionality using Haystack + Elastic Search. It works great for models data, but I need to make it work for static content too (basically HTML files). I was thinking on scrapping the content from the HTML files (BeautifulSoup?) and save them to the database, this way the templates content could be indexed. I found this module that does exactly what I need but seems deprecated: https://github.com/trapeze/haystack-static-pages So, what's the best way to allow haystack to find the content included in HTML pages? -
Django rest framework POST with a foreign key field
How can I use a jquery ajax call to POST a new record for a model that contains a ManyToMany field? My model: class Foo(models.Model): bar = models.ManyToManyField(Qux, blank=True) baz = CharField(max_length=15) class Qux(models.Model): id = models.AutoField(primary_key=True) My js: values = { bar: ???, baz: 'test' } $.ajax({ url: '/api/foo/', type: 'PUT', data: values, success: function(e){ console.log('success'); }, error: function(){ console.log('error') } }); -
TimedRotatingFileHandler raises when deploying
I am deploying my Django project (first time I ever deploy a Django project), and I get an error on a logger. This is the code used to initialise the logger: handler = logging.handlers.TimedRotatingFileHandler("log/{n}.log".format(n=name), when="midnight", backupCount=5) handler.setFormatter(logging.Formatter('%(asctime)s; %(name)s; %(levelname)s: %(message)s')) handler.setLevel(logging.DEBUG) logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.addHandler(handler) and the exception is raised on logging.getLogger(name): IOError: [Errno 2] No such file or directory: '/log/models.log' the code works fine in development (using manage.py runserver). The log directory exists in my setup (in /home/user/site.com) and I have set WSGIPythonPath in apache.conf. -
how to go back to line in a view of django
I'm new with django. I'm trying to show a message in a template . this message is written in the view as follow : def function(request) if (statement): messages.success(request, "Access failed" "you have to add your infos first" ) its showed on the template but there's no back to line. I want to have a back to line after Access failed also I want it to be on red .. is this possible ? -
django.db.utils.ProgrammingError: relation "django_session" does not exist line 1
I am using Django 1.8 python 3.5 and recently completed one app which was using sqlite and everything was fine now i created a new app that i need to connect to a existing database on postgre ( in the same project folder ) i did the database inspectdb and got the models generated from it. i didnt know how to setup two databases so i commented out the old "default" database and wrote my settings for the new one. but when i try and go on the homepage of the app i get a server error and cmd.exe gives me this django.db.utils.ProgrammingError" relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se.. ^ now i saw online i needed to migrate ( which i did ) and i saw as well i need to syncdb ( which i did ) but nothing worked but while trying to figure out i saw this way at the top of all the tracebacks AttributeError: 'SessionStore' object has no attribute '_session_cahce' -
How do I retrieve Django file db.sqlite3 from AWS using EB CLI
I am running a Django application using Elastic Beanstalk (EB) Command Line Interface (CLI). I can see that when I deploy my application, copies of it including file db.sqlite3 are available in Amazon Web Services (AWS) in “S3” and “Application Versions”, and I know how to retrieve the zip files in those two locations. However, when a website transaction occurs, the file db.sqlite3 changes. But new versions of the application are not created in “S3” and “Application Versions” with the changes to db.sqlite3. Is there a way to get the changed file db.sqlite3 from AWS to my local computer? -
Checking user group membership in permission_required
How would I check if a user is a part of a group inside the permission_required decorator? This is what I have currently but it doesn't seem to check it.. @permission_required(['user.is_super_user', "'NormalUser' in user.groups.all"], raise_exception=True) This is supposed to check whether the user is a super user OR the user is part of the group NormalUser but when I try to access the site it just give me a 403 error when the user is part of the NormalUser group. Is there a way I can get this done? I only want to use permission_required decorator, nothing else :S -
Django REST framework without model
I want to use Django REST framework to create an API to call different methods. I read the guide of django-rest-framework to work with this framework, but I still have some dudes I have no model I get my data from an extern database. I want to try first something simple Get all list of project Get the data from one project For that I create new app I include in the setting file and in my view.py I include that for the fist case from django.shortcuts import render class CPUProjectsViewSet(): """ return all project name """ all_rows = connect_database() name_project = [] for item_row in all_rows: name_project.append(item_row['project']) name_project = list(sorted(set(name_project))) def connect_database(): db = MySQLdb.connect(host='...', port=..., user='...', passwd='...', db='cpus') try: cursor = db.cursor() cursor.execute('SELECT * FROM proj_cpus') columns = [column[0] for column in cursor.description] # all_rows = cursor.fetchall() all_rows = [] for row in iter_row(cursor): all_rows.append(dict(zip(columns, row))) finally: db.close() return all_rows this return a list of project, but I don't know exactly how to use the serializer file with this list In the urls.py of my project I include this url(r'^hpcAPI/', include('hpcAPI.urls')) and in the urls.py of my app I include this from django.conf.urls import url, include from rest_framework … -
Python: For loop not working properly
Why is the for loop not working properly? It's just returned only one element. 1. rx = ['abc', 'de fg', 'hg i'] def string_m(a=rx): for i in a: l = re.sub(" ","/",i) r = l.split("/") r.reverse() rx = " ".join(r) return rx a=string_m(rx) print(a) Outputs: abc 2. rx = ['abc', 'de fg', 'hg i'] def string_m(a=rx): for i in a: l = re.sub(" ","/",i) r = l.split("/") r.reverse() rx = " ".join(r) return rx a=string_m(rx) print(a) Outputs: i hg -- Can someone help me to see what I am doing wrong? -
Page not found (404) with Django
I'm learning Django Framework and I'm following a tutorial based on Django 1.8. I have Django 1.10 on my Mac OSX and I get an error : Page not found I started a project which is named "Crepes_bretonnes" and I created an app : "Blog". The blog urls.py looks like : from django.conf.urls import url from django.contrib import admin from blog.views import home urlpatterns = [ url(r'^accueil/$', home), ] The blog views.py looks like : #-*- coding: utf-8 -*- from django.shortcuts import render from django.http import HttpResponse # Ce module permet de retourner une réponse (texte brute, HTML, JSON, ...) depuis une string # Create your views here. def home(request) : text = """<h1>Bienvenue sur mon blog ! </h1> <p> Edité sous Django 1.10 </p>""" return HttpResponse(text) And the crepes_bretonnes urls.py looks like : from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^blog/', include('blog.urls')) ] However, when I'm running the server, I get this error (picture) and I don't understand why it's not working :/ As I said, I'm beginning Django so if anyone can explain me the problem ? Thank you ! -
How to call django.setup() in console_script?
The current django docs tell me this: django.setup() may only be called once. Therefore, avoid putting reusable application logic in standalone scripts so that you have to import from the script elsewhere in your application. If you can’t avoid that, put the call to django.setup() inside an if block: if __name__ == '__main__': import django django.setup() I am using entry points in setup.py. This way I don't have __name__ == '__main__'. How to ensure django.setup() gets only called once if you use console_scripts? -
How to use pdb effectively to debug Django?
I have been recommended to use pdb to understand and debug Django applications. Though I haven't found it very effective and want to learn how to avail maximum gain. To debug, below is how I generally proceed: I set breakpoint at most suspicious code section or at a point where control is going and then proceed with next or continue. As method completes I found myself in Django source code with no hint how to proceed to next code section written by developer. Previously I have worked on big C++ application and gdb was really helpful to understand control flow and debug. I want to achieve same thing with pdb for Django project at hand and any help even apart from pdb is appreciated? -
How can I use SQLAlchemy model with Django ModelForm
I have models defined in SQLAlchemy for a django application. Can I use Django ModelForm with SQLAlchemy models? By doing so it throws an error that there is no _meta defined in the SQLAlchemy model... -
How to fetch SSL Certificate for django project in Azure?
I have my django project in Azure named > djangoproj.azurewebsites.net I would like to provide SSL layer for this application and when I try to use openssl in Azure console, I get the following error > openssl req -sha256 -new -nodes -keyout djangoproj.key -out proj.csr -newkey rsa:2048 D:\home\site\wwwroot Generating a 2048 bit RSA private key ..................+++ .......................................+++ unable to write 'random state' writing new private key to 'djangoproj.key' ----- You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:problems making Certificate Request Problems making Certificate Request. May I know how to get a proper SSL certificate for my app in azure ? -
Using foreign keys in file upload django
I have two models as follows: class LabelModel(models.Model): labelled_image = models.FileField(upload_to='documents/label', db_column='path', default='Some Value') class Meta: db_table = "label_images" class ControlModel(models.Model): control_image = models.FileField(upload_to='documents/control', db_column='path', default='Some Value') class Meta: db_table = "control_images" Finally, I have a composite model as follows: class Document(models.Model): labelled_image = models.ForeignKey(LabelModel, db_column='label') control_image = models.ForeignKey(ControlModel, db_column='control') Now in my view, I have the following: if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): # Path to files labelled_file = request.FILES['labelled_image'] control_file = request.FILES['control_image'] # How should I create the Document model instance? My question is how should I now create an instance of the Document model and save it. Do I need to first create instances of LabelModel and ControlModel and upload those files and then create the Document model instance or is there a way to do this in one go with Django? -
How to have a site hosted on Heroku with database being stored locally on my computer?
I am hosting a Django site on the Heroku. However, Heroku does not allow databases with over 10 000 records stored for free. Can I store my database locally on a computer I have direct access to and still host the site on Heroku? -
How can I create .ebextensions/01_packages.config file?
I am deploying my django app on Elastic Beanstalk and going through the tutorial step by step. The is step involved "Customizing the Deployment Process" to add additional packages to Ec2. I need to add the following packages: packages: yum: git: [] postgresql93-devel: [] and asked to create .ebextensions/01_packages.config at the root of the project and I am not abel to create it. Anyone please help me with that. Thanks! -
How to make Django Parler assets to be loaded from Amazon S3 instead of static URL?
I am using Django-Storages with Amazon S3 Boto3 driver to store all the static content in Amazon S3, including assets such as CSS, JS. I have set up everything and all the assets from Django Admin and Django Parler are in my S3 bucket. Django Admin assets are already loaded from S3 (I checked the inspector and the URLs are correct) but Django-Parler assets are loaded from local URL, specifically the static URL that is defined in settings.py. Here is my settings.py regarding assets: DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' When I upload files for my objects, they are also uploaded to S3 to the correct directory in my bucket. The only problem is Django Parler and I don't know if there is a specific setting for it to add to my settings.py. What can I do to make Django Parler work with S3 bucket? -
Django login using Chrome Plugin doesn't work
I'm trying to create a plugin which allows user to log in using this plugin, not Django web page. The problem is that when everything seems to work correctly, user is not being logged. What I've done so far: There is a username and password field in a plugin. When I fill it with correct credentials and click on send button, the AJAX send POST request to the Django view which checks whether the user is correct, if credentials are correct, it uses login(request,user) command and returns JSONResponse with their name. Then the plugin alerts the name of the user. Everything seems to work correctly but when I try to go to http://127.0.0.1:8000/admin, it acts like I'm not logged in. Do you know why? The view: @csrf_exempt def api_authentication(request): if request.method == 'POST': login_ = request.POST.get('login') password = request.POST.get('password') if login and password: username = login_ if '@' in login_: username = mainapp_models.User.objects.get(email=login_).username if not username: return JsonResponse({'success': 0}) user = authenticate(username=username, password=password) print user if user: if user.is_authenticated: login(request,user) return JsonResponse({'username': user.username, 'success': 1}) return JsonResponse({'success': 0}) login.js from plugin: $(document).ready(function () { $('#login-button-id').click(function () { var login = $('#input-email-id').val(); var password = $('#input-password-id').val(); $.ajax({ url: 'http://127.0.0.1:8000/api/authenticate', type: 'POST', …