Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add a static .txt file inside a text area using Django tags?
So I have this text area: <textarea id="input_txt" name="file_txt" class="input_size" rows="5" form="store" style="font-size: 11pt;" default_text="{{ file.txt }}">{% if store.file %}{{ store.file }} {% else %}{{ file.txt }}{% endif %}</textarea> I want to add a default txt file inside a text area if store.file is empty. Is there a way to add the text file inside the text area using Django Tags? -
redirect django runserver output in order to debug with pudb
I'm currently trying to use pudb to troubleshoot a django application. In order to do so, I'm running the runserver instead of gunicorn. Then, when I want to debug, I added: import pudb; pu.db The pudb gui shows up correctly but is quickly garbled by the runserver output. As per pudb documentation, I can avoid this by setting the PUDB_TTY variable before starting the server. $ tty /dev/pts/3 $ PUDB_TTY=/dev/pts/3 manage.py ... runserver ... Unfortunately, the GUI still gets garbled by the output of the server. Alternatively, I tried to redirect all output from the runserver (>/dev/null 2>&1), but the pudb output also get caught (obviously). Is there a way to: have the runserver not produce any output? tweak pudb ? -
ValueError at /new_animal/7/
I get a ValueError at /new_animal/7/ here is the error message:invalid literal for int() with base 10: b'11 02:07:39.299546' It sends me to my base.html file saying there's an error at "line 0". My base.html file contains the bootstrap. Here is my new_animal.html file: {% extends "zoo_animal_feeders/base.html" %} {% load bootstrap3 %} {% block header %} <h2><a href="{% url 'zoo_animal_feeders:animal_type' animal_type.id %}">{{ animal_type }}</a></h2> <h2>Add new animal:</h2> {% endblock header %} {% block content %} <form action="{% url 'zoo_animal_feeders:new_animal' animal_type.id %}" method='post' class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name='submit'>add animal</button> {% endbuttons %} </form> {% endblock content %} Let me know if I need to show you more of my project. -
Python gives error because the data is not there yet?
I wrote this code: from __future__ import print_function import requests from .forms import reisplannerForm import xmltodict import json beginstation = '' eindstation = '' def createForm(request): global beginstation global eindstation if request.method == 'POST': form = reisplannerForm(request.POST) if form.is_valid(): beginstation = form.cleaned_data['beginstation'] eindstation = form.cleaned_data['eindstation'] print(beginstation, eindstation) form = reisplannerForm() return form def apiLinkGenerator(): auth_details = ('email@gmail.com', '-password') api_url = 'http://webservices.ns.nl/ns-api-treinplanner?fromStation={}&toStation={}&departure=true'.format( beginstation, eindstation) response = requests.get(api_url, auth=auth_details) vertrekXML = xmltodict.parse(response.text) nsDump = json.dumps(vertrekXML) jsonLoads = json.loads(nsDump) jsonData = jsonLoads['ReisMogelijkheden']['ReisMogelijkheid'] return jsonData def main(): data = apiLinkGenerator() print('Dit zijn de vertrekkende treinen naar {}: '.format(eindstation)) for data in data: # Reis informatie vertrekTijd = data['GeplandeVertrekTijd'] actueleReisTijd = data['ActueleReisTijd'] status = data['Status'] aantalOverstappen = data['AantalOverstappen'] # Reis Deel reisDeel = data['ReisDeel'] vervoerder = reisDeel[0]['Vervoerder'] vervoerType = reisDeel[0]['VervoerType'] reisStops = [] print('Om {} vertrekt er een trein naar {} met de vervoerder {} {}'.format(vertrekTijd[11:16], eindstation, vervoerder, vervoerType)) print('De actuele reistijd naar {} is {}, de status is {}. Overstappen: {}'.format(eindstation, actueleReisTijd, status, aantalOverstappen)) for stops in reisDeel[0]['ReisStop']: stopNaam = stops['Naam'] reisStops.append(stopNaam) print(*reisStops, sep=', ') return vertrekTijd, actueleReisTijd, status, aantalOverstappen, reisDeel, vervoerder, vervoerType, reisStops vertrekTijd, actueleReisTijd, status, aantalOverstappen, reisDeel, vervoerder, vervoerType, reisStops = main() it works but I added the vertrekTijd, actueleReisTijd, status, aantalOverstappen, … -
Django REST Framework Web Login not working
I can't seem to figure out why my rest framework login in my django project won't work... I have got the log in link there and all and it does redirect me to the rest login page but after filling in my credentials and clicking login it just takes me back to the page I came from but it does not seem to authenticate me as it still says "Login" in the top right corner... I would expect it to change to "admin" in this case as I am trying to login using my superuser named "admin"... I am surely missing something.. Here are my REST Urls path("rest/auctions", auction_list, name="auction-list"), path('rest/auctions/<int:pk>', auction_detail, name="auction-detail"), path('rest-auth/', include('rest_framework.urls', namespace='rest_framework')), The rest-auth/ one I know is the one that somehow adds the login button and all (Magic?) But maybe I have to do something else too to make it authenticate? I don't know... I am using the built in django authentication system and User model. views.py @api_view(['GET']) def auction_list(request, format=None): if request.method == 'GET': query = request.GET.get('q') if query is not None: auctions = Auction.objects.filter(Q(title__icontains=query), deadline__gte=timezone.now(), status=Auction.STATUS_ACTIVE) else: auctions = Auction.objects.all() serializer = AuctionSerializer(auctions, many=True, context={'request': request}) return Response(serializer.data) serializer.py class AuctionSerializer(serializers.ModelSerializer): winning_bid = … -
Using join of temporary table as an alternative of `IN` in Django
In Django it's common to do the following MyModel.objects.filter(id__in=[huge array]) However it's not very efficient as described in the following answer here: https://dba.stackexchange.com/questions/91247/optimizing-a-postgres-query-with-a-large-in What would be a good way of replicating the above answer in Django given that you are using the ORM. Or would you have to drop down to raw sql for the entire query. What I'm looking for is if you have a queryset, is there a good way of joining that queryset with a temporary table that you created (possibly in raw sql). -
change size of form post box?
Hi I would like to change the size of my form post box, its quite long. I was wondering how I would change it with my code below: home.html: {% extends 'base.html' %} {% block body%} <div class="container"> <br/> <form method="post"> {% csrf_token %} {{ form.post }} <br /> <button type="submit">Submit</button> </form> <h2>{{ text }}</h2> {% for post in posts %} <h1>{{ post.post }}</h1> <p>Posted </b> on {{ post.created }}</p> {% endfor %} </div> {% endblock %} base.html: <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% block head %} <title>anonmy</title> {% endblock %} </head> <body> <br> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div id="navbar" class="navbar-collapse collapse"> {% if user.is_authenticated %} <ul class="nav navbar-nav"> <li><a href="{% url 'home:home' %}"><b>anonmy</b></a></li> <li><a href='{% url 'home:categories' %}'>categories</a></li> <li><a href="{% url 'accounts:view_profile' %}">profile</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="{% url 'accounts:logout' %}">log out</a></li> </ul> {% else %} <ul class="nav navbar-nav"> <li><a href="{% url 'accounts:login' %}">anonmy</a></li> <li><a href="{% url 'accounts:login' %}">login</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="{% url 'accounts:reset_password' %}">forgotten password?</a></li> <li><a href="{% url 'accounts:register' %}">register</a></li> </ul> {% endif … -
handling kwargs in POST and CBV
In my last question, I had trouble displaying imported choices in a select widget because I was missing a (should have been) obvious bit of code. Now, my GET (seems to) work just fine. The problem is I am doing something wrong in my POST. What I can't figure out is how the kwargs should be handled in POST. If I include kwargs in my post method in the line form = Enter_SW_Room(request.POST, **kwargs) I receive the error "init() got multiple values for argument 'data'". Looking around stack overflow, I find most of the problems with this error stem from calling self in super (or other calling errors). E.g. this problem / solution. If I try to work around this problem by NOT passing kwargs, the validation fails. (I think because there is now a value for the appropriate field, but the choices are gone.) So, what I figure is that either I'm doing something simple but importantly wrong again, or I need to modify the form validation. (or ???) Here's all the code (snipped for brevity): ''' views.py ''' class DockingBay(FormMixin, TemplateView): form_class = Enter_SW_Room def get_form_kwargs(self): kwargs = super().get_form_kwargs() # snip; create my_avatar_choices, which is more than just … -
Python Django based eCommerce framework Shuup setup issue on centos?7
I want to install and used the python and Django based eCommerce solution. https://www.shuup.com/ I have followed as mention in SHUUP https://shuup.readthedocs.io/en/latest/howto/getting_started.html but I can't move beyond step-5 which syas Once you have configured the Shuup apps you would like to use, run the following commands to create the database and initialize Shuup python manage.py migrate python manage.py shuup_init its says that python: can't open file 'manage.py': [Errno 2] No such file or directory I understand that the file is missing but can't understand how to solve the issue. I am new to python and unable to figure it out what I am missing I have tried on shuup community blog but I can't find anything useful. -
Form validation error not being raised in django
I cannot get my Django form to raise a validation error when I try to create a custom field validation. I can see the new hidden input field, but when I try to enter a value it doesn't seem to detect an error. I also tried def clean(self) instead of 'clean_honeypot' and that didn't work either. What am I doing wrong? forms.py: from django import forms class SuggestionForm(forms.Form): name = forms.CharField() email = forms.EmailField() suggestion = forms.CharField(widget=forms.Textarea) honeypot = forms.CharField(required=False, widget= forms.HiddenInput, label="Leave Empty") def clean_honeypot(self): honeypot = self.cleaned_data['honeypot'] if len(honeypot) > 0: raise forms.ValidationError( 'Honeypot should be left empty. Bad bot!' ) return cleaned_data views.py: from django.contrib import messages from django.core.mail import send_mail from django.urls import reverse from django.http import HttpResponseRedirect from django.shortcuts import render from . import forms def hello_world(request): return render(request, 'home.html') def suggestion_view(request): form = forms.SuggestionForm() if request.method == 'POST': form = forms.SuggestionForm(request.POST) if form.is_valid(): send_mail( 'Suggestion from {}'.format(form.cleaned_data['name']), form.cleaned_data['suggestion'], '{name} <{email}>'.format(**form.cleaned_data), ['leigh.christopher2@gmail.com'] ) messages.add_message(request, messages.SUCCESS, "Thanks for your suggestion") return HttpResponseRedirect(reverse('suggestion')) return render(request, 'suggestion_form.html', {'form': form}) template: {% extends "layout.html" %} {% load static %} {% block title %}Suggest an idea!{% endblock %} {% block content %} <div class="container"> <div class="row"> <form action="" method="POST"> {{ … -
Deploying Django with uwsgi and nginx, uwsgi ok but nginx not working
I am trying to run my site, when i run uwsgi --socket 0.0.0.0:8080 --protocol=http --chdir /opt/virtualenv/landivarpj/ --wsgi-file /opt/virtualenv/landivarpj/landivarpj/wsgi.py i can access 192.xxx.xxx.xxx:8080 fine and my test text appears, but if i try to go trought 192.xxx.xxx.xxx i only get an nginx welcome page, and if i try to go in trought my domain www.xxxxxxxx.com, then it doesnt work at all. in my project folder(opt/virtualenv/landivarpj) i have a uswgi_params file with uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name; then in (opt/virtualenv/landivarpj/landivarpj) the wsgi.py is import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "landivarpj.settings") application = get_wsgi_application() in etc/nginx/sites-available is have drlandivar.conf upstream django { server 192.254.145.207:8080; # for a web port socket (we'll use this first) } server { listen 80; server_name drlandivar.com www.drlandivar.com; charset utf-8; client_max_body_size 75M; # adjust to taste location /media { alias /opt/virtualenv/landivarpj/media; } location /static { alias /opt/virtualenv/landivarpj/static; } location / { uwsgi_pass django; include /opt/virtualenv/landivarpj/uwsgi_params; } } the site-available and site-enable are linked what have i done wrong why it … -
Setting the string representation of models.DateTimeField()
I'm trying to set a __str__ function for a DateTimeField in a Django model. I've found how to do it for a full model, but not for a DateTimeField. Right now datetime fields are being sent to the template as: 2018-10-24T13:31:06Z Do I have to create a custom field, inherit DateTimeField, then set the __str__ method there? If so, any code to help? This is for an API which doesn't use a template, so I want to solve this in models.py, not with template filters. -
Django: create view inline generic update view
I am working on Django 1.11. I have two models, the first one has a foreign key like this : class Book(models.Model): name=models.CharField(max_length=100) owner = models.ForeignKey(Owner, on_delete=models.PROTECT, null=True, default=None) other_properties class Owner(models.Model): some_property I use the generic.UpdateView to update my Books : class BookUpdateView(generic.UpdateView): model = Book fields = ['owner'] This works but now I want to create an Owner from the BookUpdateView page, and then modify the book to set the owner property to the newly created Owner. Is it possible to have an inline form to create an Owner inside the BookUpdateView ? (not in the admin pages) Or maybe to have a separate create view for the owner which redirect to the BookUpdateView from where it was called. But only when it was called from there ? Thanks for any suggestion! -
Resolving URL based on Requesting Namespace
I am building a website that has about 10 instances of the same app. These different instances will just be used to serve different files on different pages. Everything is working except when I go to a different instance of the application and go to the detail view it reverts back to the original application's URL and namespace. For example, going to /university/term-syncc/ and clicking on an item in the list view redirects me to /marketing/4/ or whatever the ID is of that item. If I go to /university/term-syncc/4/it works but I cannot get that URL to resolve automatically. I know it has something to do with my get_absolute_url calling the assets namespace but how can I force it to check the current app namespace and then run a reverse from there? models.py def get_absolute_url(self): return reverse("assets:asset_detail", kwargs={"id": self.id}) HTML <li> <a href="{{obj.get_absolute_url}}">{{ obj.name }} test</a> </li> urls.py url(r'^$', asset_list_view, name="asset_list"), url(r'^(?P<id>\d+)/$', asset_detail_view, name='asset_detail'), -
Django how to handle two forms with one-to-many relationship between models in one post
For the sake of simplicity, here is a short version of the issue I am dealing with. Say you have two models, Product and ProductPricing, with Product having many ProductPricing instances and a product pricing is related to only one product (one-to-many relationship). The model's clean method: models.py: class ProductPricing(models.Model): product = models.ForeignKey(Product, related_name = 'prices', verbose_name = 'Price', blank = True, null = True) customer = models.ForeignKey(Customer, related_name = 'customer_pricings', blank = True, null = True) ... def clean(self): if not self.product and not self.customer: raise ValidationError(_('Pricing requires either a product or a customer. None is provided') ) forms.py: class ProductPricingAddonForm(ModelForm): class Meta: model = ProductPricing fields = ['UOM', 'cost_per_UOM', 'product'] Now, In my UpdateView, I am doing something like this: class UpdateProductView(View): template_name = 'product.html' product_form = ProductForm pricing_form = ProductPricingAddonForm def get(self, request, *args, **kwargs): product_id = kwargs.get('pk', None) product = Product.objects.get(id = product_id) product_form = self.product_form() pricing_form = self.pricing_form() c = {} c['product_form'] = product_form c['pricing_form'] = pricing_form return render(request, self.template_name, c) def post(self, request, *args, **kwargs): ''' To update both the models in one go''' product_id = kwargs.get('pk', None) product = Product.objects.get(id = product_id) product_pricing = ProductPricing.objects.filter(product = product) product_form = self.product_form(request.POST if any(request.POST) else … -
python-social-auth (Django) - how to send disconnect request from ionic 3 app
I'm writing Ionic 3 app with Django backend. I have already managed to login this way with facebook (with social_django), but i can't afford to disconnect from it (so removing my app from my facebook app's list). Here some parts of my code: setting.py SOCIAL_AUTH_FACEBOOK_KEY = '**********************' SOCIAL_AUTH_FACEBOOK_SECRET = '***********************' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'main.views.register_social', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) SOCIAL_AUTH_DISCONNECT_PIPELINE = ( # Verifies that the social association can be disconnected from the current # user (ensure that the user login mechanism is not compromised by this # disconnection). 'social_core.pipeline.disconnect.allowed_to_disconnect', # Collects the social associations to disconnect. 'social_core.pipeline.disconnect.get_entries', # Revoke any access_token when possible. 'social_core.pipeline.disconnect.revoke_tokens', # Removes the social associations. 'social_core.pipeline.disconnect.disconnect', ) urls.py urlpatterns = [ url(r'^register-by-token/(?P<backend>[^/]+)/$', register_by_access_token, name = 'register_by_access_token'), url(r'^disconnect-from/(?P<backend>[^/]+)/$', disconnect_from_facebook, name = 'disconnect_from_facebook'), ] views.py from social_core.actions import do_disconnect from social_django.utils import psa @psa('social:complete') def register_by_access_token(request, backend): token = request.GET.get('access_token') user = request.backend.do_auth(token, ajax = True) if user: login(request, user) return HttpResponse() else: return HttpResponseBadRequest() @csrf_exempt def disconnect_from_facebook(request, backend): user = request.user username = user.username utente = Utente.objects.get(username = username) do_disconnect(backend, user = utente) def register_social(backend, user, response, strategy, *args, **kwargs): member_exists = Utente.objects.filter(user_ptr = user).exists() strategy = backend.strategy if member_exists: … -
defaced admin panel Extending the User model with custom fields in Django
I added some fields to django user so I can define permission levels to users . by choosing each level in admin panel , you can access certain part of website . but when i go to user panel in admin template , it work fine but defaced . here is my codes : models.py: class CustomUser(AbstractUser): is_level_one = models.BooleanField(default=False) is_level_two = models.BooleanField(default=False) is_level_three = models.BooleanField(default=False) admin.py(simple version) admin.site.register(CustomUser) and this is the defaced view of admin user here : first image of /admin/basic_app/user second image of /admin/basic_app/user you see these are the problems : 1.user permission box is gone and you can not assign permissions to users 2.last login and date join are separated 3.group box is almost gone 4.password field is filled with hashed password *but the 3 access levels i defined are still there ( you can see the in the bottom of the page as check boxes and actually works fine ) * and here is my decoration codes if someone needs to use the : def level_one_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, refused='basic_app:index'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_level_one, login_url=refused, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator -
Can't run a specific django project in a virtualenv
I need to edit but first run this project: https://pagure.io/fedora-commops/fedora-happiness-packets and it gives me errors even though I followed the instructions. First I forked the repo, then cloned it to my computer and I followed the instructions listed in the setup section of the README.md file. When I run the command ./manage.py collectstatic I get this error: Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/alexmarginean/Desktop/fed/fedora-happiness-packets/virtualenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/alexmarginean/Desktop/fed/fedora-happiness-packets/virtualenv/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/Users/alexmarginean/Desktop/fed/fedora-happiness-packets/virtualenv/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/alexmarginean/Desktop/fed/fedora-happiness-packets/virtualenv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/alexmarginean/Desktop/fed/fedora-happiness-packets/virtualenv/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/alexmarginean/Desktop/fed/fedora-happiness-packets/happinesspackets/messaging/models.py", line 15, in <module> from happinesspackets.tasks import send_html_mail File "/Users/alexmarginean/Desktop/fed/fedora-happiness-packets/happinesspackets/tasks.py", line 3, in <module> from happinesspackets._celery import app File "/Users/alexmarginean/Desktop/fed/fedora-happiness-packets/happinesspackets/_celery.py", line 2, in <module> from celery import Celery ImportError: No module named celery I tried importing celery but that method didn't work and I don't want to mess with the project. -
TypeError when making a Django sorting table with pagination
I tried to create a table with header sorting and pagination in Django using the answer provided on this question: django sorting table with pagination However, when I try to implement it, I get this TypeError: expected string or bytes-like object Where am I going wrong and what can I do to fix this? views.py def DocumentView(request, **kwargs): order_by = request.GET.get('order_by') direction = request.GET.get('direction') ordering = order_by if direction == 'desc' ordering ='-{}'.format(ordering) documents = AnalyticDocument.objects.all().order_by(ordering) themes = AnalyticDocument.objects.all().distinct('theme') paginator = Paginator(documents,5) page = request.GET.get('page') documents = paginator.get_page(page) return render(request, 'documents.html' {"documents":documents,"themes":themes,"order_by":order_by,"direction":direction}) Here is how I display data in my templates <thead> <tr class="thead"> <th style="font-weight:bold;"> <a href="?order_by=title&direction=asc">Name Asc</a> <a href="?order_by=title&direction=desc">Name Desc</a> </th> <th style="font-weight:bold;"> <a href="?order_by=uploaded_at&direction=asc">Uploaded at Asc</a> <a href="?order_by=uploaded_at&direction=desc">Uploaded at Desc</a> </th> <th style="font-weight:bold;"> <a href="?order_by=upload.size&direction=asc">Size Asc</a> <a href="?order_by=upload.size&direction=desc">Size Desc</a> </th> <th style="font-weight:bold;"> <a href="?order_by=theme&direction=asc">Theme Asc</a> <a href="?order_by=theme&direction=desc">Theme Desc</a> </th> <th style="font-weight:bold;"> <a href="?order_by=sensitivity&direction=asc">Sensitivity Asc</a> <a href="?order_by=sensitivity&direction=desc">Sensitivity Desc</a> </th> </tr> </thead> My pagination code: <div class="pagination"> {% if documents.has_previous %} <a href="?page=1"><<</a> <a href="?page={{ documents.previous_page_number }}"><</a> {% endif %} {% for num in documents.paginator.page_range %} {% if documents.number == num %} <strong> {{ num }} </strong> {% elif num > documents.number|add:'-5' and num < documents.number|add:'5' %} {{ num … -
Django + uwsgi + nginx broken pipe
I'm doing a stress test with JMeter and with 200 users in concurrency I'm getting this error in the uwsgi.log: Wed Oct 24 09:40:50 2018 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during GET And this error in the nginx error log: connect() to unix:/var/run/app.sock failed (11: Resource temporarily unavailable) while connecting to upstream, server: domain.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/var/run/bbrainers.sock:" How can the server support more than 200 concurrent users? This must be a wrong configuration I think... -
use weasyprint to generate a pdf in django
I want to use weasyprint to generate a pdf reporting I think weasyprint generate a pdf from an html file First I realize this task : views.py class TypeFact_detail_factures(DetailView): model = TypeFact template_name = 'TypeFact_detail_factures.html' def get_context_data(self, **kwargs): context = super(TypeFact_detail_factures, self).get_context_data(**kwargs) tasks_dev = Factures.objects.filter(type_fact=self.object) # champs de liaison context['tasks_dev'] = tasks_dev return context in models.py class TypeFact(models.Model): type = models.CharField(max_length=50, verbose_name="Type") def __str__(self): return self.type class Factures(models.Model): num_fact = models.CharField(primary_key=True, max_length=50, verbose_name="Numero") type_fact = models.ForeignKey('TypeFact', on_delete=models.CASCADE, verbose_name='Type_Facture') importance = models.IntegerField(verbose_name="Importance",null=True, default=None, blank=True) closed = models.BooleanField(default=False) def __str__(self): return self.num_fact + "/" + str(self.type_fact) example of result enter image description here the result is based of 2 model (tables) and when I try to generate a pdf file it recongnize just one, than the data of the other table is not generate I used the same template with this def in views.py def print_pdf1(request, pk): typefact = get_object_or_404(TypeFact, id=pk) html = render_to_string('pdf.html', {'typefact': typefact}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=\"factype.pdf"'.format(typefact.id) ) weasyprint.HTML(string=html).write_pdf(response) return response the pdf is generated but with only the data of typefact withou factures data I need your helps thanks -
How I can get all languages in urls django i18n?
I plugged in i18n patterns module to my urls and added some languages: urlpatterns += i18n_patterns( path('blog/', include('blog.urls')), path('contacts/', include('contacts.urls')), path('signup/', views.signup, name='signup'), path('login/', auth_views.login, {'template_name': 'login.html'}, name='login'), path('logout/', auth_views.logout, {'next_page': 'login'}, name='logout'), ) LANGUAGES = ( ('ru', 'Russian'), ('en', 'English'), ('es', 'Spain'), ) But the only language I see in urls its a language that I set up in LANGUAGE_CODE parameter and the only valid link I have it is a link with a language_code parameter. For example, now I see 'en', but I need to see 'ru' and 'es' and etc.. What should I need to do with it in order to get all another languages here? If I set up a prefix_default_language=False, so I couldn't even get a default language (and all others respectively) [name='home'] languages/ admin/ en/ ^media\/(?P<path>.*)$ -
Google Developer API for in app subscription receipt check(insufficient permissions issue)
I want to use Purchases.subscriptions:get. in my django server My Google API's project is linked my android application. And i used service account(json) of Google API, service account's permission is project's owner and google play console's admin. This is my code from oauth2client.service_account import ServiceAccountCredentials from httplib2 import Http from googleapiclient.discovery import build scopes = ['https://www.googleapis.com/auth/androidpublisher'] credentials = ServiceAccountCredentials.from_json_keyfile_name('service_account.json', scopes) http_auth = credentials.authorize(Http()) androidpublisher = build('androidpublisher', 'v3', http=http_auth) product = androidpublisher.purchases().products().get(productId="", packageName="", token="") purchase = product.execute() This is response. The current user has insufficient permissions to perform the requested operation What's wrong???? -
Using the django admindocs without adding 'contrib.admin' to the INSTALLED_APPLICATIONS
we want to document a little bit of our application for the customers prosumers. But we don't want to expose the whole admin interface or include that whole block of code in our production environment. What approaches could we look at to add the admindocs (django docs for this) without adding the admin site? The reason this is asked is due to the fact that a removal of the django.contrib.admin app leads to Django Version: 1.10.5 Exception Type: TemplateDoesNotExist Exception Value: admin/base_site.html Exception Location: /usr/local/lib/python3.5/site-packages/django/template/engine.py in find_template, line 146 Python Executable: /usr/local/bin/python -
can I pass sql query in the JWT payload to make a graph in Metabase?
I want to create different user specific Metabase graphs and display it on my Django website. Is there a way to pass sql query in the JWT payload from django to create the graph in metabase?