Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error installing psycopg2==2.6.2
I have problems when I try installing psycopg2==2.6.2 . I have installed postgresql 9.6. and I am using a virtualenv.Any help is welcome. Collecting psycopg2==2.6.2 (from -r requirements.txt (line 21)) Downloading psycopg2-2.6.2.tar.gz (376kB) 100% |████████████████████████████████| 378kB 281kB/s Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/psycopg2.egg-info writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: could not determine PostgreSQL version from '10.0' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-k7nulk7r/psycopg2/ -
DRF: Database not updating
Following are my files. It is simply adding products based on subcategories and categories. Everything is working fine but the data is not being saved in the database. I am not sure where I am going wrong. models.py from django.db import models class Category(models.Model): category = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='children') class Meta: unique_together = ('parent' , 'category') def __str__(self): return self.category class SubCategory(models.Model): subcategory = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren') class Meta: unique_together = ('parent' , 'subcategory') def __str__(self): return self.subcategory class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) subcategory = models.ForeignKey('SubCategory', null=True, blank=True) def __str__(self): return self.name views.py class AddProducts(APIView): serializer_class = AddProductsSerializer def post(self, request, format=None): data = request.data serializer = AddProductsSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) serializers.py class AddProductsSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'category', 'subcategory') def create(self, validated_data): return Product.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.category = validated_data.get('category', instance.category) instance.subcategory = validated_data.get('subcategory', instance.subcategory) instance.save() return instance -
Celery 4 not auto-discovering tasks
I have a Django 1.11 and Celery 4.1 project, and I've configured it according to the setup docs. My celery_init.py looks like from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings.settings' app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') #app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # does nothing app.autodiscover_tasks() # also does nothing print('Registering debug task...') @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) However, when I launch a worker with: .env/bin/celery worker -A myproject -l info it shows no tasks being found except for the sample "debug_task", even though I have several installed apps with Celery tasks, with should have been found via the call to app.autodiscover_task(). This is the initial output my worker generates: -------------- celery@localhost v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Linux-4.13.0-16-generic-x86_64-with-Ubuntu-16.04-xenial 2017-10-31 15:56:42 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: myproject:0x7f952856d650 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: amqp:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . myproject.celery_init.debug_task [2017-10-31 … -
Django Channel Group send then discard
I want to send a message to a Group and immediately afterwards discard one of the reply channels. It doesn't work due to the consumer_finished signal not sending until the incoming message is fully dealt with, I gather from debugging the code and witnessing when the message is sent to the frontend. The result is that my message doesn't get sent on the channel that I delete afterwards. Am I doing anything wrong, or is this a Channel bug/feature? Group(room_id).send({'text': json.dumps({'command': 'leave', 'room': {'id': room_id}, 'user': {'id': str(message.user.id)}})}) Group(room_id).discard(message.reply_channel) -
Django Rest Framework - 'ModelBase' object is not iterable
Struggling to understand this error message. I think it means that somewhere I'm trying to iterate over the Base class, instead of an instance or instances of the class? I also believe I wouldn't be able to iterate over a single instance anyway, but all I want to do is use DRF to show all Actions that FK to the object with the id in the URL. views.py: class ActionDetailListView(core.views.MixedListAPIView): resource_types_list = [ { "model": ActionDetail, "serializer": ActionDetailSerializer, "filter": ActionDetailFilter } ] def get_queryset(self, *args, **kwargs): pk = kwargs.get('pk', None) return ActionDetail.objects.filter(action__parent__grandparent_id=pk) filters.py class ActionDetailFilter(django_filters.FilterSet): pass serializers.py class ActionDetailSerializer(core.serializers.HalModelSerializer): class Meta: model = ActionDetail -
python 3.6 JsonResponse issue
So i recently migrated to Python 3.6 and Django 1.11 and my JsonResponse code looked like this: return JsonResponse({'status': '1'}) it worked fine but after the migration i started getting this error: TypeError: Object of type 'bytes' is not JSON serializable After printing the type of the data passed to JsonResponse i realized python 3.6 changed this from dict to byte. So i changed the code to make sure i was passing a dict. I still get the same error after trying all of this: data = dict([('status', 0)]) print(data) print(type(data)) # print(type(json.dumps(data))) # data = {"status": '0'} # data = json.dumps(data) # json.dumps(data.decode("utf-8")) #response = json.JSONEncoder().encode({"status": 0}) #JsonResponse(data, safe=False) # response = json.dumps(data) print(JsonResponse(data, safe=False)) return JsonResponse(data, safe=False) Prints: {'status': 0} <class 'dict'> <JsonResponse status_code=200, "application/json"> with the json.dumps options y get this error instead AttributeError: 'str' object has no attribute 'get' Any help would be much appreciated -
How to use mezzanine together with allauth?
I commented mezzanine mezzanine.accounts from settings.INSTALLED_APPS and use allauth as AUTHENTICATION_BACKEND settings.py AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend" ) urls.py: urlpatterns += [ url(r"^$", include("movies.urls")), url("^blog2", blog_post_list, name="home"), url(r"^admin/", include(admin.site.urls)), url(r"^movies/", include("movies.urls", namespace="movies")), url(r"^faq/", include("fack.urls")), url(r"^accounts/", include("allauth.urls")), url(r'^captcha/', include('captcha.urls')), url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), url(r'^tz_detect/', include('tz_detect.urls')), url(r"^h/", include("home2.urls", namespace="home2")), url(r"^profile/", include("profile.urls", namespace="profile")), url("^", include("mezzanine.urls")), ] The problem is that when I go to https://localhost/blog2, that I see the base.html of allauth.accounts. Maybe mezzanine confuses allauth accounts/base.html with its own accounts/base.html? Or maybe I'm missing something else. -
ajax function throwing HTTP 200 immediately followed by HTTP 500 error
Why do I get a HTTP 200 followed immediately by a HTTP 500? I have the impression the Ajax function is called twice in a row. The objects that I expect to be created are actually created though... my ajax function is called on a form submit: $(document).on('submit','#like_form_reading_list{{ article.pk }}', function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "userprofile:like" %}', data: { journal: '{{ journal.pk }}', section: '{{ section.pk }}', article: '{{ article.pk }}', csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function showAlertLike() { $("#success_like").show().delay(2000).fadeOut(); }, error: function showAlertPin() { $("#error_like").show().delay(2000).fadeOut(); } }); }); In my view: class LikeView(generic.FormView): """ A view that creates a LikedArticles object when a user clicks on the like badge under each article displayed. """ def post(self, request): if request.method == 'POST': user = request.user journal_pk = request.POST.get('journal') section_pk = request.POST.get('section') article_pk = request.POST.get('article') journal = Journal.objects.get(pk=journal_pk) section = Section.objects.get(pk=section_pk) article = Article.objects.get(pk=article_pk) print('IN LIKE VIEW ', user, journal_pk, section_pk, article_pk) LikedArticles.objects.create( user=user, journal=journal, section=section, article=article ) return HttpResponse('') In my terminal: Internal Server Error: /like/ Traceback (most recent call last): [SOME ERROR MESSAGE] "/Users/benoitkoenig/Desktop/projet_web/harrispierce_django/hpdjango/lib/python2.7/site-packages/django/db/models/fields/init.py", line 966, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' ('IN LIKE VIEW ', at … -
Extending User Model to an Existing DB table?
I'm having issues getting my User model to extend to an existing database table. I have a feeling i'm getting close. I don't receive any errors with my following code, but anytime I login it doesn't pull in the additional information. First of all I'm using LDAP authentication with python 3.6 and Django 1.11, once a user is validated as an AD user the username and password is written to my User table. Second my existing table is not to be changed or modified and its called AllEeActive. I have a primary key that is the username in my user table called employee_ntname. I'm trying to use a signal handler to write to connect the two models. Below is my code... What am I doing incorrectly?: from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from django.db.models.signals import post_save from django.dispatch import receiver import django_filters class AllEeActive(models.Model): employee_ntname = models.OneToOneField(User, db_column='Employee_NTName',max_length=12) # Field name made lowercase. employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, … -
which is the best way to deploy django web app
I have created one dummy test app in django python. So that how am I deploy on any web server in its cost free hosting. -
Cant access server media files in django + angular project
Because I wanted to do my routing in angular side I have added this url in my urls.py: url(r'^.*$', Home.as_view(), name='home'), in which my home view I just specify my base.html: class Home(TemplateView): template_name = "base.html" So that I can specify my <ng-view></ng-view> in base.html Now my issues the requests to get pictures in server side like localhost:8000/media/logo.png are going to the defined url for Home. How can I overcome this issue? Thank you. -
Unable to run local Celery worker, no module named myapp
I have a Django 1.11 project, with Celery 3.1.25, laid out like: env myproject myapp myotherapp settings settings.py __init__.py celery_init.py My __init__.py contains: from .celery_init import app as celery_app and my celery_init.py contains: from __future__ import absolute_import import os import sys import traceback from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.settings') from django.conf import settings app = Celery('myproject') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) When I go to start a local Celery worker for development testing, with: env/bin/celery worker -A myproject -l info -n sr@%h -Q somequeue it fails with the exception: ImportError: No module named myapp What's causing this? I assume it's some path problem and not being able to properly load my project's settings, but I don't see the problem with my configuration. I just upgraded to Django 1.11, and these settings were working fine in the prior version. What am I doing wrong? I tried adding print statements at the end of my celery_init.py, to ensure it's loading everything, and every line completes without error. -
Template Tag values not rendering
I am creating a blog as practice for learning how to use django. I have created the blog list and created links to the blog detail page. On the blog detail, along with the blog_Content, post_date, blog_Title information that should be on the page I am to also attempting to render the comments attached to the specific blog created by the writer/user Issue : The comments attached to the specific writer/user are not being rendered. Here is the repository if you care to take a look Here is all the code : models.py from django.db import models from datetime import date from django.urls import reverse from django.contrib.auth.models import User class Writer(models.Model): user = models.ForeignKey(User, on_delete = models.SET_NULL, null = True) writer_description = models.TextField(max_length = 400, help_text = "Enter your description here.") def get_absolute_url(self): return reverse('blog:writer-detail', args = [str(self.id)]) def __str__(self): return self.user.username class Blog(models.Model): blog_Title = models.CharField(max_length = 200) writer = models.ForeignKey(Writer, on_delete=models.SET_NULL, null=True) blog_Content = models.TextField(max_length = 2000, help_text="Create content here.") post_date = models.DateField(default = date.today) class Meta: ordering = ['-post_date'] def get_absolute_url(self): return reverse('blog:blog-detail', args = [str(self.id)]) def __str__(self): return self.blog_Title class Comment(models.Model): writer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) comment = models.TextField(max_length=1000, help_text="Create comment here.") post_date = models.DateTimeField(auto_now_add=True) class … -
launch sphinx commands "make clean" and "make html" from django.core.management call_command
Is there any way to launch sphinx commands "make clean" and "make html" from from django.core.management call_command? I need to refresh docs generated by sphinx every day, so I was thinking to use django-crontab to set a daily job. This job would call "make clean" and "make html" to automatically generate doc. But, maybe there is a simpler way to refresh docs generated by sphinx every day? Thanks! -
Django, get initials data from field in formset with shell
I'm using formset in Django 1.11, and in template rendering all works done. Now I want test formset in python shell. So I make a simple form and then a formset (2) with initials data: >>> from django import forms >>> class my_formset(forms.Form): ... my_field_1=forms.IntegerField() ... my_field_2=forms.IntegerField() ... >>> values=[{'my_field_1':10,'my_field_2':15}, {'my_field_1':84,'my_field_2':6}] >>> values [{'my_field_2': 15, 'my_field_1': 10}, {'my_field_2': 6, 'my_field_1': 84}] Building formset: >>> from django.forms import formset_factory >>> formset=formset_factory(my_formset,extra=0) >>> my_data_fs=formset(initial=values) Result formset: >>> my_data_fs <django.forms.formsets.my_formsetFormSet object at 0x7fdb688dda90> >>> my_data_fs.forms [<my_formset bound=False, valid=Unknown, fields=(my_field_1;my_field_2)>, <my_formset bound=False, valid=Unknown, fields=(my_field_1;my_field_2)>] Now I want get initials data: >>> my_data_fs.forms[0] <my_formset bound=False, valid=Unknown, fields=(my_field_1;my_field_2)> >>> my_data_fs.forms[0].fields OrderedDict([('my_field_1', <django.forms.fields.IntegerField object at 0x7fdb688dd7b8>), ('my_field_2', <django.forms.fields.IntegerField object at 0x7fdb688dd710>)]) but if I see single field, I get this: >>> my_data_fs.forms[0].fields['my_field_1'] <django.forms.fields.IntegerField object at 0x7fdb688dd7b8> >>> my_data_fs.forms[0].fields['my_field_1'].value Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'IntegerField' object has no attribute 'value' And if I use initials I get empty response >>> my_data_fs.forms[0].fields['my_field_1'].initial >>> What I have to do for get my initials data? -
Displaying ForeignKey attributes in DRF
When I run the api, instead of getting category name and subcategory name, I get their id, [ { "id": 1, "name": "StrawBerry", "category": 1, "subcategory": 1 } ] I actually want something like this: [ { "id": 1, "name": "StrawBerry", "category": "Fruits", "subcategory": "Berries" } ] Note: I already have category and subcategory. I just want to know how to access them. models.py from django.db import models class Category(models.Model): category = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='children') class Meta: unique_together = ('parent' , 'category') def __str__(self): return self.category class SubCategory(models.Model): subcategory = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren') class Meta: unique_together = ('parent' , 'subcategory') def __str__(self): return self.subcategory class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) subcategory = models.ForeignKey('SubCategory', null=True, blank=True) def __str__(self): return self.name serializers.py class GetProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'category', 'subcategory') views.py class GetProductViewSet(viewsets.ModelViewSet): serializer_class = GetProductSerializer queryset = Product.objects.all() -
Django formset: Unable to to submit formset due to errors
Following is my model: class ContentLineConfig(models.Model): content_template = models.ForeignKey(ContentTemplate, null=False, verbose_name="Content template") line_x_start_cord = models.IntegerField(null=False, verbose_name="Line start X cordinate") line_y_start_cord = models.IntegerField(null=False, verbose_name="Line start Y cordinate") line_x_end_cord = models.IntegerField(null=False, verbose_name="Line end X cordinate") line_y_end_cord = models.IntegerField(null=False, verbose_name="Line end Y cordinate") line_fill_color = models.CharField(max_length=10, default="WHITE", choices=COLOR_CHOICE, verbose_name="Line fill color") line_width = models.IntegerField(null=False, verbose_name="Line width") archive = models.BooleanField(default=False) Form: class ContentLineConfigForm(ModelForm): class Meta: model = ContentLineConfig fields = '__all__' exclude = ['id','archive','content_template',] View: class ContentLineConfigView(ModelFormSetView): model = ContentLineConfig form_class = ContentLineConfigForm success_url = reverse_lazy('content_templates_list') template_name = 'formtemplates/test_formset.html' def form_valid(self,form): instance = form.save(commit=False) instance.content_template_id = self.kwargs.get('pk') return super(ContentLineConfigView, self).form_valid(form) def form_invalid(self,form): return super(ContentLineConfigView, self).form_invalid(form) Template: <div class="container"> <form action="." method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.as_p }} {% endfor %} <input type="submit" value="Submit" /> </form> </div> URL: url(r'^ct/(?P<pk>[\w-]+)/lines/create/$', ContentLineConfigView.as_view(), name='content_line_create') When I am submitting the formset I get the following error: NOT NULL constraint failed: contenttemplates_contentlineconfig.content_template_id But when I see the error page in detail, I see the following: formset <django.forms.formsets.ContentLineConfigFormFormSet object at 0x10821e3d0> kwargs {'pk': u'1'} Why this error? Also, If I submit empty formset, I get redirected to success_url, there is not validation happening at all, why are the validations being skipped? -
So how can I do when user clicked like button to return only value of the post
11** and python3 I was trying to add my web site like button when I add like button I worked but when someone click like button It returns same value for every post. So how can I do when user clicked like button to return only value of the post. MY HTML CODE: <button id="" data-catid="{{ post.id }}" class="btn btn-primary likes" type="button"> <span class="glyphicon glyphicon-thumbs-up"></span> Like </button> <strong class="" id="like_count">{{ post.votes }}</strong> people like this category MY JS CODE: $(document).ready(function() { $('.likes').click(function(){ var catid; catid = $(this).attr("data-catid"); $.get('/home/like_post/', {post_id: catid}, function(data){ $('#like_count').html(data); }); return false; }); }); I use this URL.PY url(r'^like_post/$', views.like_post, name='like_post'), And this VIEWS.PY: def like_post(request): cat_id = None if request.method == 'GET': cat_id = request.GET['post_id'] likes = Post.votes if cat_id: cat = Post.objects.get(pk=cat_id) if cat: likes = cat.votes + 1 cat.votes = likes cat.save() return HttpResponse(likes) ANY IDEA? -
How to use django-registration with hashed email addresses?
I am developing a website that requires users are anonymous. I want users to log in with email address and password but I want to store them both as hashes to achieve anonymity. Is this straightforward to achieve using django-registration? I understand how to set django-registration up to use email address and password for log in and I know the password is hashed by default but I do not know if I will run into lots of problems if I want to store the email address as a hash too. I don't particularly care what hashing algorithm is used at this stage; I just need a simple example for now. At the very least I know I will need to set up a custom user class, a custom user form, and a custom authentication backend. I am unsure whether I will encounter big problems with getting django-registration to verify email addresses with its hmac workflow. Can anyone give me a simple example of how to do this or tell me the steps I need to take to get hashed email addresses working? Alternatively, I am not wedded to django-registration so please feel free to recommend a different approach if there … -
How to pass a custom schema to a drf detail_route?
I have the following route: @detail_route(methods=['post'], permission_classes=[IsOperator], schema=AutoSchema(manual_fields=[ coreapi.Field('size', location='query', schema={'type': 'number', 'example': 1024}), coreapi.Field('filename', location='query', schema={'type': 'string', 'example': 'telemetry.tlog'}) ])) def get_upload_url(self): # ... When I go to a view that shows my schema, I get: I get the following error: AttributeError: 'AutoSchema' object has no attribute '_view' Stack trace: File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 489. response = self.handle_exception(exc) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework_swagger/views.py" in get 32. schema = generator.get_schema(request=request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/generators.py" in get_schema 279. links = self.get_links(None if public else request) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/generators.py" in get_links 317. link = view.schema.get_link(path, method, base_url=self.url) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/inspectors.py" in get_link 166. fields = self.get_path_fields(path, method) File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/inspectors.py" in get_path_fields 237. view = self.view File "/Users/frederikcreemers/.virtualenvs/theproject/lib/python2.7/site-packages/rest_framework/schemas/inspectors.py" in view 123. assert self._view is not None, "Schema generation REQUIRES a view instance. (Hint: you accessed `schema` from the view class rather than an instance.)" -
Unable to filter Haystack SearchQuerySet by boolean field
I've got a view which renders objects to a table via Knockout, powered by a haystack search index which looks like this; class ResultsIndex(indexes.SearchIndex, indexes.Indexable): """ Results indexes for elasticsearch engine """ text = indexes.CharField( document=True, use_template=True ) owner = indexes.IntegerField( model_attr='owner_id', null=True ) category_year = indexes.IntegerField( model_attr='category_year_id', null=True ) event = indexes.CharField( model_attr='category_year__category__event__title' ) category = indexes.CharField( model_attr='category_year__category__name', null=True ) year = indexes.CharField( model_attr='category_year__year__year' ) cannot_claim = indexes.BooleanField( model_attr='category_year__category__cannot_claim', null=True ) def get_model(self): """ Model for the index """ return Results The SearchView attempts to filter this index so that the Result objects where cannot_claim is True aren't shown; class ClaimableResultsListView(SearchView): """ Results list view. """ form_class = ResultsSearchForm template_name = 'results/list.html' http_method_names = ['get'] ordering = ('event', 'category', '-year', 'place') def get_queryset(self): """ Get results """ queryset = super(ClaimableResultsListView, self).get_queryset() queryset.models(Results).exclude(cannot_claim=True) return queryset However the above queryset still contains all objects regardless of the cannot_claim value. I've also tried to do queryset.models(Results).filter(cannot_claim=False) but neither filter the paginated objects. In the javascript before the objects are passed to KO I do a final check to ensure that cannot_claim is False, which at the moment means whole pages of the list may not render because it's not being filtered on. -
How to write backends authentication for product table in django
As i am trying to add backend authentication for this model. can someone suggest how to add to this. models.py class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) type = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2, default="") image = models.ImageField(upload_to='image/product/', blank="True") -
order_create() takes exactly 2 arguments (1 given)
I was trying to do a celery task, the code as follows. task.py from .models import OrderItem from cart.cart import Cart from .forms import OrderCreateForm @task(name="create_order") def create_order(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: try: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) except: pass cart.clear() return None else: form = OrderCreateForm() return None views.py from .models import OrderItem, Order from cart.cart import Cart from .tasks import create_order def order_create(request, order_id): order = Order.objects.get(id=order_id) cart = Cart(request) create_order.delay(order.id) return render(request,'orders/order_created.html', {'cart': cart, 'order': order}) urls.py from .views import order_create urlpatterns = [ url(r'^create/$',order_create, name='order_create'), ] When executing the code I am getting the error 'order_create() takes exactly 2 arguments (1 given)'. Hope somebody can help me to solve it. Thank you. -
Template Block Django run after pageload
I want to include/load/run some html on template only when the page is already loaded, without use another request using Ajax. Exemple: {% block_postpone %} load everything that is inside of this block after the page loaded, and everything that is outside load immediately{% endblock_postpone %} I thinking that I need to change the process code of the template. -
Poor performance using Django Q queries.
I'm seeing quite unexpected performance when using the Q object for queries in Django. Here's an example of the issue. I have a piece of code, which uses union and distinct. import time from webapp.models import MessageRecipient from django.db.models import Q id = ... time.time() MessageRecipient.objects.filter( recipient__pk=id ).union( MessageRecipient.objects.filter( content__sender__pk=id ) ).distinct() time.time() The two times printed are: 1509466150.170969 1509466150.43806 Aka. The query returns within 300 milliseconds. Now if I rewrite the query to use Q, I get the following: time.time() MessageRecipient.objects.filter( Q(recipient__pk=id) | Q(content__sender__pk=id) ) time.time() The two times printed are: 1509466165.580193 1509466187.030747 Aka. The query now takes almost 20 seconds. The database is a postgresql, and there's about one million entries in each table. The question isn't with regards to the specific code, but rather why the Q object has so poor performance?