Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django displays only 1 item in template from queryset
Im trying to display all the keys from a queryset.objects.values() however it only displays 1 key. my views.py are from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.models import User from preferences.models import user_selection from django.contrib.auth.models import User def keys(request): uid = request.user objects = user_selection.objects.values().filter(userID=uid) rng = range(len(objects)) clean = int(''.join(map(str, rng))) for keys, values in objects[clean].iteritems(): #getting values that are True if values == True: return keys def places(request): display = keys(request) return render(request,'showme.html',{'display':display}) and my templates.html <!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> <title>Hi, it's a test</title> {% if display %} {{ display }} {% endif %} <body> </body> </html> My assumption is that the problem is in templates, but since I already filtered all the values in views I have no idea what could probably cause the trouble -
ManyToMany Relation in Template (Reverse LookUp)
I'm trying to build my own client database and I just don't get the reverse lookup to work: models.py class PersonQuerySet(models.QuerySet): def employees(self): return self.filter(role='E') class PersonManager(models.Manager): def get_queryset(self): return PersonQuerySet(self.model, using=self._db) def employees(self): return self.get_queryset().employees() class Person(models.Model): people = PersonManager() role = models.CharField(max_length=1, choices = (('C', _('Client')),('E', _('Employee')))) class Organization(models.Model): employees = models.ManyToManyField( Employee, limit_choices_to=Q(role='E'), related_name='organization_employees', related_query_name='organization_employee',) views.py class PersonDetail(DetailView): model = Person template_name = 'clients/person_detail.html' The Organization-Class relates over a ManyToMany-relation to several employees (Person-Class). The DetailView (template "person_detail.html") of every employee may now display the Organization, to which each employee belongs, I think about something like person.organization.name I've tried this and many other solutions, but it has never worked so far, I just don't get why I'm stucked. <ul> {% for organization in people.organization_set.all %} {{ organization.name }} {% endfor %} </ul> Many many thanks for any help :) -
Zinnia base.html throwing TemplateSyntaxError
I have successfully installed and setup Zinnia in my Django 1.11-Python 3.5 app. I am able to create entries and comment on them. A common next step is likely to customize the look of the blog, so I started going through this -> http://docs.django-blog-zinnia.com/en/latest/how-to/customize_look_and_feel.html. So I went to the Zinnia GitHub page to download the base.html file here -> https://github.com/Fantomas42/django-blog-zinnia/tree/master/zinnia/templates/zinnia. I placed this in my_project_dir/templates/zinnia (where my_project_dir is the directory with manage.py). After doing this, I try to access my blog. However, endless TemplateSyntaxErrors arise like: Could not parse the remainder: '&quot;zinnia/skeleton.html&quot;' from '&quot;zinnia/skeleton.html&quot;' and Could not parse the remainder: '&#39;zinnia:entry_archive_index&#39;' from '&#39;zinnia:entry_archive_index&#39;' which are always complaining about &quot; and &#39;. After going through the document changing these to their respective ASCII values, I realized that I must be doing something wrong because this is too big of an oversight by the Zinnia devs for it to not have been caught already by others. How do I proceed? I've used the base.html file from every branch on Zinnia's GitHub, but I still get these errors. I also can't seem to find any other tutorials apart from the one by Zinnia. -
Django - pre-select checkboxes if value occurs in entry
I have a webapp where tenants can select a number of facets from a list of checkboxes. There exists a many to many relationship between facets and tenants. (companies have a 'linked_facets' and facets have 'linked_companies' attribute) The facets are nested, so I used the MPTT package + a custom html page to create the following nested list of checkboxes <form action="." method="POST" class="FacetForm">{% csrf_token %} <ul id="id_linked_facets"> {% recursetree facetten %} <li> <label><input type="checkbox" name= 'facet_link' value={{ node.pk }}><h3>{{ node.name }}</h3></label> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> <div class="text-right"> <a href="{% url 'feature_list'%}" class="btn btn-default">{% block cancel-button-text %}{% trans "Cancel" %}{% endblock %}</a> <input type="submit" class="btn btn-primary" value="{% trans 'Save' %}" /> </div> </form> This page is accompanied by the following form: class FacetForm(forms.ModelForm): widgets = { 'linked_facets': CheckboxSelectMultiple() } class Meta: model = Tenant fields = ['linked_facets'] The form works and the database is updated. However, everytime the page is opened all of the checkboxes are unchecked. Since the number of facets is likely to expand, this is rather inconvenient (as user that whish to update 1 facet end up having to re-check most of … -
Offline Generation Error - djnago compressor
I am trying to setup Cabot via Flynn, which is basically like a in-house heroku. When I deploy eveything and try to run it, i get this exception. OfflineGenerationError: You have offline compression enabled but key "88dbbdf7c5e6ceca63a19023be40a840" is missing from offline manifest. You may need to run "python manage.py compress". I read here that the path for COMPRESS_ROOT might not be absolute, which could have been the problem, but when I checked, I got these in the logs. Seems absolute to me. [2017-07-28T13:50:24.532104Z] ('\n \n \n \n STATIC & CCOMPRESS ARE ', '/app/cabot/collectedstatic/', '\n \n \n \n ') [2017-07-28T13:50:24.532943Z] ('\n \n \n \n STATIC & CCOMPRESS URL ARE ', '/static/', '\n \n \n \n ') I tried running manage.py compress during the build process and got the following errors. When I ran manage.py compress Invalid template /app/.heroku/python/lib/python2.7/site-packages/django_filters/templates/django_filters/rest_framework/crispy_form.html: 'crispy_forms_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache compress extra i18n jsonify l10n log polymorphic_admin_tags polymorphic_formset_tags rest_framework static staticfiles tz Invalid template /app/.heroku/python/lib/python2.7/site-packages/rest_framework/templates/rest_framework/filters/django_filter_crispyforms.html: 'crispy_forms_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache compress extra i18n jsonify l10n log polymorphic_admin_tags polymorphic_formset_tags rest_framework static staticfiles tz Found 'compress' tags in: … -
Size of workbook xlsxwriter
I'm sending an excel file made with xlsxwriter in response in django view, i want to set content-length header, but i cant find something like .get_size() method of xlsxwriter.Workbook, is where a way to get size of workbook? -
Building a video streaming web app
I'm a junior web developer, and recently I was asked to collaborate in a new project: we have to build a web platform for live conferences (which involves live video streaming, of course) and I'm not sure where to start. I have proficiency in PHP and Django (and some experience with Node.js) but I know nothing about video streaming, so I'd be thankful if someone could give me some guidance. Thanks. -
Updating User Password in Django with Class BaseView
I'm tring write a view to administrator update a password of another user, using Class BaseView and model SetPasswordForm of Django. My views.py class UserSetPasswordUpdateView(GroupRequiredMixin, FormView): form_class = forms.SetPasswordForm model = User template_name = 'app/admin/object_update.html' success_url = reverse_lazy('portal:admin_user') group_required = u"Administrator" def get_form_kwargs(self): kwargs = super(UserSetPasswordUpdateView, self).get_form_kwargs() kwargs['user'] = User.objects.filter(pk=self.kwargs['pk']) return kwargs update_change_password = UserSetPasswordUpdateView.as_view() My urls.py url(r'^app/admin/update-user-pass/(?P<pk>[0-9]+)$', update_views.update_change_password, name='update_change_password'), And don't show any errors, just go to success_url, but the password don't updated. -
Have to refresh before my ajax request happens the text in django
I have follow button which works by using ajax the {{ total_followers }} works well by increasing or decreasing upon a click but the follow and unfollow buttons change only when I refresh the whole page which is what I do not want My views @ajax_required @require_POST @login_required def user_follow(request): user_id = request.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create(user_from=request.user,user_to=user) else: Contact.objects.filter(user_from=request.user,user_to=user).delete() return JsonResponse({'status':'ok'}) except User.DoesNotExist: return JsonResponse({'status':'ok'}) return JsonResponse({'status':'ok'}) My HTML {% extends 'base.html' %} {% load thumbnail %} {% block title %}{{ user.get_full_name }}{% endblock %} {% block content %} <h1>{{ user.get_full_name }}</h1> <div class="profile-info"> {% thumbnail user.profile.photo '180x180' crop='100%' as im %} <img src="{{ im.url }}" alt="profile photo"> {% endthumbnail %} </div> {% with total_followers=user.followers.count %} <span class="count"> <span class="total">{{ total_followers }}</span> follower{{ total_followers|pluralize }} </span> <a href="#" data-id='{{ user.id }}' data-action='{% if request.user in user.followers.all %}un{% endif %}follow' class="follow button"> {% if request.user not in user.followers.all %} Follow {% else %} Unfollow {% endif %} </a> <div id="image-list" class="image-container"> {% include "images/image/list_ajax.html" with images=user.images_created.all %} </div> {% endwith %} {% endblock %} {% block domready %} $('a.follow').click(function(e){ e.preventDefault(); $.post('{% url "user_follow" %}', { id: $(this).data('id'), action: $(this).data('action') … -
Django Admin, missing id readonly field in StackedInline
I have a StackedInline with a model that contains several fields (including an 'id' field): class MyInline(admin.StackedInline): model= myModel fields = ('id', 'foo', 'bar') This shows the 3 editable fields as expected, however, when setting those to readonly: class MyInline(admin.StackedInline): model= myModel fields = ('id', 'foo', 'bar') readonly_fields= ('id','foo','bar') The id field is missing, only the foo and bar appear (as non-editable). This behaviour happened when using StackedInline, with TabularInline works fine Why is Id missing and how can I add it as a readonly field? -
Django doesn’t set STATIC_ROOT in settings.py
Trying to understand how “upload files” works I’ve seen that views.py doesn’t get values, assigned in settings.py relative to STATIC_ROOT and STATIC_URL. But views.py gets STATICFILES_DIRS’s value and this value is not correct. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, ""),] urls.py urlpatterns = [url(r'get_object/$', views.get_object, name = 'get_object'),] views.py def get_object(self): # static_files = settings.STATICFILES_DIRS static_root = settings.STATIC_ROOT if static_root: path = static_root else: path ='No object' return HttpResponse(path) Django returns ‘No object’. When I type in in views.py static_files instead of static_root def get_object(self): static_files = settings.STATICFILES_DIRS # static_root = settings.STATIC_ROOT if static_files: path = static_files else: path ='No object' return HttpResponse(path) it returns 'C:/music/'. I guess this is not correct path. It gives correct path relative to BASE_DIR. I hope to get correct STATIC_ROOT. Thank you in advance! -
Django increment Then value in Annotate Count
Let's say I have query set A. A.annotate(c=Count(Case(When(name='Jack',then=I) Now, each time A.name == 'Jack', c will be set to I. How can I increment I for each time this happens? So that for the first case, I = 1, for the 2nd I=2 etc. -
Django URL - default value if the value doesn't exist
I am trying to set up a default value in case of no entry. URL file: url(r'^testApp/(?:(?P<view_id>test1|test2\w+)/)?$', testApp_views.main), view file: def main( request, view_id = 'test1'): print view_id and in the console i see " None " Do you know why ? Thanks in advance, -
Django REST Swagger https requests
How configure django-rest-swagger to get a https requests? -
Could not pass value in URL query string using Dajngo and Python
I need one help. I need to pass session id in URL query string after login using Dajngo and Python but in my case I am getting some error. I am explaining my code below. def loginsave(request): """This function helps to login the user """ if request.method == 'POST': password = request.POST.get('pass') uname = request.POST.get('uname') per = User.objects.all().filter( Q(password__icontains=password) & Q(uname__icontains=uname)).count() if per > 0: user = User.objects.filter( Q(password__icontains=password) & Q(uname__icontains=uname)) for use in user: uid = use.id user_name = use.uname request.session['id'] = uid request.session['sess'] = dict(dt=str(datetime.now()), value='session') request.session['sess_id'] = 'abcd1234' return render(request, 'bookingservice/home.html', {'count': per, 'username': user_name}) else: return render(request, 'bookingservice/login.html', {}) This is my login function here I am creating session id and I need to pass it over URL. My menu list is given below. <a href="{% url 'home' %}?token={{request.session["sess_id"]}}">Home</a> <a href="{% url 'booking' %}">Add Booking</a> <a href="{% url 'personal' %}">Add Personal Info</a> I am doing like this but here I am getting the following error. Exception Value: Could not parse the remainder: '["sess_id"]' from 'request.session["sess_id"]' Here I need after login the session id should come over every page URL. Please help me. -
django nginx media files
server { #listen 443; server_name www.site.md; location ~* .(jpg|svg|jpeg|gif|png|ico|css|zip|rar|pdf)$ { root /home/ubuntu/giver; error_page 404 = 404; } location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/giver; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/giver/server/giver/giver.sock; } location /media { root /home/ubuntu/giver/server/giver/giver/media; # your Django project's media files - amend as required } As you see, i have added path to media files, but they do not load... Can someone help me, please? I use django 1.10, nginx, gunicorn on ubuntu 16. -
Building an AJAX view to follow users
I am following Django By Example tutorial and unable to follow users. I click the follow button but nothing happens. I've went over that section over and over, copy and pasted the code. It still doesn't work. Here is my views @ajax_required @require_POST @login_required def user_follow(request): user_id = require.POST.get('id') action = request.POST.get('action') if user_id and action: try: user = User.objects.get(id=user_id) if action == 'follow': Contact.objects.get_or_create(user_form=request.user,user_to=user) else: Contact.objects.filter(user_form=request.user,user_to=user).delete() return JsonResponse({'status':'ok'}) except User.DoesNotExist: return JsonResponse({'status':'ko'}) return JsonResponse({'status':'ko'}) This is the ajax in my html block {% block domready %} $('a.follow').click(function(e){ e.preventDefault(); $.post('{% url "user_follow" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.follow').data('action'); // toggle data-action $('a.follow').data('action', previous_action == 'follow' ? 'unfollow' : 'follow'); // update total followers var previous_followers = parseInt( $('span.count .total').text()); $('span.count .total').text(previous_action == 'follow' ? previous_followers + 1 : previous_followers - 1); } } ); }); {% endblock %} This is the url ** #Users url(r'^user/$', views.user_list, name = 'user_list'), url(r'^users/follow/$', views.user_follow, name='user_follow'), url(r'^users/(?P<username>[-\w]+)/$', views.user_detail, name = 'user_detail'), ** Thanks for your help -
Form initial data does not display in template
I have a form with some fields that have initial values. After run my application, the form appears but its fields initial values don't display, just an empty form. I put a {{ profile_form.initial }} in my template to make sure that the form has initial data. It returns a dict with initial data: {'local_number': 'test-local-number', 'last_name': 'test-last-name', 'phone': 'test-phone', 'zip_code': 'test-zip-code', 'city': 'test-city', 'user': <User: testuser>, 'street': 'test-street', 'first_name': 'test-first-name'} Here is my code: forms.py class MyForm(forms.ModelForm): initial_fields = ['first_name', 'last_name', 'phone', 'street', 'local_number', 'city', 'zip_code'] class Meta: model = UserProfile fields = ('first_name', 'last_name', 'phone', 'street', 'local_number', 'city', 'zip_code') def __init__(self, *args, **kwargs): self.instance = kwargs.pop('instance', None) initial = kwargs.pop('initial', {}) for key in self.initial_fields: if hasattr(self.instance, key): initial[key] = initial.get(key) or getattr(self.instance, key) kwargs['initial'] = initial super(MyForm, self).__init__(*args, **kwargs) views.py def my_view(request): context = {} if request.user.is_authenticated(): profile_form = MyForm( request.POST, instance=request.user.profile) if profile_form.is_valid(): profile_form.save() context.update({'profile_form': profile_form}) } return render(request, 'template.html', context) template.html <form class="animated-form" action="" method="POST"> {% csrf_token %} {{ profile_form.initial }} {{ profile_form.as_p }} <div> <div class="row"> <div class="col-lg-12 text-center"> <button type="submit">Submit</button> </div> </div> </div> </form> -
Emojis do not render well on Heroku with Pillow but they do locally
I am using Pillow 4.2 in a Django 1.10 application to insert some text containing unicode emojis over images. Locally it works like a charm. I am using OpenSansEmojis.tff by the way. When I push my code on Heroku though, the emoji characters are not displayed properly and I get the "square" character instead (🐼). I should add that the function is run by a Celery 4.* worker (separate dyno on Heroku). What I tried already I tried to set PYTHONIOENCODING but it did not help. I tried to use the trick mentioned here but it didn't help either. -
django - Refresh jwt in django restframework jwt
from http://getblimp.github.io/django-rest-framework-jwt/#refresh-token Each time the user loads the page, you can check if there is an existing non-expired token and if it's close to being expired, refresh it to extend their session. In other words, if a user is actively using your site, they can keep their "session" alive. Can anyone explain to me how we can implement client-side like that? -
django blog views.py "method" member function definition, not sure where it is defined or where it takes me to
all process depicted pictured here I am finding it difficult to get a hold on some Django concepts, using pycharm and learning from Django by example by packt publishing on it's blog project I am trying to find where everything i use is basically coming from since im unsure of what methods come from main libraries just yet I am having problem with this .method impementation, when i try goto > definition a whole bunch of possibilities pop up, since all have the f icon i presume these are just funcions, so i go to the lowest one which looks like the most serious one and directs me to QHttPRequestHeader.py def method(self) from my imports i can see that im not using this header, i know i could be indirectly using an import through indirect linking but I yet have no basic knowledge to know if this is the case i presume so many possibilities on the drop-down come from the fact that this is some sort of ambiguous parameter can anyone help me? any lecture of what i am doing at all? Im adding some images of the case cheers -
Load static files with django template tag
Im trying to load image files saved in the static directory but this does not seem to do it {% thumbnail image.user.profile.photo "40" as in %} <a href="{{ image.user.get_absolute_url }}"> <img src="{{ in.url }}" class="gametime"></a> {% endthumbnail %} <a href="{{ image.user.get_absolute_url }}" class="time"> {{ image.user.username }}</a> </div> <div id="details"> {% thumbnail image.image "551" as im %} <a href="{{ image.image.url }}"> <img src="{{ im.url }}" alt="{{ image.title }}"class="image-detail"> </a> {% endthumbnail %} i tried img src="{% static "rango.jpg" %}" alt="Picture of Rango"> and it displayed the rango.jpg image I think i need the {% static %} tag to accomplish this with image variable but still have not gotten it right. -
django-tables2 how to add a field to the end of parent table?
I use a table as defined below class CustomerTable(BaseTable): pk = ToggleColumn() title = tables.LinkColumn('users:user', args=[A('pk')]) class Meta(BaseTable.Meta): model = Customer fields = ('pk', 'name', 'address', 'status') Then i created just extending CustomerTable as below class Customer2Table(CustomerTable): class Meta(BaseTable.Meta): model = Customer fields = ('country') It works well, added a new column to display country. But it's coming as the first column. How can we move it to the end? fields = ('pk', 'name', 'address', 'status','country') will work. I don't like to add existing fields again in the child class. Would like to just add extra field. -
create nested JSON from DB output in django rest framework
I am trying to create nested json from DB output, using django rest framework. I have created the models, serializers and views.py as follows: Models.py class SecondModel(models.Model): USERNO = models.CharField(max_length=30, primary_key=True) USERNAME = models.CharField(max_length=250) PERIOD = models.CharField(max_length=250) class Meta: managed = False db_table = 'view1' class FirstModel(models.Model): CODE = models.ForeignKey(SecondModel,db_column='CODE', related_name='clients', primary_key=True) NAME = models.CharField(max_length=250) STUDY = models.CharField(max_length=250) class Meta: managed = False db_table = 'view2' views.py: class NestedViewSet(viewsets.ModelViewSet): serializer_class = SecondSerializer queryset = SecondModel.objects.filter(USERNO=11) serializer = SecondSerializer(instance=queryset) serializers.py: class FirstSerializer(serializers.ModelSerializer): class Meta: model = FirstModel fields = ('NAME', 'CODE', 'STUDY') class SecondSerializer(serializers.ModelSerializer): clients = FirstSerializer(many=True,read_only=True) class Meta: model = SecondModel fields = ('USERNO', 'USERNAME','PERIOD','clients') The output I am getting is as below. I am getting "clients" as empty list. { "USERNO": "11", "USERNAME": "smith,John", "PERIOD": "APR-17", "clients": [] }, { "USERNO": "11", "USERNAME": "smith, John", "PERIOD": "APR-17", "clients": [] } The output I am looking for is: { "USERNO": "11", "USERNAME": "smith,John", "PERIOD": "APR-17", "clients": [ { "NAME" : "comp1", "CODE" : "ABC111", "STUDY" : "stu11" }, { "NAME" : "comp2", "CODE" : "ABC222", "STUDY" : "stu22" } ] } Am I missing something here to get the desired output? -
how to get user's informations by clic on the user_object in a user_list view
I'm beginner in django, what i'm trying to do is: I want to build a view for a Staff_User that lets him get some users's informations (Specifically check the files uploaded by the selected user) through a list showing All users some of my code : models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(('Date de Naissance'), null=True, blank=True) phone_number = models.IntegerField(('N° de Téléphone'), null=True, blank=True) profile_completed = models.BooleanField(('Profile completé'), default=False) #DOCUMENTS TO UPLOAD id_card = models.FileField(('Carte Nationale d\'Identité'), upload_to='documents/CNI') drive_licence = models.FileField(('Permis de conduire'), upload_to='documents/PERMIS_CONDUIRE') police_record = models.FileField(('Casier judiciaire'), upload_to='documents/CASIER_JUDICIAIRE') carte_vitale = models.FileField(('Carte vitale'), upload_to='documents/CARTE_VITALE') medical_visit = models.FileField(('Visite médicale'), upload_to='documents/MEDICAL_VISIT') rib = models.FileField(('Relevé d\'Identité Bancaire (RIB)'), upload_to='documents/RIB') uploaded_at = models.DateTimeField(('Ajouté le'), auto_now_add=True) docs_are_checked = models.BooleanField(('documents verifés'), default=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() App/urls.py from django.conf.urls import url, include from django.contrib.auth import views as auth_views from . import views as core_views urlpatterns = [ url(r'^accounts/login/$', auth_views.login, {'template_name': 'login.html'}, name='login'), url(r'^accounts/logout/$', auth_views.logout, {'next_page': 'login'}, name='logout'), url(r'^accounts/signup/$', core_views.signup, name='signup'), url(r'^account_activation_sent/$', core_views.account_activation_sent, name='account_activation_sent'), url(r'^accounts/activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za- z]{1,13}-[0-9A-Za-z]{1,20})/$', core_views.activate, name='activate'), url(r'^accounts/email_confirmation_done/$', core_views.email_confirmation_done, name='email_confirmation_done'), url(r'^accounts/complete_profile/$', core_views.complete_profile, name='complete_profile'), url(r'^accounts/upload_files/$', core_views.upload_files, name='upload_files'), …