Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add django-simple-captcha to django-allauth
I want to add captcha on signup and password_reset, so is there a way to add django-simple-captcha to django-allauth (django-recaptcha is not available in my region)? Thanks. -
How to use django-tus?
Could you give an example of implenenting django-tus https://github.com/alican/django-tus? Using django's FileField -
Building a basic function calling api using Django
I'm trying to build a very basic api, that for a given input, computes an output using existing functions and spits them out as a json. Keeping in mind, I'm new to Django, a lot of videos and tutorials are just going above my head ! -
Django tasks, reminders, notifications
I have a fairly simple web app in Django (Apache, Ubuntu) for keeping some meetings documentation. Meetings have their appointment time stored in database (postgres) in datetime format. Now, I'd like to have a custom reminder module that would enable to user to setup their preferred reminders. For example: Meeting will be held at a certain date (let's say 25th of April 2018, 8:00 PM) and user should be able to setup a custom reminder (via SMS for example but the question is not about the sending texts or emails - I got this covered) to be fired up 24h before the time of meeting. It got me thinking that this requires some kind of a permanent process browsing through the meetings table and checking if now() is the appointment time -24h and if yes then perform the reminder. I started with rabbitmq and celery but these look a bit complicated at first glance (here's one of the tutorials I found) and looks like it's not designed for what I need. So, question is - how to setup a permanent process that would check if a set reminder time is now and if yes - perform the reminder task? -
How to use Python script in Django using AJAX or something like that?
Sorry for a badly asked question! I am building an IoT project for schools and colleges written in Django framework. I am using Raspberry Pi in the project and database and web is hosted on DigitalOcean. So, My Raspberry Pi takes care of hardware side, i.e. RFID, Fingerprint, etc and DigitalOcean takes care of admin stuff just for viewing purposes. Now, I have written a script that enrolls students in the database with RFID and Fingerprint and to make purchases in the canteen. It is working without any issues but problem is that there is no GUI to add students or to make purchases. I am using the terminal as of now, which is okay as I can use that stuff but the real operator doesn't know anything about terminal or virtualenv or any of that. So My terminal script is totally useless for them, plus that can expose code. So I have decided to create a web interface for them, where the operator can easily add students and do stuff. I think I can use JSON-AJAX to do that but don't know how. RFID and Fingerprint will return string once successfully scanned, and I need to use those on … -
my nginx cannot load uwsgi on Ubuntu 16.04
trying to run django app "mysite" through uwsgi with nginx on Ubuntu 16.04, but when I start uwsgi and check in my browser, it just hangs. i set django upstream socket to on port 8002 and nginx to listen on 8003. In the browser i visit 192.168.0.17:8003 prior to running uwsgi and it throws 502 which is expected, so I start uwsgi with uwsgi --http :8002 --module mysite.wsgi --logto /tmp/uwsgi.log --master and 8003 now hangs when I reload in the browser. I looked through /var/log/nginx/error.log but it's blank (so is access.log). Here is nginx config, which is symlinked to /etc/nginx/sites-enabled: sudo nano /etc/nginx/sites-available/mysite_nginx.conf # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8002; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8003; # the domain name it will serve for server_name 192.168.0.17; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/myusername/uwsgi-tutorial/mysite/media; # your Django project's media files … -
Does django hits the database when you request for an object's attribute from a chached query?
I'm having trouble to understand how to properly use the Caches Framework. lets say I have this code: class Book(models.Model): title = models.CharField() author = models.ForeignKey(User) @classmethod: def get_all_books(cls): query = cache.get_or_set( 'all_books', cls.objects.all() ) return query now I know that every time that I run Book.get_all_books() it returns the already cached result. but what if I run this code in shell: >>> list = listBook.get_all_books() >>> list[0].title # does this line hits the database? >>> list[0].author # does this line hits the database? >>> list.filter(title='for dummies') # does this line hits the database? what did I missed to study? can you please guid me? thank you in advance. -
django max retries exceed with url
I am new to django. I have an API that when I am trying to call it, I get the following error: {ConnectionError}HTTPConnectionPool(host='testserver', port=80): Max retries exceeded with url: #my_url (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000002060CBFB2E8>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',)) If any code is needed please tell me to add. The problem is not solved using this question answers. p.s The problem does not seem to be from my API because I have a breakpoint at the beginning of it, but is not reached. -
What is the meaning of redirect_field_value in django
What is the meaning of this code? {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} -
No module named 'stripe' in production on Heroku - Django App
I have install the Stripe module to accept payment on my app. Everything is working as a charm on local but since I pushed my app on Heroku I cannot access it anymore and I get an error message that Exception Type: ModuleNotFoundError Exception Value: No module named 'stripe' Here is my code: from Authentication_project import settings from django.views.generic import TemplateView from django.shortcuts import redirect import stripe from django.contrib import messages stripe.api_key = settings.STRIPE_SECRET_KEY class payment_form(TemplateView): template_name = "transaction.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_key'] = settings.STRIPE_PUBLIC_KEY return context def checkout(request): import pdb; pdb.set_trace() if request.method == "POST": token = request.POST.get("stripeToken") price = 6000 volume = int(request.POST.get("credit")) final_price = price * volume try: charge = stripe.Charge.create( amount=final_price, currency="usd", source=token, description="SoftScores Team Assessment", receipt_email=request.user.email, ) user = request.user user.credit = user.credit + volume user.save() except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught body = e.json_body err = body['error'] messages.error(request, "There was a problem processing your payment: %s" % err['code']) return redirect('website:payment') else: return redirect('website:create_project') The error is on line 4: Import stripe. I searched on the web, but no idea how to solve it .. Any idea ? -
noreversematch django form error
I am new in django for. I am getting NoReverserMatch from django form, could you please suggest some way to get rid of this error. Thanks for the help in advance. here is my view.py from django.shortcuts import render from django.http import HttpResponse from myapp.models import Students from django.db import connection from myapp.forms import LoginForm def datasent(request): text = "Data sent" return HttpResponse(text) def insertmenu(request): return render(request,"insertmenu.html") def login(request): username = "not logged in" if request.method == "POST": #Get the posted form MyLoginForm = LoginForm(request.POST) if MyLoginForm.is_valid(): username = MyLoginForm.cleaned_data['username'] else: MyLoginForm = Loginform() return render(request, 'loggedin.html', {"username" : username}) forms.py #-*- coding: utf-8 -*- from django import forms class LoginForm(forms.Form): user = forms.CharField(max_length = 100) password = forms.CharField(widget = forms.PasswordInput()) urls.py here i am calling insertmenu function from django.conf.urls import patterns, include, url urlpatterns = patterns('myapp.views', url(r'^menuadmin/', 'insertmenu',name="insertmenu"), url(r'^login/', 'datasent',name="datasent"), ) I am supposing, I need to write one more url pattern for reverse match so I added datasent view. template <form name = "form" action = "{% url "myapp.views.login" %}" method = "POST" >{% csrf_token %} <div style = "max-width:470px;"> <center> <input type = "text" style = "margin-left:20%;" placeholder = "Identifiant" name = "username" /> </center> </div> <br> … -
How to input query flat output from a different database to a Django model?
First off, I'm new to Django and Python overall - so I might be asking the wrong question, if that's the case please tell me where to look. If not, continue: I'm working with a Django app that queries a Wordpress database, I have created a connection and wrote the query as such: cnxn = MySQLdb.connect(host="localhost", user="root", passwd="password", db="dbname") query = '''SELECT post_id, label, meta_value FROM table''' The issue is that the data is in a flat format, where the label should be the column name and the meta_value should be the value, output: post_id label meta_value ------- ----- ---------- 1 name example name 1 email example@mail.com 2 name example name 2 2 email example2@mail.com Please keep in mind that there are 24 labels for each post_id, so each form entry adds 24 lines to the table. How would I got about creating a Django model that appends the data from the table in a pivot style format to be able to display it nicely in the template? The goal is to be able to display 4-5 labels on the main page with a link on each line that shows the full input on a separate page. Desired output: post_id … -
Signing in a user through django restframework (Android)
I am new to django rest-framework, but I am able create basic apis . But I wanted to know how can I log in a user from Android. Should I create a api view which takes post data (username,password) and then tries the login method and return if user is successfully logged in or not? How should I proceed ? Thanks. -
Django Model design and user profile
I want to implement Organisation,department and user relation model. Where in super user of organisation can add departments along with department details like phone, address, email etc. A user can belongs to one are more departments, and user with department owner or organisation super user can edit user info as well department info. After analysis,I came up with below model relation. class Organization(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Departments(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) email= models.CharField(max_length=30, unique=True) phone= models.CharField(max_length=30) org_linked=models.ForeignKey(Organization) user_linked=models.ForeignKey(User) Please let me know how can I complete this model by adding other properties like -Org super user -Department super user -Users Edit permission -Adding/Deleting user as super user other permission -
not much change in queries time when using redis cache
I am learning caching django apps using django-redis. In my home page, there is nothing dynamic. I have used the caching over there. I see not much difference. The following query has taken more time and I don't know what it is for and why SELECT ••• FROM "djconfig_config" WHERE "djconfig_config"."key" = '''_updated_at''' 90.03221908981072% 1.07 The way I have used the caching is CACHE_TTL = getattr(settings, 'CACHE_TTL', DEFAULT_TIMEOUT) @cache_page(CACHE_TTL) def index(request): # if not request.user.is_authenticated(): # return render(request, "index.html") # else: # return render(request, "index.html") return render(request, "index.html") No query is done here instead it's taking that much time due to the query of djconfig_config. However, I have used middleware to check the invitation exist or not in every request to set the session of invite_code and email. Here is the screenshot before and after caching Do I have to do something more? -
pycharm django test custom setting is overridden
I am new to django. When I try to run tests, I encounter the following error: NotImplementedError: Language af is not supported and tests run with no problem on other devices, which means the problem is of my pyCharm. My test configuration is same as the other device. the line which raises the error is: VALID_CHARACTERS = {lang: _get_valid_characters(lang) for lang in LANGUAGE_LIST} where LANGUAGE_LIST = [x[0] for x in settings.LANGUAGES] and settings.LANGUAGES is returning all languages, instead of my language (where af is the first language in list). In my projectcomon/settings.py I have LANGUAGES = [ ('fa', 'Farsi'), ] bu it seems to be overridden by default setting. Where is the problem? thanks -
request.POST.get() doesn't work when I pass context to the view
I'm using Stripe for my django site to accept one-off payments. The following code works fine and the charge is successfull: def pay(request): # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = "sk_test_exhH8mdKfkXkaxzvtVphJOBZ" # Token is created using Checkout or Elements! # Get the payment token ID submitted by the form: if request.POST.get('stripeToken'): print(request.POST) token = request.POST.get('stripeToken') charge = stripe.Charge.create( amount=999, currency='usd', description='Boosted Post', source=token, ) print('Charge:', charge) return HttpResponseRedirect('/') else: print('NO') context = { 'amount': 999, } return render(request, 'advertising/pay.html', context) however if I add context to this view, it doesn't work (if request.POST.get('stripeToken') doesn't fire): def post_ad(request): boost_form = AdvertisePostForm(request.POST or None, request.FILES or None) if boost_form.is_valid(): instance = boost_form.save(commit=False) instance.total_price = ad_price(instance.position, instance.duration) instance.ad = True instance.save() context = { 'hash': instance.hash, } return pay(request, context) else: pass context = { 'boost_form': boost_form } return render(request, 'advertising/post_ad.html', context) def pay(request, context): ad = get_object_or_404(AdvertisePost, hash=context['hash']) amount = ad.total_price * 100 # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = "sk_test_exhH8mdKfkXkaxzvtVphJOBZ" # Token is created using Checkout or … -
[django]how can i change Settings.py?
Several configuration files exist. If these files have different names How do I change the settings file every time I run this command? "python manage.py runserver" -
django models get nearby time range
With given datetime; how can find the cloest datetime using django models query? order = locale.order_set.filter(Q(timestamp__gte=(datetime.datetime.today()))).first() following gives me all the dates greater than today; instead I want a single most closest(shouldn't be past date) only future dates for the given timestamp. -
Dropzone returns no file to view in Django
I m using Gentelella for Django, which includes an implementation of Dropzone. It has been kind of troublesome, but I have managed to make ir work without errors, but the view receives no files. This is the html file: {% extends "StylingApp/base_site.html" %} {% block title %} Form Upload {% endblock title %} {% block stylesheets %} {{ block.super }} <!-- Dropzone.js --> <link href="/static/vendors/dropzone/dist/min/dropzone.min.css" rel="stylesheet"> {% endblock stylesheets %} {% block content %} <div class="right_col" role="main"> <div class=""> <div class="page-title"> <div class="title_left"> <h3>Álbum: {{ album.name }}</h3> </div> </div> <div class="clearfix"></div> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="x_panel"> <div class="x_title"> <h2>Agregar fotos</h2> <div class="clearfix"></div> <div class="nav nav-bar"> <input form="upload_form" type="submit" id="submit-accept" name="submit-accept" value="Aceptar" class="btn btn-success"/> <input form="upload_form" type="submit" id="submit-cancel" name="submit-cancel" value="Cancelar" class="btn btn-danger"/> </div> </div> <div class="x_content"> <p>Arrastra varios archivos al área que está abajo para agregarlos al mismo tiempo, o haz click en ella para seleccionarlos.</p> <form id="upload_form" action="{% url 'AlbumsManagerApp:album_add_photo' album_pk=album.id %}" class="dropzone" method="POST" enctype="multipart/form-data" dropzone> {% csrf_token %} </form> </div> </div> </div> </div> </div> </div> {% endblock content %} {% block javascripts %} {{ block.super }} <!-- Dropzone.js --> <script src="/static/vendors/dropzone/dist/min/dropzone.min.js"></script> <script type="text/javascript"> Dropzone.options.uploadForm = { // Prevents Dropzone from uploading dropped files immediately autoProcessQueue : … -
Pre-Populate template field with default value from model in Django/Wagtail
I want to add a default value and have it populate the field in a Wagtail template based on a Django model. I know I am returning the value because if I populate 'help-text' attribute with this value, it works but I cannot get it populate the field with the default attribute. I am using a field panel for the content panel. This Class is very long so I did not post the whole thing. class MeetingPage(Page): ... def live_video_url(): return constants.streaming_info['live-video-captions'] ... live_video_url = models.URLField(default=live_video_url, blank=False, help_text=live_video_url, null=True) .... FieldPanel('live_video_url'), I am getting this in the actual field in the Wagtail editor, but the correct url string in help-text: <django.db.models.query_utils.DeferredAttribute object at 0x104547470> -
Django: Context Processors Returning same value for different Users
I have a django app in which users can Answer a Question, I'm having some trouble while printing the number of views different users. Here's my Answer model, class Answer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) content = models.TextField() views = models.IntergerField(default=1) Here's how I'm getting the number of views per user inside the context_processors.py, def all_views(request, pk=None): if pk: my_user = User.objects.get(id=pk) else: my_user = request.user user_views = Answer.objects.filter(user=my_user).aggregate(Sum('views')) context = {'user_views': user_views } return context But the problem is that it's returning the number of views of request.user for every single user. Means if I log in as abc (id=1) having 20 views & visit xyz (id=2) profile having 40 views, then it shows 20 views on xyz profile as well instead of 40. Why if pk: condition is not working? & How can we fix that? Thank You! -
I can't input Quantity order to add to cart, in HTML file - Django
I'm working on a Django blog, and having implemented category for detail page. I've stumbled upon an issue. I have created a forms.py file, in order to add items to the cart, and this is the following code. cart/forms.py file from django import forms PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)] class CartAddProductForm(forms.Form): quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) cart/views.py code file from django.shortcuts import render, redirect, get_object_or_404 from django.views.decorators.http import require_POST from myshop.models import Product from .cart import Cart from .forms import CartAddProductForm @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('cart:cart_detail') def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True}) return render(request, 'cart/detail.html', {'cart': cart}) I use the following code to display the form that has been created in the product page <form action="{% url "cart:cart_add" product.id %}" method="post"> {{ cart_product_form }} {% csrf_token %} <input type="submit" value="Add to cart"> </form> and this is the myshop/templates/product/detail.html file where I put the code {% extends "shop/base.html" %} {% load static … -
__range django isn't working
I have __range that looks like this: backwards = str(distance-10).split('.')[0] frontwards = str(distance+10).split('.')[0] route = Route.objects.filter(miles_from_warehouse__range=(backwards,frontwards)) backwards can be an integer simple as 6 and frontwards can be 26; I want data everything within range of 6-26 however it gives me nothing, but instead when I use 0 instead of 6; it gives me it. How come? miles_from_warehouse = models.CharField(max_length=120,default=None, blank=True, null=True) -
How to pass data from template button to a view in Django
the project I am working on analyzes csv files that are uploaded by users and saved in the 'media' folder, I then did a search view and template to show these files' metadata, but here is where I got stuck, how can I make these files be 'taken' and opened in another view by clicking a button? views.py def search(request): query = request.GET.get('q') if query: results = Files.objects.filter(Q(target__contains=query) | Q(tag_1__contains=query) | Q(tag_2__contains=query) | Q(Description__contains=query)) return render(request, 'repo/search.html', {'results':results}) else: return render(request,"repo/search.html",{}) search.html <div class="container-fluid mt-5 ml-5 "> <h4 class="pt-3">{{ results.count }} result(s) found:</h4> <div class="row ml-5" > <div class="col-lg-4 rounded bg-light ml-5 mt-2 "> {% if results %} {% for each_target in results %} {% csrf_token %} <p class="pt-2"><a href="{{each_target.Upload_file }}" class="button" download><i class="fa fa-download text-primary"></i> Download Sample</a></p> <h5 class="lead"><strong>{{each_target.target}}</strong></h5> <h5 class="lead">Description: {{each_target.Description}}</h5> <h5 class="lead">Tags: {{each_target.tag_1}}, {{each_target.tag_2}}</h5> <!--HERE !! --> <form action="{% url go to url %}" method="POST"> <input id="submit" type="button" value="Click" /> <!-- somehow take each_target.Upload_file with you to a different view to analyze --> </form> <hr> {% endfor %} </div> </div> {% endif %} </div> I've been reading other posts but can't find something to help me achieve what I want to do, any help or comments will …