Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert an string with array form to an array?
I got a string in this form payload = ["Text 1", "Text 2"] I want to use Text 2 as an object. How can I return it? UPDATE I'm making a function which returns a generic template Facebook API. The first payload works well, but I want to return a string and a object in the second payload ( result ) button = [ { "type": "postback", "title": "Buy item", "payload": "Buy this item: " + (product['id']) }, { "type": "postback", "title": "Add to wishlist", "payload": result } ] My second payload should look like this: payload = { 'Order_item', product['title'] } Because I got this error [buttons][1][payload] must be a UTF-8 encoded string so I did convert it and it returns a STRING in this form ["Order_item", "Ledverlichting Fiets Blauw"] Because I want that when a Facebook user clicks on a postback ( Add to wishlist ), the product['title'] value will be save in Django database. And product['title'] is the Text 2 in the question above. -
'type' object is not iterable in using django_enums
I tried to use django_enums and got an error with list(cls): Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/rita/Serpentarium/ServiceForServices/project/serviceforservices/service/models.py", line 84, in <module> class EmployeesStatus(models.Model): File "/home/rita/Serpentarium/ServiceForServices/project/serviceforservices/service/models.py", line 86, in EmployeesStatus status = enum.EnumField(StatusEnum, default=StatusEnum.AT) File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django_enums/enum.py", line 53, in __init__ kwargs['max_length'] = self.enum.get_max_length() File "/home/rita/Serpentarium/ServiceForServices/venv/local/lib/python2.7/site-packages/django_enums/enum.py", line 39, in get_max_length return len(max(list(cls), key=(lambda x: len(x.key))).key) TypeError: 'type' object is not iterable I installed django-enums, enum and six: (venv:SFS)rita@rita-notebook:~/Serpentarium/ServiceForServices/project/serviceforservices$ pip install django-enums (venv:SFS)rita@rita-notebook:~/Serpentarium/ServiceForServices/project/serviceforservices$ pip install enum (venv:SFS)rita@rita-notebook:~/Serpentarium/ServiceForServices/project/serviceforservices$ pip install six Using in Models.py: ... from django_enums import enum ... class EventTypes(enum.Enum): __order__ = 'I W E' # for python 2 I = (u'I', u'Info') W = (u'W', u'Warning') E = (u'E', u'Error') class EventLog(models.Model): event_time = models.DateTimeField(default=datetime.now) event_type = enum.EnumField(EventTypes) It seems like project is alive, it also was updated for Django 1.10 and compartible with python 2 allegedly. So, what I'm doing wrong? -
Apache virtualenv and mod_wsgi : ImportError : No module named 'django'
I'm having issues running django and apache2/mod_wsgi. This is my current setup: Ubuntu: 16.0 Apache: 2.4.18 Python: 3.5 Django: 1.10 I have installed a virtualenv inside my django project for user 'carma'. Structure is: /home/carma/mycarma |- manage.py static mycarma |__init__.py |settings.py |urls.py |wsgi.py mycarmanev bin include lib This is the content of /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> Alias /static /home/carma/mycarma/static <Directory /home/carma/mycarma/static> Require all granted </Directory> <Directory /home/carma/mycarma/mycarma> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mycarma python-path=/home/carma/mycarma/ python-home=/home/carma/mycarma/mycarmavirtuale$ WSGIProcessGroup mycarma WSGIScriptAlias / /home/carma/mycarma/mycarma/wsgi.py This is the content of wsgi.py import os,sys from django.core.wsgi import get_wsgi_application DJANGO_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..') sys.path.append(DJANGO_PATH) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mycarma.settings") application = get_wsgi_application() And I have already given permissions: sudo chown -R www-data:www-data /home/carma/mycarma/mycarmaenv sudo chown -R www-data:www-data /home/carma/mycarma The problem comes when I try to access the url of my server, checking the apache log this is the issue: [wsgi:error] [pid 25183] mod_wsgi (pid=25183): Target WSGI script '/home/carma/mycarma/mycarma/wsgi.py' cannot be loaded as Python module. [wsgi:error] [pid 25183] mod_wsgi (pid=25183): Exception occurred processing WSGI script '/home/carma/mycarma/mycarma/wsgi.py'. [wsgi:error] [pid 25183] Traceback (most recent call last): [wsgi:error] [pid 25183] File "/home/carma/mycarma/mycarma/wsgi.py", line 12, in <module> [wsgi:error] [pid 25183] from django.core.wsgi import get_wsgi_application [wsgi:error] [pid 25183] ImportError: No module named 'django' I … -
Django and uuid generated by database
I'm creating a rest api using Django and DRF. I don't want to expose IDs directly to client so I'm trying to setup my models like this example: class AbstractGuidModel(models.Model): uuid = models.UUIDField(blank=True, default=uuid.uuid4, unique=True, editable=False) class Meta: abstract = True class MyModel(AbstractGuidModel): name = models.CharField(max_length=NAME_LENGTH) Since the AbstractGuidModel has default=uuid.uuid4, uuid are generated by python code and migrations look like: CREATE TABLE "MyModel" ( ... "uuid" uuid NOT NULL UNIQUE, ... ); I've read Postgres has an extension for generating automatically uuids. Once setup, how can I tell django to use that extension? -
Adding in 2 tables in the same function in backand service
I am tring to add a new user and a new reporter in the same time knowing that the reporter is an user .... In the backand I am using a django rest project which means I am using the one to one relation between users table and reporters table ans in the frontend I am using ionic 2 with a backandservice this is my function : public signUp (first_name, last_name, media, email, address, phone, office_phone, username, password){ let user_data = { first_name: first_name, last_name: last_name, email: email, username:username, password: password, }; let header = new Headers(); var user = this.http.post(this.api_url+'users/', user_data, { headers: header }) .subscribe( data => { console.log(data); }, err => { console.log(err); }, () => console.log('user saved !') ); let reporter_data = { address: address, media: media, phone: phone, office_phone: office_phone, user: user, }; var reporter = this.http.post(this.api_url+'reporters/', reporter_data, { headers: header }) .subscribe( data => { console.log(data); }, err => { console.log(err); }, () => console.log('reporter saved !') ); return reporter; return user + reporter; } this code can only add a new user but not both in the same time which I want to do I need help please ! -
Django : How can I make (generic) View only accept POST or GET request
views.py class CustomerInfoCheckView(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): # CustomerInfoForm by ajax request if request.is_ajax(): form = CustomerInfoForm( request.POST, ) if form.is_valid(): return JsonResponse( data={ "valid": True, } ) else: return JsonResponse( data={ "valid": False, "errors": form.errors } ) As you can see here, it only accept POST request. I want to prevent user from accessing this view using GET requests. I found @require_http_methods but it only support function-based-view. Need helps. Thanks -
django_tables2, django-filters and crispy forms interactive column selection
I am currently using crispy-forms and django-filters to select a subset of my data and using django-tables2 to render it. My solution CBV adapted from (Django Tables - Column Filtering) to interact with my model. I would like to offer users the opportunity to select which columns they'd like to see in the table. I cannot figure out how to implement this kind of behaviour. Any pointers would be appreciated. views.py class ClientProfile(PagedFilteredTableViewClientProfile): model = Modelone table_class = ModeloneTable filter_class = ClientProfileFilter formhelper_class = ModeloneListFormHelper template_name = "legacy/profile.html" tables.py class ModeloneTable(tables.Table): class Meta: model = Modelone filters.py class ClientProfileFilter(django_filters.FilterSet): name = django_filters.CharFilter() age = django_filters.NumberFilter() utils.py class PagedFilteredTableView(SingleTableView): filter_class = None formhelper_class = None context_filter_name = 'filter' def get_queryset(self, **kwargs): qs = super(PagedFilteredTableView, self).get_queryset() self.filter = self.filter_class(self.request.GET, queryset=qs) self.filter.form.helper = self.formhelper_class() self.filter.form.helper.form_action = reverse_lazy('clientprofile') self.filter.form.helper.form_show_labels = False self.filter.form.helper.layout = Layout( PrependedText('name', 'Name'), PrependedText('age', 'Age'), FormActions( Submit('submit_filter', 'Filter', css_class='btn-primary'), Button('clear', 'Clear', css_class='btn-sm', onclick='window.location.href="{}"'.format(self.filter.form.helper.form_action)) ) ) return self.filter.qs def get_context_data(self, **kwargs): context = super(PagedFilteredTableView, self).get_context_data() context[self.context_filter_name] = self.filter return context -
MySQLdb python module installation director point to wrong folder
I hv installed Bitnami Python stack earlier at D:/Bitnami and then uninstalled it. Becuz as a beginner i find it distracting since some of the set up there is different from the official Django website. And then I reinstall Python from the official site to C:/Python. After that when I tried to install MySQLdb python module, the setuptools install wizard default installation path is set to D:/Bitnami/Python. I tried to uninstall and reinstall everything but the path is still set to Bitnami directory (which doesnt exist now)... How can I fix this? -
set_cookie() missing 1 required positional argument: 'self'
In Django, Im trying to render a template and send a cookie at the same time with this code: template = loader.get_template('list.html') context = {'documents': documents, 'form': form} if ('user') not in request.COOKIES: id_user = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(30)) HttpResponse.set_cookie(key='user', value=id_user, max_age=63072000) return HttpResponse(template.render(context, request)) But I get the Error: TypeError at /myapp/list/ set_cookie() missing 1 required positional argument: 'self' I have checked the documentation, but I dont find the solution. Help me please :) -
I am deploying Django App on heroku, after successful deployment , I am getting operational Error
OperationalError at /admin/login/ could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Request Method: POST Django Version: 1.10b1 Exception Type: OperationalError Exception Value: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Exception Location: /app/.heroku/python/lib/python2.7/site-packages/psycopg2/init.py in connect, line 164 Python Executable: /app/.heroku/python/bin/python Python Version: 2.7.12 Python Path: ['/app', '/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python27.zip', '/app/.heroku/python/lib/python2.7', '/app/.heroku/python/lib/python2.7/plat-linux2', '/app/.heroku/python/lib/python2.7/lib-tk', '/app/.heroku/python/lib/python2.7/lib-old', '/app/.heroku/python/lib/python2.7/lib-dynload', '/app/.heroku/python/lib/python2.7/site-packages', '/app/.heroku/python/lib/python2.7/site-packages/setuptools-25.2.0-py2.7.egg', '/app/.heroku/python/lib/python2.7/site-packages/pip-8.1.2-py2.7.egg'] -
Django Gunicorn Nginx file change on server
I have deployed my app on a Ubuntu 14.04 server by following the steps in this tutorial. Everything was working fine until i needed to make some changes in my templates and views. I have made the changes on my local machine and copied the files to server using SCP as i hadn't developed the app under a version controlling system. I tried restarting Gunicorn and Nginx but it didn't help. What is the proper way of making the server accept my changes? Thanks. -
Change the CharField to TextField
I want convert one of my field type from CharField to TextField I changed as followings: From: project = models.CharField('Project',max_length=500) To: project = models.TextField('Project',blank=True) And after I run the migrate cmd , I met the following errors: django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'project' used in key specification without a key length") I performed the steps mentioned in Django: Convert CharField to TextField with data intact MySQL: BEGIN; ALTER TABLE TestLog MODIFY failed_reqs TEXT NULL, MODIFY passed_reqs TEXT NULL; COMMIT; Bug met the same errors: mysql> ALTER TABLE ct_task -> MODIFY project TEXT NULL; ERROR 1170 (42000): BLOB/TEXT column 'project' used in key specification without a key length Anyone can help how can i do this conversion ? many thanks -
Django: Is remote database connect faster than Default database?
I had to load a million entries in my postgreSQL table from xls file and with default database settings it was taking more than 5 minutes (even after using raw SQL queries with cursor connect). So to improve the performance I tried it by remotely connecting (using psycopg2) the same database and it hardly took 100 seconds to insert all the entries. mydb = psycopg2.connect(database="test", user="test", password="test") cursor = mydb.cursor() cursor.execute('INSERT INTO TABLE') Although I was able to find a faster solution, I was unable to find the reason behind why connecting to a database remotely is faster than connecting to the default database. -
Get ID from template model form and display data from db django ajax django model forms
I have a view which starts by displaying the latest ID and data related to that id from the database. Please see the sample form here. http://i63.tinypic.com/s2gyhc.jpg I want to get that displayed ID, send it to my view, increment it and display the data corresponding to next ID. I have already posted the ID to the view. Now how do i show the new data without refreshing? Ajax code $("#next").click(function(e){ $.ajax({ type:'POST', url:'/next/', data:{ voucher_id:$('#id_voucher_id').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ alert('yo!') } }); return false;}); Views.py def master_detail_next(request): author_form = TmpForm() ''' Decide what we want to show''' if request.method == 'POST': author = TmpForm(request.POST) voucher_id = str(int(request.POST['voucher_id']) + 1) ''' Define the three forms here''' author = TmpPlInvoice.objects.get(voucher_id=voucher_id) author_form = TmpForm(instance=author) return render_to_response('main.html', {'form': author_form}, context_instance=RequestContext(request)) How can i do this in Django model forms/Ajax? -
Edit the many to many field Inline using Django Admin
I want to edit the cuisines associated with a dish on the dish panel in django admin.The problem is that I can edit the DishCuisinesMap objects but not the cuisines object. Here is the screenshot This is my models.py: class Cuisines(models.Model): cuisine_id = models.IntegerField(primary_key=True) cuisine_mtom = models.ManyToManyField('DishInfo', through='DishCuisinesMap') name = models.TextField() cuisine_sf_name = models.TextField() type = models.IntegerField() insert_time = models.DateTimeField() update_time = models.DateTimeField() class Meta: managed = False db_table = 'cuisines' class DishCuisinesMap(models.Model): dish = models.ForeignKey('DishInfo', on_delete=models.PROTECT, related_name='dcm_dish') cuisine = models.ForeignKey(Cuisines, on_delete=models.PROTECT, related_name='dcm_cuisine') insert_time = models.DateTimeField() update_time = models.DateTimeField() class Meta: managed = False db_table = 'dish_cuisines_map' unique_together = (('dish', 'cuisine'),) class DishInfo(models.Model): dish_id = models.BigIntegerField(primary_key=True) bid = models.ForeignKey(Brands, on_delete=models.PROTECT, db_column='bid', related_name='dinfo_brand') name = models.TextField() is_live = models.IntegerField() veg_nonveg_ind = models.SmallIntegerField(blank=True, null=True) sf_name = models.TextField() descr = models.TextField(blank=True, null=True) expert_tag = models.TextField(blank=True, null=True) special_desc = models.TextField(blank=True, null=True) reco_percent = models.IntegerField(blank=True, null=True) one_liner = models.TextField(blank=True, null=True) nutrition = JSONField() insert_time = models.DateTimeField() update_time = models.DateTimeField() images = ArrayField(models.TextField()) class Meta: managed = False db_table = 'dish_info' unique_together = (('bid', 'name'), ('bid', 'sf_name'),) def __unicode__(self): brand_name = self.bid.name return self.name and this is my admin.py: class CityDishFilter(admin.SimpleListFilter): title = ('city name') parameter_name = 'city_id' def lookups(self, request, model_admin): list_of_cities = list() queryset … -
How to include tag into static tag?
I am trying to load different stars images for rating (1 to 5 stars). The star images themselves are in the static directory. But in code I will decide which image to load. So how can I do something like this? {% static '{{ image_name_from_code_behind }}' %} -
Django best practice for web service
I want to create a webservice in a django project. What i mean by webservice is a route which will talk with json structures instead of html. I am wondering if a show put the webservice code in views.py or if i should create a separate file (like api.py ?). It will work on both cases, i juste want to know which is the cleanest way -
Does django debug_toolbar runs with static files stored on S3?
My app works well : with S3 and without debug_toolbar without S3 and with debug_toolbar. But when i combine S3 and debug_toolbar i got one error when loading the 1st static file loaded on S3. Error: Error when calling the metaclass bases function() argument 1 must be code, not str <link href="{% static "/css/mycss.css"%}" "" media="all" rel="stylesheet" type="text/css" /> -
User related attribute in admin view
Django==1.10.2 Trying to use Group.members related attribute in admin view with models: from django.utils.translation import ugettext as _ from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): group = models.ForeignKey( 'Group', verbose_name=_('Groupe'), related_name='members', blank=True, null=True, ) class Group(models.Model): name = models.CharField( max_length=255, unique=True, verbose_name=_('Nom'), error_messages={ 'unique': _('Ce nom est déjà utilisée.'), }, ) creator = models.ForeignKey( User, related_name='created_groups', blank=False, null=False, ) def __str__(self): return self.name Admin views: from django.contrib import admin from meal.models import Group, User class GroupAdmin(admin.ModelAdmin): fields = ('name', 'members') list_display = ('name', 'members') search_fields = ( 'name', ) class UserAdmin(admin.ModelAdmin): fields = ('email', 'last_name', 'first_name', 'group') list_display = ('email', 'last_name', 'first_name', 'group') search_fields = ( 'username', 'email', 'first_name', 'last_name', ) admin.site.register(Group, GroupAdmin) admin.site.register(User, UserAdmin) But admin view raise error: KeyError at /admin/meal/group/ 'manager' Complete trace here: http://pastebin.com/raw/awtW3p7w Error is related to ForeignKey related name usage ? How to list an modify Group.members in admin ? -
I want to use more than one custom user managers for my project. I have 3 Types of user in my project
3 Types of Users with different Login Systems. Student : Uses unique student_id and password for login. SchoolAdmin: Uses email and password for login. Developer (Team): Uses email and password for login and is able to login in admin panel. Here is My BaseUser class BaseUSER(AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) USERNAME_FIELD = 'email' Here is My user no.1 the student class StudentUser(BaseUSER): student_id = models.CharField(primary_key=True,max_length=10) address = models.CharField(max_length=500, blank=True) city = models.CharField(max_length=50,blank=True, null=True) state = models.CharField(max_length=50, blank=True, null=True) pincode = models.CharField(max_length=6,blank=True, null=True) email_id = models.EmailField(blank=True) phone_number = models.CharField(max_length=10, blank=True, null=True) mother_phone = models.CharField(max_length=10, blank=True, null=True) father_phone = models.CharField(max_length=10, blank=True, null=True) standard = models.CharField(max_length=2,blank=True, null=True) # bus_transport = models.ForeignKey(Bus,blank=True,null=True) USERNAME_FIELD = 'student_id' Here is My user no.2 SchoolAdmin class SchoolAdmin(BaseUSER): school = models.ForeignKey(School,blank=True,null=True) objects = NewUserManager() USERNAME_FIELD = 'email' Here is my user no. 3 the developer team (That need access to admin panel) class team(BaseUSER): pin_level = models.CharField(max_length=10) def get_full_name(self): return self.first_name I have created different user manager for each UserManager for School Admin class NewUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ if not email: raise … -
Any Point of Sale System using django?
I want to build a POS System using Django for my varsity project! I've googled but only found this, frankly this is not much helpful what I'm looking for ! I'm wondering is there any other project, from which I can get idea or guidelines! Note: I am newbee in Django. -
calling django list variable in HTML javascript
Is there a way to call a Django list variable in HTML JavaScript? I am unable to call the variable using {{list}}. The list has been returned from the view in Django. If I use "{{list}}" it calls the list but now it is a string. I am also facing similar issues in JSON.parse(). All help appreciated -
Don't have permission to access / on this server (apache2) in docker
Iam trying to host django project in Docker using apache2 server. Iam starting the apache server manually and able to access the the default site. But when i configure the 000-default.config file iam getting error You don't have permission to access / on this server. This is my 000-default.config file <VirtualHost *:8000> DocumentRoot /code/demo WSGIScriptAlias / /code/demo/app/wsgi.py <Directory "/code/ilab/backup"> Require all granted </Directory> CustomLog ${APACHE_LOG_DIR}/access.log combined ErrorLog ${APACHE_LOG_DIR}/error.log </VirtualHost> And this is my Dockerfile FROM ubuntu MAINTAINER kketan@somemail.com RUN apt-get update && apt-get -y --force-yes install build-essential RUN apt-get -y --force-yes install python python-pip python-dev RUN apt-get -y --force-yes install libffi-dev libssl-dev RUN apt-get install -y --force-yes libmysqlclient-dev RUN mkdir /code ADD evn_packages.txt /code ADD python_packages.txt /code RUN apt-get install -y apache2 RUN apt-get install -y mariadb-server RUN pip install --upgrade pip RUN pip install -r python_packages.txt RUN apt-get install -y vim ADD django /code EXPOSE 8000 RUN apt-get install -y libapache2-mod-wsgi Iam importing django project form the same directory shown above. Even with the default django server is able to run the project but not able to access the int the browser. I have also changed the port listen to 8000 as it was not working on default port … -
UnicodeDecodeError when ssh from OS X
My django app loads some files on startup (or when I execute management command). When I ssh from one of my Arch or Ubuntu machines all works fine, I able successfully run any commands and migrations. But when I ssh from OS X (I have El Capital) and try to do same things I got UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) To open my files I use with open(path_to_file) as f: ... Error happens when sshing from both iterm and terminal. I found out that reason was in LC_CTYPE environment variable. It wasn't set in my other linux machines but on mac it was UTF-8 so after I ssh to server it was set the same. Error was fixed after I unset LC_CTYPE. So the actual question is what is that happened and how to avoid this further? I can unset this variable in my local machine but will it take some negative effects? And what is best way of doing this? -
shell script for django VE causing deactivation of VE
So I am trying this simple script which is essentially this (a full gist can be found here): #!/bin/bash virtualenv env source ./env/bin/activate pip install --upgrade pip pip install django pip freeze > requirements.txt django-admin startproject mysite . git init git config user.name "somename" git config user.email "some-email@somedomain.com" gitIgnore=" env/ *.pyc " echo '$gitIgnore' > .gitignore git add . git commit -a -m 'Initial commit' After running the script I see that I am no longer within the virtual environment. Not sure why that is. I didn't deactivate at any point, so I would expect that I would still be in the env virtualenvironment. Anyone can please shed some light on why my virtual environment is getting deactivated?