Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Invalid embedded document instance provided to an EmbeddedDocumentField
I am currently working on an billing app and require to have orders inside a bill for that I have following two models Bill and orders class Bill(Document): billNo = IntField(unique=True, blank=False) table = ReferenceField('Table',reverse_delete_rule=1) orders = EmbeddedDocumentListField('Order', required = False) total = models.FloatField() discount = models.FloatField(blank=True) grandtotal = models.FloatField() payment_option = ReferenceField('PaymentOption',reverse_delete_rule=1) paid = models.BooleanField(default=False) class Order(EmbeddedDocument): food = ReferenceField(Food) quantity = IntField(required = True) complementory = BooleanField(default = False) and their serializers are as class OrderSerializer(EmbeddedDocumentSerializer): class Meta: model = Order fields = 'all' read_only_fields = ('id',) class BillSerializer(DocumentSerializer): orders = OrderSerializer(many = True) class Meta: model = Bill fields = '__all__' read_only_fields = ('id',) def create(self, validated_data): orders = validated_data.pop('orders') bill = Bill.objects.create(**validated_data) bill.orders = [] for order in orders: print(order) bill.orders.append(order) bill.save() return bill But whenever I pass a json like { "billNo": "4", "table":"5a93eb7f59951a3320a0b4d8", "payment_option":"5a93eddf59951a2fd4dbabe9", "orders":[{ "food":"5a93c2c759951a018c5e18b5", "quantity":"2", "complementory":"False" }] } the bill object is created but the order is not added and it gives the error mongoengine.errors.ValidationError: ValidationError (Bill:5a94f76859951a19d4688aeb) (Invalid embedded document instance provided to an EmbeddedDocumentField: ['orders']) I am using django rest framework and since it is mongodb i am using django rest framework mongo engine. What is the actual error and what … -
Unicode issue with pygithub and django
I'm trying to connect to this org githubtraining This is my code on views.py: def home(request): global org email=request.GET['email'] password=request.GET['password'] g = Github("user", "paswword") org = g.get_organization('githubtraining') list_rep= org.get_repos() context = { 'list_rep': list_rep, 'org':org } return render(request, 'Github/repo.html',context) But everytime I try to render the view I got this error: UnicodeEncodeError at /auth/ 'ascii' codec can't encode character '\u200b' in position 24: ordinal not in range(128) Is this because of something wrong in my call? Or maybe there's something else there? -
Django-haystack can not filter by datetime
Version: django-haystack (2.6.1) Django (1.11.4) I am trying to creating a search form, following by the tourial: After filtering the start date, the sqs become empty. What's wrong? class DateRangeSearchForm(SearchForm): start_date = forms.DateTimeField(required=False) end_date = forms.DateTimeField(required=False) def search(self): sqs = super(DateRangeSearchForm, self).search() print (sqs[0].object.publish_date) #2017-10-23 02:10:40.673000+00:00 print (self.cleaned_data['start_date']) #2017-10-17 00:00:00+08:00 print (self.cleaned_data['start_date']<sqs[0].object.publish_date) #true print (len(sqs)) #19 if not self.is_valid(): print("no query found/n") return self.no_query_found() if self.cleaned_data['start_date']: sqs = sqs.filter(publish_date__gte=self.cleaned_data['start_date']) print(len(sqs))#0 return sqs -
Django: Querying M2M table after object creation returns empty array
I'm using a Django signal to run a block of code after a model saves using post_save. The signal receiver in post_save gets an instance of the object sends it to a method for some processing before the instance is sent to a third party via network. One of my models, foo, has a many-to-many relation with another model, bar, and I need to add an array named bar_id that contains ids of each bar before I send foo to the third party. This configuration works when updating a foo instance however when I create a new instance of foo and I query for its relations (see the troublesome query in the Add Bar's ID to Foo and send it to third party section, the query is returning an empty query set even though the relation exists in the database. This exact same query returns a query set if I update the same model moments later. Any ideas of why this may be happening? Here's the code: Register the signal from django.apps import AppConfig class FooConfig(AppConfig): name = 'foo' def ready(self): import foo.signals Signal Code from django.dispatch import receiver from django.db.models.signals import post_save from django.conf import settings from django.db.models import … -
Django-Rest-Framework can not load the Styles and Scripts
I use Django-Rest-Framework, but get bellow error when I open the DRF APIs: The styles and Scripts can not load: GET http://localhost:8000/static/rest_framework/css/bootstrap.min.css net::ERR_ABORTED localhost/:20 GET http://localhost:8000/static/rest_framework/css/bootstrap-tweaks.css net::ERR_ABORTED localhost/:23 GET http://localhost:8000/static/rest_framework/css/prettify.css net::ERR_ABORTED localhost/:24 GET http://localhost:8000/static/rest_framework/css/default.css net::ERR_ABORTED (index):219 GET http://localhost:8000/static/rest_framework/js/ajax-form.js net::ERR_ABORTED (index):218 GET http://localhost:8000/static/rest_framework/js/jquery-1.12.4.min.js net::ERR_ABORTED (index):220 GET http://localhost:8000/static/rest_framework/js/csrf.js net::ERR_ABORTED (index):221 GET http://localhost:8000/static/rest_framework/js/bootstrap.min.js net::ERR_ABORTED (index):222 GET http://localhost:8000/static/rest_framework/js/prettify-min.js net::ERR_ABORTED (index):223 GET http://localhost:8000/static/rest_framework/js/default.js net::ERR_ABORTED (index):219 GET http://localhost:8000/static/rest_framework/js/ajax-form.js 404 (Not Found) (index):220 GET http://localhost:8000/static/rest_framework/js/csrf.js net::ERR_ABORTED (index):221 GET http://localhost:8000/static/rest_framework/js/bootstrap.min.js net::ERR_ABORTED (index):222 GET http://localhost:8000/static/rest_framework/js/prettify-min.js net::ERR_ABORTED (index):223 GET http://localhost:8000/static/rest_framework/js/default.js net::ERR_ABORTED and the Network: but the docs is ok, the Style and Script all work fine: -
django rest + axios put request error 403
I've read the duplicates and nothing seems to be working. I can do the put request directly from the form in the url but I can't seem to get the axios request working. I tried: CSRF with Django, React+Redux using Axios https://gist.github.com/paltman/490049a64fa4115a2cea My axios request: axios({ method: 'put', url: '/f/'+id, data: { item: item, }, }).then(function (response) { this.setState({needReceipt: true}); }) .catch(function (error) { console.log(error); }); In my settings.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), } in my webpack.config.dev.js: const axios = require('axios'); axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken"; -
context and dictionaries python Django
So I have the following code: views.py: def topics(request): """Show all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) return render(request, 'learning_logs/topic.html', context) I understand that I am querying the database and sorting the data by date then storing that data in the topics variable. My first question is, is the topics variable storing the data as a list? (assuming multiple entries). If so when I have the following code in my html file topics.html: <ul> {% for topic in topics %} <li>{{ topic }}</li> {% empty %} <li>No topics have been added yet.</li> {% endfor %} </ul> why do I need pass the data stored in topics into a context dictionary for topics.html to loop through and display the data? why not loop through the topics variable itself? I'm just confused on the use of "contexts" Thanks for the help in advance. -
Django Model.objects.all() returns unexpected empty QuerySet
I have some problem while trying to use a MySQL database with Django. The database contains a table named items. This database is imported from a development system to a production system. This database is the second database in addition to an existing SQLite databased used by other teams. There had been an error message about no such table, but I was able to solve it with this question. It assume that there are no migration errors. The MySQL database works fine in the development system (tested using python manage.py shell), but it doesn't work in the production system (tested the same way.) I tested the import with: $ python manage.py shell >> from project.models import Item >> Item.objects.all() <QuerySet []> I created the models.py file with: $ python manage.py inspectdb > models.py I verified that the database and the table items actually contains records. (Although some fields are stored as unicode text, if that makes any difference to the situation.) I am using Django 2.0.2 with Python 3.6.3. -
Error [mportError: No module named 'django'] while trying integrate apache2 with Django 1.11
I really need help with this as I've been trying to get the bottom of it for a while. I'm trying to get Django to use the apache2 server.However, when I try to log unto the apache page i get : Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache/2.4.7 (Ubuntu) Server at 127.0.1.1 Port 80 I have copied my version(s) output from the ubuntu 1404LTS Python 3.6.0+ (default, Feb 4 2017, 11:11:33) [GCC 4.9.4] on linux Type "help", "copyright", "credits" or "license" for more information. django.VERSION (1, 11, 4, 'final', 0) dpkg -l | grep wsgi ii libapache2-mod-wsgi-py3 3.4-4ubuntu2.1.14.04.2 amd64 Python 3 WSGI adapter module for Apache When I open the logs, I see the below: [Tue Feb 27 02:32:43.409875 2018] [:error] [pid 3211:tid 140311519147904] AssertionError: [Tue Feb 27 02:32:44.388403 2018] [:warn] [pid 3567:tid 139906080114560] mod_wsgi: Compiled for Python/3.4.0. [Tue Feb 27 02:32:44.388477 2018] [:warn] [pid 3567:tid 139906080114560] mod_wsgi: Runtime using … -
How to show a update form while keeping the original data in Django?
I'm using Django Forms to do some updating work.For example,I write a FilmForm to present a film information form: class FilmForm(forms.Form): name = forms.CharField() director = forms.CharField() release_year = forms.DateField() ......(many other infos) And I create and save a model instance using the form.Next time I want to modify only one info,like 'director',and update the model info using the FilmForm. def FilmUpdate(request,pk): if request.method == 'POST': ... else: form = FilmForm() return render(request,'film_update.html', {'form':form}) but when the form show up,the html inputs are all blank,and have to input all the original data again while the only item I want modify is just 'director'.So how to present the update form with the original data keeping? -
Django - Trying to delete 3rd party app, but getting "doesn't declare an explicit app_labels"
I am trying to uninstall a 3rd party app called Silk. I have removed all traces from Silk from my project, include settings.py, urls.py and anywhere else in the project. Now when I try to start the server, I get the following error - RuntimeError: Model class silk.models.Request doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.. I tried doing python manage.py migrate silk zero, but it says that silk is not a valid app (it's not in my project folder). Then I said screw it, and ran python manage.py reset_db to completely reset my database, but even after that, I still get the same error. How do I get rid of Silk? -
proper way to set up many to many relation where intermediary field has foreign keys django
I have a custom user field and a permissions field in a django app. The documentation says the following: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ManyToManyField that we are to use the manytomany through method. But I am confused on its proper implementation. Below I have my two models. I am asking for assistance in understanding how the through field applies in this case or at all. class STUser(AbstractBaseUser): email = models.EmailField(unique=True) name = models.CharField(max_length=255) companyname = models.CharField(max_length=200, blank=True, null=True) userphoto = models.CharField(max_length=200, blank=True, null=True) signupvaildatestring = models.CharField(max_length=200, blank=True, null=True) is_active = models.BooleanField(default=False) phone = models.CharField(max_length=10, null=True, blank=True) jobtitle = models.CharField(max_length=100, null=True, blank=True) # password field function is provided by AbstractBaseUser and the permissions table class Permissions(models.Model): venue = models.ForeignKey(Venue, on_delete=models.SET_NULL, blank=True, null=True) user = models.ForeignKey(STUser, on_delete=models.DO_NOTHING) isclient = models.BooleanField(default=False) isvenueviewer = models.BooleanField(default=False) isvenueeventplanner = models.BooleanField(default=False) isvenueadministrator = models.BooleanField(default=False) issuitsviewer = models.BooleanField(default=False) issuitsadministrator = models.BooleanField(default=False) issuitssuperuser = models.BooleanField(default=False) now I am supposed to use the through fields on this? The Example the docs uses its below does it differ in a way from my implementation where I do not need to use the through field? from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), … -
psycopg2.OperationalError: FATAL: password authentication failed for user "<my UNIX user>"
I am a fairly new to web developement. First I deployed a static website on my vps (Ubuntu 16.04) without problem and then I tried to add a blog app to it. It works well locally with PostgreSQL but I can't make it work on my server. It seems like it tries to connect to Postgres with my Unix user. Why would my server try to do that? I did create a database and a owner via the postgres user, matching the login information in settings.py, I was expecting psycopg2 to try to connect to the database using these login informations: Settings.py + python-decouple: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config ('NAME'), 'USER': config ('USER'), 'PASSWORD': config ('PASSWORD'), 'HOST': 'localhost', 'PORT': '', } } This is the error message I get each time I try to ./manage.py migrate 'myportfolio' is my Unix user name, the database username is different: Traceback (most recent call last): File "/home/myportfolio/lib/python3.5/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/myportfolio/lib/python3.5/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/myportfolio/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/home/myportfolio/lib/python3.5/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "myportfolio" … -
Django/Python Regex Error -- No Reverse Match
Back with what I suspect is one more regex error.. have tried a ton of different iterations, but nothing is working. Here are urls in my 'deals' folder: url(r'^$', DealListView.as_view(), name='deals'), url(r'^(?P<slug>[\w-]+)/', deal_by_detail, name='deal_detail'), url(r'^category/(?P<category>\w+)\/$', deals_by_category, name='category'), url(r'^(?P<pk>[0-9]+)/like', like, name='like'), The error is happening if i visit an individual deal page like this: http://localhost:8000/deals/free-bike-dicks-sporting-goods/ And here is the 'deal_by_detail' view: def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) Here is my error and traceback NoReverseMatch at /deals/free-bike-dicks-sporting-goods/ Reverse for 'deal_detail' with arguments '()' and keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['deals/(?P<slug>[\\w-]+)/'] Request Method: GET Request URL: http://localhost:8000/deals/free-bike-dicks-sporting-goods/ Traceback: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py" in reverse 586. extra, resolver = resolver.namespace_dict[ns] During handling of the above exception ('dealmazing.deals'), another exception occurred: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\defaulttags.py" in render 507. current_app=current_app) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py" in reverse 596. key) During handling of the above exception ('dealmazing.deals' is not a registered namespace), another exception occurred: File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\Desktop\JSPROJ\dealmazing\deals\views.py" in deal_by_detail 23. return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\shortcuts.py" in render 67. template_name, context, request=request, using=using) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\loader.py" in render_to_string 97. return template.render(context, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\template\backends\django.py" in render … -
django sqlite3 URIs not supported
Odd situation. Django 2.x in its features for sqlite3 drive turns on uri support. It seems to only be a problem seen in python 3. On machines with older version of sqlite, in my case 3.6.20, the problem of URIs not supported does not arise with exactly the same virtualenv and codebase. On machine with sqtlite3 --version showing 3.7.17 it does arise. The funny thing is the feature is only supported in sqlite3 after 3.7.7 or so from what I read. So apparently django sees it is supported but it really isn't at the level of the internal sqlite3 drivers in python? (guessing) In [3]: sqlite3.version_info Out[3]: (2, 6, 0) In [4]: sqlite3.sqlite_version_info Out[4]: (3, 7, 17) On the machine it does not work on and as expected last line is (3, 6, 20) on machine it does work on. Now I don't have full control of the machine. I thought just to pull over the lower version but no luck there. Internal libraries determine actual version even when you run sqlite3 on the command line. I can hack the relevant part of the django driver setup but that is less than pleasing even though I do have control of … -
Wagtail blog example gallery image not loading
I'm following the blog tutorial on the Getting Started page and I've added the BlogPageGalleryImage. I've done all the migrations and I'm able to add images to a post I created earlier as an admin. The templates and models have all been modified as required. However when I view the page, the image doesn't get displayed. Below are the relevant code excerpts. Model.py class BlogIndexPage(Page): intro = RichTextField(blank=True) def get_context(self, request): # Update context to include only published posts, ordered by # reverse-chron context = super(BlogIndexPage, self).get_context(request) blogpages = self.get_children().live().order_by('-first_published_at') context['blogpages'] = blogpages return context content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('intro'), FieldPanel('body', classname="full"), InlinePanel('gallery_images', label="Gallery images"), ] class BlogPageGalleryImage(Orderable): page = ParentalKey(BlogPage, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) caption = models.CharField(blank=True, max_length=250) panels = [ ImageChooserPanel('image'), FieldPanel('caption'), ] blog_page.html {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block body_class %}template-blogpage{% endblock %} {% block content %} <h1>{{ page.title }}</h1> <p class="meta" >{{ page.date }}</p> <div class="intro" >{{ page.intro }}</div> {{ page.body|richtext }} {% for item in page.gellery_images.all … -
DoesNotExist --Matching Query Error
I'm trying to list a group of deals by category I have a Deal model and a Category Model, where the Category is a Foreign Key of a Deal like so: class Deal(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=140, unique=True) description = models.TextField(default='') category = models.ForeignKey(Category) The urlpattern for a category page looks like this: url(r'^category/(?P<category>\w+)/$', deals_by_category, name='category') The view for this urlpattern is this: def deals_by_category(request,category): category_deals = Deal.objects.filter(category__name=category, ) return render(request, 'deals/category.html', {'category_deals': category_deals}) and then my category.html template is looping through these returned deals like this: {% for deal in category_deals %} <h5 class="card-retailer">{{ deal.retailer}}</h5> <p class="card-title">{{ deal.title }}</p> Now the issue arises if i click on predetermined category link like this: http://localhost:8000/deals/category/Apparel/ but the error is pointing NOT to my 'deals_by_category' view, but to the individual view for each deal---the stack trace is pointing to that second line below. I think this must be an easy fix, but have been staring at this for the past few hours and can't determine what the issue is. def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail}) -
Django sort and regroup multiple fields
I am trying to regroup a field and sort on another in Django. My use case is different, but let's use the Django regroup template as an example. Using this dataset. cities = [ {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'}, {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'}, {'name': 'New York', 'population': '20,000,000', 'country': 'USA'}, {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'}, {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'}, ] Using the regroup tag, this is the output: India Mumbai: 19,000,000 Calcutta: 15,000,000 USA New York: 20,000,000 Chicago: 7,000,000 Japan Tokyo: 33,000,000 How can I sort this information by population and yet still keep the grouping? This is the expected output that I would like to see: Japan Tokyo: 33,000,000 USA New York: 20,000,000 Chicago: 7,000,000 India Mumbai: 19,000,000 Calcutta: 15,000,000 How would one query the database to keep the groupings that are needed for reorder in the Django template to work properly and yet still maintain the sort order of population? How would this work on a date object instead of an int? -
DJango TypeError - JSFiles object is not reversible
I am trying to include this datepicket widget in my DJango version 2.0.2, but it raises error TypeError at /xuser/1/edit 'JSFiles' object is not reversible I have already looked around for similar errors in following threads What does it mean by object not reversible Django TypeError at /admin/ 'set' object is not reversible But these are just typo errors about urlpatterns and does not even disclose what reversible actually mean in python. The google search about reversible object does not yield anything more than the above threads. So, my question is, What does reversible object mean? How can I solve this issue? -
Bootstrap auto-complete on pycharm
I've been working on a Django project, I'm using Pycharm as my IDE, the problem is that , firstly I don't have a CSS file type in the new file section, also I don't have autocomplete for bootstrap so I have to write everything manually which really is a pain in the ass. Any help would be much appreciated. I'm using Pycharm community edition 2017 and i'm on Ubuntu 16.0.4. -
How do i display passwords fields on a registration form made by extending django user model?
I'm trying to create a custom django registration form which users can sign up from but i'm not sure how to go about letting the user set the password. I have tried extending the model by using OneToOneField but all i get on the templates are the usual username, email but no password fields?can someone help? from django import forms from django.contrib.auth.models import User from django.forms import ModelForm from administration.models import Agent, Post from django.contrib.auth.forms import UserCreationForm class userForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email', 'password1', 'password2'] class agentForm(forms.ModelForm): class Meta: model = Agent fields = ['bio','photo','phone','address','company','location'] class ContactForm(forms.Form): name = forms.CharField(max_length=150) email = forms.EmailField() subject = forms.CharField() message = forms.CharField(widget = forms.Textarea) -
CSS is not showing in the admin page -Django
So I upload my site to digitalocean and when I went to the admin page the CSS was not showing I visit all these sites but nothing seems to work Django doc-static files Pythonanywhere-DjangoStaticFiles StackOverflow -why my django admin site does not have the css style I set up my STATIC_ROOT and STATIC_URL, and then I ran python manage.py collectstatic And here is my seting STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/home/django/django_project/django_project/static') -
django get_all_permissions() return set([]) only set permission with user.user_permission.set([list of perm, ...])
If I set permissions in admin work and get_all_permissions() return a list of permissions but if I set permissions with user.user_permission.set([list_of_permissions, ...]) not work and i dont find how to make I am using python 3.5 and django 2.0.2 -
Django autocomplete light Creation of new choices
I installed autocomplete light and add the according to this tutorial : https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html models.py : class Stocks(models.Model): user=models.ForeignKey(User, null=True) name=models.CharField(max_length=128,verbose_name=_('stockname')) number=models.CharField(blank=True,null=True,max_length=64,verbose_name=_('number')) suffix=models.CharField(blank=True,null=True,max_length=12,verbose_name=_('uffix')) comment=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('comment')) def __str__(self): return str(self.name)+ '-' +str(self.number) class Meta: verbose_name=_('Stock') verbose_name_plural=_('Stocks') def get_absolute_url(self): return reverse('BallbearingSite:mystocks' ) forms.py : class StocksForm(forms.ModelForm): name=forms.ModelChoiceField(queryset=Stocks.objects.values_list('name', flat=True).distinct(),label=_('name')) class Meta(): model=Stocks fields=('name','number','suffix','brand','comment','price') widgets = { 'name': autocomplete.ModelSelect2(url='country-autocomplete') } views.py: class StocksAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Stocks.objects.none() qs = Stocks.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs urls.py : url(r'^stock-autocomplete/$',views.StocksAutocomplete.as_view(create_field='name'),name='stock-autocomplete',), template.html : <form enctype="multipart/form-data" method="post" > {% csrf_token %} {{ stocks_form.as_p }} {{form.media }} {% block javascript %} <input id="savestocks" type="submit" name="" value="submit"> </form> <script type="text/javascript" src="{% static 'js/jquery-1.12.4.min.js' %}"> </script> <script type="text/javascript" src="{% static 'js/jquery-ui.min.js' %}"> </script> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery-ui.css' %}"> {% endblock %} it was written in tutorial to add (create_field='name') in url to be able to add new choice to autocomplete list but the autocomplete in my form is like a dropdownlist and i can not write anything in it . it is like this : -
Django Channels Live Chat: AttributeError: 'Message' object has no attribute 'as_dict'
I've been following this tutorial to implement a live chat system into my Django project. so far it has gone well and i've fixed any issues which have come up but this one stumped me. 2018-02-26 19:45:34,241 - ERROR - worker - Error processing message with consumer TestApp.consumers.ws_receive: Traceback (most recent call last): File "/home/.virtualenvs/blog/lib/python3.5/site-packages/channels/worker.py", line 46, in run consumer(message) File "/home/.virtualenvs/blog/lib/python3.5/site-packages/channels/sessions.py", line 57, in inner return func(message, *args, **kwargs) File "/home/blog_dev/TutorsTalk/TestApp/consumers.py", line 23, in ws_receive Group('chat-'+label).send({'text': json.dumps([m.as_dict()])}) AttributeError: 'Message' object has no attribute 'as_dict' This error seems to only come up when websocket data is being received which is why when i'm trying to send data it is saved to the database. This means that I can read the messages if I open it on another browser or refresh the page. I can also tell that my disconnect code works too because in the Django development console it is telling me when IPs are disconnecting from the websocket. As you can probably tell I am quite new to this. This is my code in consumers.py @channel_session def ws_receive(message): label = message.channel_session['room'] room = Room.objects.get(label=label) data = json.loads(message['text']) m = room.messages.create(handle=data['handle'], message=data['message']) Group('chat-'+label).send({'text': json.dumps([m.as_dict()])}) I have tried some things that …