Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python's self vs instance
What is the difference between the self and instance keywords in Python 3? I see code like, def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance -
Django CMS – Group has No Permissions to Add/Edit/Delete Pages
I have a site that has been upgraded form Django 1.8 to Django 1.9.9 which has a Django CMS 3.3.2 (I think upgraded from 3.2). settings.py has CMS_PERMISSION = True. There is a staff user in a group created with Django CMS which has every CMS permission (add/edit/delete pages/users and groups/page permissions) but staff users belonging to this group have only permissions to these actions for users and groups. Even adding every possible permission for Django on top of these changes nothing – there is no permission to do anything to pages and I haven't found anyone with the same problem. -
Django : How do i save foreign key object in django rest api class base view
I 'm having Two models User & Location User having foreign key of Location. So at the time of Post request how do i save the location object in serializer. I'm using classbase view. Following is my code class UserList(ListCreateAPIView): def create(self, request, *args, **kwargs): location_id = self.request.data.get("user_location_id") location = Location.objects.get(pk=location_id) serializer = self.get_serializer(data=request.data, partial=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) response = { "status" : status.HTTP_201_CREATED, "message" : "User Created.", "response" : serializer.data } return Response(response) class UserSerializer(serializers.ModelSerializer): location = LocationSerializer(source='user_location_id') class Meta: model = UserInfo fields = ['user_id','user_firstname', 'user_lastname' ,'user_email','user_dob','user_mobileno','user_image','user_blood_group','user_profession','user_fb_id','user_random_id','location'] class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ["location_id", "location_name"] -
Django Logging Works Intermittently
I'd really like to use Logging to make sure my application is working correctly, but I can't get it to work reliably. I've only noticed the issue after I delete all the existing lines from the log file and I'm not sure if it happens at other times or not, but sometimes the requested information is successfully added to my log file, and other times nothing is and the file remains blank. I've got it set up like so, logger = logging.getLogger(__name__) and am using logger.info("Log This!") Is this caused by manually deleting things from the log file? Or perhaps something is wrong with my configuration? LOGGING = {'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs/GeniusLogs.log'), 'formatter': 'verbose' }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True }, 'django': { 'handlers':['file'], 'propagate': True, 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, } } -
Python social auth can't create a model that relates to user
I have python social auth configured to create a user using steam Open ID. And I have a separate model, player, that is related in a one-to-one relationship with user that stores extra fields, one of which is the user's steamid. I have extended the pipeline to include a function that creates a player and saves the steamid into one of its fields. Everything goes well when it is a user that isn't already stored in the database. So in other words, the application creates the user and saves the field the first time I log in, but the second time I log in it throws this error: Cannot assign "{Dictionary}": "User.player" must be a "Player" instance. Where Dictionary is the set of fields. Here is my function: def save_profile(backend, user, response, *args, **kwargs): import pdb; pdb.set_trace() if backend.name == 'steam': player = Player(user = user, ingamename = kwargs['uid'], avatar = kwargs['details']['player']['steamid']) player.save() -
No module named virtualenvwrapper
I have Django 1.9.7 installed, and its works fine, but every time I open the terminal, I get this message. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is set properly. When I startproject in Django, it works fine. I wonder whether this will cause problems in the future, and how can I fix it? I speculate that it is causing this problem because I used to use Python 2.7 with Django 1.9.7. I have recently upgrade by python to 2.4, but it seems that my packages for python 2.7 still exist in my computer. However, when I tried removing the python 2.7 packages with pip uninstall python == 2.7, I get this error Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/uninstall.py", line 76, in run requirement_set.uninstall(auto_confirm=options.yes) File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 336, in uninstall req.uninstall(auto_confirm=auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move copy2(src, real_dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2 copystat(src, dst) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat … -
Have Django check csrftoken from Cookie instead of POST data or header
I have an api on api.mysite.com and the frontend on other.mysite.com and need AJAX to work, ideally with CSRF protection. I can a csrftoken from an XHR, and it sets the cookie. When I make another XHR with withCredentials: true, that new XHR sends the csrftoken in the Cookie header. But it seems the Django CsrfViewMiddleware only checks if the csrftoken is in the POST data, or in the x-csrftoken header. It does not check the cookie (if I'm not mistaken). My problem is that there is no way the Javascript can read the csrftoken from the cookie, as it is a cookie from another site. I see two solutions: get an XHR to get a csrftoken in the body. That works when I land on the site, but the csrftoken can change (if I log out and in I believe) have Django read the csrftoken from the cookie. This is what I would ideally achieve. How would I make that work? -
WSGI: Django App is not getting the required site-packages
Unfortuanetely I am stuck with my Website returning a 500 error. The apache log is not really specific, and so I do not really know what to do. Before some apt-get upgrades everything worked fine. I do think this might be a permission error. How do I have to set the permissions working with WSGI? Or do you know why this problem could be occuring for another reason? apache conf: ... WSGIDaemonProcess aegee-stuttgart.org python-path=/home/sysadmin/public_html/aegee-stuttgart.org:/home/sysadmin/.virtualenvs/django/lib/python2.7 WSGIProcessGroup aegee-stuttgart.org WSGIScriptAlias / /home/sysadmin/public_html/aegee-stuttgart.org/aegee/wsgi.py ... wsgi.py: ... import os, sys # add the aegee project path into the sys.path sys.path.append('/home/sysadmin/public_html/aegee-stuttgart.org/aegee') # add the virtualenv site-packages path to the sys.path sys.path.append('/home/sysadmin/.virtualenvs/django/lib/python2.7/site-packages') import django from django.core.handlers.wsgi import WSGIHandler ... error.log: mod_wsgi (pid=23202): Exception occurred processing WSGI script '/home/sysadmin/p$ Traceback (most recent call last): File "/home/sysadmin/public_html/aegee-stuttgart.org/aegee/wsgi.py", line 31, i$ return super(WSGIEnvironment, self).__call__(environ, start_response) File "/usr/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 189,$ response = self.get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 218,$ response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 264,$ if resolver.urlconf_module is None: File "/usr/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 395, $ self._urlconf_module = import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/sysadmin/public_html/aegee-stuttgart.org/aegee/urls.py", line 8, in$ from .userprofile.views import AccountPersonalInfoView File "/home/sysadmin/public_html/aegee-stuttgart.org/aegee/userprofile/views.py$ from django.contrib.auth.mixins import LoginRequiredMixin ImportError: No module named mixins -
django Q object nested with reduce
Got very complex query (please do not try to solve example - the problem is more complex) crit=[] crit.append(Q(firstcond = name) | Q(firstcond__isnull = True) crit.append(Q(secondcond = name) | Q(firstcond__isnull = True) MyObject.objects.filter(reduce(operator.and_, crit)) This works as expected: WHERE (firstcond = name OR firstcond IS NULL) AND (secondcond = name OR secondcond IS NULL) But now I need some OR: WHERE ((firstcond = name OR firstcond IS NULL) AND (secondcond = name OR \ secondcond IS NULL)) OR (third = value) I can't add third int crit list, because operator.and_ in reduce. I have to add operator._or after reduce, but HOW? -
Django encrypt the query string
I use Django and I would to add an additional layer of security (I already use SSL and an authentication system) to protect some my free APIs. I was thinking about the encrypt my query string: the client send a request with encrypted Query String. the server will decrypt the query string in received response. Already exist something like this in Django? -
Django 1.10 - Use django.shortcuts.render to generate a webpage with variables which includes a javascript as parameter
I'm new to Django, trying to migrate a website that I have built to a Django application. I have generated an HTML template on which I want to present dynamic content based on the URL that was requested. The HTML template looks like this: {% load staticfiles%} <!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript"> {{ script }} </script> <meta charset="UTF-8"> <link rel="stylesheet" href="{% static 'styles.css' %}"/> <title>{{ title }}</title> </head> <body> <header> <h1>{{ title }}</h1> </header> <section> <p> {{ date }}<br/><br/> SiteID: {{ site }} <br/> ----------------- </p> </section> </body> </html> On my views.py file, I'm generating the URL using this method (for example): def site(request): return render(request, "sites/site.html", {'date': strftime("%A, %B %d %Y"), 'site': '123456', 'title': 'Test', 'script': "window.lpTag=window.lpTag||{};if(typeof window.lpTag._tagCount==='undefined'){window.lpTag={site:'123456'||'',section:lpTag.section||'',autoStart:lpTag.autoStart===false?false:true,ovr:lpTag.ovr||{},_v:'1.6.0',_tagCount:1,protocol:'https:',events:{bind:function(app,ev,fn){lpTag.defer(function(){lpTag.events.bind(app,ev,fn);},0);},trigger:function(app,ev,json){lpTag.defer(function(){lpTag.events.trigger(app,ev,json);},1);}},defer:function(fn,fnType){if(fnType==0){this._defB=this._defB||[];this._defB.push(fn);}else if(fnType==1){this._defT=this._defT||[];this._defT.push(fn);}else{this._defL=this._defL||[];this._defL.push(fn);}},load:function(src,chr,id){var t=this;setTimeout(function(){t._load(src,chr,id);},0);},_load:function(src,chr,id){var url=src;if(!src){url=this.protocol+'//'+((this.ovr&&this.ovr.domain)?this.ovr.domain:'lptag.liveperson.net')+'/tag/tag.js?site='+this.site;}var s=document.createElement('script');s.setAttribute('charset',chr?chr:'UTF-8');if(id){s.setAttribute('id',id);}s.setAttribute('src',url);document.getElementsByTagName('head').item(0).appendChild(s);},init:function(){this._timing=this._timing||{};this._timing.start=(new Date()).getTime();var that=this;if(window.attachEvent){window.attachEvent('onload',function(){that._domReady('domReady');});}else{window.addEventListener('DOMContentLoaded',function(){that._domReady('contReady');},false);window.addEventListener('load',function(){that._domReady('domReady');},false);}if(typeof(window._lptStop)=='undefined'){this.load();}},start:function(){this.autoStart=true;},_domReady:function(n){if(!this.isDom){this.isDom=true;this.events.trigger('LPT','DOM_READY',{t:n});}this._timing[n]=(new Date()).getTime();},vars:lpTag.vars||[],dbs:lpTag.dbs||[],ctn:lpTag.ctn||[],sdes:lpTag.sdes||[],ev:lpTag.ev||[]};lpTag.init();}else{window.lpTag._tagCount+=1;}"}) The problem is, that this method actually renders all my strings so that it's escaping characters such as apostrophe ('), which is causing the JavaScript not to work. That's what I see in the browser console when running the page: <script type="text/javascript"> window.lpTag=window.lpTag||{};if(typeof window.lpTag._tagCount===&amp;#39;undefined&#39;){window.lpTag={site:&#39;123456&#39;||&#39;&#39;,section:lpTag.section||&#39;&#39;,autoStart:lpTag.autoStart===false?false:true,ovr:lpTag.ovr||{},_v:&#39;1.6.0&#39;,_tagCount:1,protocol:&#39;https:&#39;,events:{bind:function(app,ev,fn){lpTag.defer(function(){lpTag.events.bind(app,ev,fn);},0);},trigger:function(app,ev,json){lpTag.defer(function(){lpTag.events.trigger(app,ev,json);},1);}},defer:function(fn,fnType){if(fnType==0){this._defB=this._defB||[];this._defB.push(fn);}else if(fnType==1){this._defT=this._defT||[];this._defT.push(fn);}else{this._defL=this._defL||[];this._defL.push(fn);}},load:function(src,chr,id){var t=this;setTimeout(function(){t._load(src,chr,id);},0);},_load:function(src,chr,id){var url=src;if(!src){url=this.protocol+&#39;//&#39;+((this.ovr&amp;&amp;this.ovr.domain)?this.ovr.domain:&#39;lptag.liveperson.net&#39;)+&#39;/tag/tag.js?site=&#39;+this.site;}var s=document.createElement(&#39;script&#39;);s.setAttribute(&#39;charset&#39;,chr?chr:&#39;UTF-8&#39;);if(id){s.setAttribute(&#39;id&#39;,id);}s.setAttribute(&#39;src&#39;,url);document.getElementsByTagName(&#39;head&#39;).item(0).appendChild(s);},init:function(){this._timing=this._timing||{};this._timing.start=(new Date()).getTime();var that=this;if(window.attachEvent){window.attachEvent(&#39;onload&#39;,function(){that._domReady(&#39;domReady&#39;);});}else{window.addEventListener(&#39;DOMContentLoaded&#39;,function(){that._domReady(&#39;contReady&#39;);},false);window.addEventListener(&#39;load&#39;,function(){that._domReady(&#39;domReady&#39;);},false);}if(typeof(window._lptStop)==&#39;undefined&#39;){this.load();}},start:function(){this.autoStart=true;},_domReady:function(n){if(!this.isDom){this.isDom=true;this.events.trigger(&#39;LPT&#39;,&#39;DOM_READY&#39;,{t:n});}this._timing[n]=(new Date()).getTime();},vars:lpTag.vars||[],dbs:lpTag.dbs||[],ctn:lpTag.ctn||[],sdes:lpTag.sdes||[],ev:lpTag.ev||[]};lpTag.init();}else{window.lpTag._tagCount+=1;} </script> So my question is - How can I generate a dynamic page that is getting the actual JavaScript code as … -
Can I send sms when user click button using AWS SNS?
I make a practice project virtual book saleweb site using django 1.9.7 I want create a send mobile message feature here's my think logined user(A) can post book sale post another logined user(B) can click button named I wand buy this book in a post sms will send to logined user(A) (User B want buy your book) I search so many sms api, I find aws sns service and it is very good(it's almost free for me!) but I'm not good at english so I can't under stand aws document perfectly AWS SNS service only send develop log message about web site backend error, or develop No AWS SNS service can accomplish the my dream(think feature) I'm not sure AWS SNS service support send sms when client click a button please give me a information about my question and if it is not good choice please tell me some sms api -
Django: ManyToMany URL in Template
I can't add URL my category title in homepage. There is my code and error. What i can add instead of {{ c.get_absolute_url }}. What i am missing here? models.py class Category(models.Model): title = models.CharField(max_length=120, unique=True) slug = models.SlugField(unique=True) description = models.TextField(null=True, blank=True) is_active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) class Meta(object): verbose_name_plural = 'Categories' def __str__(self): return self.title def get_absolute_url(self): return reverse("category_url", kwargs={"slug": self.slug }) class Product(models.Model): name = models.CharField(max_length=120, unique=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(decimal_places=2, max_digits=20) is_active = models.BooleanField(default=True) slug = models.SlugField(max_length=200, unique=True) categories = models.ManyToManyField('Category', blank=True) stock = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) images = models.ImageField(upload_to='images', blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("product_detail", kwargs={"slug": self.slug}) views.py class HomePageView(ListView): model = Product context_object_name = 'product_list' template_name = 'products/index.html' def get_queryset(self): return Product.objects.all() index.html {% for product in product_list %} <a href="{{ product.get_absolute_url }}">{{ product.name }}</a> {% for c in product.categories.all %} <a href="{{ c.get_absolute_url }}">{{ c.title }}</a> {% endfor %} {{ product.description }} {% endfor %} ERROR NoReverseMatch at / Reverse for 'category_url' with arguments '()' and keyword arguments '{'slug': 'vans'}' not found. 0 pattern(s) tried: [] -
Test failure because model couldn't be imported
Application I am working on is proprietary and thus I will try to provide as much information as possible. When running python manage.py test, which runs all the tests, only one application among many others fails. Too many hours have been burned on this. The output is: ImportError: Failed to import test module: app.aom.apps.forum.tests after this, tracing is listed and then one line which says that the problem occurs when importing models into tests.py file, that is: from .models import ForumSectionGroup, ForumSection, ForumThread, ForumPost and the last line of the output is: RuntimeError: Model class app.aom.apps.forum.models.ForumSectionGroup doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I have Googled and researched what could cause this problem, and the conclusion: either I am importing module before application is loaded or I don't have the application listed in INSTALLED_APPS. But none of these seems to be the problem. Maybe testing mechanism somehow skips few steps and renders the model unloaded before importing it. Explicitly assigning app_label as part of class Meta in the model results in conflict, because the model ends up registered twice, when I force it. I was driven to this conclusion by looking at the code at … -
pass data to form in many Django CreateViews
I have several models which share an attribute, course_offering. On my site, the relevant value of the attribute is generally determined by keyword arguments from the url. So, in many subclasses of CreateView, I would like automatically to pass the relevant value to the form. For any particular model class, this post offers an approach: override get_form_kwargs() to set an initial object. For example in the present case, class OfferingMixin(Object): def get_course_offering(self,**kwargs): offering_slug = self.kwargs['offering_slug'] course_offering = CourseOffering.objects.get( slug=offering_slug) return course_offering class CreateSyllabusView(OfferingMixin,CreateView): model=Syllabus def get_form_kwargs(self,**kwargs): course_offering=self.get_course_offering(**kwargs) instance = Syllabus(course_offering=course_offering) kwargs.update({'instance':instance}) return kwargs But, this applies to a fixed model class, and I would like to handle many model classes while avoiding unnecessary duplication of code. For example, would it be possible somehow to subclass CreateView to, say, OfferingCreateView, and then subclass OfferingCreateView to CreateSyllabusView? If so, I'm not sure how to do it! Of course, it could be that this idea is totally misguided, in which case it would be nice to learn a good approach. Thanks in advance. -
How do I make a custom model Field call to_python when the field is accessed immediately after initialization (not loaded from DB) in Django >=1.10?
After upgrading from Django 1.9 to 1.10, I've experienced a change in behaviour with a field provided by the django-geolocation package. This is the change that was made for 1.10 compatibility that broke the behaviour: https://github.com/philippbosch/django-geoposition/commit/689ff1651a858d81b2d82ac02625aae8a125b9c9 Previously, if you initialized a model with a GeopositionField, and then immediately accessed that field, you would get back a Geoposition object. Now you just get back the string value that you provided at initialization. How do you achieve the same behaviour with Django 1.10? Is there another method like from_db_value that needs to be overridden to call to_python? -
how to store modelform data to database
I have searched 20-30 posts and I did not find anything useful. I am to store data to database by selecting values from HTML file or form in view. Please tell me how I can achieve this. what code I am missing. Thanks in advance for Help. view.py actions = Action.objects.all() employees = Employee.objects.all() def blog_list(request): form = AttendanceForm() if request.method == "POST": form = AttendanceForm(request.POST) if form.is_valid: form.save return render(request, 'blog/blog_list.html',{ 'form':form, }) my forms.py class AttendanceForm(forms.ModelForm): action = forms.ModelChoiceField(queryset=Action.objects.all(), empty_label="-----------", required=True) employee = forms.ModelChoiceField(queryset=Employee.objects.all(), empty_label="-----------", required=True) class Meta: model = Action fields = ['employee','action'] my model.py class Action(models.Model): action_name = models.CharField(max_length = 100) def __str__(self): return self.action_name class Employee(models.Model): employee_id = models.AutoField(primary_key = True) employee_name = models.CharField(max_length = 100) def __str__(self): return self.employee_name class Attendance(models.Model): u_Id = models.ForeignKey(Employee) action_Id = models.ForeignKey(Action) action_time = models.CharField(max_length =100) -
Django Rest framework Viewset Permissions "create" without "list"
I have the following viewset: class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer def get_permissions(self): if self.action in ['update','partial_update','destroy','list']: self.permission_classes = [permissions.IsAdminUser,] elif self.action in ['create']: self.permission_classes = [permissions.IsAuthenticated,] else : self.permission_classes = [permissions.AllowAny,] return super(self.__class__, self).get_permissions() As seen, Im trying to allow the 'create' method without allowing the 'list', for an Authenticated user (which is not an admin). Weirdly, this Viewset results no create nor list for the Authenticated user. Iv'e checked, just to rull off, the following code: class RouteOrderingDetail(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): queryset = RouteOrdering.objects.all() serializer_class = RouteOrderingSerializer This did allowed for a view in which there is create but not list (but its not usable for me, since i do need the list option avilable. Hope the problem is clear. Any help will be appriciated. -
Django 'instancemethod' object has no attribute '__getitem__'
Html <ul class="dropdown-menu" role="menu"> <li>java <input type="checkbox" name="categories[]" value="Java"></li> <li class="divider"></li> <li>c <input type="checkbox" name="categories[]" value="C"></li> <li class="divider"></li> <li>network <input type="checkbox" name="categories[]" value="Network"></li> <li class="divider"></li> </ul> Python list_categories = request.POST.getlist['categories'] This code cause error 'instancemethod' object has no attribute '__getitem__'. And I already tried list.categories = request.POST['categories'] -
Django IOError - No such file or directory
I've read the previous threads on this topic and tried to modify the code, but no success again. The problem is that I get IOError message at %s. No such file or directory error in the following view: def some_view(request): MYDIR = os.path.dirname(__file__) with open(os.path.join(MYDIR, '/static/egais_files/client.xml'), 'w') as f: # .... client.xml is located in the following folder: \\10.8.0.1\share\djprj\djprj\static\static\egais_files\client.xml Any ideas what am I doing wrong ? -
Django Rest Framework not saving reference to Many to Many
I have a model (Notifications) that has a Many-to-Many relationship (NotifictionGroups). Serializing data coming out of the models works just fine with DRF but when I want to save to Notification referencing the Many-to-Many relationships I get nothing. Models: class Notifications(models.Model): notification = models.CharField(max_length='125') groups = models.ManyToManyField('NotificationGroups') class NotificationGroups(models.Model): name = models.CharField(max_length='100') Serializers: class NotificationGroupSerializer(serializers.ModelSerializer): class Meta: model = NotificationGroups fields = ('id', 'name',) class NotificationSerializer(serializers.ModelSerializer): groups = NotificationGroupSerializer(many=True, read_only=True) class Meta: model = Notifications fields = ('id', 'notification', 'groups',) JSON body of the request: { "notification":"This is a test from the API", "groups":[ { "id":1 }, { "id":3 } ] } ViewSet: def create(self, request): serializer = NotificationSerializer(data=request.data) if serializer.is_valid(raise_exception=True): print serializer.validated_data return Response(serializer.data, status=status.HTTP_201_CREATED) When I save there is nothing saved for the Notification Groups. I am printing the validated data in the ViewSet at the moment just to test but I do not get any of the group data. I realize I am missing something obvious here but I have not been able to find my issue. All the examples I can find talk about writing the Many-To-Many data as new data, not referencing it as I need here. -
Exception handling in Django of queryset
I'm trying to catch an exception if a user does not exist and redirect if that's the case. When I run this I get an error saying: 'NoneType' object is not iterable try: return {'sub_user': User.objects.get(username=username)} except User.DoesNotExist: redirect('home') How can I catch this error? I tried with: try: return {'sub_user': User.objects.get(username=username)} except User is None: redirect('home') But that gave me another error: catching classes that do not inherit from BaseException is not allowed -
Convert Model.Objects.all() to JSON in python using django
I have a list of objects of the same model type. I want to iterate over this list and create a JSON to send back. I tried some things like 2-dim arrays, google,... but can't find something like this? Though I think it can't be difficult. my code now is: def get_cashflows(request): response_data = {} cashflow_set = Cashflow.objects.all(); i = 0; for e in cashflow_set.iterator(): c = Cashflow(value=e.value, date=str(e.date)); response_data[i] = c; return HttpResponse( json.dumps(response_data), content_type="application/json" ) here it is not possible to give model in json.dumps. But how i give more then 1 object to it? error : TypeError: coercing to Unicode: need string or buffer, float found [08/Sep/2016 14:14:00] "GET /getcashflow/ HTTP/1.1" 500 85775 -
Getting GET in django view
I have this URL pattern to get to my view: url(r'^api/cabinet/(?P<cabinetid>[0-9]+)/bin/$', views.api_cabinetbin), and pointing my browser to http://domain/api/cabinet/10/bin/ gives me the info on cabinet 10. I would like to put some extra info to the URL, like this: http://domain/api/cabinet/10/bin/?info=extra. However, this gives me a 404 ({"detail":Not found."} is the message I see in my browser. -
Django-oscar Add-ons (Food order website)
i have a question regarding django-oscar (python). we are trying to add stuff to the product's of the website. I guess people know the websites where you order, for example pizza and make it your own. So you get a form and you can follow that and order your own made pizza.. We're trying to make that too in Django-oscar but for some reason it won't work. We have tried everything.. followed all kinds of tutorials regarding add-ons. i have added some pictures for example I hope someone can help me. Thanks!