Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple forms on one view
I have a Django template that has data from a few different model types combining to make it. A dashboard if you will. And each of those has an edit form. Is it best to process all those forms in one view as they are posted back to the same place and differentiating between them by a unique field like below? Or if having lots of different dedicated avenues is the way forward? Thanks for any guidance class ProjectDetail(DetailView): template_name = 'project/view.html' def get_object(self): try: return Project.objects.filter(brief__slug=self.kwargs['slug']).filter(team=get_user_team(self.request)).first() # add loop to allow multiple teams to work on the same brief (project) except Exception as e: project_error = '%s (%s)' % (e.message, type(e)) messages.error(self.request, 'OH NO! %s' % project_error) return redirect('home') def get_context_data(self, **kwargs): project = self.get_object() context = dict() context['project'] = project context['milestone_form'] = MilestoneForm(initial={'project': project}) context['view'] = self return context def post(self, request, *args, **kwargs): # get the context for the page context = self.get_context_data() try: # switch for each of the form types on the team profile page (shown if member) if 'milestone_form_submit' in request.POST: project=self.get_object() # set date arbitrarily to half way to brief deadline brief = Brief.objects.get(project=project) last_milestone = self.milestones().last() milestone_del_date = last_milestone.del_date + timedelta(days=7) new_milestone … -
How to retrieve a data requested by user from django models?
I have a model and it has user table as "foreign key" in it . I need a query by which i can get user requested value . Here is my models: from django.db import models #from django.contrib.auth.models import User from django.db import models from datetime import datetime from django.conf import settings class schedulesdb(models.Model): f_name = models.CharField(max_length=100) dateAndTime = models.DateTimeField(['%Y-%m-%d %H:%M:%S'],null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) def __unicode__(self): # on Python 2 return self.f_name I was trying in this way I don't know what was wrong here : Here is my views.py: from app.models import schedulesdb import django_filters from django.template import RequestContext from django.contrib.auth.models import User def new_job(request): user = request.user print user.username print user.id print "asdfjalksdjfklasjdf" if schedulesdb.objects.filter(user__id=user.id): data = schedulesdb.objects.get(user__id=user.id) print data.user return HttpResponse (data_set) Thanks in advance #peace -
Django Python Script
I've been sifting through the documention but I don't feel like I'm getting a clear answer. Is it possible to run something python-like if company_name.startswith(('A')): enter code here from within a Django site or app? How would I go about it? Currently the code I use is {% for TblCompanies in object_list %} <tr class="customer-table"> <td>{{ TblCompanies.company_id }}</td> <td>{{ TblCompanies.company_name }}</td> <td>{{ TblCompanies.contact_phone }}</td> <td>{{ TblCompanies.billing_address }}</td> <td>{{ TblCompanies.contact_e_mail }}</td> </tr> {% endfor %} but our customer database is too large and it's a burden to have to go through the list to find a customer. I want to instead sort it alphabetically using urls like http://path/to/customer_list/A -
Args and dictionary in render_to_response
How to pass arguments and a dictionary in the query ? My example does not work return render_to_response('bookmarks_add.html', {'categories': categories, 'args':args}) Separately work return render_to_response('bookmarks_add.html', args) and return render_to_response('bookmarks_add.html', {'categories': categories}) -
Django (1.10) override AdminSite
I've tried to override AdminSite class with my own custom class. I followed tutorial from django's documentation: https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#customizing-adminsite but it didn't work. To be specific, I'd like to override original AdminSite with my own class and not just add another admin site into my project. I've created my custom class MyAdminSite which inherit from class from django.contrib.admin import AdminSite class MyAdminSite(AdminSite): pass Then in my app urls.py I've add: from django.conf.urls import url, include import django.contrib.admin as admin from .admin_site import MyAdminSite admin.site = MyAdminSite() admin.autodiscover() urlpatterns = [ url(r'^', admin.site.urls), ] It seemed to work, but admin models are register to AdminSite insted of MyAdminSite. How can I permanently override admin.site and register all models to MyAdminSite? -
How to handle data retention period in django framework
Is there is a way to manage data retention period in Django? As data protection rule we have to get disposed of personal data that is not used any more. What is the most straightforward direction to handle this in django? -
Django session working on local server but not on AWS server
In my Django view I use self.request.user to identify the user of a REST Framework API call. This works fine when the Django project is running on a server on my laptop, the code correctly picks up the user. I am now trying to run my Django project on AWS EB and am having the problem that the self.request.user no longer identifies the user. The app code that is making the API call is exactly the same as is the Django server code. Do I have to adjust my server settings in some way? My settings.py looks like this: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '9-s0gj3$)(--+mgc^3qhy=iva#azu+7a@3=' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.linkedin', 'allauth.socialaccount.providers.twitter', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'imagekit', #'blog', 'storages', 'items', 'userprofile', 'dashboard', 'twip', 'django.contrib.gis' ] SITE_ID = 1 MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', "django.core.context_processors.request", ], }, }, ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS … -
Can't upload image file while testing Django
I am developing API using Django REST Framework. I have a Django model that has models.ImageField and it works just fine. But when I want to unittest creating model object, I get error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte My code: class PlacesTest(APITestCase): . . . def test_create_place_full(self): . . . image = SimpleUploadedFile(name='test.jpg', content=open('test.png', 'rb').read(), content_type='image/jpeg') request = self.factory.post(reverse('place-list'), {'name': 'test_place_1', 'picture': image, }) I have tried passing string with path to image, and I've tried methods from Django testing model with ImageField to do tests, but no success. What type should I pass to Django REST framework when adding image: file object or string with path? How can I add real file to my tests? -
Django add common conditions in model
I have model class QuerySetManager(models.Manager): def get_query_set(self): return self.model.QuerySet(self.model) class Post(models.Model): objects = QuerySetManager() STATUS = ( (1, 'PENDING'), (2, 'ACTIVE'), ) title = models.CharField(max_length=512,blank=False,null=True) status = models.IntegerField(default=1,choices=STATUS) class QuerySet(models.query.QuerySet): def active(self): return self.filter(status=2) When I try to access this way Post.objects.active().filter(other_condition='xxx').all() it throws error 'QuerySetManager' object has no attribute 'active' Can anyone help me to achieve this? -
Custom 'static' template tag in Django
everyone! I need to make some specific changes for static tag. It's result of hours of my work, but I got not what I needed. Following code works properly only if I remove "django.contrib.staticfiles" from INSTALLED_APPS. But it's not right way, because I turn off whole functionality of this app. Please, help me solve this issue. How can I specific a priority of "staticfiles". settings.py: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # 'django.contrib.staticfiles', ) myapp/templatetags/staticfiles.py: import re from django import template from django.contrib.staticfiles.templatetags.staticfiles import StaticFilesNode from myapp.settings.local import STATIC_VERSION class CustomStaticFilesNode(StaticFilesNode): @classmethod def handle_token(cls, parser, token): path = versioning_js_and_css( token.split_contents()[1], get_actual_version() ) node_obj = super().handle_token(parser, token) node_obj.path = parser.compile_filter(path) return node_obj def get_actual_version(): return STATIC_VERSION def versioning_js_and_css(path, version, tpl="'{path}?v={version}'"): try: cleaned_path = re.search("\'(.*?)\'", path).group(1) if cleaned_path.endswith('.css') or cleaned_path.endswith('.js'): path = tpl.format(path=cleaned_path, version=version) except AttributeError: pass return path def do_static_custom(parser, token): return CustomStaticFilesNode.handle_token(parser, token) register = template.Library() register.tag('static', do_static_custom) Thanks in advance! -
when something like insert into xxx select xxx in a procedure,how to use django-mssql get the recordset of procedure?
In My website,I use django-mssql to connect sqlserver 2008.In My database ,the table are be divide in groups,like t_inout_master_01,t_inout_master_02,...so in the procedure,I use temp table to select the data,when I use insert into xxx select xxx in my procedure,something error happened in both cursor.callproc and cursor.execute。the error says the the recordset is empty。I search for all day but nothing useful got,and the code in dbapi can't help too,can somebody help me?Thanks。 -
python django call chat.py in template $ajax ? giving error not found
hi i am new at python django. i have template where i wana call a file through ajax $.ajax({ type: "POST", url: "chat.py", data: {foo: 'bar', bar: 'foo'}, and urls.py from django.conf.urls import include , url from . import views from . import chat urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^$', chat.main, name='main'), ] and chat.py import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(file)))) sys.path.append("../../tf_seq2seq_chatbot_parent") import tensorflow as tf from tf_seq2seq_chatbot.lib.chat import chat def main(_): #chat() print('kjgjkh') if name == "main": tf.app.run() and views.py from django.shortcuts import render def index(request): return render(request , "base.html" , {}) error: poll/chat.py not found -
django app multiple hard drives [Errno 18] Invalid cross-device link
I have a django app on a debian server and my current site_media directory on the current disk is full. So I want to upload files On a second disk. The path on server is /disk : obj = form.save(commit=False) obj.user_id = self.request.user.pk obj.save() initial_path = obj.file.path print(initial_path) new = settings.MEDIA_ROOT_NEW + obj.file.name print(new) os.rename(initial_path,new) shutil.move(initial_path, new) and in my settings.py I have: MEDIA_ROOT = os.path.join(PROJECT_PATH, 'site_media/') MEDIA_ROOT_NEW = '/disk/site_media/' still I get error: django [Errno 18] Invalid cross-device link Any ideas??? -
Setting height of html img element with function
I'm trying to set the height of images loaded into my html file with Django as such: <img data-original={{img.url}} width='310' height=calcHeight({{img.height}}, {{img.width}})/> With the 'calcHeight(h,w)' function being a simple function to scale the height of the image in proportion to the width of 310. I have to do this because I use a lazyloader plugin that needs to generate empty placeholders for the images prior to loading the images themselves. The images are of varying dimensions so I need to get the height and the width of the images before the actual images are loaded, otherwise the placeholders will be of 'no height' prior to loading the actual images, causing the layout to get messed up in the process. The code above doesn't work and I'm guessing it is because you can't call a function for height like that. I hope I explained the question precise enough and thanks in advance for any tips! -
How to convert nested list to object
When I receive JSON data like [ { "id":1, "name":"New Island", "residents":[ { "name":"Paul", "age":"25" } ] }, { "id":2, "name":"One Nation", "residents":[ { "name":"James", "age":"23" }, { "name":"Jessica", "age":"26" } ] } ] drf deserializer makes it to list which contain OrderedDict But I want to make it to list of class object. Here are my django models class Country(models.Model): name = models.CharField(max_length=20) class Resident(models.Model): name = models.CharField(max_length=20) country = models.ForeignKey('Country', related_name='residents') -
Creating multiple SignupForm allauth
I am trying to create a way to signup as 3 different types of users using allauth with each their own SignUp fields. I have created the CustomUsers using How to customize user profile when using django-allauth The 3 custom user SignupForm wouldn't require the same fields : some require first_name/last_name but no name, while the other require name but no first/lastname For now, just for tests, I differenciate user_type with a <select> in the SignupForm, but now I want to have 3 URLs pointing to /usertype1/signup , /usertype2/signup, /usertype3/signup However, I see I can only customise with one ACCOUNT_SIGNUP_FORM_CLASS = 'yourproject.yourapp.forms.SignupForm' One way I tried to do was be to create 3 templates with a hidden <input>, but it not really elegant : any idea how to customise SignupForm maybe ? Thank you :) -
Tryng to run 2 Python applications with different Python versions with mod_wsgi
I have in my Apache 2 applications: Django app and MoinMoin app. The first one is running now with Python3.4 and the second one (MoinMoin) with Python2.7 When running dpkg: ruben@babylon:/var/log/apache2$ dpkg -l | grep wsgi rc libapache2-mod-wsgi 3.4-4ubuntu2.1.14.04.2 amd64 Python WSGI adapter module for Apache ii libapache2-mod-wsgi-py3 3.4-4ubuntu2.1.14.04.2 amd64 Python 3 WSGI adapter module for Apache but Apache can't run the 2 modules at the same time. Django (Python3) is working but MoinMoin (Python2.7) not. How can I fix that? Thanks. -
Pandas to_sql() not working with Posgresql - value too long for type character varying
I'm using Pandas with SQLAlchemy to apply some ETL on one CSV file After validating the fields and transforming some of them I try to export to my PostgreSQL database, but I'm getting one error which does not make sense: sqlalchemy.exc.DataError: (psycopg2.DataError) value too long for type character varying(50) I already changed the field to many values (it was initially setup as 15). I tried to get NaN values for that field and replacing with '' (there was only one field). For that I used: >>> df.loc[df['foo'].isnull(), 'foo'] = '' I tried changing the chunksize to 5000 and 1000. Initially, it was not set. >>> df.to_sql("mytable", con, index=False, if_exists='append', chunksize=1000) The command above worked with sqlite After having those problems I checked the column which was throwing the error again to see if there was any problem with its length. Apparently, it did not, but I ran the following code anyway: >>> df.foo.str.len().max() 11.0 I also tried the following: >>> df.fillna(value='', inplace=True) >>> df['foo'] = df['foo'].str.strip() Then I also added for f in Inventory._meta.get_fields(): if f.get_internal_type() == 'CharField': df[f.name] = df[f.name].str[:f.max_length] But it did not work either I finally put the length of the column to 100, but this is … -
Login from local db/sqlite3 in django rest services
i just want to login from local db/sqlite3 in django Rest Services.here is my serializer.py class LoginSerializer(serializers.Serializer): username = serializers.CharField(required=True, allow_blank=True, max_length=100) password = serializers.CharField(required=True, allow_blank=True, max_length=100) def create(self, validated_data): return Login.objects.create(**validated_data) and my model.py is class Login(models.Model): username = models.TextField() password = models.TextField() class Meta: ordering = ('username','password') and view.py is class LoginDetail(generics.ListCreateAPIView): queryset = Login.objects.all() serializer_class = LoginSerializer and the url is url(r'^log/', views.LoginDetail.as_view()), am not sure what i did is correct or not, please excuse if its totally ircorrect can anyone please help me to do this..? -
Error: [Errno 71] Protocol error: pyvenv
I am using Centos7 with vagrant and virtualbox on windows10. I am trying to create pyvenv virtual environment to develop python web apps with django. I have installed python 3.4. However, when I type pyvenv-3.4 name_of_environment, it gives back an error Error: [Errno 71] Protocol error: 'lib' -> '/vagrant/django_apps/app1/name_of_environment/lib64' What is wrong? -
Celery: one worker process blocks execution of other worker processes? Shared what?
I experience a strange interaction between Celery worker processes, which I assumed to be independent. Can you suggest a possible reason for this? I have a celery worker with multiple worker processes: PPID PID 5892 5919 \_ /bin/bash -c sleep 10 && python manage.py makemigrations --noinput; python manage.py migrate --noinput; python manage.py initservice; celery -B -A workflows --workdir=/srv/workflows -l info --autoscale=2,30 -n UNIVERSE_NODE -Q workflows worker 5919 6168 \_ /usr/bin/python /usr/local/bin/celery -B -A workflows --workdir=/srv/workflows -l info --autoscale=2,30 -n UNIVERSE_NODE -Q workflows worker 6168 6180 \_ /usr/bin/python /usr/local/bin/celery -B -A workflows --workdir=/srv/workflows -l info --autoscale=2,30 -n UNIVERSE_NODE -Q workflows worker 6168 6185 \_ /usr/bin/python /usr/local/bin/celery -B -A workflows --workdir=/srv/workflows -l info --autoscale=2,30 -n UNIVERSE_NODE -Q workflows worker 6168 6186 \_ /usr/bin/python /usr/local/bin/celery -B -A workflows --workdir=/srv/workflows -l info --autoscale=2,30 -n UNIVERSE_NODE -Q workflows worker 6168 6187 \_ /usr/bin/python /usr/local/bin/celery -B -A workflows --workdir=/srv/workflows -l info --autoscale=2,30 -n UNIVERSE_NODE -Q workflows worker 6168 6188 \_ /usr/bin/python /usr/local/bin/celery -B -A workflows --workdir=/srv/workflows -l info --autoscale=2,30 -n UNIVERSE_NODE -Q workflows worker ... ... Sometimes, one of the worker processes gets stuck and ... somehow it blocks all the other worker processes. When this process stops, other worker processes resume execution. By design, there … -
Django Generic ForeignKey
i have three models named company, admin and jobpost . Here Both company and admin can post the job. So i would like to implement generic foreignkey in post model . class Admin(models.Model): id = models.AutoField(primary_key=True) class Company(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class JobPost(models.Model): content_type = models.ForeignKey() object_id = models.PositiveIntegerField() post_by = GenericForeignKey('content_type', 'object_id') here id of Admin is integer and id of Company is UUID. Is it possible to implement a generic foreignkey in this case. -
Django Zinnia allow users to add entries
Ok so Django Zinnia ( http://docs.django-blog-zinnia.com/en/develop/) currently has the option to add entries, but for superusers only and from the admin page. I am new to Django and I am looking for a way to allow normal users to add entries(draft status, preset categories, etc.). I have seen this question posted 2 times already here but no answer.. Can anybody help me with this please? -
Django looking for id with primary key field defined
I'm using Django version 1.10.1, and i have to use external database with read only permission. I have generated my models with inspectdb commands. Everything works well untill i changed one field to Foreign key because i must included relations that inspectdb doesn detect. I have primary key's defined in both tables but when i define Foreign Key django looking for id field in referrence which is not exist in database. That's error which i got: (1054, "Unknown column 'vicidial_callbacks.lead_id_id' in 'field list'") And here is my models: class VicidialList(models.Model): _DATABASE = "dialer" lead_id = models.AutoField(primary_key=True) entry_date = models.DateTimeField(blank=True, null=True) modify_date = models.DateTimeField() status = models.CharField(max_length=50, blank=True, null=True) user = models.CharField(max_length=20, blank=True, null=True) vendor_lead_code = models.CharField(max_length=20, blank=True, null=True) source_id = models.CharField(max_length=50, blank=True, null=True) list_id = models.BigIntegerField() class Meta: managed = False db_table = 'vicidial_list' class VicidialCallbacks(models.Model): _DATABASE = "dialer" callback_id = models.AutoField(primary_key=True) lead_id = models.ForeignKey(VicidialList, related_name='lead',to_field='lead_id') list_id = models.BigIntegerField(blank=True, null=True) campaign_id = models.CharField(max_length=8, blank=True, null=True) status = models.CharField(max_length=10, blank=True, null=True) class Meta: managed = False db_table = 'vicidial_callbacks' So why Django looking for id column? Docs saying that Django wants to add its own id field until we have defined primary_key... -
How to use hex numbers in Django
I'm new to Django (and python) and I'm trying to use hexadecimal numbers. I have a model in which I use a PositiveIntegerField. But I'd like to enter numbers like 0x0000 in the form, and display as hex too when I list the table. Where should I look to have this behavior ? A custom widget, a manager, a meta subclass ? I have so much to learn (oh yeah baby!) but so little time. A little help to know where to look for would be appreciated :) Thanks