Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django does not want to include models in migration - PostgreSQL
I have quite a specific problem, with django-admin.py not creating tables for model in . I have created a PostgreSQL database, and user, then granted this user all Privileges on the database, then included this database in settings.py. The relevant section of settings.py looks like below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'crawler', 'USER': 'austinpowers', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '' } } Django is able to access this database, as manage.py dbshell works well. Now i want Django to create tables based on following models.py file of application "crawler": from django.db import models class Files(models.Model): id = models.IntegerField(primary_key=True, blank=False, null=False) filename = models.TextField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) def __unicode__(self): return self.filename class Meta: verbose_name = 'File' verbose_name_plural = 'Files' class IpLog(models.Model): id = models.IntegerField(primary_key=True, blank=False, null=False) ip = models.TextField(blank=True, null=True) time_changed = models.TextField(blank=True, null=True) def __unicode__(self): return self.time_changed class Meta: verbose_name = 'IP Log' verbose_name_plural = 'IP Logs' class Jobs(models.Model): id = models.IntegerField(primary_key=True, blank=False, null=False) run_no = models.IntegerField(blank=True, null=True) shop = models.TextField(blank=True, null=True) pzn = models.TextField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) def __unicode__(self): return self.shop + ": " + self.pzn class Meta: verbose_name_plural = 'Jobs' verbose_name = 'Job' So I make sure "migrations" folder in "crawler" … -
django-shibboleth-remoteuser ShibbolethValidationError
I am building django application where user is authenticated using django-shibboleth-remoteuser. settings.py INSTALLED_APPS += ( ‘myapp’, 'shibboleth', ) Default provided at django-shibboleth-remoteuser SHIBBOLETH_ATTRIBUTE_MAP = { "shib-user": (True, "username"), "shib-given-name": (True, "first_name"), "shib-sn": (True, "last_name"), "shib-mail": (True, "email"), } Modified SHIBBOLETH_ATTRIBUTE_MAP = { "shib-user": (True, "uid"), "shib-given-name": (True, "displayName"), "shib-sn": (True, "sn"), "shib-mail": (True, "email"), } In request meta information I can see (uid, title, sn, mail, id, displayName) attributes. With both above settings i get ShibbolethValidationError So my question is how can I custom attribute-map shibboleth meta-attributes in the django settings? -
How to make all Models readonly for a particular group in Django?
I want all my superusers to edit the models in the admin interface but staff just to read. What is the easiest way to do this? -
how to get data/value from html in django
I am working on a chess game. Below is a view file and Html file. I want to get move from html and I want to call getmove(self, board) function. I am using ajax for sending and receiving data to/from view to/from html. I am new to python but I have worked in java. so please help me figure out my mistake or any suggestion would be appriciated. def index(request): main() return render(request, 'chessGame/index.html', { }) def ajax_data(request, source, destination, piece): if True: return HttpResponse('true') else: return HttpResponse('false') class Player(object): allsquares = [(x, y) for x in range(8) for y in range(8)] dullmoves = 0 def __init__(self, colour, nature, name): self.colour = colour self.nature = nature self.name = name self.can_castle_long_this_turn = False self.can_castle_short_this_turn = False self.playedturns = 0 def __str__(self): if self.nature is 'AI': return self.name + ' (' + self.nature + ')' + ' as ' + self.colour else: return self.name + ' as ' + self.colour def set_opponent(self, opponent): self.opponent = opponent def getpieces(self, board): return [pos for pos in board if board[pos].colour is self.colour] def potentialtargets(self, playerspieces): return [pos for pos in self.allsquares if pos not in playerspieces] def kingpos(self, board): for mine in self.getpieces(board): if board[mine].piecename … -
Filtering fields with duplicates in django
Guys am trying to filter duplicates in a field in my model for Example my models are: class Household(models.Model): office = models.ForeignKey( Office, related_name='households', help_text=_('The office that manages this data'), ) uuid = UUIDField( auto=True, version=4, help_text=_('Unique identifier for each household'), ) name = models.CharField( _('Family Name'), max_length=255, help_text=_('Name by which the household goes by'), db_index=True class Person(models.Model): uuid = UUIDField(auto=True, version=4, help_text=_('unique id')) last_name = models.CharField(_("Last name"), max_length=255, help_text=_('last name'), db_index=True) first_name = models.CharField(_("First name"), max_length=255, blank=True, null=True, help_text=_('first name')) middle_name = models.CharField(_("Middle name"), max_length=255, blank=True, null=True, help_text=_('middle name')) location = models.ForeignKey(Location, verbose_name=_('Location'), help_text=_('location')) household = models.ForeignKey( Household, related_name='active_or_inactive_members', blank=True, null=True, verbose_name=_("Household"), help_text=_('Household') ) am using this query to get all duplicate persons in a household: first am filtering all households in an office households = Household.objects.filter(office='so-co') then i iterate over this households to filter persons with duplicate ids for household in households: persons = Person.objects.values('last_name').annotate(Count('id')).order_by().filter(id__count__gt=1) for person in persons: print person The problem is that my queryset is printing all persons, what am i missing out here? -
Raspberry pi, python, detect os
I am developing a django app which will run on the raspberry pi 3 in production. I must know at the start of the app if its running on raspberry, or in dev environment. In dev i use fake sensor data instead of the pins. Until now i used this method: from sys import platform as _platform test_environment = "win" in _platform or "darwin" in _platform This was working nice for both my pc and mac, but now i would like to deploy this to an ubuntu webserver online. Raspbian is also a linux dist, so i need something else. This is my currently working solution, but it hurts me deep inside. Any suggestion to make it better? try: import RPi.GPIO as gpio test_environment = False except: test_environment = True -
Open edX, How to setup CAS login?
I need to integrate my CAS into the Open edX platform. Where can I find the corresponding documentation? How is the process? (github.com/edx/configuration/wiki/Setting-Up-External-Authentication is not helpful) -
upgrade pip on mac to install a Django library?
I am working on a python/ django project from a mac, and have recently decided to switch to a different library for date/ time input on some of the forms on my website. The library I have decided to change to is Bootstrap3, and I am following the instructions at: https://github.com/nkunihiko/django-bootstrap3-datetimepicker to install it. The guide says that the first step is to 'Run pip install django-bootstrap3-datetimepicker', which I have done- and the bash console has displayed the message: Successfully built django-bootstrap3-datetimepicker Successfully installed django-bootstrap3-datetimepicker-2.2.3 However, it then displayed a message stating: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this... It also displayed another message stating: You are using pip version 8.1.2, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command I am quite new to Python/ Django, and have decided to change the library being used for the datetimepicker on the forms because of an issue with the current one that I haven't been able to resolve (it's not possible to select a date beyond … -
Django - queryset values return the same model multiple time for each category of a same model
I'm returning a json object from my views to my client side. Thus, in order to keep the code as simple as possible, here is what I do: def get(self, request, *args, **kwargs): inspirations = Inspiration.objects.active_translations(get_language()).filter(publish=True) inspirationsFilter = inspirations.values('translations__title', 'translations__slug', 'categories__translations__name', 'main_image__file') data = JsonResponse(list(inspirationsFilter), safe=False) return HttpResponse(data, status=200, content_type='application/json') But the problem I'm facing here, is this one, from a print with only categories and titles: [('First Inspiration!', 'category1'), ('Hey max how are you', 'category2'), ('A third inspiration', 'category1'), ('A third inspiration', 'category2')] As you can see, "A third inspiration" has 2 categories associated, thus it returns the item for each category. categories is a ManyToMany model field created by me, translations is a ManyToMany from django-parler. Thus, do you know of a solution to "concat" it? Or do I have to do it manually? I've tried values_list but the return is the same. -
SQL update query no such column in django
When i try to call a method from my view which runs a raw SQL query i get an operational error however when i check the database using sqlite manager on firefox it shows i have this column with the correct value //Wallet model class Wallet(models.Model): username = models.CharField(max_length=15,default='') amount = models.IntegerField(validators=[validate_not_neg], default=0) def add_money(self, money): self.amount = self.amount + int(money) cursor = connection.cursor() cursor.execute('UPDATE wallet_wallet SET amount= %s WHERE username=%s' %(self.amount, self.username)) def subtract_money(self, money): if int(money) > self.amount: raise ValidationError( ('%s greater than amount in wallet can not process.' % money), params={'value': money} ) else: self.amount -= int(money) cursor = connection.cursor() cursor.execute('UPDATE wallet_wallet SET amount= %s WHERE username=%s' % (self.amount, self.username)) def __str__(self): return self.username class Meta: permissions = (('add_money', 'can deposit money'), ('subtract_money', 'can take withdraw money')) //add_money view def add_money(request): print ("Request %s %s" % (request,type(request))) if request.user: if request.POST and request.POST.get('amount'): username = request.user.username add_amount = request.POST.get('amount') wallet = Wallet.objects.filter(username=username) wallet = wallet.get(pk=request.user.userprofile.wallet_id_id) print(wallet.username) wallet.add_money(add_amount) wallet.save() now = datetime.now() trans = Transaction(from_name=username, wallet_id=wallet.id, date=now, amount=add_amount) trans.save() print ("Request s %s" % request) return render(request, 'user_profile.html', {'user': request.user}) else: print ("Request j %s" % request) return render(request, 'add_money.html') else: print ("Request rf %s" % request) return … -
ModelChoiceField: displaying a list with attritbutes of the selected objects
In a ModelForm I want to have the user select a user from a list of all user's last_names. After reading the docs on ModelChoiceField I thought I would use the following: (in a ModelForm in forms.py): myfield = forms.ModelChoiceField(queryset=User.objects.all(), to_field_name="last_name") However, the effect is my form has the user select a choice from a list of usernames, and not of last names. What am I doing wrong? -
model_to_dict is not returning DateTimeField with auto_now_add = True
I have created a model as: class Job(models.Model): jobId = models.AutoField(primary_key = True) startTime = models.DateTimeField(auto_now_add = True) When I'm doing print(model_to_dict(job)) I'm getting only {'jobId': 1} as output. Why 'startTime' filed is not coming in the output? Please help me with this issue. -
Create a custom aldryn_forms plugin
First of all, aldyn_forms is great for my users. Now I would like to add a custom "range" element for Django CMS (<input type="range" />). I tried the following, but it does not render the element. What am I doing wrong? cms_plugins.py: from aldryn_forms.cms_plugins import Field from cms.plugin_pool import plugin_pool from django.forms import Widget from django.utils.translation import ugettext_lazy as _ from django import forms class RangeWidget(Widget): def __init__(self, attrs=None): super().__init__(attrs) def render(self, name, value, attrs=None): return 'This should render, but it does not render' class RangeForm(forms.ModelForm): def __init__(self, *args, **kwargs): if 'instance' not in kwargs: # creating new one initial = kwargs.pop('initial', {}) initial['required'] = False kwargs['initial'] = initial super().__init__(*args, **kwargs) class Meta: fields = ['label', 'help_text', 'required', 'required_message', 'custom_classes', 'min_value', 'max_value'] class RangeElement(Field): widget = RangeWidget def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def widget_attrs(self, widget): return super().widget_attrs(widget) class RangeField(Field): name = _('Range Field') form = RangeForm form_field = RangeElement form_field_widget = RangeElement.widget fieldset_general_fields = [ 'label', ('min_value', 'max_value'), 'required', ] fieldset_advanced_fields = [ 'help_text', 'required_message', 'custom_classes', ] plugin_pool.register_plugin(RangeField) -
auto delete data which is older than 10 days in django
In my django project i want to auto delete data which is older than 10 days. How can i write this view. how can it execute automatically. In my model there is a post_date field.by which i want to check whether it is 10 days old or not? model.py class CustomerLeads(models.Model): title = models.CharField(max_length=100, null=True, blank=True) budget = models.IntegerField(default=0,null=True, blank=True) posting_date = models.CharField(max_length=300,null=True, blank=True) quantity = models.IntegerField(default=1,null=True, blank=True) Thanks in advance. -
Django template filters: apply floatformat to widthratio
widthformat automatically rounds up. However I would like to perform a division and round up to n decimal places in the template tag if possible. For instance: <h4>Strike Rate: {% widthratio selected_replies user.projectreply_set.count 100 %}</h4> Currently it returns an integer. How would I apply floatformat here, or do I need to do this work in the view? -
Django Static Files in Production Using Whitenoise
Firstly apologies for the length of this. I have a django project running on Centos6 and Apache using a C-Panel plugin to install Django and I am trying to serve the static files in production. My project uses Django 1.9 and I am trying to use Whitenoise to serve my static files. My settings.py contains the following: STATICFILES_STORAGE ='whitenoise.django.GzipManifestStaticFilesStorage' STATIC_URL = '/static/' STATIC_ROOT = STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'common-static'), And this is my MIDDLEWARE_CLASSES MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', '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', ] ) This is the wsgi.py for my django app import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() And this is the one generated by the plugin: import os import sys import site vepath = '/home/mysite/virtualenv3.5/lib/python3.5/site-packages' prev_sys_path = list(sys.path) site.addsitedir(vepath) sys.path.append('/home/mysite/djangosites/mysite') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE","mysite.settings" application = get_wsgi_application() I have DEBUG = False in my settings.py. When I run ./manage.py collectstatic the files are collected and if I run the server with 0.0.0.0:8000 the static files are found. I tried add the following to both wsgi.py files but to no avail: from whitenoise.django importDjangoWhiteNoise application = DjangoWhiteNoise(application) Any advice on how to solve this would be … -
Django @csrf_exempt not working
Django version:1.10.4 I've used @csrf_exempt decorator with @require_POST decorator, but I'm still getting the error 403 Forbidden (CSRF cookie not set.) Any solution? -
How to run a celery worker with Django app scalable by AWS Elastic Beanstalk?
How to use django with Elastic Benastalk that would also run tasks by celery on main node only? -
How can I change charset and collation with Django's migrations?
I have a character field that's utf8 I want it to be utf8mb4, how do I accomplish that with Django's migrations? -
Throw Exception When Parameter Missing Django Rest Framework
I am new to Python, Django and the Django Rest Framework - although I am loving the learning curve! I would like to know what is the standard (most common) way of raising an exception when an API's parameter is not provided ? Obviously if conditions in the view's body is not the way to go. Are there an decorators that I can pass parameter names to ? -
pagenumberpagination not working in generic view django rest framework
from rest_framework import viewsets from .models import Hospital, Patient from .serializers import HospitalSerializer, PatientSerializer from rest_framework.pagination import PageNumberPagination from rest_framework import mixins class ListModelViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): pass class SmallPagesPagination(PageNumberPagination): page_size = 100 class PatientViewSet(ListModelViewSet): queryset = Patient.objects.all() serializer_class = PatientSerializer pagination_class = SmallPagesPagination class HospitalViewSet(ListModelViewSet): queryset = Hospital.objects.all() serializer_class = HospitalSerializer pagination_class = SmallPagesPagination pagination is not working for me -
Inherit python object in Django model
I am trying to understand if it is possible to inherit a regular python class in a django model. The idea is that I need a common "interface" for the models and for another part of the system(that works with mongo). the example is: class myC(object): def __init__(self): self.f = "test" class myM(myC, models.Model): name = models.CharField(max_length=50) making myC inherit from Model and making it abstract is not really possible for me. and even more so i wonder what would the table for myM look like(if what i am trying to do is possible). -
request object does not have a user Django
I am making a wallet app so if someone goes to http://127.0.0.1:8000/add_money/ to add money and they press submit the money has to be added to their wallet but after submit there is an error AttributeError at /add_money/ 'unicode' object has no attribute 'user' I have put some checkpoints for better understanding the flow of operations Request <WSGIRequest: GET '/add_money/'> Request j <WSGIRequest: GET '/add_money/'> [15/Dec/2016 15:26:34] "GET /add_money/ HTTP/1.1" 200 420 Request <WSGIRequest: POST '/add_money/'> Request 3 [15/Dec/2016 15:26:37] "POST /add_money/ HTTP/1.1" 500 66535 //add_money view def add_money(request): print ("Request %s" % request) if request.user: if request.POST and request.POST.get('amount'): username = request.user.username add_amount = request.POST.get('amount') wallet = Wallet.objects.filter(username=username).update(add_money(add_amount)) now = datetime.now() trans = Transaction(from_name=username, wallet_id=wallet.id, date=now, amount=add_amount) trans.save() print ("Request s %s" % request) return render(request, 'user_profile.html', {'user': request.user}) else: print ("Request j %s" % request) return render(request, 'add_money.html') else: print ("Request rf %s" % request) return HttpResponseRedirect('/login/?next={}'.format('/add_money/')) //add_money template <form method="post"> Amount:<input type="number" name="amount"> <input type="submit" value="Submit"> <button type="button" name="cancel">Cancel</button> {% csrf_token %} </form> -
Django 1.10: Error when deleting a model with a GenericRelation
In my project I am mapping models inheriting from class A to models of type B using a GenericRelation via a third model, ABMapping. models.py: class A(models.Model): b = GenericRelation(B) class Meta: abstract = True class ABMapping(models.Model): b = models.ForeignKey(B) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class B(models.Model): x = ... y = ... In the Django admin when I try to delete an object of child of A, I get an error, "Cannot resolve keyword u'object_id' into field. Choices are: x, y, id, abmapping." It seems like it's trying to take a field from ABMapping, but find it in B. As you can see, I stripped down my models to the bare minimum, but the problem still happens. Even when I delete all the ABMappings for the object of a child class of A, the same problem occurs. All the seemingly related questions on StackOverflow relate to people complaining that the cascade-delete isn't happening... but I can't even get the top-level delete to take place. What am I missing here? Thanks! -
Django: How to take row wise input in Django forms?
I want to take row-wise input in Django forms. The table is as shown in: enter image description here The rows of 'Source' field should be headings and corresponding to it should be input field belonging to 'Data' field (in html template) such that the input correspondingly goes into proper record.