Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: __init__() got an unexpected keyword argument 'widget'
I am getting runtime sever error while writing command python manage.py runserver. The Terminal is showing errors "C:\Users\aw\Desktop\firstphase\customer\forms.py", line 35, in CustomertaskForm startdate=forms.DateInput(widget=forms.DateField()) TypeError: init() got an unexpected keyword argument 'widget' forms.py class CustomertaskForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CustomertaskForm, self).__init__(*args, **kwargs) title=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'required': 'required'})) discription=forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'required': 'required'})) startdate=forms.DateInput(widget=forms.DateField()) enddate=forms.DateInput(widget=forms.DateField()) class Meta: model=Customertask fields=['title','discription','startdate','enddate'] models.py class Customertask(models.Model): title=models.CharField(max_length=200) discription=models.CharField(max_length=500) startdate=models.DateTimeField() enddate=models.DateTimeField() view.py def createtasks(request): if request.method == 'POST': form=CustomertaskForm(request.POST) if form.is_valid(): tasksave=Customertask.objects.create( title=form.cleaned_data['title'], discription = form.cleaned_data['discription'], startdate=form.cleaned_data['startdate'], enddate=form.cleaned_data['enddate'] ) tasksave.save() return HttpResponseRedirect('/customer/tasktable') else: form=CustomertaskForm() return render(request, 'customer/createtasks.html', {'form': form}) -
pytest & django, database remains empty while testing
I'm running some unittests that need manual debugging. Now I run in to the problem that somehow nothing is written to the database during those tests. Is there any way to force Django (or pytest?) to commit changes directly when executed so I can actually see what is in the database when I hit a breakpoint? my_object = SomeDefaultDjangoModel() my_object.some_random_text = 'Just adding some data' my_object.save() foo = 'bar' <= Hitting breakpoint here. Doing a manual SQL query against my database return 0 rows. How can I make this work? -
How to save all items to memcached without losing them?
In [11]: from django.core.cache import cache In [12]: keys = [] In [13]: for i in range(1, 10000): ...: key = "Key%s" % i ...: value = ("Value%s" % i)*5000 ...: cache.set(key, value, None) ...: keys.append(key) ...: # check lost keys ...: lost = 0 ...: for k in keys: ...: if not cache.get(k): ...: lost += 1 ...: if lost: ...: print "Lost %s in %s" % (lost, i) I am using Django, memcached with python-memcached with below cache settings: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } For the above program, I started losing caches from i=1437. Can you please tell me what to do so I can save all items to cache ? -
Handling celery task dependency
I'm developing using Python and Django and using celery for async tasks. I have two celery tasks c_task1 and c_task2 being called at completely different instances. Multiple other code execution happens between the two calls. c_task2 should start only after c_task1 ends. I don't want to block the celery worker by the putting the "wait for c_task1 to finish using loop or so" logic inside c_task2. What would be a decent way to do this ? -
Issues with using swagger using Django Rest Framework
I just started using swagger go my API documentation. I followed your docs , but more then half of the urls were excluded by swagger. As you can see in image below, it is showing some urls but few urls are excluded and the urls displayed by swagger do not include full functionality like there is no body part to test the end points. If you click Try it out! it will send the request with blank params (no body to edit request params). Below is my urls file. I have used include() to includes my app urls may be that is the reason but then how it is showing some urls and excluding some. urlpatterns = [ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/v3/', include('identify.routers_v3', namespace='v3')), # swagger schema url url(r'^docs/', schema_view), ] I have also checked the console and there are no errors in console. Also I am using djnago rest APIView -
Django internationalisation: POST is redirected as GET
I have an Android native app that uses Django as its backend. The sign up page is a native Android Activity, with all information packaged into JSON and sent as POST to the server. Everything worked fine till I enabled internationalisation (i18n). Now when I send POST I see the following messages on the server: [12/Oct/2016 07:27:06] "POST /student/activation HTTP/1.1" 302 0 [2016-10-12 07:27:06] DEBUG <WSGIRequest: GET '/he/student/activation'> [12/Oct/2016 07:27:06] "GET /he/student/activation HTTP/1.1" 500 51426 The 2nd line comes from my view that simply logs the incoming request. Now the view expects POST and can't handle GET, thus the 500 error in the 3rd line. So my conclusion is that the POST comes in and django appends language specific prefix and issues redirect to the new URL, but instead of POST redirect goes out as GET. How can I ensure redirect is POST with all its JSON data intact? Thanks. -
django test error: django.db.utils.InternalError: (7, "Error on rename of
I am running a django 1.9.6 app with MYSQL5.7 on IIS 8.5 When i run the python manage.py test command I get the following error message: django.db.utils.InternalError: (7, "Error on rename of '.\test_\#sql-95c_9a.frm' to '.\test_\home_mytable.frm' (Errcode: 13 - Permission denied)") did test with -v 3 and it throws this error when running the migration files (not always on the same one). I have granted necessary permissions on this folder C:\ProgramData\MySQL\MySQL Server 5.7\Data any pointers on how to solve this error? thanks! -
Two Celery Processes Running
I am debugging an issue where every scheduled task is run twice. I saw two processes named celery. Is it normal for two celery tasks to be running? $ ps -ef | grep celery hgarg 303 32764 0 17:24 ? 00:00:00 /home/hgarg/.pythonbrew/venvs/Python-2.7.3/hgarg_env/bin/python /data/hgarg/current/manage.py celeryd -B -s celery -E --scheduler=djcelery.schedulers.DatabaseScheduler -P eventlet -c 1000 -f /var/log/celery/celeryd.log -l INFO --pidfile=/var/run/celery/celeryd.pid --verbosity=1 --settings=settings hgarg 307 21179 0 17:24 pts/1 00:00:00 grep celery hgarg 32764 1 4 17:24 ? 00:00:00 /home/hgarg/.pythonbrew/venvs/Python-2.7.3/hgarg_env/bin/python /data/hgarg/current/manage.py celeryd -B -s celery -E --scheduler=djcelery.schedulers.DatabaseScheduler -P eventlet -c 1000 -f /var/log/celery/celeryd.log -l INFO --pidfile=/var/run/celery/celeryd.pid --verbosity=1 --settings=settings -
Can not set django-ckeditor on my app
I hate to ask those kind of question which has already been solved in similar cases but I am getting mad on it since 3 days. I use django 1.10 & Jquery 3.1.1 (already loaded in my page for another tool). And try to make django-ckeditor 5.1.1 work on my project. I alread run the ckeditor_demo and it worked so the package is properly installed. I have follow the git doc. And spent several hours on Stack. The settings concerned by ckeditor in my settings.py: from __future__ import absolute_import import tempfile import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'blog', 'CreateYourLaws', 'captcha', 'registration', 'ckeditor', 'ckeditor_uploader', ] # Plenty of others Settings for other tools... # Settings for ckeditors STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(tempfile.gettempdir(), 'ck_static') MEDIA_ROOT = os.path.join(tempfile.gettempdir(), 'ck_media') CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Basic', }, } CKEDITOR_UPLOAD_PATH = "uploads/" CKEDITOR_IMAGE_BACKEND = "pillow" I also already tried with the setting: CKEDITOR_JQUERY_URL = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js' It does not work either. I prefered to remove it because I have already load jquery 3.1.1 in my template. I have also … -
How to split template for the given link for pagination :
https://django-endless-pagination.readthedocs.io/en/latest/twitter_pagination.html Given above is a link for twitter-style pagination in django. I'm trying to implement the same in my app but can't understand the splitting of template. I'm giving here the code of my html page for which I want to apply the pagination . Can anyone please help me by answering to what should I write in the two templates one is entry_index.html and other is entry_index_page.html(as mentioned in the link) according to my html code? Below is my code to html page for which I'm applying pagination : {% extends 'talks/base.html' %} {% block content %} <!-- .header-bottom-wrapper --> <div class="header-bottom-wrapper"> <div class="container"> <div class="row"> <!-- Page Head --> <div class="page-head col-lg-12"> <h2 class="page-title">Gallery</h2> </div> <!-- End Page Head --> </div> </div> </div><!-- End of .header-bottom-wrapper --> <!-- page-container --> <div class="page-container container"> <!-- Gallery Filter --> <div id="gallery-container"> <div class="row gallery-4-columns isotope clearfix"> {% for photo in pics %} <div class="gallery-item isotope-item issues col-lg-3 col-md-3 col-sm-3 col-xs-6"> <figure> <a class="zoom swipebox" href="{{photo.image.url}}" title="{{photo.title}}"></a> <div class="media_container"></div> <img src="{{photo.image.url}}" alt="{{photo.title}}" width="346px" height="200px"> </figure> </div> {% endfor %} </div> </div> </div><!-- End of .page-container --> {% endblock %} -
Celery (Django) + RabbitMQ + nodejs server exchange data
I have an Django project using Celery with RabbitMQ broker. And now I want to call django (celery) task from NodeJS server. In my NodeJS I'm using amqplib. Which is allow me to send tasks to RabbitMQ: amqp.connect('amqp://localhost', function(err, conn) { conn.createChannel(function(err, ch) { var q = 'celery'; ch.assertQueue(q, {durable: true}); ch.sendToQueue(q, new Buffer('What should I write here?')); }); }); My question is what format celery use? What should I write to Buffer to call celery worker? For example, in my CELERY_ROUTES (django settings) I have blabla.tasks.add: CELERY_ROUTES = { ... 'blabla.tasks.add': 'high-priority', } how to call this blabla.tasks.add function? I've tried many ways but celery worker giving me error: Received and deleted unknown message. Wrong destination?!? -
In django Form set choices for ChoiceFiled in MultiValueField
TestField is Multivaluefield with three choice filed. class TestField(forms.MultiValueField): def __init__(self,*args, **kwargs): error_messages = { 'incomplete': 'incomplete', } a = forms.ChoiceField(choices=((1,'a'),),required=True) b =forms.ChoiceField(choices=((2,'b'),),required=True) c = forms.ChoiceField(choices=((3,'c'),),required=True ) fields = (a,b,c ) widget = TestWidget(mywidgets=[fields[0].widget, fields[1].widget, fields[2].widget]) super(TestField, self).__init__( error_messages=error_messages, fields=fields,widget=widget, require_all_fields=True, *args, **kwargs ) def compress(self, data_list): if data_list: return {'academic':data_list[0],'ugs':data_list[1],'stu_sec':data_list[2]} class TestWidget(widgets.MultiWidget): def __init__(self, mywidgets,attrs=None): _widgets = ( widgets.Select(attrs=attrs, choices=mywidgets[0].choices), widgets.Select(attrs=attrs,choices=mywidgets[1].choices), widgets.Select(attrs=attrs,choices=mywidgets[2].choices), ) super(TestWidget, self).__init__(_widgets, attrs) def decompress(self, value): if value: return [value['academic'], value['ugs'], value['stu_sec']] return [None, None, None] When I override choices of ChoiceField in Forms init , it is not getting updated class TestForm(forms.Form): t=TestField() def __init__(self, *args, **kwargs): super(TestForm, self).__init__(*args, **kwargs) self.fields['t'].fields[1].choices = ((1,1),) please give me a solution for this.... -
How do I keep an initial field value in a Django form
In my django form I have an object_id that is a hidden UUIDField: class MyForm(forms.Form): object_id = forms.UUIDField(widget=forms.HiddenInput) In my view, I populate this id field with an initial value. form = MyForm(initial={'object_id': pk,}) The idea is that I pass a primary key to the form and then get it back again when the for is submitted. That works. But what if the user tampers with the hidden field? To prevent this I set disabled=True on my object_id, which according to the documentation means that the initial value should be respected (although perhaps this only means an initial value defined on the field, rather than one defined on the form, through the view?). Unfortunately the result is that now my object_id returns a None object. So the question is, should disabling a field mean that it doesn't return a value. If it does, is there any way to ensure that a hidden value does a safe round trip through a submitted form? -
howto create fronted add/list/delete/update/ in django
I am new to Django and would like to create a sortable ListView (just like the Lists in Django Admin) for an array of object-instances. The objects themself are non Django-Models and are pre-populated in an array before showing the view. I've got a basic ListView working (https://docs.djangoproject.com/en/1.7/topics/class-based-views/), but the important question remains: *How do I make it sortable? * Can you give me to some examples to check out how to implement a sortable ListView? -
How to provide current time to DateTimeFields in Django fixtures?
I am trying to create a JSON fixture for one of my Django models. The model is quite simple: class Tag(models.Model): tag = models.CharField(max_length=50, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) My fixture is also simple: [ { "model": "myapp.tag", "pk": 1, "fields": { "tag": "Test 1" } }, { "model": "myapp.tag", "pk": 2, "fields": { "tag": "Test 2" } } ] Unfortunately I get the following error when trying to run the fixture: IntegrityError: NOT NULL constraint failed: myapp_tag.created_at So it looks like auto_now_add=True doesn't get called when a fixture is run. I don't want to hardcode some date as that seems weird. (I also think hardcoding the PK is weird.) Is there any way to get the created_at date to automatically use today? And as a bonus, can the PK automatically auto-increment? Thanks for your help. -
Switching DEBUG and ALLOWED_HOSTS in settings.py automatically with Django
I think I applied DEBUG and ALLOWED_HOSTS to settings.py as the situation demands with if statements before. But I forgot how. Now, I chenge DEBUG and ALLOWED_HOSTS everytime I upload my project to heroku. For instance, under the local environment, DEBUG = True ALLOWED_HOSTS = ['*'] when I upload, DEBUG = False ALLOWED_HOSTS = ['something.herokuapp.com'] But, I feel tiresome about changing these. Would you please teach me how to change these settings automatically, I mean, the way to make the server apply or interpret these settings automatically? Django-1.9.2 -
Perform actions on server after CircleCI deployment
I have a Django project that I deploy on a server using CircleCI. The server is a basic cloud server, and I can SSH into it. I set up the deployment section of my circle.yml file, and everything is working fine. I would like to automatically perform some actions on the server after the deployment (such as migrating the database or reloading gunicorn). I there a way to do that with CircleCI? I looked in the docs but couldn't find anything related to this particular problem. I also tried to put ssh user@my_server_ip after my deployment step, but obviously it doesn't work. Here is what my ideal circle.yml file would look like: deployment: staging: branch: develop commands: - rsync --update ./requirements.txt user@server:/home/user/requirements.txt - rsync -r --update ./myapp/ user@server:/home/user/myapp/ - ssh user@server - workon myapp_venv - cd /home/user/ - pip install -r requirements.txt -
VariableDoesNotExist at /list/ Failed lookup for key [nodes] in u"[
I'm having problem with Django MPTT my models is class Catalog(MPTTModel): name = models.CharField(verbose_name='name',max_length=256,blank=True ) name_slug = models.CharField(verbose_name='Name_slug',max_length=250,blank=True) parent = TreeForeignKey('self',null=True,blank=True,related_name='children') class MPTTMeta: order_insertion_by = ['name'] def __unicode__(self): return u"%s %s %s " %(self.name,self.name_slug,self.parent) def __str__(self): return u"%s %s %s " %(self.name,self.name_slug,self.parent def get_absolute_url(self): return reverse("catalog",kwargs={"slug":self.name_slug}) Now, I use MPTT in base.html, like this: <ul class="root"> {% recursetree nodes %} <li> <a href="{{ node.get_absolute_url }}">{{ node.name }}</a> {% if not node.is_leaf_node %} <ul class="children"> <a href="{{ children.get_absolute_url }}">{{ children }}</a> </ul> {% endif %} </li> {% endrecursetree %} However when I go to my page with mptt tree I can see: VariableDoesNotExist at /list/ Failed lookup for key [nodes] in u"[{'False': False, 'None': None, 'True': True}, {}, {}, {'places': <QuerySet [<Place: \u041b\u044c\u0432\u0456\u0432 lvv \u0441\u0456\u0456\u0441\u0441\u0456\u0441\u0456\u0456\u0441 list.Catalog.None >, <Place: \u0421\u043a\u0430\u043b\u0430\u0442 skalat \u0421\u043a\u0430\u043b\u0430\u0442 list.Catalog.None >]>}]" Can you tell me where is my problem? -
Why does django insert padding and characters into my html file?
Over the last few days I've been experimenting with Django. I've had some issues with random characters (notably '<') and what I would describe as padding appearing in my html files. I decided to ignore using Django and rewrote a test template with just html/css. It worked perfectly, and I thought that perhaps it had been an error in my HTML/CSS, until I put the Django template code back in. Now, even though I've removed the Django code and moved the files outside of the root directory for the project, the problem persists. I can't see why this has happened, and the error appears in Firefox, Chrome and even IE. The source looks right in these browsers, but right click -> inspect in Google Chrome shows there's something not right. Here's the HTML: <!DOCTYPE html> <link rel="stylesheet" type="text/css" href="main.css" /> <html> <head> <title></title> <meta charset="utf-8" /> </head> <body> <div id="container"> <div id="header"> <div class="nav"> <ul> <li><a href="#">Link 1</a></li> <li><a href="#">Link 2</a></li> <li><a href="#">Link 3</a></li> <li><a href="#">Link 4</a></li> <li><a href="#">Link 5</a></li> </ul> </div> </div> <<div id="content"></div> <div id="footer"></div> </div> </body> </html> And the CSS: body { margin:0; padding:0; height:100%; } #container { min-height:100%; position:relative; width:50%; margin:0% 25% 0% 25%; } #header … -
Resize django-dashing widget and add responsive slider
Ive create a custom widget for my dashboard using the django-dashing framework. And i want to resize each widget so it can fill my whole page. Besides that i want to add slider to make my widget as slide show. I search for the example and can't find any of them. This is my widget example:- dashboard.addWidget('upload_in_widget', 'Countdown', { getData: function () { $.get('http://localhost:8000/api/v1/file/?folder_id=1', function(data) { total_s1 = data.meta.total_count; }); $.get('http://localhost:8000/api/v1/file/?folder_id=2', function(data) { total_s2 = data.meta.total_count; }); $.get('http://localhost:8000/api/v1/file/?folder_id=3', function(data) { total_s3 = data.meta.total_count; }); $.get('http://localhost:8000/api/v1/file/?folder_id=4', function(data) { total_s4 = data.meta.total_count; }); total_in = total_s1+total_s2+total_s3+total_s4; $.extend(this.scope, { title: 'TOTAL SCANNED', value: total_in, }); }, }); -
what is the purpose of solid_i18n_patterns?
i am new to python/django and i just want to know the purpose of below function/code (solid_i18n_patterns). I have tried to search but found none that is explained in an easy way so i resorted to go in this site hoping someone can provide a brief but precise explanation. thanks. from django.conf.urls import url from solid_i18n.urls import solid_i18n_patterns urlpatterns = solid_i18n_patterns(<appname.views>,<urlpattern>,<anotherurlpattern>.....) + solid_i18n_patterns(<anotherappname.views>,<urlpattern>,<anotherurlpattern>.....) what is the purpose of solid_i18n_patterns and its arguments? -
Python import error: No module named 'echipe_fotbal.teams'
i'm a beginner in django and i have a problem with importing a module. I'm trying to do a login page, but when i'm trying to import forms from teams into echipe_fotbal/urls it says. I have tryed even from teams.forms import LoginForm, unsuccesfully. (venv) alex@alex-X750JB:~/Documents/Proiecte/Django/Fotbal/echipe_fotbal$ python manage.py runserver 8080 Performing system checks... Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f1d709340d0> Traceback (most recent call last): File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "/home/alex/Documents/Proiecte/Django/Fotbal/venv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
including/passing slug and pk(or any other variable) in url conf
Currently my config looks something like this: urls.py: url(r'^(?P<slug>[-_~\w]+)/$', SomeDetailView.as_view(), name='detail'), views.py is plain vanilla like so: class GetDetailView(SomeDetailViewMixin, DetailView): model = Dummy template_name = "detail.html" and html is like so: <h2><a href="{% url 'detail' i.slug %}" rel="nofollow"></a>Text</h2> .. and everything works perfectly fine. However, what I am now looking for is to pass another variable (such as pk - say var2) via the html to the url conf. So, something like: html (which is a ListView): <h2><a href="{% url 'detail' i.slug i.var2 %}" rel="nofollow"></a></h2> and urls.py something like: url(r'^(?P<slug>[-_~\w]+)/$', SomeDetailView.as_view(), kwargs={'var2': var2}, name='detail'), is something along these lines possible? What I do not want is to include the var2 in the url itself (because var2 is ugly)... I remember doing something along these lines a year ago, but my memory has let me down again... Would appreciate any help on this... -
Improving table rendering speed in Django templates (using endless pagination)
I am facing a terrible issue of VERY SLOW rendering of my table. It contains only 3000 records (yes, three thousand !!!), and it takes me 19 seconds (!!!) to render the table. Here's my code JS DATA_LIST_REQUEST = $.ajax( { type:'GET', url:"/my_view/", beforeSend : function() { if(DATA_LIST_REQUEST != null) DATA_LIST_REQUEST.abort(); }, data:data, success: function(response) { $('my_table').find('tbody').html(response); } }); View (purposely provide the genuine code so that I do not smth important): def ajax_refresh_order_suggestions(request): legal_entity_own_queryset = get_sale_points(request.user.id) legal_entity_own_id = request.GET.get('legal_entity_own_id') legal_entity_own_instance = LegalEntityOwn.objects.get(legal_entity_id = legal_entity_own_id) order_suggestions_qs = Order.objects.suggestions(legal_entity_own_instance).\ filter_legal_entity_own(legal_entity_own_instance).\ full_info() selected_vendors = json.loads(isnull(request.GET.get('vendors'), '[]')) selected_merchandise = json.loads(isnull(request.GET.get('merchandise'), '[]')) if selected_vendors: order_suggestions_qs = order_suggestions_qs.filter_vendors(selected_vendors) if selected_merchandise: order_suggestions_qs = order_suggestions_qs.filter_merchandise(selected_merchandise) return render_to_response('order_scheduler/order_suggestions_paginator.html', {'order_suggestions_qs':order_suggestions_qs}, context_instance=RequestContext(request)) class OrderQuerySet(models.query.QuerySet): def suggestions(self, legal_entity_own): result = self.filter(status_id = 1, is_active_flg = 1) pending_orders = Order.objects.filter_legal_entity_own(legal_entity_own).\ with_pending_status() vendor_id_list = pending_orders.values('agreement_vendors_merchandise_list__agreement_vendors__vendor').distinct() vendors = Vendors.objects.exclude(id__in = vendor_id_list) result = result.filter_vendors(vendors) return result This topic seems to one of those which should have clear guidelines as to how thinks should be organized, but the only think I found relevant is this (with quite sketchy info for beginners). They say that endless pagination dramatically slows down template rendering, but I would expect this to happen on millions of records, not 3000 ! … -
Django, post method not allowed (405) Detail View
iam new to django, and trying to build a BLOG app. The last step is to be able to create a comment in detail blog post, I tried to put the form for creating a comment in the same Detail View as the blog_post and the comments, when I try to create a comment with the form error shows up in console: method post is not allowed, I tried everything but still doesnt work please help , I highly appreciate yourhelp MY CODE VIEWS from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import HttpResponse from django.views.generic import View from django.views.generic.base import TemplateView, TemplateResponseMixin, ContextMixin from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.shortcuts import render from django.utils.decorators import method_decorator from django.contrib.contenttypes.models import ContentType from .models import blog_post, Category from .forms import blog_postForm from comments.models import Comment from comments.forms import CommentForm class CategoryListView(ListView): model = Category queryset = Category.objects.all() template_name = "blog/category_list.html" class CategoryDetailView(DetailView): model = Category def get_context_data(self, *args, **kwargs): context = super(CategoryDetailView, self).get_context_data(*args, **kwargs) obj = self.get_object() blogpost_set = obj.blog_post_set.all() default_blogpost = obj.default_category.all() blogposts = ( blogpost_set | default_blogpost ).distinct() context["blogposts"] = blogposts return context class LoginRequiredMixin(object): @classmethod def as_view(cls, …