Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show images and use stylesheets in a vew for pdf rendering NOT using weasyprint
I want to use stylesheets and images in a template and then render it as pdf to download. At this point the pdf appears in the browser, the content loads correctly but the styles are not applied and there is no image. I don't want to use weasyprint. I am using Django 1.10, foundation sites 6.3.1, xhtmltopdf, pisa and here is the code I have. This is the view that renders the PDF @login_required def project_pdf_report(request, pk): project = get_object_or_404(Project, pk=pk) context = Context( { 'pagesize': 'A4', 'project': project } ) html = render_to_string(template_name='pdf_base.html', context=context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8', link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') else: return HttpResponse('Errors') This is the function that should fetch css styles and stuff def fetch_resources(uri, rel): if uri.startswith(settings.MEDIA_URL): path = os.path.join(settings.MEDIA_ROOT,uri.replace(settings.MEDIA_URL, "")) elif uri.startswith(settings.STATIC_URL): path = os.path.join(settings.LOADING_STATIC_FOR_PDF,uri.replace(settings.STATIC_URL, "")) return path And this is the html template that I want to use. {% load static i18n %} <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>{% block page_title %}{% endblock page_title %}</title> <meta name="description" content="Gutenberg"> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="author" content="david anchorena"> <link rel="stylesheet" href="{% static "/css/typography.css" %}"> <link rel="stylesheet" href="{% β¦ -
Heirarchical permissions
Kind of a django newbie. I'm making a CRUD app for learning and fun. I've seen some django apps that help with django object level permissions but I'm not sure which one is right. I've looked at django-guardian but it doesn't seem to do roles. Let's say I have an app with expenses that are small records of purchaes, commets, etc. Users create expenses. Users also report to managers who report to admins. A manager can see theirs and their users' expenses. A user can only see their expenses. Admins can see all of their managers and their user's expenses. t βββ admin_1 β βββ manager_1 β βββ manager_2 β βββ user_1 β β βββ expense β βββ user_2 β βββ expense βββ admin_2 βββ manager_3 βββ user_3 βββ expense I've used django groups and it sort of works out but a lot of manually checking permissions seems to happen. It works right now but I can tell this isn't the best way and it took longer than I'd like to confess. I was thinking of implementing a tree but I'd worry about DB performance. I've looked at things like django-teamwork and others but not sure which one is right β¦ -
Django favourite/compare feature
Just wondering if Sessions can be used to create a quick compare view of two products on my Django app. I'm listing items for sale and would like a user to be able to 'like' multiple items then have a new view to compare the selected products. Any thoughts? Thanks -
Django 1.7 getting ImportError, Cannot import name patterns
Right now when I attempt to do makemigrations, I get the infamous cannot import names pattern message, upon reviewing my urls.py file. I've been searching online for a potential solution given that I am working in Django 1.7, but I haven't found success. I still don't know why this is happening on my current version of django at all and any possible explanation on what could be causing it would be appreciated. In my urls.py file I have from django.conf.urls import patterns, include, url from django.views.generic import RedirectView from django.contrib import admin admin.autodiscover() from new_bridge import views urlpatterns = patterns('', url(r'^$', views.IndexView, name='index'), url(r'^admin/import', views.myimport), (r'^favicon\.ico$', RedirectView.as_view(url='/static/images/bridge_favicon.ico')), url(r'^words_page_redirect/(?P<language>[a-zA-Z]+)/$', views.words_page_redirect),.... ) and the final line of the message I get on terminal is simply File "/srv/bridge-repo/new_bridge/urls.py", line 1, in <module> from django.conf.urls import patterns, include, url Please let me know what other info I could provide to be of more help. Any input on what I could do to actually learn more about this issue, alongside resolve it, is appreciated. -
'question_text' is an invalid keyword argument for this function
I'm trying to follow the Polls tutorial I include both the urls.py, from the project and the models.py from the polls directory. q = Question(question_text="some text", pub_date=timezone.now)) yields the error text: 'question_text' is an invalid keyword argument for this function. mysite/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] polls/models.py import datetime from django.db import models from django.utils import timezone Create your models here. class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text -
What is the benefit of using python package for django frontend?
I don't understand why people use python package for frontend (css/js) i cant see the benefits. For example with python package django-bootstrap3 my form will use bootstrap3 style. i think just put bootstrap3 to static file easier than using and configure python package django-bootstrap3. The most important part is not everyone will understand what the package done and i think its gonna be bad idea to use those package. So, What is the benefit of using python package for Django frontend? -
Filling out a choice field in Django using other models
I want to make a choice field in a form that adds a choice every time I make a new instance in another model. Here is the relevant code: models.py class Instructor(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) class Schedules(models.Model): instructor = models.CharField(max_length=128) forms.py class ScheduleForm(forms.ModelForm): instructor = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'})) I want it so that each choice in the instructor choice field of the schedule form will always be first_name + ' ' + last_name and will add more choices each time a new Instructor instance is made. I heard that using ModelChoiceField is a good idea, but I only want part of the instances, not all of it. Do I need to use population or sqlite3 operations? Thanks. -
How to serve media from Amazon S3 in Django
I am trying to serve my media files from Amazon S3 on Django, but have not had any luck so far. This is my aws.conf file: import datetime AWS_ACCESS_KEY_ID = "AKIAJ2AON2BUBGCXMMIA" AWS_SECRET_ACCESS_KEY = "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" AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True DEFAULT_FILE_STORAGE = 'education_haiti.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'education_haiti.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'education-haiti' S3DIRECT_REGION = 'us-east-2' S3_URL = '//{}.s3.amazonaws.com/'.format(AWS_STORAGE_BUCKET_NAME) MEDIA_URL = '//{}.s3.amazonaws.com/media/'.format(AWS_STORAGE_BUCKET_NAME) MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' two_months = datetime.timedelta(days=61) date_two_months_later = datetime.date.today() + two_months expires = date_two_months_later.strftime("%A, %d %B %Y 20:00:00 GMT") AWS_HEADERS = { 'Expires': expires, 'Cache-Control': 'max-age=%d' % (int(two_months.total_seconds()), ), } This is a snippet from my html page: <div class="carousel slide" data-ride="carousel" id="carousel-1"> <div class="carousel-inner" role="listbox"> {% for story in stories %} {% if story.featured %} {% if forloop.first %} <div class="item active"> <img src="{{ story.article_picture.url }}" alt="Slide Whenever I run my server, however, the url for the article's given image is longer than it should be. For instance, if it is supposed to be domain/media/item.jpg it adds a long line containing Amazon Web Services request header settings. This is rather confusing because I did have this issue for serving static files at first, then resolved them when I β¦ -
Tree view from json Django
I have a backend that gives me a json response like this { "compiler": { "type": "GCC", "version": "5.4" }, "cpu": { "architecture": "x86_64", "count": 4 } } I need to visualize this response in the form of a tree. What should I do? Maybe try to transform it to django-model? Or something else? -
Get list of selected elements from dropdown menu to django view
I am new to UI design. My objective is to select the multiple items from a dropdown menu and send the selected to a django view. I wrote the entire code and able to select multiple fields using bootstrap+chosen but after submitting I am getting this error: "GET /static/app/css/chosen-sprite.png HTTP/1.1" 304 After searching in the web, I found out that this file is required as chosen saves the selected items in this file. I have this file in my css folder(downloaded from net) but dont know what I am doing wrong. Below is my code and right now I am printing the selected items in the same html page. Please help me :( project_select.html {% block body %} <p><br/></p> <div class="container"> <div class="row"> <div class="col-md-6"> <h3>Select projects:</h3> <form id="selectProject" role="search" method="get" action="{% url 'displayselectedprojects' %}"> <select form="selectProject" data-placeholder="Choose projects" class="chosen-select" multiple tabindex="4" name="params[]"> {% for project in project_names %} <option> {{ project.projectname }} </option> {% endfor %} </select> </form> </div> <div class=""> <h3><br></h3> <input type="button" value="Submit" style="padding: 4px 28px;border-radius: 4px;"> </div> </div> </div> <p>Here is selection:</p> <p>{{ title}} <br /> {{ projectList }}</p> <script src="http://harvesthq.github.io/chosen/chosen.jquery.js"></script> <script> $('.chosen-select').chosen(); </script> {% endblock %} urls.py url(r'displayselectedprojects/', views.displayselectedprojects, name='displayselectedprojects'), views.py def displayselectedprojects(request): selected_packages = β¦ -
Django 1.6: on a dropdown event, then filter a filter_horizontal widget?
Here is my code: class ClassName(models.Model): name = models.CharField(max_length = 32) class Student(models.Model): name = models.CharField(max_length = 32) id = models.CharField(max_length = 16) class Class(models.Model): name = models.ForeignKey(ClassName) # Event handler here? students = models.ManyToManyField(Student, blank = True, related_name = 'BackwardStudents') # The ClassAdmin class is for the Class model class... class ClassAdmin(admin.ModelAdmin): filter_horizontal = ['students'] What I actually want is when you select a ClassName, an event is triggered in order to filter the students in the filter_horizontal choice dialog. I want to select all of the Students that are attending that class when the ClassName is selcted -
multi-email login support (with different permissions)
Background I am designing a system (django + postgresql) that needs to support multi-email login support. When a user is logged in with Email1 then it will treated a different account and totally different account with Email2. For example, Think of slack (based on team, shows totally different functionality) with different emails support. I have researched it and found a github-library(multi-mail) for multi-email support, but this library only support multiple emails not the login support. I normally use djoser for authentication purposes as it provides most of the api functionality out of the way. My Approach I am thinking to add a new model EmailAddress which will have foreign key to user model and extend Djoser Authentication Backend to support multi-email login. Questions Is the above approach making any sense to you ? What are you thoughts ? How will sessions with work ? Can I login with multiple emails at the same time ? How will the permissions work with each email ? -
Python virtualenv switch to 3.5 from 2.7
How can I switch from python 2.7 to python 3.5 in virtualenv? I have already started my project in python 2.7 and I want to switch to 3.5 -
Django Context and Variables
I am currently using Django and Oscar to set up a shopping cart for someone. I am also using the django-oscar-stores extension. I was wondering if there is a way for me to incorporate the context of a django-oscar-stores view in to my other views and templates so I can use the variables to dynamically add the store information to the site. So if I go to the view of the stores app I can call a variable in that template {{ store_list }} but if I am in any other view I cannot access this variable. I understand why I cannot, but I was wondering how I would give access to the store_list variable so that I can use it on every page (so I can have the store information in the header of the site dynamically and not hard coded in to the template). I am new to Django, so sorry if this is a dumb question. -
Django - Converting from {{STATIC_URL}} to {% static %}
I have the following line of code in my base file: document.write('<img src="{{ STATIC_URL }}images/' + images[selected_image] + '" alt="' + images_text[selected_image] + '" title="' + images_text[selected_image] + '" class="image_random" />'); Recently I have upgraded from Django 1.6 to 1.11 and am switching from using STATIC_URL to using {% static %}. However, with this line of code in particular, I am having trouble with quotation parsing, given how the image is randomly selected and thus me using the document.write method in my base.html file. Could someone show me the proper way to do this conversion, since all of my attempts have failed (they always involve extraneous string literals, even when I am sure that I am balancing my quotes correctly. -
Django CSRF token missing and API
I am using django 1.11.2 and rest-framework 3.6.3 and the error about csrf token missing is always appearing when sending a react form to API. The annoying thing is that it appears to my only tester/helper (who is quite PC iliterate, that's why he is testing), not to me. I was able to reproduce the situation in private browsing only, the CSRF cookie is not appearing even when i set ensure_csrf_cookie on the view. Any ideas how to solve this? This is my settings: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'drf_braces', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.linkedin_oauth2', 'rest_auth.registration', (...) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', 'project.middleware.TimezoneMiddleware' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '60/minute', 'user': '60/minute' } } I have tried to use rest-framework's api_view decorator and also the ensure csrf decorator. Nothing helped. The view is class based (from FormView) and the post method, that doesn't work, looks like this: from rest_framework.decorators import api_view from django.utils.decorators import method_decorator #@method_decorator(ensure_csrf_cookie) @api_view(['POST','GET']) def post(self, request, *args, **kwargs): (...) -
How to submit/post multiple data value with the same name?
I have a form: <form method="post"> <div class="trip"> <select name="state" value="CA">California</select> <select name="city" value="SF">San Francisco</select> <select name="building" value="TR">Transamerica</select> </div> <div class="trip"> <select name="state" value="NY">New York</select> <select name="city" value="NYC">New York City</select> <select name="building" value="ES">Empire State</select> </div> <input type="submit"> </form> I'd like to post the values in an array to be process in the backend. Is there a way to building an array or structured data for django to process? -
Making Django-Jet autocomplete with TabularInlines
My team has been using "django-jet" as a skin to the admin in our django application. We have inlines with very large select widgets, so as the django-jet documentation recommends, we added autocomplete fields to our models. The problem is that it doesn't support TabularInlines. Inspecting django-jet's code you can see how what to change to make the widget work: Copy Django's admin "tabular.html" in your template dirs. Load jet_tags in the first line. Add the filter jet_select2_lookup to the fields. tabular.html 1 {% load i18n admin_urls static admin_modify jet_tags %} ... ... 55 {% if field.is_readonly %} 56 <p>{{ field.contents }}</p> 57 {% else %} 58 {{ field.field.errors.as_ul }} 59 {{ field.field|jet_select2_lookups }} 60 {% endif %} This approach works to add the autocomplete widget, but it fails with a "invalid option" error. At the same time, the widget doesn't seems to use the formfield_for_foreignkey method defined in the admin, so the queryset isn't filtered. Has anyone successfully added autocomplete to a TabularInline using django-jet? -
Django (FileField) + subprocess on video files, how to make it works with S3
I'm dealing with a lot of videos that I'm processing for Machine Learning purpose. I've now a storage problem on the server, as I receive the file from external sources and I recently switched to AWS. Thus I thought that S3 could be a good solution for my storage problem but no. After configuring the DEFAULT_FILE_STORAGE with django-storage, my model look like this: original_video = models.FileField( upload_to='media/videos/original', max_length=255 ) converted_video = models.FileField( upload_to='media/videos/converted', max_length=255, blank=True ) processed_video = models.FileField( upload_to='media/videos/processed', max_length=255, blank=True ) So, perfect, every file uploaded will go through s3, at least the original one. But now here is my second problem: I've celery tasks that take care of the processing and sometimes I need to do this kind of operations: def ffmpeg__clean_metadata(input_file_path, output_file_path): cmd = 'ffmpeg -fflags +genpts -y -i {input_file_path} -r 24 {output_file_path}'.format( input_file_path=input_file_path, output_file_path=output_file_path ) p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) p.communicate('') p.wait() return p.returncode Or this one: def ffmpeg__make_crossbrowser_video(input_file_path, output_file_path): write_to_temp_first = input_file_path == output_file_path original_output_file_path = output_file_path if write_to_temp_first: output_file_path = '{}.temp'.format(output_file_path) cmd = '{} {} {}'.format( 'ffmpeg -i {input_file_path} -y -strict experimental -acodec aac -ac 2 -ab 160k -vcodec libx264', '-s 640x480 -pix_fmt yuv420p -preset slow -profile:v baseline -level 3.0 -maxrate β¦ -
Reducing initialization overhead on Django app
I have a Django app that needs to do some expensive processing on requests. A large chunk of time is spent initializing the libraries used to perform the processing. I think the best way to avoid the initialization overhead would be to have a pool of workers that each initialize the libraries needed when they're started and then just service the requests. Is there a standard way of doing this in Django? Is there a better alternative? NOTE: The libraries do not keep state so I don't need to worry about resetting anything between requests. -
wagtail admin interface on django project
please anybody have idea on how to use the wagtail admin interface for my project instead of the usual django admin interface. i have tried installing wagtail as part of the project but django default admin interface is what my project is using. Or suggestions on how to overide the default django admin template will be helpful to me thanks -
Django_filters ModelChoiceFilter display text input
I am using Django_filters to create filters. I have to use ModelChoiceFilter due to foreign key in models. The filter automatically returns a drop down list, is there a way to display a text input box instead of drop down list when I use ModelChoiceFilter? Thanks code: GPA = django_filters.ModelChoiceFilter(name='persontoschool__GPA', queryset=PersonToSchool.objects.values_list('GPA',flat=True).distinct(),to_field_name='GPA', lookup_expr='gte') -
Login URL does not redirect, when the user is logged in succesfully in Django
I am trying to redirect the user to their Profile page when they have logged into their account, the redirect is not working and I do not get any errors in the terminal. I am using the latest version of Django. main urls from django.conf.urls import url, include from django.contrib import admin from authentication import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name="index"), url(r'^authentication/', include('authentication.urls')), url(r'^emails/', include('emails.urls')), url(r'^profiles/', include('profiles.urls',namespace='profiles')), ] profiles urls from django.conf.urls import url from profiles import views app_name='profiles' urlpatterns = [ url(r'^profile/(?P<user_id>\d+)/$', views.user_profile, name='user_profile'), ] profiles view def user_profile(request,user_id): return render(request,'profiles/detail/profile.html') login view if user is not None: login(request, user) return redirect('profiles:user_profile',request.user.id) -
Django (Wagtail CMS) Taggit : tag filtering probleme
I used Django with Wagtail CMS I need to filter BlogPages based on "li" id supposed that i have News when i click the link it should show all blogpages with "News" tag i hope someone help me :D because this one wasted lot of my time :/ and thanks My files : note : i removed all taggit installation based on documentaion models.py from __future__ import absolute_import, unicode_literals from django.db import models from modelcluster.fields import ParentalKey from wagtail.wagtailcore.models import Page, Orderable from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel from wagtail.wagtailsearch import index class BlogIndex(Page): def get_context(self, request): context = super(BlogIndex, self).get_context(request) blogpages = self.get_children().live().order_by('-first_published_at') context['blogpages'] = blogpages return context class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'),], heading="Blog information"), FieldPanel('intro'), FieldPanel('body'), ] blog_index.html {% extends "base.html" %} {% block body_class %}template-blogindex{% endblock %} {% block content %} {% include "blog/snippet/header.html" %} {% include "blog/snippet/top_slider.html" %} {% include "blog/blog_index_posts.html" %} {% endblock %} blog_index_posts.html {% block content %} #style ... <ul class="nav nav-pills "> <li id="Latest" role="presentation" class="active" ><a href="#">Latest</a</li> <li id="News" role="presentation" ><a href="#">News</a></li> <li id="Aricles"role="presentation""><a href="#">Aricles</a></li> <li id="Reviews" role="presentation"><a href="#">Reviews</a></li> <div class="container" style="padding-top:9px;min-height:396px;width:100%"> <div β¦ -
Sending mail via smtp in Django
I'm trying to send a simple email using python/django shell and have been strugling with this problem for the last few hours: in django shell i do the following: from django.core.mail import send_mail send_mail('django mail', 'this was sent with django', 'myaddress@gmail.com',['myaddress@gmail.com'], fail_silently=False) the returned result should be 1, meaning that the mail is sent successfully, but insead, i get this: raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbu9\n5.7.14 0cv5jjPsAITCLvsSIKoDuJcz5I18H7PMX8Nsxz2ajtgAJfxls4wIKIVMUENCrFmoXNHdgM\n5.7.14 NpSKlFYuaGHtwqDodV09jIf_GaDklCUUzJLY7oSJITQqXADDWxYRU7LUbVRFPxwpd2cKzl\n5.7.14 g70grCboTaCtEofq3-5edwoRC0ukZT-z97AgOelTTvSteaEjuf5n7F417VvFFE1hXcBnyg\n5.7.14 n2NWXBFMlV_74532aXU0vguceCC84> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 2sm2181268wrn.24 - gsmtp') I read the url suggested in the error, and also a few similar questions on the web, and there were no good it them for me. also, in the settings.py file, the required code is included: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'me@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 as i mentioned above, the other questions/problems on this site weren't the same. I've already enable the access for less secure apps on my gmail account, and also i have no two step verification.