Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Saving data across paginated formset
I'm using modelformsets to edit 100's of items at once and I'm using pagination according to the solution at http://missfilly.github.io/2013/02/17/how-to-paginate-django-formset/ This works in general, however the form data is not held when moving pages, therefore if I fill in 10 pages of forms, only the last one is saved. I thought sessions may be the way to solve this however there is no POST data when the 'next' button is pressed. Has anyone come across a need to solve this problem before or could advise me on how I may solve it? Edit: I guess Ajax may also be an avenue to go down to solve this but I'm not sure where I would start. -
Django Internal Server Error - RecursionError
I've tried a very basic load test on my django app, something among the lines: for _ in {1..50}; do for x in {1..50}; do curl http://example.com &> /dev/null; done & done After a while server started returning http 500, the reason for that was RecursionError: Serving on http://unix:/tmp/waitress/socket WARNING:django.template:Exception raised while rendering {% include %} for template 'django/forms/widgets/email.html'. Empty string rendered instead. Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py", line 216, in render return template.render(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 209, in render return self._render(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/usr/local/lib/python3.6/site-packages/django/template/defaulttags.py", line 166, in render values = self.sequence.resolve(context, True) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 708, in resolve obj = self.var.resolve(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 849, in resolve value = self._resolve_lookup(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 882, in _resolve_lookup current = current[bit] File "/usr/local/lib/python3.6/site-packages/django/template/context.py", line 84, in __getitem__ for d in reversed(self.dicts): RecursionError: maximum recursion depth exceeded while calling a Python object WARNING:django.template:Exception raised while rendering {% include %} for template 'django/forms/widgets/text.html'. Empty string rendered instead. Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/template/loader_tags.py", line 216, in render return template.render(context) File "/usr/local/lib/python3.6/site-packages/django/template/base.py", line 209, in render return … -
How to request get method for loading another HTML page
I want to load the another html page using ajax getmethod . Currently I am loading my HTML page simply like as follow- Views.py def about(request): context = {} template = 'about.html' return render(request,template,context) I want to load the same html page using ajax get method so I tried as- def about(request): if request.GET.get('id'): data = request.GET.get('id', '') template = loader.get_template('about.html') context = { 'data': data, } return HttpResponseRedirect(template.render(context, request)) But I am struggling doing this and about.html page content is not displaying, I am beginner in ajax and django, please help me.. this is my about.html page {% extends 'base.html' %} {% block content %} {{data}} <h1>hello about</h1> {% endblock %} Here is urls.py details- url(r'^data/', profiles_views.about, name='about'), I am getting this error- ValueError at /data/ The view profiles.views.about didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/data/ Django Version: 1.11.5 Exception Type: ValueError Exception Value: The view profiles.views.about didn't return an HttpResponse object. It returned None instead. Exception Location: C:\Users\prash\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py in _get_response, line 198 Python Executable: C:\Users\prash\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.2 Python Path: ['C:\\Users\\prash\\Desktop\\tryTen', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32\\python36.zip', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32\\DLLs', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32\\lib', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32', 'C:\\Users\\prash\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages'] Server time: Mon, 25 Sep 2017 10:39:51 +0000 -
how to use filter() function to fetch data between a range?
I have write down a model like this: from future import unicode_literals from django.db import models Create your models here. class SequenceDetails(models.Model): IDs = models.CharField(max_length=30) country = models.CharField(max_length=30) year = models.IntegerField(max_length=30) def __unicode__(self): return self.IDs To fetch data from the data base i have write down a query like this: SequenceDetails.objects.all().filter(country='india').filter(year='2002') which is returning expected results but further I want to filter out data on the basis of country and year range. I have write down a query set like this. SequenceDetails.objects.all().filter(country='india').filter(year__range =['2002','200']) but its now working and throwing error like given bellow: SyntaxError: invalid syntax How can i achieve this thanks -
Best performance web server to handle AJAX requests
I have a web application that should handle thousands of AJAX requests. I want to know which web server I have to use in order to handle these requests efficiently and with low latency. Back-end logic is written in python. I did try Apache-Mod_WSGI->Django and did not get the required efficiency. I thought of using Python-tornado so any any suggestion on which web server I should use? -
Django Pagination: Loads all Element from first page
I have a page blog.html, and pagination sequence loads just fine, But i query the paginator to show one element in a page to test if pagination works. I have 4 items in DB, the pagination reads 4 elements but shows all elements in all pages . Views.py def blog(request): blog_cat = Blog_Categorie.objects.all() all_blog = Blog.objects.all() page = request.GET.get('page') paginator = Paginator(all_blog, 1) try: blog = paginator.page(page) except PageNotAnInteger: blog = paginator.page(1) except EmptyPage: blog = paginator.page(paginator.num_pages) return render_to_response('blog.html',{'blog':all_blog,'blog_cat':blog_cat,'blog_p':blog}) blog.html <div class="col-lg-12 col-md-12 text-center"> {% if blog_p.has_other_pages %} <ul class="pagination"> {% if blog_p.has_previous %} <li><a href="?page={{ users.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in blog_p.paginator.page_range %} {% if blog_p.number == i %} <li class="active"><span>{{ i }}</span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if blog_p.has_next %} <li><a href="?page={{ users.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} -
Django sending back parameters to the view
I have trouble with one of the page of my project. I have a page, use to look up mouvements history : The Page url contain an ID to search for a specific location for the query Once on the page, the user must choose a begin and end date and then with those informations a sql query get the informations in my view and django fill a datatable with the result. My problem is how do i send back the dates informations to the view once the user picked them on the template ? -
Python: var set in __init__ not available [duplicate]
This question already has an answer here: Python method name with double-underscore is overridden? 2 answers I'm failing to understand the following behaviour inside my debugger: (Pdb++) ll 58 def __init__(self, content=None): 59 import pdb; pdb.set_trace() 60 self.__content = BytesIO() 61 self.__len = 0 62 -> self.read_started = False 63 if content is not None: 64 self.write(content) (Pdb++) !self.__len *** AttributeError: 'FakePayload' object has no attribute '__len' instead I can prove that the object has an attribute like that: (Pdb++) fpl = environ['wsgi.input'] (Pdb++) fpl._ -> <TAB-TAB> _FakePayload__len I have never seen anything like that before and I'd be glad for any hint to make me understand. -
Django mptt DraggableMPTTAdmin and callback on move node
I use DraggableMPTTAdmin in a model of my app. I need to update a field when a node is moved. How can I do it? I can't find a callback or something -
Django foreignkey not set when using an object instance
I bumped into a strange bug this morning and if anyone could explain to me why this fails it would be great. Let say I have two really simple models: class MoMo(models.Model): pass class Objo(models.Model): hef_k = models.ForeignKey(MoMo, null=True, blank=True) When I try to create one of them then adding a foreignkey this way: from foreing_save import models obj = models.Objo() obj.save() obj.hef_k = models.MoMo() obj.hef_k.save() the obj.hef_k seams to exists: obj.hef_k Out[9]: <MoMo: MoMo object> But as soon as I refresh from db or simply get it again it's gone: obj.refresh_from_db() In [12]: obj.hef_k In [13]: obj = Objo.objects.get(pk=obj.pk) obj.hef_k in [14]: Do I miss something ? It seams strange to me and any help on this would be greatly appreciated -
Validate size of list in django drf ListSerializer
How can I validate the (read-only) ListSerializer. In my particular case, I would like to enforce the length of the given iterable. I did the following, it works. However, is it the right place to intercept the data? How can I intercept at the earliest stage? class CustomListSerializer(serializers.ListSerializer): def __init__(self, *args, **kwargs): count = kwargs.pop('count', None) self.count = count super().__init__(*args, **kwargs) def to_representation(self, data): if self.count is not None: if len(data) != self.count: raise serializers.ValidationError("Incorrect list size") -
Django: get model instance from a ModelForm
I have a ModelForm to create/update a particular entity. I need to validate in the form whether an equivalente instance already exists in the database to prevent saving duplicates: class EntityForm(models.ModelForm): def clean(self): if Entity.objects.filter(attr1=self.cleaned_data['attr1'], attr2=self.cleaned_data['attr2']).exists(): raise ValidationError('Entity already exists') But if we are editing an entity, it is obviously going to find itself, therefore throwing a validation error and preventing the form from editing that very instance. I would need to exclude that entry: Entity.objects.filter(...).exclude(id=this_instance.id) How can I get in the ModelForm the instance/id of the model being edited? -
OSError at /app/ Why does such a strange error happen?
I got an error,OSError at /app/ [Errno 63] File name too long: "/Users/xxx/testapp/templates/jinja2/{'items': [{'---': '---', ‘A’: ‘a’, ‘B’: ‘b’, ‘C: ‘c’, ‘D’: ‘d’}]} . I wanna embed json_dict of json_parse method's result in views.py to index.html. I wrote in views.py like from django.shortcuts import render import json def index(request): f = open('./data/data.json', 'r') json_dict = json.load(f) return render('./index.html',json_dict) I wrote in index.html like <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css"> </head> <body> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for k, v in json_dict.items %} <option>{{ v }}</option> {% endfor %} </select> </body> </html> json_dict has dictionary of {'items': [{'---': '---' ~~~ .I really cannot understand why I cannot send json_dict to index.html.Am I wrong to use render method?How can I fix this? -
Everything related to everything
I'm trying to put together a system where certain models are all related to each other, and can be modified in each others change form within the admin. An example would be Person A being related to Event A and Event B, and when editing either Event A or Event B you'd be able to see, modify, and order Person A. Initially I did this with one super relations table which I used as a through table. This table consisted of a foreign key to each model type. I then used django admin inlines using this relations table which gave me a solution to my example. This also allowed me to have separate inlines for each model type so it is easy to manage. The problem I'm having though is I can't have Event A directly related to Event B because I'm missing the two Event foreign keys on my relations table. Is there a way to solve the self relations using the super table, or is there another method I should be using? -
Can I replace Celery with Django Channels for task scheduling?
I used Celery in my past projets, and recently read about Django Channels concepts. And after reading Django Channels concepts, it seems it does support background processing / task scheduling. The question is NOT: is Django Channels better for task scheduling than Celery?" (I'm pretty sure the answer is NO) The question is: If I'm sure I need Django Channels for something in my project, and then I need to add task scheduling to this project, how would you determine if I need to use Celery in addition to Channels? -
how to get form name from post request using django?
How to get form name(attribute) from post request using django? I cant image how to resolve this. Please let me know. -
How can I upload the image file by using formdata
I have a problem on my code. I want to upload the image file by using formdata and ajax to the server side python program. But I got django.utils.datastructures.MultiValueDictKeyError: "'image'" error in my server uwsgi.log. I think it may not upload the image file to the server, but I don't understand what is wrong on my code. My client code is the following. // Test if the image is shown -> success document.getElementById("previewimage").src = image var formData = new FormData(); formData.append('filename', image_file_name); formData.append('image', image); $.ajax({ url: HOST_NAME + "user/api/file_uploader/", type: 'POST', timeout: 10000, data: formData, processData: false, contentType: false, }) .done(function (data) { jsondata = JSON.parse(data); alert("File upload completed..."); }) .fail(function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); }) And my server side code is the following. def post(self, request, format=None): outputLogFile("Upload Function is called...") req_file_name = request.data['filename'] req_image = request.FILES['image'] I can get filename from the client when I comment the code of image. Please give me an advice. -
How to generate slug field in the Wagtail CMS?
I use a Wagtail CMS with the Russian language. When I save page, I get slug on Russain. But I need an English slug. I found unidecode package for transliterate Russian to English (for example unidecode(title)). Then I found a "full_clean" method on the Page class where the title is converted into a slug. class Page(six.with_metaclass(PageBase, AbstractPage, index.Indexed, ClusterableModel)): def full_clean(self, *args, **kwargs): if not self.slug: if DJANGO_VERSION >= (1, 9): base_slug = slugify(self.title, allow_unicode=True) else: base_slug = slugify(self.title) if base_slug: self.slug = self._get_autogenerated_slug(base_slug) if not self.draft_title: self.draft_title = self.title super(Page, self).full_clean(*args, **kwargs) I tried to inherit the Page class and change the full_clean method, but I failed. Then I implemented the save method and change slug there. But with this method slug changed each time I save the page. Please tell me is this correct method or is there another way? -
Django: Filtering the Questions
Here's the model, class Question(models.Model): timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) .... class Answer(models.Model): question = models.ForeignKey(Question) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) How can I filter out those questions which received an answer in last 24 hours. How it can I filter them out? Please help me. Thank You! -
ajax change html tag successfully,but can not be used
I have a html file , purpose is click tag <a class="favorite">,turn to <a ="unfavorite">,then click it again ,it should change back to the original value(<a class="favorite">), part of html code like this: <div class="extra content" extra_id="{{ article.article.id }}"> {% if user.is_authenticated %} {% if collections %} {% if article.article.title in collections %} <a class="unfavorite"> <i class="heart icon"></i> {{article.article.favorite}} </a> {% else %} <a class="favorite"> <i class="empty heart icon"></i> {{article.article.favorite}} </a> {% endif %} {% else %} <a class="favorite"> <i class="empty heart icon"></i> {{article.article.favorite}} </a> {% endif %} {% else %} <a class="favorite"> <i class="empty heart icon"></i> {{article.article.favorite}} </a> {%endif%} <span class="right floated"> <a > <i class="comment icon"></i> {{ article.comments_num }} </a> </span> </div> and part of js code: $(".favorite").bind("click",function(){ var id = $(this).parent('.extra.content').attr('extra_id'); $.ajax({ url:"/api/favorite/", data:{"extra_id":id}, async:false, success:function(result){ if (result.status == 200) { $('[extra_id='+ result.article_id +']').find('a.favorite').attr("class","unfavorite"); $('[extra_id='+ result.article_id +']').find('a.unfavorite').html("<i class='heart icon'></i>"+result.favorite); } if (result.status == 10020){ location.href="accounts/login/"; } }}); }); $(".unfavorite").bind("click",function(){ var id = $(this).parent('.extra.content').attr('extra_id'); $.ajax({ url:"/api/unfavorite/", data:{"extra_id":id}, async:false, success:function(result){ if (result.status == 200) { $('[extra_id='+ result.article_id +']').find('a.unfavorite').attr("class","favorite"); $('[extra_id='+ result.article_id +']').find('a.favorite').html("<i class='empty heart icon'></i>"+result.favorite); // $('[extra_id='+ result.id +']').find('i.up').attr("class","thumbs up icon"); } }} ); }); when click <a class="favorite">, $(".favorite"){} runs success, it turn to <a class="unfavorite">, then click it … -
Could not parse the remainder: '():'
I got an error, TemplateSyntaxError at /app/ Could not parse the remainder: '():' from 'json_dict.items():'. I wanna embed json_parse method's result in views.py to index.html. I wrote in views.py like from django.shortcuts import render import json def index(request): return render(request, './index.html') def json_parse(): f = open('./data/company_demand.json', 'r') json_dict = json.load(f) I wrote in index.html like <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css"> </head> <body> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for k, v in json_dict.items(): %} {% for i in range(len(k)) %} <p>{{ i }}</p> <p>{{ i }}</p> <p>{{ i }}</p> <p>{{ i }}</p> <p>{{ i }}</p> {% endfor %} {% endfor %} </select> </body> </html> json_dict's is {'items': [{'---': '---', ‘A’: ‘a’, ‘B’: ‘b’, ‘C: ‘c’, ‘D’: ‘d’}]}. I wanna embed ---&a&b&c&d in this place of i variable of p tag. I did not think Syntax Error happens in my codes, so I really cannot understand why this error happens.How should I fix this?What can I write it? -
ValueError: Cannot assign "'assignee'": "Task.assignee" must be a "User" instance
I create tests for api and models. The issue is to test if models are created. User model is this one: class User(AbstractUser): CUSTOMER = 1 EXECUTER = 2 USER_TYPES = ( (CUSTOMER, 'Customer'), (EXECUTER, 'Executer'), ) user_type = models.IntegerField(choices=USER_TYPES, default=EXECUTER, verbose_name='Тип пользователя') balance = models.DecimalField(decimal_places=2, max_digits=7, default=0, verbose_name='Баланс') def __str__(self): return self.username Task models look like: class Task(models.Model): title = models.CharField(max_length=255, verbose_name='Заголовок') description = models.CharField(max_length=255, verbose_name='Описание') money = models.DecimalField(max_digits=7, decimal_places=2, default=0, verbose_name='Цена') assignee = models.ForeignKey('users.User', related_name='assignee', null=True, verbose_name='Исполнитель') created_by = models.ForeignKey('users.User', related_name='created_by', verbose_name='Кем был создан') I want to test models creation, but test model doesn't want to be made. Problem is in assignee and created by fields. This is my test: def test_creating_models_instance(self): User.objects.create(username="assignee", first_name="First_name_2", last_name="Surname_2", user_type=2, balance="16155.00") User.objects.create(username="created_by", first_name="First_name_1", last_name="Surname_1", user_type=1, balance="16155.00") Task.objects.create(title="Task_1", description="Description_1", money="155.00", assignee="assignee", created_by="created_by") And I have mistake like: self.field.remote_field.model._meta.object_name, ValueError: Cannot assign "'assignee'": "Task.assignee" must be a "User" instance. -
Subprocess error in wkhtmltopdf in a docker environment
Getting the error below when I try to run wkhtmltopdf in a docker environment. subprocess.CalledProcessError: Command '['wkhtmltopdf', '--encoding', 'utf8', '--margin-top', '10', '--quiet', '/tmp/wkhtmltopdf85qv7fvc.html', '-']' died with <Signals.SIGABRT: 6>. The code is seen below. It is working in an Ubuntu 16.04 vagrant machine. However, when I move it to a docker environment, it fails with the error above. At first I was using a Python3.6 image then changed to an Ubuntu 16.04 image thinking that maybe wkhtmltopdf requires a fuller linux environment. But still no luck. from django.http import HttpRequest from wkhtmltopdf.views import PDFTemplateResponse def generate_invoice_pdf(download_pdf=False, **kwargs): """ Render html to PDF """ file_name = kwargs['file_name'] template = kwargs['template'] context = { "first_Name": "John", "last_name": "Doe" } # Create request object request = HttpRequest() params = { 'request': request, 'template': template, 'filename': os.path.basename(file_name), 'context': context, 'cmd_options': {'margin-top': 10, }, 'show_content_in_browser': True } response = PDFTemplateResponse(**params) # write the rendered content to a file with open(file_name, "wb") as f: f.write(response.rendered_content) # Part throwing the error if download_pdf: return response else: msg = 'PDF Generated: {}'.format(file_name) return msg -
Error with uwsgi
I am trying to load uwsgi configs with: sudo uwsgi --ini /var/www/alpanahub/conf/uwsgi.ini But, I am getting error: open("./python_plugin.so"): No such file or directory [core/utils.c line 3686] !!! UNABLE to load uWSGI plugin: ./python_plugin.so: cannot open shared object file: No such file or directory !!! Can someone help me? Thanks in advance. -
how to use Ajax to get request, Django
Currently I am loading my html page like as follow- def home(request): context = {} template = 'home.html' return render(request,template,context) def about(request): context = {} template = 'about.html' return render(request,template,context) If i want to load using ajax then how i request for get. please help