Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error during template rendering In template unsupported operand type(s) for /: 'map' and 'int'
I am using django version 1.11 and was trying to build up wine recommendation code for wine_detail is {{ wine.name }} {{ wine.review_set.count }} reviews ({{ wine.average_rating | floatformat }} average rating) i got the error in line 2 . -
Using Jquery Datatables In Django
How to use Jquery Datatables on django views for large data? class LargeData(View): ..... ..... ..... return ..... -
Get All StreamField Blocks of Specific Type
I have created a custom photoBlock to embed photos in a blog post. I am trying to create a template tag that would allow me to get every photoBlock that is stored in the database, almost like you query pages in Wagtail. I would prefer not to have to create a separate page for every photo, but instead be able to display them on a different page if possible via the template tag. class photoBlock(blocks.StructBlock): date = blocks.DateBlock("Date Image Was Taken") location = blocks.CharBlock(max_length=100) image = ImageChooserBlock() latitude = blocks.DecimalBlock(max_digits=9, decimal_places=6) longitude = blocks.DecimalBlock(max_digits=9, decimal_places=6) description = blocks.RichTextBlock() I am able to get the following to work, but it feels like the query is very heavy and will get bogged down once I have a bunch of posts. for page in BlogPage: for block in page.body.stream_data: if block['type'] == 'photoBlock': return block Is there any better way to query a specific block from Streamfield? Anytime I try something like this photoBlock.objects.all() I always get an error response that photoBlock doesn't have attribute Object. Any ideas? -
Prevent save_formset from saving - Django Admin
class VotesInline(admin.StackedInline): model = Votes class VoteAreaAdmin(admin.ModelAdmin): model = VoteArea inlines = [VotesInline, ] def save_formset(self, request, form, formset, change): if check_some_condition(): #prevent saving formset else: super(MyAdmin, self).save_formset(request, form, formset, change) All I want to achieve is - when a certain condition is met do not save the formset, do not make any changes in database. If I simply return when I try to finish, I get an error " 'VotesFormFormSet' object has no attribute 'new_objects' ". How can I prevent saving the formset? -
Django Smart-Selects uncaught TypeError when using admin inline
I use Django Smart Selects to dynamically choose a document based on its document type. It work fine on an Admin Page, but I have another Page with an Inline Admin and there I've got this error: Uncaught TypeError: $(...).formset is not a function at HTMLDocument.<anonymous> (?_changelist_filters=o%3D-3.2:11511) at fire (jquery.js:3143) at Object.fireWith [as resolveWith] (jquery.js:3255) at Function.ready (jquery.js:3467) at HTMLDocument.completed (jquery.js:3498) MyClass model: class MyClass(BaseModel): idcliente = models.IntegerField(default=102, editable=False) (...) idtipodoc = models.ForeignKey('Tipodoccliente', db_column='idtipodoc', related_name='+') nrdoc = ChainedForeignKey( Cliente, chained_field="idtipodoc", chained_model_field="idtipodoc", show_all=False, auto_choose=True, db_column='nrdoc', related_name='+' ) class Cliente(BaseModel): idtipodoc = models.ForeignKey('Tipodoccliente', db_column='idtipodoc', verbose_name='Tipo do Documento', related_name='+') nrdoc = models.CharField(primary_key=True, unique=True, max_length=15, verbose_name='Numero do Documento', validators=[numeric]) nome = models.CharField(max_length=100, verbose_name='Nome') (...) MyClass admin inline: class MyClasslInline(admin.TabularInline): model = MyClass fields = ['idcliente', (...), 'nrdoc'] max_num = 1 -
django - Can't login after creating user
I can't login after create user. Here's my code: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' def create(self, validated_data): username = validated_data.pop('username') password = validated_data.pop('password') return User.objects.create_user(username, password, **validated_data) My api: from django.contrib.auth.models import User class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer any help is appreciated. -
XML parsing with Django Rest Framework XML: elements of my request are missing
I use Django Rest Framework XML to create a simple api that accepts requests in XML format. The following view: from rest_framework_xml.parsers import XMLParser from rest_framework_xml.renderers import XMLRenderer class Process(APIView): parser_classes = (XMLParser,) renderer_classes = (XMLRenderer,) def post(self,request): print request.DATA combined with following request: curl -H "Content-Type: application/xml;charset=UTF-8" -H 'Accept: application/xml' -XPOST http://{server_address}:8000/process/ -d @books.xml works but the result of the xml parsing is not good (it seems to get only the last element of each node). File books.xml <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book category="web" cover="paperback"> <title lang="en">Learning XML</title> <author>Kurt Cagle</author> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore> result of print request.DATA in post method: {'book': {'price': Decimal('39.95'), 'author': 'Erik T. Ray', 'year': 2003, 'title': 'Learning XML'}} Am I missing something? -
Make Django build contenteditable div for TextField instead of textarea
In my Django 1.10 project, I have a model: class Contact(models.Model): notes = models.TextField() ...and ModelForm: class ContactForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control input-sm plain' if field.required == True: field.widget.attrs['required'] = '' class Meta: model = Contact fields = ('notes',) I have two questions regarding this: Can I make Django render the notes field as div with contenteditable=true rather than textarea? If yes, how do I automate the form.save() method? The second question is a bit vague, so I would be grateful for a hint regarding the first question. I have read through the doc, but couldn't find relevant section :( -
Django allauth, google login,using HD parameter
I am using django-allauth to login to my website using google login. I want to allow users having email from particular client, for that google provides the hd parameter. https://developers.google.com/identity/protocols/OpenIDConnect#hd-param SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': ['email'], 'AUTH_PARAMS': { 'access_type': 'online' }, 'HD': '*****.com' } } I have used hd, using flask, and it worked pretty well, but I can't make it work here. What am I missing here? I tried keeping HD as part of AUTH_PARAMS, but to no use. -
UnicodeEncodeError disparity between code run via django test suite vs django URL
Specifically I'm using the webob library where I posted a similar issue (https://github.com/Pylons/webob/issues/320), since I'm not sure if it's my usage, or a bug / documentation issue Take the following code: from webob.request import BaseRequest req = BaseRequest.blank('http://example.com/%D0%B4%D1%8D%D0%BB%D1%8C%D1%8D%D0%BD%D0%B9%D1%82') print req.environ['PATH_INFO'] print req.path If I run this via a django shell, I get: >>> req = BaseRequest.blank('http://example.com/%D0%B4%D1%8D%D0%BB%D1%8C%D1%8D%D0%BD%D0%B9%D1%82') >>> print req.environ['PATH_INFO'] /дэльэнйт >>> print req.path /%D0%B4%D1%8D%D0%BB%D1%8C%D1%8D%D0%BD%D0%B9%D1%82 Where as running it as part of a Django test case I get the following from the first print: /дÑлÑÑÐ½Ð¹Ñ Followed by the exception: File "/code/frontend/tests/test_views.py", line 55, in test_event print req.path File "/virtualenv/frontend/local/lib/python2.7/site-packages/webob/request.py", line 485, in path bpath = bytes_(self.path_info, self.url_encoding) File "/virtualenv/frontend/local/lib/python2.7/site-packages/webob/descriptors.py", line 68, in fget return req.encget(key, encattr=encattr) File "/virtualenv/frontend/local/lib/python2.7/site-packages/webob/request.py", line 175, in encget return val.decode(encoding) File "/virtualenv/frontend/lib/python2.7/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-16: ordinal not in range(128) I get that this is probably some weird configuration with my test suite, however both run via the same method in the same environment (Django's manage.py test vs manage.py shell) and so I'm struggling to identify what's different. We're also running a ton of other unicode related tests without issue. Thanks for any light … -
Django - Logging into one subdomain of a website
Like Slack, you log into just one team, and not the entire system, how could this be achieved in Django? Using the django.contrib.auth module, we can log in the user to the website but I'm having difficulty understanding how to log a user into a subdomain. Apologies for the lack of code, but will I need to write my own custom log in? Thanks. -
django - dynamically generated form not posting data to request.POST
I've created a webform that consists of multiple forms and formsets on a single page. For the formsets, I made a button to add forms. When I create a new form using this button, the information I input into these forms is not POSTed and as such leads to an error in my formset as required fields are not filled out. Here is my views.py def general(request): class RequiredFormSet(BaseFormSet): def __init__(self, *args, **kwargs): super(RequiredFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False RecFormSet = formset_factory(RecForm, max_num=15, formset=RequiredFormSet) RiskFormSet = formset_factory(RiskForm, max_num=15, formset=RequiredFormSet) LCFormSet = formset_factory(LCForm, max_num=15, formset=RequiredFormSet) LCFormSet2 = formset_factory(LCForm2, max_num=15, formset=RequiredFormSet) print 'initial forms created' if request.method == 'POST': state_form = StateForm(request.POST, instance=State()) submitter_form = SubmitterForm(request.POST, instance=Submitter()) ivv_gen_form = IVVGeneralForm(request.POST, instance=IVV()) lc_formset = LCFormSet(request.POST, request.FILES, prefix='lc') lc_formset2 = LCFormSet2(request.POST, request.FILES, prefix='lc2') risk_formset = RiskFormSet(request.POST, request.FILES, prefix='risk') rec_formset = RecFormSet(request.POST, request.FILES, prefix='rec') print 'POST data reached' # print lc_formset print 'POST INFORMATION' print request.POST.items() print 'END POST INFORMATION' if lc_formset.is_valid(): print 'formset is valid' else: for form in lc_formset: if form.is_valid(): print 'form is valid' else: print form.has_changed() print form.errors print 'error in form' if state_form.is_valid() and submitter_form.is_valid() and ivv_gen_form.is_valid() and lc_formset.is_valid() and lc_formset2.is_valid() and risk_formset.is_valid() and rec_formset.is_valid(): print … -
Update all data from html table Django/python to database
I have created a system with Django to display certain data on a html table that can be modified as you can see in the picture belown: What I need is to find a way on how to insert the data that user will input bu the time user click the button. Here is my html from the table (using datatables): <table class="table table-striped table-bordered table-hover dataTables-example" > <thead> <tr> <th>Local</th> <th>level</th> <th>Qty</th> </tr> </thead> <tbody> {% for linea in lineas_de_reporte %} <tr> <td>{{ linea.local }}</td> <td> <input type="hidden" name="comments-id" value="{{ linea.id }}" /> <input type="text" name="case-opened" value="{{ linea.rack }}" id="caseOpened"/> </td> <td> <input type="hidden" name="comments-id" value="{{ linea.id }}" /> <input type="text" name="case-opened" value="{{ linea.line }}" id="caseOpened"/> </td> </tr> {% endfor %} </tbody> </table> Is there any way on doing this with django or any other way? I have made something similar but users can modify and save one input by a time. Thanks for your time. -
Accessing Django Admin with requests library
I'm trying to access to my Django Admin through request library. r1 = requests.get('page.com/admin') r1_cookie = r.cookies['csrftoken'] req_cookies = {'csrftoken': '{}'.format(r_token)} # Cookie for the request req_data = {'csrfmiddlewaretoken': '{}'.format(r_token),'username':'my_username','password':'my_password'} # Data for request res = requests.get('page.com/admin', cookies=req_cookies, data=req_cookies) At this point, I should have accessed to my admin page but it keeps asking for my credentials. Any idea? -
Django render redirect to page with changing url
I am creating a custom login for my django application and problem occurs when i click logout on template I programmed it so it go to index page but the url in the browser remains http://127.0.0.1:8000/logout/ even reaching index page. I want it to become http://127.0.0.1:8000/ . views.py def logout(request): try: del request.session['uid'] return render(request, 'home.html') except: pass return render(request, 'home.html') def home_page(request): return render(request, 'home.html') template <p> Publisher Dashboard, Welcome {{ user.name }}. <a href="{% url 'logout' %}" class="btn btn-primary">Logout</a> </p> urls.py from django.conf.urls import url from django.contrib import admin from mainapp import views urlpatterns = [ url(r'^$', views.home_page, name='homepage'), url(r'^registration/$', views.signup_user, name='signup_user'), .... url(r'^logout/$', views.logout, name='logout'), ] -
Add friend error in django
I can log in from one user, when i try logging in with other user accounts, i get the following error Friend matching query does not exist. below is my views.py. i get an error on the line 7 class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id) friend = Friend.objects.get(current_user=request.user) ... friends = friend.users.all() args = { 'form': form, 'posts': posts, 'users': users, 'friends': friends } return render(request, self.template_name, args) -
How to ensure lower server load in Django
I'm working on a Django web app. The app includes messages that will self-delete after a certain amount of time. I'm using timezone.now() as the sent time and the user inputs a timedelta to display the message until. I'm checking to see if the message should delete itself by checking if current time is after sent time plus the time delta. Will this place a heavy load on the server? How frequently will it automatically check? Is there a way that I can tell it to check once a minute (or otherwise set the frequency)? Thanks -
Django 1.10 Form doesn't store data to DB
I feel very stupid and confused, tackling this issue for so long. It works completely fine, displays survey fine, however it does not store(save) submited form to my database. I have seen tons of questions/solutions, however none of them helped me. Here are my models.py from __future__ import unicode_literals from django.db import models #from multiselectfield import MultiSelectField, from django.contrib.auth.models import User #from django.forms import ModelForm # Create your models here. class user_prefs(models.Model): cuisine_choice = ( ('1', 'Italian'), ('2', 'American'), ('3', 'Japanese'), ('4', 'French'), ('5', 'Mexican'), ('6', 'Chinese'), ('7', 'Indian'), ('8', 'Middle Eastern') ) lunch_pref = ( ('1', 'Coffeehouse'), ('2', 'Cafe'), ('3', 'Restaurant'), ('4', 'Fast Food'), ('5', 'Takeaway'), ('6', 'Stake House') ) dinner_pref = ( ('1', 'Restaurant'), ('2', 'Takeaway'), ('3', 'Delivery'), ('4', 'Fast food'), ('5', 'Coffeehouse'), ('6', 'Cafe'), ('7', 'Cooking at home') ) sunday = ( ('1', 'Cultural activities(Museums, Galleries, Exhibitions etc.)'), ('2', 'Sport activities'), ('3', 'Attending sport events'), ('4', 'Music events'), ('5', 'Hiking'), ('6', 'Going to park') ) friday = ( ('1', 'Bar'), ('2', 'Nightclub'), ('3', 'Karaoke'), ('4', 'Netflix & chill'), ('5', 'Videogames'), ('6', 'Cinema'), ('7', 'Theater'), ('8', 'Restaurant') ) userID = models.ForeignKey(User) #related_name='User', null=True Cuisine = models.IntegerField(choices=cuisine_choice) Cuisine1 = models.CharField(max_length=30) LunchPref = models.IntegerField(choices=lunch_pref) DinnerPref = models.IntegerField(choices=dinner_pref) Sunday = models.IntegerField(choices=sunday) … -
Django admin signal when open/load detail view
Problem I'm developing and app using the native django admin app with some changes, the ideia is that the people are going to access the list and change some info in the detail view, but I have a problem when two people open/load the same view, whats gonna happen is that the last guy gonna overide the changes of the firsts. The Solution I thought I have a field called status and the list change based on the value of this field, I'm using get_queryset method. My idea is use signals for change this list when someone open/load the detail view. But I didn't find any good explanation for doing that, someone can help me with documentation/blog/tutorial/explanation for signals in Django for this? Thanks -
Postgres DB Password Not match on Kubernetes
I have one Django app which I am deploying on kuernetes, Django gets Database settings from env variables : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': get_env_setting('DATABASE_NAME'), 'USER': get_env_setting('DATABASE_USER'), 'PASSWORD': get_env_setting('DATABASE_PASSWORD'), 'HOST': get_env_setting('DATABASE_HOST'), 'PORT': get_env_setting('DATABASE_PORT') } } My replica and postgres yaml files code looks like : Repica code : apiVersion: v1 kind: ReplicationController metadata: name: auth-service labels: name: auth-service spec: replicas: 1 template: metadata: labels: name: auth-service spec: containers: - name: auth-service image: inforian/auth-service:v2.3 env: - name: DATABASE_NAME_AUTH value: my_service - name: DATABASE_USER value: my-user - name: DATABASE_PASSWORD value: mypassword - name: DATABASE_HOST value: auth-postgres - name: DATABASE_PORT value: "5432" ports: - containerPort: 80 Postgres code : apiVersion: extensions/v1beta1 kind: Deployment metadata: name: auth-postgres labels: name: auth-postgres spec: replicas: 1 template: metadata: labels: name: auth-postgres spec: containers: - name: auth-postgres image: postgres env: - name: PGDATA value: /var/lib/postgresql/data/pgdata - name: POSTGRES_USER value: my-user - name: POSTGRES_PASSWORD value: mypassword - name: POSTGRES_DB value: my_service ports: - containerPort: 5432 volumeMounts: - name: postgresdata mountPath: /var/lib/postgresql/data volumes: - namsistentVolumeClaim: claimName: postgres-data e: postgresdata persistentVolumeClaim: claimName: postgres-data Password in both above files is same but still it is giving me error when I access my app FATAL: password authentication failed for user … -
Django Cirspyforms render field readonly but editable by Javascript
i have a Django Crisypforms Form. I want to render an input element as readonly (greyed out) than i use a javascript to populate the field by making it writable, change the value, and put it back to readonly. I want the form to accept the edited value. The other options (disabling, readonly etc.) i found involving Crispyforms form rendering disables the field permanently but i want it to be editable on the form level but editable by my clientside javascript. So how do i render a django crisypforms field as "disabled" by default but change that status with clientside javascript? -
Building Cosign Filter for the Apache Webserver from Source docker
I need to implement and configure Cosign filter into Apache webserver. I'm running Apach in the docker container, so the problem I'm having is not knowing how to start implementing this, the documentation for this filter are good, but I'm doing this for the first time. Configuration for the apache is simple, I've used this blog post, created a simple django app and docker-compose-it on docker, now I need to add this filter. So can anyone help me and at least advice me from where to start implementing this into my Apach webserver. -
Django: How to use local copy of base theme?
I am working in Django 1.10, and have inherited a project. The base.html template extends a theme template that is not included in the project: {% extends "theme_base.html" %} It seems there is another theme repo, which is specified as a github URL in the requirements file. I now want to make changes to the base theme, but I'm not sure how to do this and run them locally. I have checked out a copy of the theme repo locally, and installed it with: pip install -U -e ../dc_base_theme But when I make changes in that local repo, they don't appear in my running Django site on localhost. How do I make sure my Django repo is pointing to that local copy of the theme? -
Directing to a secured URL through a Django app
I want to login (or redirect) to a remote URL from my Django application by passing the URL credentials securely. I have tried using the redirect("username:password@url") approach, but that is not secure as it (the credentials) can be seen in the Developer tools of the browser. What is the best way to do this? -
how to fi this error in Django, Queryset, filet, Attribute Error, how to improve it?
I can not access the entry in the model, although the entry exists, and it is corrected, it is accessed by such a line in any other views. It works correctly, but it is in this views.py error in seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) error herself watched_serial = seriess.serial_of_this_series AttributeError: 'QuerySet' object has no attribute 'serial_of_this_series' views def mark_and_unmark_this_episode(request, serial_slug=None, season_slug=None, series_slug=None): return_dict = {} data = request.POST is_delete = data.get('is_delete') seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug) for i in seriess: print(i) watched_serial = seriess.serial_of_this_series watched_serie = seriess minutes_of_series = seriess user = request.user if is_delete == 'true': mark_it = watched_series.objects.get(user=request.user, watched_serial__slug=serial_slug, watched_serie__slug=series_slug, minutes_of_series__slug=series_slug) #m = watched_series.objects.get(user=user, watched_serial=instance.watched_serial) mark_it.delete() update_profile, created = UserProfile.objects.filter(user=request.user) if not created: update_profile.user = user update_profile.series_watched_nmb -= 1 update_profile.save(force_update=True) if is_delete == 'false': mark_it_watched, created = watched_series.objects.get_or_create(user=request.user, watched_serial__slug=serial_slug, watched_serie__slug=series_slug, defaults={"user":user, "watched_serial":watched_serial, "watched_serie":watched_serie, "minutes_of_series":minutes_of_series}) if not created: mark_it_watched.user = user mark_it_watched.watched_serial = watched_serial mark_it_watched.watched_serie = watched_serie mark_it_watched.minutes_of_series = minutes_of_series mark_it_watched.save(force_update=True) return_dict["watched_info"] = list() product_dict = {} product_dict["user"] = request.user product_dict["watched_serial"] = seriess.serial_of_this_series product_dict["watched_serie"] = seriess product_dict["minutes_of_series"] = seriess return_dict["watched_info"].append(product_dict) print(return_dict) return JsonResponse(return_dict) i have another one view in same page, just what was up obly for upgrade button but this is content on this page and this serie …