Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form is not valid forms.widgets.CheckboxSelectMultiple
I got a table Campaigns,Campaign_type and Campaign_campaign_type I want to insert into Campaign_campaign_type "Campaign_types" for a specific Campaign using a CheckboxSelectMultiple. As I have to initiate the CheckboxSelectMultiple with some parameters for the query everything is ok. But when I submit it the form is invalid I got a message that campaing_type_id is missing class Campaign(models.Model): client_id = models.ForeignKey(Company) name = models.CharField(max_length=45, null=True) campaign_status = models.ForeignKey(CampaignStatus) def __str__(self): return self.name class Campaign_type(models.Model): campaign_type = models.CharField(max_length=45) client_id = models.ForeignKey(Company) def __str__(self): return self.campaign_type + ' ' + str(self.client_id) class Campaign_campaign_type(models.Model): campaign_id = models.ForeignKey(Campaign) campaign_type_id = models.ForeignKey(Campaign_type) def __str__(self): return str(self.campaign_id) This is the Form class CampaignCampaignTypeForm(forms.ModelForm): options = forms.MultipleChoiceField(label='some label', choices=(('happy', 'Happy'), ('sad', 'Sad')), widget=forms.CheckboxSelectMultiple(attrs={'checked': 'checked'})) class Meta: model = Campaign_campaign_type exclude = ['campaign_id'] campaign_type_id = forms.MultipleChoiceField(widget=forms.widgets.CheckboxSelectMultiple()) widget = {'campaign_type_id': forms.ModelMultipleChoiceField(Campaign_type.objects.filter())} def __init__(self, *args, **kwargs): company = kwargs.pop("company") super(CampaignCampaignTypeForm, self).__init__(*args, **kwargs) self.fields["campaign_type_id"].widget = forms.widgets.CheckboxSelectMultiple() self.fields["campaign_type_id"].help_text = "help...." self.fields["campaign_type_id"].queryset = Campaign_type.objects.filter(client_id=company) -
How can I use auto increment in my composite unique key in Django?
I have a model class like this: class TestModel(models.Model): class Meta: unique_together = ('prefix', 'number') prefix = models.CharField(max_length=30) number = models.IntegerField() prefix and number together form a natural key for my model, but I don't particularly care what the number is. Thus, auto increment (not per-prefix) would be fine. I don't want to have to specify the number, but I want to be able to (e.g. because there are existing prefix+number pairs that need to put into this system). As I understand it, only Single-column PKs are supported, so I can't use prefix+number as a composite PK directly; only AutoField is auto-incrementing, and there can be only one AutoField per model (and it must be the PK), so I can't have both id & number auto incremented; and instead making prefix+id unique together makes no sense, as id is already unique on its own. Is there a way to achieve this (or is one of my statements wrong)? If there is a database-agnostic solution, that would of course be preferred, but otherwise, SQLite (development) and MySQL (production) are most important to me personally. Workarounds are also welcome - I'm trying to use the PK as "default" for number, but keeping … -
Django: python manage.py makemigrations returns IntegrityError: Column 'content_type_id' cannot be null
I hooked up my Django project the the MySQL Database, and I am certain that it is actually connected because when I try to makemigrations. I checked MySQL workbench and all my models are synced into the database. However, the problem is when i try to migrate, I get this error. It is complaining that No migrations to apply because mysql.connector.errors.IntegrityError: 1048 (23000): Column 'content_type_id' cannot be null. I am not even sure where content_type_id is coming from because my model doesn't even have that. Operations to perform: Target specific migration: 0001_initial, from bookSell Running migrations: No migrations to apply. Traceback (most recent call last): File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/django/base.py", line 177, in _execute_wrapper return method(query, args) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/cursor.py", line 515, in execute self._handle_result(self._connection.cmd_query(stmt)) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/connection.py", line 488, in cmd_query result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query)) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/mysql/connector/connection.py", line 395, in _handle_result raise errors.get_exception(packet) mysql.connector.errors.IntegrityError: 1048 (23000): Column 'content_type_id' cannot be null During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/JenniferLiu/.virtualenvs/bookSell/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) … -
Latest entry of every month
I have a model with a time_stamp (DateTime field) and I want to get the latest entry of every month. How can I approach this problem? This can easily be accomplished in mysql which I am familiar with, and there are lots of answers for them in SO, here's an example: SELECT * FROM table WHERE created_on in (select DISTINCT max(created_on) from table GROUP BY YEAR(created_on), MONTH(created_on)) Get last record of each month in MySQL....? How can I accomplish this in Django? Any help or direction would be appreciated. Thanks in advance, -
Specifying custom nested objects in Django Rest Framework ModelSerializer
I have lat, long specified in my DB as: ... lat = models.DecimalField(_('Latitude'), max_digits=8, decimal_places=5, null=True, blank=True) lng = models.DecimalField(_('Longitude'), max_digits=8, decimal_places=5, null=True, blank=True) ... I want my ModalSerialization to come out as: { ... "location": { "lat": ..., "long": ... } ... } How do I achieve that? -
Attach a newly created object to the current user in Django
Assume I have a Django application where a user may create a fantasy football team Team. This is accomplished using TeamCreateView, a regular CreateView (class-based generic). The User model has a field called my_team, which by default is empty. What is the best way to ensure that after User creates a new Team, my_team will be set to the newly created model instance? -
Django on Google App Engine- How to import/use 3rd party libraries?
I'm a begginer in both Django and Google App Engine. Running Django 1.9 on GAE, I would like to use these '3rd party' tools in my project: django-geojson: https://github.com/makinacorpus/django-geojson and django-leaflet: https://github.com/makinacorpus/django-leaflet My problem is: How to upload these tools to the GAE, together with the rest of my project files, so that they can be used there, by my app? I've already looked for answers here and found this question: How to use custom python libraries and apps in Google App Engine? But I really don't understand what the person meant/what to do. -
Create a User Profile or other Django Object automatically
I have setup a basic Django site and have added login to the site. Additionally, I have created a Student (Profile) model that expands upon the built in User one. It has a OneToOne relationship with the User Model. However, I have yet not come right with forcing the user to automatically create a Profile the first time they log in. How would I make sure they are not able to progress through anything without creating this? I have tried by defining the following in views: def UserCheck(request): current_user = request.user # Check for or create a Student; set default account type here try: profile = Student.objects.get(user = request.user) if profile == None: return redirect('/student/profile/update') return True except: return redirect('/student/profile/update') And thereafter adding the following: UserCheck(request) at the top of each of my views. This however, never seems to redirect a user to create a profile. Is there a best way to ensure that the User is forced to create a profile object above? -
How to fix django send mail?
I'm trying to send mail in django project for several days.I've got documentation from djangoproject.com, but that's not working for me. my settings.py contains these lines of code for sending mail: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = '**********' #my gmail account's password EMAIL_HOST_USER = 'showkatalisalim@gmail.com' my views.py contains these lines for contactform: def contactForm(request): form = LocalContactForm(request.POST or None) if form.is_valid(): send_mail( 'Subject here', 'Here is the message.', settings.EMAIL_HOST_USER, ['zellaic.showkatali@gmail.com'], fail_silently=False, ) return HttpResponseRedirect('thanks') context = {"page":"contact_form", "title":"Contact with us", "form":form} return render(request, 'form.html', context) While I'm trying send mail via my form: It show up: SMTPAuthenticationError at /contact/ (534, '5.7.14 <https://accounts.google.com/signin/continue? sarp=1&scc=1&plt=AKgnsbtZ\n5.7.14 4CcZKxu-As7S5tfd-3YTAz6XMdwLYcJKWk7_bViejaO8v_-mx-aD8PLO5zixLUMbTv38LY\n5.7.14 qE3ifOl5aXJOXaOVN5jU9Tl-HJVDj1_bc0n9nJ4PHERsBsyu8L0JRr9rM3ED0TdFXLV3wl\n5.7.14 _GF3jCTuCHIydf-YXcFZidIIqrERHyAORvqYmuPs0qHd_rt3ecbJUBOIW9PvzOXxGBiXg2\n5.7.14 ehh9XhyakjWXfOEuJgbxiNBMdCIM0> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 ao5sm46546625pad.1 - gsmtp') Request Method: POST Request URL: http://www.zellaic.com/contact/ Django Version: 1.10.1 Exception Type: SMTPAuthenticationError Exception Value: (534, '5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbtZ\n5.7.14 4CcZKxu-As7S5tfd-3YTAz6XMdwLYcJKWk7_bViejaO8v_-mx-aD8PLO5zixLUMbTv38LY\n5.7.14 qE3ifOl5aXJOXaOVN5jU9Tl-HJVDj1_bc0n9nJ4PHERsBsyu8L0JRr9rM3ED0TdFXLV3wl\n5.7.14 _GF3jCTuCHIydf-YXcFZidIIqrERHyAORvqYmuPs0qHd_rt3ecbJUBOIW9PvzOXxGBiXg2\n5.7.14 ehh9XhyakjWXfOEuJgbxiNBMdCIM0> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 ao5sm46546625pad.1 - gsmtp') Exception Location: /usr/lib64/python2.7/smtplib.py in login, line 621 Python Executable: /usr/local/bin/python Python Version: 2.7.5 Python Path: ['/home/showkatali/webapps/zellaic/lib/python2.7/Django-1.10.1-py2.7.egg', '/home/showkatali/webapps/zellaic', '/home/showkatali/webapps/zellaic/src', '/home/showkatali/webapps/zellaic/lib/python2.7', '/home/showkatali/lib/python2.7/pip-8.1.2-py2.7.egg', '/home/showkatali/lib/python2.7', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/PIL', '/usr/lib64/python2.7/site-packages/geos', '/usr/lib/python2.7/site-packages'] … -
updating account balance with django
absolute n00b here, just fiddling around. Trying to make a very simple app to track my personal expenses. I have a class for entering the expenses, a class for the categories and a class for my account balance. Plan is to create en entry in the account balance everytime I create an expense. How do I update my account balance? I'll have to get fields from the latest entry in expenses to do the math with in my balance class, right? This is what I have. Any help appreciated. from django.db import models from django.utils import timezone class Category(models.Model): category = models.CharField(max_length=200,blank=False) def __str__(self): return self.category class Balance(models.Model): date = models.DateTimeField(default=timezone.now) previous_balance = ???? transaction = ???? current_balance = previous_balance - transaction class Expense(models.Model): date = models.DateTimeField(default=timezone.now) spender = models.ForeignKey('auth.User') description = models.CharField(max_length=200) category = models.ForeignKey(Category,default=1) ABN = 'ABN' ING = 'ING' ACCOUNT_CHOICES = ( (ABN, 'ABN'), (ING, 'ING'), ) account = models.CharField( max_length=30, choices=ACCOUNT_CHOICES, default=ABN, ) amount = models.DecimalField(max_digits=10, decimal_places=2) def commit(self): self.commit_date = timezone.now() self.save() def __str__(self): return u"%s. Kosten: %s" % (self.description, self.amount) -
Django Template - Cannot iterate throught this list
I am passing this object to my template from my view with the name "student_collection" <class 'list'>: [[31, 'John', ‘Jacob', '1'], [31, 'Jeffrey', ‘Mark', '2'], [39, ‘Borris', ‘Hammer', '1']] and accessing it as such in my template {% for rows in student_collection %} <tr> {% for items in rows %} {% for entry in items %} <td>{{ entry }}</td> {% endfor %} {% endfor %} </tr> {% endfor %} I am getting an error at the point {% for entry in items %} django says 'int' object is not iterable why is that I was expecting to iterate through 31,John,Jacob,1 . Any help in this regard would be appreciated. -
Implementation of like model design in Django
First question, is it a correct model design of Like concept considering that I need stand-alone 'like' class(not just as part of Question class), so that I will be able to create Notification class later including new likes, followings and stuff? class Question(models.Model): like = models.OneToOneField('Like',related_name='like_QUESTION',null=True, blank=True) class Like(models.Model): what_post_is_liked = models.OneToOneField('Question', related_name='what_post_is_liked_LIKE') who_liked = models.OneToOneField('UserProfile', related_name='who_liked_LIKE') whom = models.OneToOneField('UserProfile', related_name='whom_LIKE') The second question is, how do I get properties('what_post_is_liked') of class Like through 'like' child element of 'Question' class? According to the documentation on OneToOne relationships I should just write properties of Like class just after 'like' just like this e.like.who_liked ? questions = Question.objects.filter(whom=request.user.profile) for e in questions: print(e.like) Although 'Like' object exists, 'e.like' returns None, which means that 'like' doesn't automatically inherits 'Like' newly created object ? like = Like(whom=a,who_liked=b,what_post_is_liked=c) like.save() I'v got into a total mass. Could someone please explain how it actually works? How can I make automatically copied/inheritable and get 'Like' properties through like of 'Question' class? -
apache mod_wsgi error with django in virtualenv
I can't seem to find a good answer to this. Who needs to own the virtualenv when running it as a WSGIDaemon? I assume on my OS (Ubuntu 16) www-data, but I want to be sure. Trying some new things to get this thing working based off of the answer from this post... django apache configuration with WSGIDaemonProcess not working Does the django project, the virtualenv folder, or both need to be owned by the apache group? What ownerships need to be in place to serve a django project without specifying a port? Why do I get the following? The root problem: Call to 'site.addsitedir()' failed for '(null)' When I start apache, I get this error. I've followed several different guides, including: http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html and https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/ but have had zero success. My virtual environment path is /usr/local/virtualenvs/servicesite My django project path is /home/addohm/projects/rtservice/servicesite this is where manage.py resides, which leaves /home/addohm/projects/rtservice/servicesite/servicesite as the location of my wsgi.py. wsgi.py: SERVICESITE = ['/usr/local/virtualenvs/servicesite/lib/python3.5/site-packages'] import os import sys import site prev_sys_path = list(sys.path) for directory in SERVICESITE site.addsitedir(directory) new_sys_path = [] for item in list(sys.path): if item not in prev_sys_path: new_sys_path.append(item) sys.path.remove(item) sys.path[:0] = new_sys_path """ **Doesn't seem to work, throwing error in apache … -
How to get values from my python file to my form using Flask?
I'm trying to extract "address" from my python file "get interfaces.py" display it into my form using flask, but my code is not working, and may be I'm doing it wrong. I'm new in Flask Here's my python file get_interfaces.py with open('/etc/network/interfaces', 'r+') as f: for line in f: found_address = line.find('address') if found_address != -1: address = line[found_address+len('address:'):] print 'Address: ', address found_network = line.find('network') if found_network != -1: network = line[found_network+len('network:'):] print 'Network: ', network found_netmask = line.find('netmask') if found_netmask != -1: netmask = line[found_netmask+len('netmask:'):] print 'Netmask: ', netmask found_broadcast = line.find('broadcast') if found_broadcast != -1: broadcast = line[found_broadcast+len('broadcast:'):] print 'Broadcast: ', broadcast Where the variable "address" is what I want. My flask: from flask import render_template, request, redirect, url_for, Response from app import app, lm from flask.ext.login import login_required, login_user, logout_user, UserMixin from Mensajeria.ConfiguracionInterfaces import ConfiguracionInterfaces import zmq import struct import subprocess import os import threading, time, json import cProfile, pstats, StringIO @app.route('/ibisaserver_cliente/') def ibisaserver_cliente(): pr = cProfile.Profile() pr.enable() Ci = ConfiguracionInterfaces() pr.disable() s = StringIO.StringIO() sortby = 'calls' ps = pstats.Stats(pr, stream=s).sort_stats(sortby) ps.print_stats() logging.debug(s.getvalue()) return render_template('ibisaserver_cliente.html', title='Ibisa Link', Ci=Ci) Here's my configuracioninterfaces.py : import ConfigParser import os class ConfiguracionInterfaces(object): def __init__(self): self.config = ConfigParser.RawConfigParser() #Ruta para … -
Django 1.10: get user profile
i am trying to get a user profile in my project. Here is my model: # /Extension of User model/ class Profile(models.Model): user = models.OneToOneField(User, related_name='profile') sexe = models.CharField(max_length=1, blank=True) city = models.CharField(max_length=50, blank=True) def __unicode__(self): return self.user.username from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=User) def create_user_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = Profile(user=user) user_profile.save() post_save.connect(create_user_profile, sender=User) And than, my form: class UserProfileForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password'] The main problem is my view: @login_required def EditProfile(request, pk): user = User.objects.get(pk=pk) user_form = UserProfileForm(instance=user) ProfileInlineFormset = inlineformset_factory(User, Profile, fields=('sexe', 'city')) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: if request.method == "POST": user_form = UserProfileForm(request.POST, request.FILES, instance=user) formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user) if formset.is_valid(): created_user.save() formset.save() return HttpResponseRedirect('/accounts/profile/') return render(request, "account/update_profile.html", { "noodle": pk, "noodle_form": user_form, "formset": formset, }) else: raise PermissionDenied When i create a new user, i get an error saying: missing 1 required positional argument 'pk'. I don't understand the meaning of the error and i don't know how to resolve the problem. Thank you! -
Renaming model brakes migration history
I have two models in two different apps: # app1 models.py class App1Model(models.Model): pass # app2 models.py from app1.models import App1Model class App2Model(App1Model): pass And I want to rename App1Model and then recreate App2Model to have explicit OneToOneField instead of magic app1model_ptr. So I create migration which deletes App2Model completely (I don't care about data because whatever reason), it runs successfully. Then I create migration in first app which renames App1Model and it runs perfect too, I check this table with new name and all it's relationships (and to it too), it's fine. And then weird thing happens: when I run makemigrations or migrate on app2 I get an error django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'app2.App2Model'>] It fails while creating current project state on very first migration of app2 (0001_initial.py in app2 migrations) where this model was created first time by inheriting from App1Model with its old name. Is there some way of fixing this? In current state App2Model already deleted, App1Model renamed and I can't do anything with migrations on app2 because of this issue. -
Django multiple one to many join
I have one to many relationship in many places in my Django app. For example I have user, home and key: class User(Model): id_user = models.AutoField(primary_key=True) class Home(Model): id_home = models.AutoField(primary_key=True) id_user = models.ForeignKey('user.User', models.DO_NOTHING, db_column='id_user_home') class Key(Model): id_key = models.AutoField(primary=True) id_home = models.ForeignKey('home.Home', models.DO_NOTHING, db_column='id_home_key') From session I have user = User(1) and I want to get all keys. -
mod_wsgi apache2 loading failure
I've set this up using a multitude of documentation and repeatedly get the same result. This particular one below is following https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/#daemon-mode exactly as it says. I need help! [Sun Oct 09 14:52:09.208810 2016] [wsgi:warn] [pid 53237] mod_wsgi: Compiled for Python/3.5.1+. [Sun Oct 09 14:52:09.208844 2016] [wsgi:warn] [pid 53237] mod_wsgi: Runtime using Python/3.5.2. [Sun Oct 09 14:52:09.210835 2016] [mpm_prefork:notice] [pid 53237] AH00163: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations [Sun Oct 09 14:52:09.210866 2016] [core:notice] [pid 53237] AH00094: Command line: '/usr/sbin/apache2' [Sun Oct 09 14:52:09.245977 2016] [wsgi:error] [pid 53240] mod_wsgi (pid=53240): Call to 'site.addsitedir()' failed for '(null)', stopping. [Sun Oct 09 14:52:09.246021 2016] [wsgi:error] [pid 53240] mod_wsgi (pid=53240): Call to 'site.addsitedir()' failed for '/home/addohm/projects/rtservice/projectenv/lib/python2.7/site-packages'. -
Django Testing - access session in RequestFactory
I am using RequestFactory in a Django test, and I can't find the right way to access the session variable, and I'm getting the following error when I try self.factory._session["zip_id"] or self.factory.session["zip_id"]. ====================================================================== ERROR: test_middleware (dj_geo.tests.IPToZipMiddleWareTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "c:\dj_site_test\dj_geo\tests.py", line 36, in test_middleware assert self.factory._session["zip_id"] != None AttributeError: 'RequestFactory' object has no attribute '_session' ---------------------------------------------------------------------- @override_settings(MIDDLEWARE_CLASSES=( 'dj_geo.middleware.IPToZipMiddleWare' )) class IPToZipMiddleWareTest(TestCase): def test_middleware(self): Zipcode.syncdb() assert Zipcode.objects.all().count() > 0 self.factory = RequestFactory() self.request = self.factory.get('/', {}, **{'REMOTE_ADDR':'108.31.178.99'}) assert self.factory._session["zip_id"] != None assert self.factory._session["zip_id"] != "" -
How to continue the object in django get_next/previous_by_created by published?
Anyone can help me how to continue the object in Django get_next/previous_by_created by published only? >>> obj_4 = Post.objects.get(pk=4) >>> obj_4.publish True >>> obj_4.get_previous_by_created() <Post: Title Post 3> >>> obj_4.get_previous_by_created().publish False >>> obj_4.get_previous_by_created().pk 3 >>> obj_2 = Post.objects.get(pk=2) <Post: Title Post 2> >>> obj_2.publish True >>> obj_4.get_next_by_created() <Post: Title Post 5> >>> obj_4.get_next_by_created().publish True >>> I need to continue the object by published only. For example: >>> obj_1 = Post.objects.get(pk=4) >>> obj_1.get_previous_by_created_and_published() <Post: Title Post 2> Other conditions, if we have such as bellow: [1 , 2, 3, 4, 5, 6, 7, 8 ] [True, False, False, False, True, True, False, True] And then, if i starting from pk=5, the output should be pk=1. >>> obj_5 = Post.objects.get(pk=5) >>> obj_5.get_previous_by_created_and_published().pk 1 >>> Thanks so much before... -
How make google charts in realtime with django and socket io from arduino data
I'm testing an electric monitoring system made with arduino, django, node.js, socket io and google chart. Appreciate it help in getting to the graph in real time. I tried with node.js and socket io but I do not work for me. The arduino sends a request post every 20 seconds a json object database records in a django view restframework. There it goes well. But not update the page as the chart whenever you enter information into the database to be presented in real time. I followed several tutorials: Can I use Socket.IO with Django? http://www.maxburstein.com/blog/realtime-django-using-nodejs-and-socketio/ But even I have not succeeded. -
Django queryset many to many through relationship - complex queryset
I am working on a practice ecommerce project and am trying to get the seller for each product in a cart for 2 reasons. To find out if the order is shared with other sellers or of just one seller. If the order has multiple sellers then show the order as shared order. This is how my models are designed: class Cart(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) items = models.ManyToManyField(Variation, through=CartItem) class CartItem(models.Model): cart = models.ForeignKey('Cart') item = models.ForeignKey(Variation) class Product(models.Model): seller = models.ForeignKey(SellerAccount) title = models.CharField(max_length=120) class Variation(models.Model): title = models.CharField(max_length=120, blank=True, null=True) product = models.ForeignKey(Product) Please note User in Cart is not the seller. The seller is associated with Product. The problem I am facing is with building the queryset. I have tried with ModelManager, custom queryset but have not been able to do this successfully. Through the cart I would like to get seller and their variation and if there are more than one seller in the queryset mark the cart as shared and accordingly display the results to the seller. As of now I am only struggling with getting the queryset. -
Receiving only a part of string which is passed as a parameter to http get command - Semicolon Perhaps?
I am trying to pass this string as a get parameter. This string starts with the following characters : string name is some_html it is basically some html <p style=\"-qt-block-indent: 0; text-indent: 0px; margin: 18px 0px 12px 0px;\"><span style=\"font-size: xx-large; However I only get this <p style=\\"-qt-block-indent: 0 This is how I am passing the string: http://127.0.0.1:8000/service_SubmitResult?htmlstring=some_html Any idea on what I might be doing wrong. I am sending the string via Qt and receiving it on Django endpoint? I believe its because of the semicolon . I am using the following function for encoding the url before sending it out QUrl ServiceCalls::UrlFromUserInput(const QString& input) { QByteArray latin = input.toLatin1(); QByteArray utf8 = input.toUtf8(); if (latin != utf8) { // URL string containing unicode characters (no percent encoding expected) return QUrl::fromUserInput(input); } else { // URL string containing ASCII characters only (assume possible %-encoding) return QUrl::fromUserInput(QUrl::fromPercentEncoding(input.toLatin1())); } } Why am I receiving only a part of the string. On django i am getting the parameter value in the following way def service_foo(request): try: htmlResult = request.GET.get('htmlstring', '') .... return HttpResponse(); except Exception as e: print(e) return HttpResponse("Error Service from sqlite") Any suggestions on how I can fix this or what … -
Django: How to properly make shopping cart? ( Array string field )
lately i needed to create a server-side shopping cart for my website that would have products inside, I could add cart and product in session cookies, but i prefer to add it to my custom made User model, so it can stay when user decides to log out and log back in. Since i am making a shopping cart, i needed to make a model for it, that will hold products as objects, so then they can be easily used, but i couldn't find any way to do so properly. class User(models.Model): username = models.CharField(max_length=150) joined = models.DateTimeField('registered') avatar = models.CharField(max_length=300) balance = models.IntegerField(default=0) ban = models.BooleanField() cart = models.??? def __str__(self): return self.username How can i achieve having array string in models with using Django's system? If not then can it be possible by other libraries ( Json, Pickle ), but i've seen it can be done by ForeignKey, if so how is it possible? -
Django downgrade from 1.9 to 1.8
I am trying to use a Django package that is only compatible with Django 1.8, so I think I should downgrade my current project from 1.9 to 1.8. What would be the best course of action for achieving that?