Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django TypeError: object() takes no parameters
Background: I need to do a POST request to add data to my program. I'm currently using advanced REST client to simulate the data packet that will be send by a arduino. it is currently sending this as a POST request: {"cellVoltageLow":28,"cellVoltageHigh":415,"cellVoltageAvg":415, "cellTempMin":5,"cellTempMax":15,"cellTempAvg":10,"stateOfCharge":50, "errorBitmap":0,"batteryVoltageIn":420,"motorAmp":200,"usageAmp":210, "auxAmp":10,"rpmMotor":1000,"uiState":0,"chargingStatus":1, "motorTemp":15,"inverterTemp":30,"inletTemp":5,"ambientTemp":5, "chargingAmp":10,"chargingVoltage":420,"apsVoltage":42, "maxAmpsInCharge":10,"bmsErrorValue":0,"energyDriveAH":1000, "energyRegenAH":100,"energyChargeAH":10,"energyDischargeAH":10, "energyDriveWH":1000,"energyRegenWH":10,"energyChargeWH":2300, "energyDischargeWH":23000,"drivenDistanceCM":100000, "chargedEnergyWH":1000,"returnedEnergyWH":10000, "connectedTimeSec":100,"driveTimeSec":240} if i post this to this class (csrf is disabled) def Voltage(request): global Voltage if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) Voltage.cellVoltageLow = data["cellVoltageLow"] Voltage.cellVoltageAvg = data["cellVoltageAvg"] Voltage.cellVoltageHigh = data["cellVoltageHigh"] Voltage.batteryVoltageIn = data["batteryVoltageIn"] Voltage.chargingVoltage = data["chargingVoltage"] Voltage.apsVoltage = data["apsVoltage"] print("got ur message" + str(request.body)) return HttpResponse("OK") if request.method == 'GET': return HttpResponse('{ "cellVoltageLow":' + str(Voltage.cellVoltageLow) + '{ "cellVoltageAvg":' + str(Voltage.cellVoltageAvg) + '{ "cellVoltageHigh":' + str(Voltage.cellVoltageHigh) + '{ "batteryVoltageIn":' + str(Voltage.batteryVoltageIn) + '{ "chargingVoltage":' + str(Voltage.chargingVoltage) + '{ "apsVoltage":' + str(Voltage.apsVoltage) + ' }' ) else: return HttpResponse ('Not allowed') class Voltage: cellVoltageLow = 0; cellVoltageAvg = 0; cellVoltageHigh = 0; batteryVoltageIn = 0; chargingVoltage = 0; apsVoltage = 0; Then i get the error. Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, … -
Django REST with generic m2m relations
Im trying to implement a trivial case, when i have a model (Project), that may have several blocks of content (types of blocks are limited). So, i cant decide, how to do it in a flexible way, easy to use as API. Im using postgres, and tried to do the following: Using JSONField for data in a block, so i can save different kind of data there, and just specifying block type. And m2m relationship through a intermediate model ProjectBlock, so i can sort blocks by a sort value. This thing is very important. I need to be able to sort these blocks. But it seems to me, that there is a better solution. Because, for instance, i want to save images in block data too, but i cant save it in json field. For now i have: class ProjectBlock(models.Model): block = models.ForeignKey(Block) project = models.ForeignKey('main.Project', related_name='project_blocks') sort_value = models.PositiveSmallIntegerField() class Project(models.Model): name = models.CharField() blocks = models.ManyToManyField(Block, blank=True, through='main.ProjectBlock') class Block(models.Model): BLOCK_TYPES = ( (1, 'video'), (2, 'image'), (3, 'text') ) block_type = models.PositiveSmallIntegerField( choices=BLOCK_TYPES, default=3, ) data = JSONField(blank=True, null=True) With this structure i can use nested django rest serializers, but need to clear relations every update of … -
Python: creating a mockclass and use it as a contextmanager
I'm trying to unit test a dynamic class that is supposed to be used as an inherited object to easily add functionality to the grand scheme. But also act as a standalone package, so testing should be minimum. This class has quite a few difficulties. NotImplemented Errors on method calls. Generic functions. For example: class SomeClass(object): def something(a): raise NotImplementedError(...) def process(self, data, route): func = getattr(self, route) if callable(func): return func(data) else: return func My question is whether it is possible to use a MockClass per such: class MockClass(SomeClass): # Patch problematic methods, I'm having difficulty # finding the right patching approach def patched_process(self, data, route): return 'example' @patch('MockClass.process', patched_process) def process(self, data, route): return super(MockClass, self).process(data, route) So that in my TestCase (Django, fyi)... class ClassTests(TestCase): def test_process(self): with MockClass() as testee: # run tests result = testee.process(1, 2) self.assertTrue(result == 'example') This would result then in no failed tests? -
Run button in Visual Studio gives options for manage.py instead of running
I am trying to run a Django project with manage.py as the startup file. I can run it fine from command prompt using python manage.py runserverand manually navigate to the site. I am expecting that when I press the run button in Visual Studio that it will start the server and open my browser to show me the page, but instead it just opens the options for manage.py: Type 'manage.py help <subcommand>' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser etc. I've tried re-setting manage.py as the startup file, resetting the startup project, and setting the startup script for the Python Tools Interactive Windows to manage.py. Thanks in advance for any help. -
Gulp AngularJS without gulp serve
I have been developing an angularJS website that has a decoupled backend(django) which serves api to it. Recently I moved to production and I was able to set django up for production with nginx successfully. Now on the way to get angular into production(which depends on gulp) I got to know that I would have to inject all the scripts(controllers, directives etc) in django home directory's html(say home.html). Since I have hundreds of these js files, it'd be stupid to inject them manually(hard-code) into home.html. So I moved on further and stumbled upon the dist or distribution version that gulp gives you when you run gulp serve:dist, I was happy since I got a "release" folder where if I double clicked on index.html, it loaded the home page(which is auth page) so I tried to log in but no functionality worked thereafter. Now it works with gulp serve:dist but does not if it isn't served. My questions are- Is there anyway to run index.html in distribution without depending on gulp serve? Is there a way in gulp with which you can create a standalone app that has all the necessary files injected and right structure which does not depend on … -
key and value of dictionary in html file Django
Hi guys I have a pretty basic question in a template of Django I have this {% for item in new_object_list %} {% for lista in item.select_opc %} {{ lista }} {% endfor %} {% endfor %} lista return this {'v': 'By Visit'} {'p': 'by Patient'} a dictionary I want to create a select with this but I only obtain de key, no the value I try this {% for item in new_object_list %} {% for lista in item.select_opc %} {% for k, v in lista %} {{ k }} {{ v }} or {{ lista.k }} {% endfor %} {% endfor %} {% endfor %} I try this too {% for k, v in lista.iteritems %} but nothing work, but if I try in the terminal works!! Any idea -
drf: Default value for serialization
I have the following set of serializers: class BackendSerializer(serializers.ModelSerializer): def to_representation(self, instance): return instance.backend.name or 'sample' class Meta: model = Backend fields = ('name', ) class UserSerializer(serializers.ModelSerializer): default_headers = serializers.JSONField() domains = serializers.JSONField() organization_id = serializers.SerializerMethodField() backend = BackendSerializer(source='backenduser') And the problem I am trying to solve: I want to have a default backend (e.g. sample) if it's not specified for the user, and currently I am getting null in all cases when there is no backend for this particular user. -
How to POST data with M2M?
I want to write an API endpoint that creates data for 2 models, linked together by a many-to-many relationship. Let's say these models are User and Group. Requirements: Both involved models does not exist yet, so I can not use pk to describe them. The endpoint can create as many users/groups as I want. If the relation between those models would have been a 1->N (ie. a user can be in N groups, but a group can be related to 1 user), the solution would have been trivial: 'user1': {'name': "robert", 'groups': [{'name': 'group1'}, {'name': 'group2'}] } 'user2': {'name': "jean", 'groups': [{'name': 'group3'}, {'name': 'group4'}] } But as it's a M2M, how I am supposed to do this? Nesting does not work: 'user1': {'name': "robert", 'groups': [{'name': 'group1'}, {'name': 'group2'}] } 'user2': {'name': "jean", 'groups': [{'name': 'group2'}, {'name': 'group3'}] } In this case, the server will probably try to create 4 groups instead of 3. Plus, I'm repeting myself trying to specify 1 object twice. Note that here, a group object is a simple model, but in my real case, the object is a complex one with multi-level nesting one, so I can not repeat myself. How would you solve … -
Formsets in UpdateView
I'm trying to group some of the fields of a large user model in to fieldsets to be displayed in UpdateView. (eg group address fields into address fieldset.) Is there a way this can be done? views.py class UserUpdateView(LoginRequiredMixin, UpdateView): fields = ['title', 'first_name', 'last_name', 'date_of_birth', 'email', 'phone_number', 'house_name_number', 'street_name', 'town_city', 'county', 'postcode', ] model = User def get_success_url(self): return reverse("users:detail", kwargs={"username": self.request.user.username}) def get_object(self): return User.objects.get(username=self.request.user.username) -
Django user id is null
I have a user in my django table - auth_user. The username = 'django' but when I check the id its None. When I check in the tables, the id is set to 1. Not sure why u.id is None. -
Insert function in update() method of Django ORM
I need to transliterate some fields of my model in queryset. For example, i have : class Review(models.Model): author = models.CharField(max_length=128) author_en = models.CharField(max_length=128) text = models.TextField() And i want to make something like this: Review.objects.all().update(author_en=utils.transliterate(F('author'))) So author = "боб" should be author_en = "bob". -
django multiple database: could not create table with secondary database
I am developing an app that need to deal with two databases and I could get the two database setup running however while makemigrations it is not detecting the changes made in the model which are not associated with default database: Here is the code snippet of what I am doing: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': "name", 'USER': "user", 'PASSWORD': "pass", 'HOST': "", 'PORT': '', }, 'mysqlData': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name2', 'USER': 'user2', 'PASSWORD': 'pass2', 'HOST': "", "PORT": '' } } DATABASE_ROUTERS = ['router.DataRouter', ] DATABASE_APPS_MAPPING = {'mysql-data': 'mysqlData', } router.py: class DataRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'mysql-data': return 'mysqlData' return 'default' def db_for_write(self, model, **hints): if model._meta.app_label == 'mysql-data': return 'mysqlData' return 'default' def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'mysql-data' and obj2._meta.app_label == 'mysql-data': return True elif 'mysql-data' not in [obj1._meta.app_label, obj2._meta.app_label]: return True return False def allow_migrate(self, db, model): if db == 'mysqlData' or model._meta.app_label == "mysql-data": return True else: return True models.py: class data(models.Model): x = models.FloatField(default=0) y = models.FloatField(default=0) class datamysql(models.Model): x = models.FloatField(default=0) y = models.FloatField(default=0) class Meta: app_label = 'mysql-data' the problem is it only detects the changes in model data which corresponds to … -
Selecting Distinct Objects based on Value of Related Field AND order of DateTime Field
Given the following two (simplified) Models: class User(AbstractUser): pass class Device(models.Model): user = models.ForeignKey(User) last_reported_location_date = models.DateTimeField() last_reported_location_lat = models.FloatField() last_reported_location_lng = models.FloatField() I want to return a list of Devices distinct on user such that if a user has multiple devices, only the device with a more recent last_reported_location_date is selected. I would prefer an ORM solution, but a SQL-only solution might also be insightful. I am using Django v1.8.13 with PostgreSQL v9.4 - thanks. -
Django - Circumvent "Forbidden (CSRF cookie not set.)"
I'm creating a webserver for a raspberry pi3 that will get postdata from a arduino mega over ethernet with tcp/ip. I'm currently trying to receive POST data via the advanced REST client from chrome but i cant post data without getting the error: Forbidden (CSRF cookie not set.): /api/voltage/ [26/Oct/2016 12:54:15] "POST /api/voltage/ HTTP/1.1" 403 2857 I have tried adding a @csrf_exempt in front of the class and this has worked for the first 2 classes but when i tried to add more it wouldn't work. csrf cookie is not needed because the raspberry isnt connected to the internet and the connection will be in a car without connection to the car itself. I have the code attached under here from django.shortcuts import render from django.http import HttpResponse from django.core import serializers # Create your views here. from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def index(request): global tempmotor, tempaccu, toeren global temp if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) Temperatuur.accu = data["temperatuuraccu"] Temperatuur.motor = data["temperatuurmotor"] toeren = data["toerentalmotor"] print("got ur message" + str(request.body)) return HttpResponse("OK") if request.method == 'GET': return HttpResponse('temperatuur motor = ' + str(Temperatuur.motor) + ", temperatuur accu = " + str(Temperatuur.accu) ) else: return HttpResponse ('Not allowed') … -
Periodic task in celery doesn't work
I'm new in Celery. I'm trying to properly configure Celery with my Django project. To test whether the celery works, I've created a periodic task which should print "periodic_task" each 2 seconds. Unfortunately it doesn't work but no error. 1 Installed rabbitmq 2 Project/project/celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') from django.conf import settings # noqa app = Celery('project') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def myfunc(): print 'periodic_task' @app.task(bind=True) def debudeg_task(self): print('Request: {0!r}'.format(self.request)) 3 Project/project/__init__.py from __future__ import absolute_import from .celery import app as celery_app 4 Settings.py INSTALLED_APPS = [ 'djcelery', ...] ... ... CELERYBEAT_SCHEDULE = { 'schedule-name': { 'task': 'project.celery.myfunc', # We are going to create a email_sending_method later in this post. 'schedule': timedelta(seconds=2), }, } And before python manage.py, I run celery -A project worker -l info Still can't see any "periodic_task" printed in console every 2 seconds... Do you know what to do? -
python virtualenv can not access file in home directory
I am using this code in Django settings to construct the DB path from os.path import expanduser defautl_db_path = expanduser("~")+"/db.sqlite3" The code runs well if I installed Django system wide but if I run the application inside virtualenv the application throws an exception saying unable to open database file. How can I solve this? -
Django objects.create() causing duplicate primary keys
I'm running load tests with JMeter on a Django project with a Postgres database. This has managed to cause duplicate primary key errors when creating M2M objects; IntegrityError: duplicate key value violates unique constraint "entry_entrycharityenquiry_pkey" DETAIL: Key (id)=(108) already exists. This is happening when trying to create the relationship to objects after a user has selected from a list; for ec in to_add: EntryCharityEnquiry.objects.create(**kwargs) I can't see a problem with creating objects in a loop, so where/what could the error come from? -
Ember data JSONAPIAdapter: fetch nested resources
I'm trying to get Ember Data's JSONAPIAdapter to work with nested resources. For the server part django-rest-framework-json-api is used. My (simplified) ember models: case.js export default Model.extend({ firstName: attr('string'), lastName: attr('string'), comments: hasMany('comment'), }) comment.js export default Model.extend({ text: attr('string'), case: belongsTo('case'), }) The server's response for /api/v1/cases/4 looks like this: { "data": [ { "type": "cases", "id": "4", "attributes": { "first-name": "Hans", "last-name": "Peter", }, "relationships": { "comments": { "meta": { "count": 1 }, "data": [ { "type": "comments", "id": "5" } ], "links": { "related": "http://localhost:8000/api/v1/cases/4/comments" } } } } ] } Now, if i understand Ember Data and the JSON-API spec correctly, ember should request /api/v1/cases/4/comments when i reference the comments. Instead, it requests /api/v1/comments/5, which obviously returns a 404. My questions in summary: Does the server response comply to the JSON-API spec? How do i get ember to respect the nested route? I'm using ember v2.8. Bonus question: I face the same problem for creating a new comment - how do i get ember to POST to /case/4/comments instead of /comments? -
Ajax form submit. View request.POST just gets a string
I'm trying to submit my form data with a POST. But it just gets a string of all the form inputs. So I cannot seperate them by request.POST['name']. Is there some way to turn this string into something so I may get value by their name? <form class='searchForm' method='POST' action="{% url 'manager:Search' %}"> {% csrf_token %} <label><input class="searchBy" type="radio" name="searchBy" value="Symbol"> Symbol</label> <label><input type="radio" name="searchBy" checked="checked" value="Name"> Name</label> <input type="text" class="Input" name="Field" placeholder="Search for stocks!"> </form> Ajax $.ajax({ url : "{% url 'manager:Search' %}", type : "POST", data : { csrfmiddlewaretoken : '{{ csrf_token }}', 'form' : $(".searchForm").serialize(), }, success : function(data) { populate(data); }, error : function() { } }); View def Search(request): form = request.POST['form'] print(form) <------ prints just a string. console: csrfmiddlewaretoken=NPgg0DyIoXBftDgvdKtdmUXZGdO2OMiD&searchBy=Name&stockSearchField=AAA -
Django - How does a query query itself?
I have two models Product id: delivery_date: DateTimeField contract: FK Contract id: safety_days: IntegerField I need to get the products to deliver in the next X days. This X are defined in the contract as safety_days. products = Product.objects.filter( Q(delivery_date__lte=(datetime.datetime.now() + timedelta(days=contract__safety_days))) ) However,I am not able to do -> days=contract__safety_days I do not know how I can reference the object itself inside the query to do this dynamically. Best regards, Ruben Barros -
Django Rest many to many model update error
I have model classes like this class Area(models.Model): city = models.ForeignKey(City) name = models.CharField(max_length=255) class SubscribeAlert(models.Model): category = models.ForeignKey(Category) user = models.ForeignKey(settings.AUTH_USER_MODEL) created = models.DateTimeField(auto_now_add=True, auto_now=False) status = models.BooleanField(default=False) attributes = JSONField('Subscriptions', null=True, blank=True) area = models.ManyToManyField(Area) My Views are class NotifyAPIView(CreateAPIView): serializer_class = SubscribeAlertSerializer class NotifyRetriveUpdateView(RetrieveUpdateAPIView): queryset = SubscribeAlert.objects.all() serializer_class = SubscribeAlertSerializer My serializer class SubscribeAlertSerializer(serializers.ModelSerializer): class Meta: model = SubscribeAlert fields = ('id', 'user', 'status', 'attributes', 'area', 'category') def create(self, validated_data): print 'creating----' area = validated_data.pop('area') instance = SubscribeAlert(**validated_data) instance.save() instance.area.add(*area) return instance def update(self, instance, validated_data): print 'updating----' instance.attributes = validated_data.get('attributes') area = validated_data.get('area') instance.area.add(*area) # instance.save() return instance My update method validated_data coming like this as i expected {u'status': True, u'attributes': u"{u'test': 10, u'tessst1': 100}", u'category': <Category: Category 1>, u'user': <User: foo>, u'area': [<Area: Area1>, <Area: Area2>, <Area: Area3>]} The add method will automatically add the areas as bult insert or one by one inserting ? But When I update the objects its is giving me an error (-1, 'error totally whack') first time i am trying with many to many any help please. -
How to insert a breakline in django documentation with docutils
I'd like to see the breaklines that I insert in my comments in the documentation of my Django project. My project is using django 1.9.7 Thanks. -
Django: decorator in class based view
I want to restrict access to a particular view so that only AJAX requests are accepted, so I implemented the following decorator: def require_ajax(func): def decorator(func): def inner(request, *args, **kwargs): if not request.is_ajax(): return HttpResponseBadRequest() return func(request, *args, **kwargs) return inner return decorator This works perfectly in function views, but I cannot figure out how to use it in class based views. I have tried this but got errors, I assume due the old version of Django I am using. And well, my class-based view: class AjaxView(TemplateView): template_name = '...' def get_context_data(self, **kwargs): ... return context -
Django + bdd + selenium
I am using BDD features to describe some of our project. Most of scenarios are then implemented using django test client https://docs.djangoproject.com/en/1.10/topics/testing/tools/, but some are being tested by selenium. In theory some of these features could be tested by both approaches (both by selenium and test client), but I don't know how to approach this from coding perspective. I want to keep my bdd scenarios implementation free (nothing like "Given I am using selenium as test tool"). I was thinking of having multiple definitions of each step when viable and then use implementation (or even more) that has all steps implemented for given scenario. That would require changing python-behave implementation I guess. Anyone facing similar issue? -
Can I memoize *some* of the fields within tastypie resource?
I have the following resource: class PizzaResource(ModelResource): topping = fields.ForeignKey(ToppingResource, 'topping') price_range = fields.ForeignKey(PriceRangeResource, 'price_range') class Meta: queryset = Pizza.objects.all() Now, suppose the topping data is modified frequently, yet the price range data is barely getting touched, so I'd like to query the db for the topping at all times, but to memoize the price range, and the price range only (and not to cache the whole record) - can I do that with tastypie?