Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
troubles at rendering the form field label in Django
When I tried to render field label, that contains HTML tags, in the template, it was rendered to the simple text. erotrotsity = forms.DecimalField(max_digits=7, decimal_places=3, label='Erot<sup>12</sup>', required=False, validators = [MinValueValidator(0)]) filter |safe and autoescape don't work -
How to switch from ascii postgresql database to utf8 on docker?
I'm having an issue in my docker bash, i'm trying to create a super user on django using docker-compose exec web python manage.py createsuperuser but I have this error below. Traceback (most recent call last): File "docker-compose", line 3, in <module> File "compose\cli\main.py", line 68, in main File "compose\cli\main.py", line 118, in perform_command File "compose\cli\main.py", line 431, in exec_command File "compose\cli\main.py", line 1236, in call_docker File "distutils\spawn.py", line 220, in find_executable File "ntpath.py", line 85, in join UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 8: ordinal not in range(128) Failed to execute script docker-compose I think it's because my database Postgresql is encoded in 'ascii' instead of utf-8, what are the commands to encode my psql database to utf-8? -
How to extract some specific special charcter from input value using python
I need some help. I need to escape some specific special character like semicolon, pipe, redirection and ampersand from input string which is got by post method using python and Django. I am explaining my code below. if request.method == 'POST': rname = request.POST.get('react') Here from the above input value I need to remove the special character. Please help me. -
Pass a list through Ajax in Django
I have made an Ajax call: $.ajax({ url:'/quespaper/intermediate_table', type:'GET', processData: false, data:{'url_link':url_link_copy,'updated_url_link':er}, success: function(data){ alert('Urls updated');}, error:function(error){ alert(error); console.log(error); } }); Here,url_link_copy is a list,which is being properly printed at the console and er is the collection of value of all text boxes: var er = $(".form-control.input-sm").val(); The mapping to a views.py function is correct,but,in that function,when I print the data,it prints:None. I tried JSON.stringify also: data:JSON.stringify({'url_link':url_link_copy,'updated_url_link':er}) But,it also didn't work. Please suggest what is wrong in this implementation. Thanks. -
passing argument to the url in django
in views.py def parts_home(request): part_list_= models.part_list.objects.all() gly_name = ['glyphicon glyphicon-plus', 'glyphicon glyphicon-log-out'] link_list = ['parts:part_add', 'main:login_page'] link_name = ['Add Part', 'Log Out'] my_list = zip(gly_name, link_list, link_name) return render(request,'parts.html',{'part_list':part_list_,'my_list':my_list}) in template <ul class="nav navbar-nav navbar-right"> {% for i,j,k in my_list %} <li class="nav-item"><a href="{% url j %}" class="nav-link"><span class="{{ i }}"></span>{{k}} </a> </li> {% endfor %} </ul> URL pattern url(r'^(?P<login_status>[0,1])/$',views.login_page,name='login_page') Another url directly mapped but 'login_page' needs argument how can I pass an argument through my views.py to the template so that 'login_page' is mapped? or is there any way to do so? basically, i have created a navigation bar base template and for each page, i passed the names and link to the template so that I can use the same navigation bar in all of my pages by passing arguments to the {% include 'template name ' with my_list=my_list%},is it a good idea? -
Django REST Framework - set filename.
I got custom renderer(XLSXRender) and its works, but downloaded file has title only "downloaded" without extention. How I can set a filename with file extension? XLSXRender is in default renderers in settings.py. View is: class CountryViewSet(viewsets.ModelViewSet): queryset = Country.objects.all() serializer_class = CountrySerializer Thank you! -
How to recover a value of a field to stock it in a variable ? Django Admin Form
In my Django Admin Form I have a field which looks like that : I would like to complete all others fields when I press the button above. To do that I am using an API which give me a JSON file : import requests post_data = {'cdNom': value} response = requests.post('https://inpn.mnhn.fr/inpn-web-services/mobile/biodiv/taxongeomobile/json', data=post_data) resp = response.json()[0] print(resp) The variable value is not define here but I want to recover CDN_Name when I press the button to put this value in the variable. How can I do that ? It's possible with python or I have to use a jQuery script in this HTML button ? If I can achieve this, that will recover me a specific JSON file, and after I just had to put each key/value on the good fields ? -
Django-Haystack: Grouping price facets into a range
Currently working on a shop website. I'd like to be able groups price facets into a range. i.e £0.00 - £99, £100 - £249, £250 - £499. So all price prices within the ranges will fall under the single facet rather than display each price as a facet. forms.py from haystack.forms import FacetedSearchForm from django import forms class FacetedProductSearchForm(FacetedSearchForm): desc = forms.ChoiceField(choices=[('n', 'Ascending'), ('y', 'Descending')], label='', initial='y', required=False, widget=forms.Select) def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.retailer = data.get('retailer', []) self.location = data.get('location', []) self.price = data.get('price', []) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() query = None if self.retailer: for retailer in self.retailer: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(retailer) sqs = sqs.narrow(u'retailer_exact:%s' % query) if self.location: for location in self.location: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(location) sqs = sqs.narrow(u'location_exact:%s' % query) if self.price: for price in self.price: if query: query += u' OR ' else: query = u'' query += u'"%s"' % sqs.query.clean(price) sqs = sqs.narrow(u'location_exact:%s' % query) if self.cleaned_data['desc'] == 'y': sqs = sqs.order_by('price') else: sqs = sqs.order_by('-price') return sqs searchresults.html <div class="collapse-box"> <h5 class="collapse-title"> … -
template syntax error in django
I have been running a django site on localhost for a couple of years now with no problem. I've cloned the app to work on developments, renaming it from 'guests' to 'bookings' and this has broken one of the templates. The code is here. The error refers to something which I can't see in the template. Any help gratefully received. -
Django - form fields attributes for logged user
I would like to add readonly attribute to one of form fields. This is a part of my forms.py file: class SiteAddFormFull(forms.ModelForm): def __init__(self, *args, **kwargs): super(SiteAddFormFull, self).__init__(*args, **kwargs) email = self['email'].value() url = forms.URLField(widget=forms.TextInput(attrs={'readonly': 'readonly'}), label='Adres internetowy') kod = forms.CharField(label="Kod premium", required=False) user = forms.CharField(label="Nazwa użytkownika", widget=forms.TextInput(attrs={'readonly': 'readonly'})) if user_is_authenticated: email = forms.EmailField(label="Email adress", widget=forms.TextInput(attrs={'readonly': 'readonly'})) name = forms.CharField(widget=forms.TextInput(attrs={'style': 'min-width:30%'})) I would like to add readonly attribute to email field. I don't have any idea how could I use authentication system here. What should I put instead of user_is_authenticaded? Thanks for any clues. -
Django Beginner Forms, not able to make two forms work on one template page
I would like to have more than one form on a page. So far I have a simple form that a user enters numbers and gets a number returned. When I trying to add another form (which will be Post2 in my models) on the same page I cant. I end up getting the same form twice. All help appreciated. urls.py from django.conf.urls import url from django.contrib import admin from amat.views import AmatView from . import views urlpatterns = [ url(r'^$', AmatView.as_view(), name='home'), ] oddsmat.html {% load staticfiles %} <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" name="form1"/> </form> ... {{ round1 }} {{ round2 }} {{ round3 }} {{ betround1 }} {{ betround2 }} {{ betround3 }} <br> its the same as {{ thesameas }} views.py from django.shortcuts import render from django.views.generic import TemplateView from amat.forms import AmatForm # Create your views here. class AmatView(TemplateView): template_name = 'oddsmat.html' def get(self, request): form = AmatForm() args = { "form": form } return render(request, self.template_name, args) def post(self, request): form = AmatForm(request.POST) if form.is_valid(): round1 = form.cleaned_data['round1'] round2 = form.cleaned_data['round2'] round3 = form.cleaned_data['round3'] form = AmatForm() betround1 = ((round2+1)*(round3+1))/((round1)*(round2+2)+(round2)*(round3+2)+(round3)*(round1+2)+3) betround2 = ((round1+1)*(round3+1))/((round1)*(round2+2)+(round2)*(round3+2)+(round3)*(round1+2)+3) betround3 = ((round2+1)*(round1+1))/((round1)*(round2+2)+(round2)*(round3+2)+(round3)*(round1+2)+3) thesameas = … -
Django UpdateView: translate form labels
I created a rather simple form using Django's UpdateView class, however, now that I want it's labels to be translated into other languages, I can't figure out how to do that. Here is the code of the view class: class EntityUpdate(UpdateView): model = Entity template_name = "entity/settings.html" fields = ["enabled"] And in my template, all i have is: <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans 'Save' %}" /> </form> Where do I lookup translated strings? -
Django model object exists() return "" instead of "None"
So for a basic delivery form, i have a dropdown called "customer" in which customer is specified in first name, last name and prefix. For now the dropdown shows: Customer: Yvonne, Groot, de Kaleigh, Water, van der Tim, Klein, None Cees, Swart, None What I'd like to do, is check is Customer.prefix exists and display a "" instead of the value "None". #models.py class Customer(models.Model): """ Model representing the customer """ first_name = models.CharField(max_length=200) prefix = models.CharField(max_length=4, null=True, blank=True) last_name = models.CharField(max_length=200) def __str__ (self): """ String for representing the Model object. """ if Customer.objects.filter(prefix='').exists(): # Display first name, last name and prefix return '%s, %s, %s' % (self.last_name, self.first_name, self.prefix) else: # Display first name and lastname return '%s, %s' % (self.last_name, self.first_name) This instead will return an error: name 'prefix' is not defined, what would be the proper way for checking if the 'prefix' value exists? -
How to set environment variable using Django and python
I need one help. I need to set some environment variable and it should be fetched inside function and the values will go for save inside db using Django and python. I am explaining my code below. def plantsave(request): rname = request.POST.get('react') status = request.POST.get('status') Here I am getting the value by post method but instead of it I need to set the value by using environment variable and access those values here to submit. Please help. -
Pass JSON to JS using Django render
In my views.py file, I have dictionary: data = {'pk': '1980.24', 'model': 'artworks.metaData', 'fields': {'medium': 'Oil on canvas ', 'description': 'missing', 'credit': 'Gift of Nicholas Wyeth, 1980 ', 'collection': 2, 'height': '21.7', 'culture': 'Missing value', 'depictedPeople': 'missing', 'creation_date': '1896 ', 'account': 'n/a', 'original_url': 'http://www.metmuseum.org/art/collection/search/10738?sortBy=Relevance&amp;what=Canvas%7cOil+paintings&amp;ao=on&amp;ft=*&amp;offset=0&amp;rpp=100&amp;pos=1', 'url': 'annotatie01.io.tudelft.nl/collections/Metropolitan/1980.24.jpg', 'title': 'Gooseberries ', 'object_number': '1980.24', 'width': '35.7', 'artist': 'Joseph Decker '}} I wish to be able to use/access this dictionary on my webpage. My attempts: I tried to send data using the render in my views.py, def foo(): ctx = {'data':data} return render(request, 'imageView/index.html', context=ctx) to access it using: <script type="text/javascript"> var received_data = "{{data}}"; </script> Using this, data is transmitted, but it's garbled: "{&#39;pk&#39;: &#39;1980.24&#39;, &#39;model&#39;: &#39;artworks.metaData&#39;, &#39;fields&#39;: {&#39;medium&#39;: &#39;Oil on canvas &#39;, &#39;descripti...etc I tried using json.dumps(data) and JSON.parse(received_data ) but this raised an error: Uncaught SyntaxError: Unexpected token & in JSON at position 1. In short: How can I send JSON data from Py to JS using Django Render()? -
how to override "def save_related()" in django admin
Below is code for save_related() in django source code def save_related(self, request, form, formsets, change): """ Given the ``HttpRequest``, the parent ``ModelForm`` instance, the list of inline formsets and a boolean value based on whether the parent is being added or changed, save the related objects to the database. Note that at this point save_form() and save_model() have already been called. """ form.save_m2m() for formset in formsets: self.save_formset(request, form, formset, change=change) I do not want my form to call save_formet for my inlines in admin, I tried but didn't find the correct way to do it. -
django is displaying exception as internal server error
In django, is there any way to capture the python script exception and present in the html page, rather than allowing django to provide 500 or page full of exception page(debug=on) try: result = my_resolver.query(host,raise_on_no_answer=False) for a in result: r = r.address except resolver.NXDOMAIN: r = "No record found" args = {'message':r} return render(request, 'dns.html', args) -
Select a valid choice. That choice is not one of the available choices. (When I try to save dropdown list selected data in database)
I already saw all question on Stackoverflow. But Still Not possible for me to solve this error. I want a dropdown list data to appear on my website. And that data I am getting from another model. So till here I am going good. Now When I try to save this data in database this error appear. Select a valid choice. That choice is not one of the available choices. My Model is like this apn = models.CharField(null=True, blank=False, max_length=255) My form.py file is like this class labelModelForm(forms.ModelForm): class Meta: model = Labels_tool apn = forms.ModelChoiceField(queryset=Field.objects.values_list('sql_name', flat=True), empty_label="(Choose field)") And view.py file is : def ImportLabelView(self): urlItems =self.request.path.split('/') i = urlItems.index('layers') self.layer = Layer.objects.filter(id=urlItems[i + 1],map=self.map.id).first() self.form = labelModelForm(self.request.POST) # self.form = self.layer.form(self.request.POST) if self.save_form_if_appropriate('label'): return self.redirect('mapport.maps.layers.importlabel', self.map.id, self.layer.id) return self.render('mapport/maps/layers/Labels_detail.html') Dropdown appearing on page is good . Just issue is when I try to save it in database. -
Dajngo operator inside for loop
I want to add the number of starts that is the division of two IntegerField in django. So I am trying to do: {% for i (object_list.0.score//object_list.0.num_votes) %} <span class="glyphicon glyphicon-star"></span> {% endfor %} or {% for i in "x"|rjust:(object_list.0.score//object_list.0.num_votes) %} <span class="glyphicon glyphicon-star"></span> {% endfor %} But seems is not allow to do operations inside for loop. Is that true? Any workaround? -
Variable images within a django template
I'm new to Django and I'm wondering what is the best way to achieve this. I hold a large(15K+) amount of images within my static folder, and I wish to present those on a webpage, 3 at a time. My attempt: I could hardcode the names within my template, like so: <div id="imageholder"> <img src="{% static "images/im1.jpg" %}" /> <img src="{% static "images/im2.jpg" %}" /> <img src="{% static "images/im3.jpg" %}" /> </div> But this is of course not an option for 15k+ images. I though of using jquerry to change the names within a function. For example: <div id="imageholder"> </div> <script> names = ['im1','im2','im3'] for (i = 0; i < names.length; i++) { html = `<img src="{% static "images/${names[i]}" %}" />` $('#imageholder').append(html) } </script> I believe this would work, yet it requires me to have a list of all the names which I do not have. I though maybe i could use os.listdir() but I woudn't know how to get that into the webpage. -
How to connect django version 1.11 with mongodb using mongoengine
How to connect django version 1.11 with mongodb using mongoengine How to use mongoengine.django.mongo_auth How to use mongoadmin -
usecase - django logging to rsyslog
I am sending django logs to rsyslog via unix socket. I want to know that how rsyslog will affect django's response to requests ? Like, what if rsyslog goes down sometime, then will the request be completed or not? On what thing does this behaviour depends ? -
Diference between get_cotext_data and queryset in Django generic views?
What is the difference between get_cotext_data and queryset in Django generic views? They seem to do the same thing? -
Can't install Django, runserver error
So I have been trying to set up Django, the way it's showed on youtube by thenewboston (a.k.a. Bucky Roberts). This is the link: https://www.youtube.com/watch?v=CHjXtRrhqxc&index=2&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK But when I run the server I get errors like in the image. How do I fix that ? -
are app caches redundant when using serverless architecture (e.g. Amazon Lambda via python Zappa)
Django advises on using a Redis or Memcached cache for high traffic sites, to cut down on the work done by the server. Apps running on Amazon Lambda via Zappa have fantastic horizontal scale-ability. There does not seem to be the need to minimise the processing efforts of a server when another server can be fired up easily and very cheaply. Are Caches such as Memcached and Redis redundant when using server-less architectures?