Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the difference between a Viewsets `create()` and `update()` and a Serializers `create()` and `update()`?
Over here: http://www.django-rest-framework.org/api-guide/viewsets/#modelviewset it says "The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy()." Over here: http://www.django-rest-framework.org/api-guide/serializers/#modelserializer it says "The ModelSerializer class is the same as a regular Serializer class, except that: It includes simple default implementations of .create() and .update()." 1) Assuming there is a Viewset UserViewSet and router user and serializer UserSerializer. If I sent a POST to /user/ does it call the UserViewSet's create() or the UserSerializer's create()? 2) Suppose UserViewSet has this permission: class NoCreate(permissions.BasePermission): """ No one can create this object. """ message = 'You do not have permission to complete the action you are trying to perform.' def has_permission(self, request, view): if view.action == "create": return False return True Does the UserSerializer's create() still get called if I send a POST to /user/? -
how to pull out all the data from excel sheet and print in html web by using django and python
How to print data in excel sheet by using django and python? -
Why won't this code do anything?
I'm trying to re-create a simple django app from the tutorial here: https://godjango.com/18-basic-ajax/ Here is the repo for that code: https://github.com/GoDjango/episode-18-basic-ajax I have followed instructions right and yet, something is going wrong somewhere and I don't know where. When I click on the "Get more TODO" button, nothing happens, but what it is supposed to do is add two more items to the list. This is my code so far. My URLs: from django.conf.urls import include, url, patterns from . import views from django.views.generic import TemplateView urlpatterns = [ url(r'^ajax_way/$', TemplateView.as_view(template_name='alte_backend/email_who_bought/ajax_way.html')), url(r'^ajax_way/add/$', views.ajax_customers), My views: def ajax_customers(request): if request.is_ajax(): todo_items = ['Mow Lawn', 'Buy Groceries', ] data = json.dumps(todo_items) return HttpResponse(data, content_type='application/json') else: raise Http404 My templates: Base.html {% load static %} <html> <head> <meta charset="utf-8"> <title>{% block title %}Everest Ajax{% endblock %}</title> {% block stylesheet %}{% endblock %} </head> <body> <header> </header> <main> {% block content %} {% endblock %} </main> <footer> </footer> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> {% block javascript %}{% endblock %} </body> </html> ajax_way.html: {% block h1 %}Everest Ajax{% endblock h1 %} {% block content %} <div class="container"> <div class="container"> <h3>TODO:</h3> <ul> <li>Take out trash</li> </ul> <button class='btn get-more'>Get More Todos</button> </div> <div class="container"> <h3>Add Todo</h3> {% csrf_token … -
Django Channels Websockets Connecting and Disconnecting right away
First some background, I am working off of this tutorial: https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django On Windows 64-bit using the Vagrant distribution of Redis from here: https://github.com/ServiceStack/redis-windows Using Python 3.4 and Django 1.10 I am able to clone, build and run the project fine. the problem is that when I access the django view through my browser it loads the chat fine but when I send a message in the console it says the websocket connects then almost immediately disconnects and the message does not send. If I manually enter data into the database than the messages will show up when i first load the view but for some reason the javascript application cannot keep the websocket open to send messages to broadcast. Below is the relevant code: consumers.py import re import json import logging from channels import Group from channels.sessions import channel_session from .models import Room log = logging.getLogger(__name__) @channel_session def ws_connect(message): # Extract the room from the message. This expects message.path to be of the # form /chat/{label}/, and finds a Room if the message path is applicable, # and if the Room exists. Otherwise, bails (meaning this is a some othersort # of websocket). So, this is effectively a version of … -
confusion in deploying module's with djangobook
Good day. I'm a newbie to Django and I have a slight confusion: When deploying my Django app, do I need to deploy it with all the Python 'come-with' modules, or the hosts already have them installed. Also, I installed PIL for image manipulation. Would they also have it installed or i have to find a way to install it on their servers. Thanks in advance -
Cannot pass Helper to django Crispy Formset in template
I'm trying to set up crispy form on a form and a formset (Visit and VisitService). I'm having trouble attaching the helper to the formset, no matter how I do it. I added helper as an attribute to the Formset and added the helper to view and context but it keeps giving me the following error: VariableDoesNotExist - Failed lookup for key [helper] (also tried [helper_attribute]) here is what I'm using: forms.py: class VisitForm(forms.ModelForm): class Meta: model = models.Visit fields = [ [...all visit fields go here...] ] def __init__(self, *args, **kwargs): super(VisitForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( [...fields go here...] ), ButtonHolder( Submit('submit', 'Submit', css_class='button white btn-wide') ) ) class VisitServiceForm(forms.ModelForm): class Meta: model = models.VisitService fields = [ 'service', 'unit', ] def __init__(self, *args, **kwargs): super(VisitServiceForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Div(Field('service'),css_class='col-sm-4'), Div(Field('unit'),css_class='col-sm-4'), ) VisitServiceFormSet = forms.modelformset_factory( models.VisitService, form=VisitServiceForm, extra=2, ) VisitServiceInlineFormSet = forms.inlineformset_factory( models.Visit, models.VisitService, extra=5, fields=('service', 'unit'), formset=VisitServiceFormSet, min_num=1, ) views.py: def create_visit(request, patient_pk): patient = get_object_or_404(models.Patient, pk=patient_pk) form_class = forms.VisitForm form = form_class() visitservice_forms = forms.VisitServiceInlineFormSet( queryset=models.VisitService.objects.none() ) helper = forms.VisitServiceForm() if request.method == 'POST': form = form_class(request.POST) visitservice_forms = forms.VisitServiceInlineFormSet( request.POST, queryset=models.VisitService.objects.none() ) if form.is_valid() and visitservice_forms.is_valid(): … -
Why does my Django webpage look different during functional test and when I go to localhost:8000?
I'm going through the Obey The Testing Goat tutorial/book and I've noticed that the browser window that comes up when running functional tests looks different than if I open up a browser and go to localhost:8000. In fact, it functions completely differently, too. It seems as if the webpage from manually going to localhost:8000 is from "old code" as in previous commits. In the browser that is opened in the functional test, the URL is localhost:8081. When I open a browser window and try to go to that URL, nothing comes up. Do these differences in webpages have something to do with git commits? -
Pysqlite2 error while starting django project
Im trying to start a django project from scratch but i have an error that says "ImportError: No Module Named 'pysqlite2'" I'm using Python 3.6.0. I will write steps which im following Creating project > django-admin startproject testproject Trying to start an app > python manage.py startapp demo Immediately after enters that command, it returns me a long text which includes error's path etc. Traceback (most recent call last): File "/home/berkin/pythonenv/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 34, in <module> from pysqlite2 import dbapi2 as Database ModuleNotFoundError: No module named 'pysqlite2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/berkin/pythonenv/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 36, in <module> from sqlite3 import dbapi2 as Database File "/usr/local/lib/python3.6/sqlite3/__init__.py", line 23, in <module> from sqlite3.dbapi2 import * File "/usr/local/lib/python3.6/sqlite3/dbapi2.py", line 27, in <module> from _sqlite3 import * ModuleNotFoundError: No module named '_sqlite3' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/berkin/pythonenv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/berkin/pythonenv/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/berkin/pythonenv/local/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/berkin/pythonenv/local/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/berkin/pythonenv/local/lib/python3.6/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/home/berkin/pythonenv/lib/python3.6/importlib/__init__.py", line 126, in … -
Access AppConfig members
I want to make my application independent from the project and control branding over the AppConfig. I override the config in my project and every thing seems to work. But how can I access the verbose_name from code? It's not covered in the documentation. -
Django transaction does not appear to run sql commands
The intent of this code segment is to create a lockout function. When I want to perform an action here (in this case, increment a counter) I want to avoid race conditions if multiple processes are attempting to perform the same function by using a field state. from django.db import models, IntegrityError import time class Obj(models.Model): state = models.TextField() counter = models.IntegerField(default=0) def lock(self, current_state): locked = Obj.objects.filter(id=self.id, state=current_state).update(state='locked') if locked: return else: raise IntegrityError('Model is currently being locked by another transaction') def increment(self): self.lock('ready') time.sleep(2) self.counter += 1 self.state = 'incremented' self.save() with a test case to run multiple processes in an attempt to get a race condition... from django.test import TestCase from pathos.multiprocessing import ProcessingPool from transactions.models import Obj class ObjTestCase(TestCase): def setUp(self): self.obj = Obj(state='ready') self.obj.save() def test_lockout_functionaility(self): obj = Obj.objects.get(id=self.obj.id) print 'obj counter before transaction: ', obj.counter run_increment_func = lambda obj: obj.increment() num_processes = 2 pool = ProcessingPool(processes=num_processes) results = pool.map(run_increment_func, [obj]*num_processes) pool.close() pool.join() obj = Obj.objects.get(id=self.obj.id) print 'obj counter after transaction: ', obj.counter When this test case is ran, neither process raises an error (while one should raise an integrity error with the lock function). Also, the object counter does not change after the pool … -
uploading/creating my Django project API
i'ev developed and test my Django project on the local host..Now i've upload it in the web faction server to deploy it. so far everything is working fine, BUT the local version of my project i've created the API using rest-framework and it worked very well BUT now i need API it for my website communication. (i'm using Python 3.5 , Django 10, sqlite3) how i can create or upload my local one? -
Django: Correct way to save HTML code inside database
I want to save HTML code inside my Postgresql database so that I can directly send this code as HttpResponse instead of serving static HTML file. I did saved it inside database but following error keeps on coming. What is correct way of doing this task? -
Django tutorial part 4: except error, SyntaxError: invalid syntax
I've been struggling with this error with 'except and have copy-and-pasted the Django tutorial's code into the views.py file, to no avail. Here is the full output of the error report and the code, although the last line of the error report and line 53 of the code what is probably relevant here: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 342, in execute self.check() File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/chrx/Projects/mysite/mysite/urls.py", line 20, in <module> url(r'^polls/', include('polls.urls')), File "/usr/local/lib/python2.7/dist-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = … -
How can I redirect from view In Django
This is a view written for my posts app in Django. The problem is that after filling the update form and submitting it happens successfully. But it creates confusion for the user because the same HTML page is there and how can I redirect into the updated object? def post_update(request,id=None): instance=get_object_or_404(Post,id=id) if instance.created_user != request.user.username : messages.success(request, "Post owned by another user, You are having read permission only") return render(request,"my_blog/denied.html",{}) else : form=PostForm(request.POST or None,request.FILES or None,instance=instance) if form.is_valid(): instance=form.save(commit=False) instance.save() context={ "form":form, "instance":instance } return render(request,"my_blog/post_create.html",context) ThankYou. -
Checkbox not working in a Django form (bug?)
In this Django program the checkbox in the form is not shown. I want to show it. Please explain what is my error. Django version 1.10.3. -
How Configure ViewFlow, many funcionality
How Configure ViewFlow on django project I am new in django comunity and i try to install and test the functionality that have ViewFlow in Django i've see the demo online but i would like install in my computer and testing all the funcionality and play with the code in specific i would like know: - how create and configure a new form - how create a new flow, and assign a user specific, (because in demo, just assign a My User) - I've see in documentation a user interface graph to model flow but in demo i don't see any. link demo: http://demo.viewflow.io/ Thanks -
Error in Django matching query does not exist
I am calculating property in my Extra model from my second model LeaseExtra. However it doesn't work for me. Why I am getting this error?: LeaseExtra matching query does not exist. class Extra(CommonInfo): version = IntegerVersionField( ) number = models.CharField(max_length=30,null=True, blank=True) max_occupants = models.PositiveSmallIntegerField() _lease = None def _get_total(self): from conditions.models import LeaseExtra le_dict = LeaseExtra.objects.get(extra_id=self.id, is_active = True ) if le_dict: lease = le_dict.lease else: lease = 0 self._lease = lease class LeaseExtra(CommonInfo): version = IntegerVersionField( ) extra = models.ForeignKey(Extra,on_delete=models.PROTECT) lease = models.ForeignKey(Lease,on_delete=models.PROTECT) is_included = models.BooleanField(default=True) Traceback: File "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 22. return view_func(request, *args, **kwargs) File "C:\Users\PAPA\DEV\rent_unit\src\unit\views.py" in extra_available_list 163. extra_list = [obj for obj in extra_list if ( (obj.lease)==0)] File "C:\Users\PAPA\DEV\rent_unit\src\unit\models.py" in lease 166. self._get_total() File "C:\Users\PAPA\DEV\rent_unit\src\unit\models.py" in _get_total 151. le_dict = LeaseExtra.objects.get(extra_id=self.id, is_active = True ) File "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\db\models\manager.py" in manager_method 127. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\db\models\query.py" in get 334. self.model._meta.object_name Exception Type: DoesNotExist at /unit/list/extra/available/ Exception Value: LeaseExtra matching query does not exist. -
Dynamically Populating JSON with API Data
I am building a Facebook bot and trying to populate the JSON elements with dynamic values from an api. This is the template from Facebook's website: curl -X POST -H "Content-Type: application/json" -d '{ "recipient":{ "id":"RECIPIENT_ID" }, "message": { "attachment": { "type": "template", "payload": { "template_type": "list", "top_element_style": "compact", "elements": [ { "title": "Classic White T-Shirt", "image_url": "https://peterssendreceiveapp.ngrok.io/img/white-t-shirt.png", "subtitle": "100% Cotton, 200% Comfortable", "default_action": { "type": "web_url", "url": "https://peterssendreceiveapp.ngrok.io/view?item=100", "messenger_extensions": true, "webview_height_ratio": "tall", "fallback_url": "https://peterssendreceiveapp.ngrok.io/" }, "buttons": [ { "title": "Buy", "type": "web_url", "url": "https://peterssendreceiveapp.ngrok.io/shop?item=100", "messenger_extensions": true, "webview_height_ratio": "tall", "fallback_url": "https://peterssendreceiveapp.ngrok.io/" } ] }, { "title": "Classic Blue T-Shirt", "image_url": "https://peterssendreceiveapp.ngrok.io/img/blue-t-shirt.png", "subtitle": "100% Cotton, 200% Comfortable", "default_action": { "type": "web_url", "url": "https://peterssendreceiveapp.ngrok.io/view?item=101", "messenger_extensions": true, "webview_height_ratio": "tall", "fallback_url": "https://peterssendreceiveapp.ngrok.io/" }, "buttons": [ { "title": "Buy", "type": "web_url", "url": "https://peterssendreceiveapp.ngrok.io/shop?item=101", "messenger_extensions": true, "webview_height_ratio": "tall", "fallback_url": "https://peterssendreceiveapp.ngrok.io/" } ] }, { "title": "Classic Black T-Shirt", "image_url": "https://peterssendreceiveapp.ngrok.io/img/black-t-shirt.png", "subtitle": "100% Cotton, 200% Comfortable", "default_action": { "type": "web_url", "url": "https://peterssendreceiveapp.ngrok.io/view?item=102", "messenger_extensions": true, "webview_height_ratio": "tall", "fallback_url": "https://peterssendreceiveapp.ngrok.io/" }, "buttons": [ { "title": "Buy", "type": "web_url", "url": "https://peterssendreceiveapp.ngrok.io/shop?item=102", "messenger_extensions": true, "webview_height_ratio": "tall", "fallback_url": "https://peterssendreceiveapp.ngrok.io/" } ] }, { "title": "Classic Gray T-Shirt", "image_url": "https://peterssendreceiveapp.ngrok.io/img/gray-t-shirt.png", "subtitle": "100% Cotton, 200% Comfortable", "default_action": { "type": "web_url", "url": "https://peterssendreceiveapp.ngrok.io/view?item=103", "messenger_extensions": true, … -
python-social-auth: get user with GitHub username
I cannot, for the life of me, figure out how to find a specific user by github username. for i in UserSocialAuth.objects.filter(provider='github').all(): print(i) I want to find the user with a specific GitHub user name (not site username), say, "DanielPBak". How would I do this? UserSocialAuth can only filter by provider and user, so it doesn't seem possible to use only filter(). However, iterating through the filtered users seems impossible, because it doesn't seem possible to access the UserAuth username, only the site's username. How can I get the UserSocialAuth username? dir(i) doesn't reveal anything to do with an auth username or github username. -
Strange AttributeError in django
In my model file I have class extra . That has property lease that calculates lease based on other model LeaseExtra class Extra(CommonInfo): number = models.CharField(max_length=30,null=True, blank=True) max_occupants = models.PositiveSmallIntegerField() floor = models.PositiveSmallIntegerField() _lease = None def _get_total(self): from lease.models import Lease from conditions.models import LeaseExtra le_dict = LeaseExtra.objects.filter(extra_id=self.id, is_active = True ).aggregate(Max('id')) if le_dict: lease = le_dict.lease else: lease = 0 self._lease = lease class LeaseExtra(CommonInfo): version = IntegerVersionField( ) extra = models.ForeignKey(Extra,on_delete=models.PROTECT) lease = models.ForeignKey(Lease,on_delete=models.PROTECT) is_included = models.BooleanField(default=True) Why I am getting error in this model class ? Exception Value: 'dict' object has no attribute 'lease' Traceback: File "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\PAPA\DEV\rent_unit\rent_unit_venv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 22. return view_func(request, *args, **kwargs) File "C:\Users\PAPA\DEV\rent_unit\src\unit\views.py" in extra_available_list 163. extra_list = [obj for obj in extra_list if ( (obj.lease)==0)] File "C:\Users\PAPA\DEV\rent_unit\src\unit\models.py" in lease 182. self._get_total() File "C:\Users\PAPA\DEV\rent_unit\src\unit\models.py" in _get_total 160. lease = le_dict.lease Exception Type: AttributeError at /unit/list/extra/available/ Exception Value: 'dict' object has no attribute 'lease' -
Django Programming error column does not exist even after running migrations
I run python manage.py makemigrations and I get: No changes detected Then, python manage.py migrate and I get: No migrations to apply. Then, I try to push the changes to production: git push heroku master Everything up-to-date Then, in production, I repeat the command: heroku run python manage.py migrate No migrations to apply. Just in case, I run makemigrations in production: heroku run python manage.py makemigrations No changes detected WHY then I get a ProgrammingError at .... column .... does not exist "No changes detected" means the database is coherent with the code. How can I debug this?¡? -
Inconsistent Migration History deleted all migrations, yet still showing in migration history django
I have received this error when making migrations ile "/home/rickus/.local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 285, in check_consistent_history migration[0], migration[1], parent[0], parent[1], django.db.migrations.exceptions.InconsistentMigrationHistory: Migration authtoken.0001_initial is applied before its dependency users.0001_initial so I deleted all the migrations on my project and tried again. before I ran make migrations again I ran show migrations and all the migration files are showing in the show migrations output even though I deleted the actual files admin [X] 0001_initial [X] 0002_logentry_remove_auto_add auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length authtoken [X] 0001_initial [X] 0002_auto_20160226_1747 contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial users (no migrations) I'm trying to fix this error but I am unsure of what to do. How is it that my show migrations is showing files I deleted? What is the best way to solve this problem? -
Python - Django - Pass Argument To Form Clean Method
I am trying to pass a variable to a ModelForm clean method using __init__ arguments but have had no success so far - I looked at various posts on StackOverflow but none seemed to help. My code is the following: forms.py class property_booking_form(forms.ModelForm): check_in_date = forms.DateField(widget=SelectDateWidget) check_out_date = forms.DateField(widget=SelectDateWidget) class Meta: model = Properties_bookings fields = ['check_in_date', 'check_out_date'] def __init__(self, property_id): self.property_id = property_id super(property_booking_form, self).__init__(self, property_id) def clean(self): check_in_date = self.cleaned_data.get('check_in_date') check_out_date = self.cleaned_data.get('check_out_date') property_min_nights = Properties.objects.get(id=self.property_id).property_minimum_nights ... views.py def view(request): ... if request.method == 'POST': booking_form = property_booking_form(request.POST, property_id=property_id) if booking_form.is_valid(): ... else: booking_form = property_booking_form(property_id=property_id) return render(...) This raises the following error: 'property_booking_form' object has no attribute 'get' Which seems to be related to the widget as per the error description: Exception Location: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/widgets.py in value_from_datadict, line 1058 The form works fine without the overriding __init__. Does anyone know what would be the underlying cause of this issue? Thanks. -
How can I tell if a django RelatedManager .add() found that the object was already added?
I have the following code in a post_save function @receiver(post_save) def update_parent_location(sender, instance=None, created=False, **kwargs): list_of_models = ('A', 'B', 'C') if sender.__name__ in list_of_models: groups = instance.group_set.all() fields_to_update = tuple(field.lower() for field in list_of_models) for field in fields_to_update: parent = getattr(instance, field, None) if parent is not None: parent.groups.add(*groups) parent.save() How would I know if the parent.groups.add(*groups) part actually added a new object or failed silently? -
Django REST Framework: nested serializer not serializing
I am having bit of a pickle with Django REST Framework nested serializers. I have a serializer called ProductSerializer. It is a serializers.ModelSerializer and correctly produces following output when used alone: {'id': 1, 'name': 'name of the product'} I'm building a shopping cart / basket functionality, for which I currently have the following class: class BasketItem: def __init__(self, id): self.id = id self.products = [] and a serializer: class BasketItemSerializer(serializers.Serializer): id = serializers.IntegerField() products = ProductSerializer(many=True) I have a test case involving following code: products = Product.objects.all() # gets some initial product data from a test fixture basket_item = BasketItem(1) # just passing a dummy id to the constructor for now basket_item.products.append(products[0]) basket_item.products.append(product1[1]) ser_basket_item = BasketItemSerializer(basket_item) Product above is a models.Model. Now, when I do print(ser_basket_item.data) {'id': 1, 'products': [OrderedDict([('id', 1), ('name', 'name of the product')]), OrderedDict([('id', 2), ('name', 'name of the product')])]} What I expect is more like: { 'id': 1, 'products': [ {'id': 1, 'name': 'name of the product'} {'id': 2, 'name': 'name of the product'} ] } Where do you think I'm going wrong?