Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Datatables with Django date pattern
I am using data tables and need to sort the date based on the Django template tag. I believe this is the standard formatting which I would like to keep. <td class="text-left">{{ d.date|date:"N d, Y" }}</td> I found these pages with plugins but none of them seem to cover this format. https://datatables.net/plug-ins/sorting/ https://cdn.datatables.net/plug-ins/1.10.19/sorting/ How can I sort the date for the Django template date format? thank you. -
Run selenium in parallel/scrape multiple sites in parallel or in order?
I'm new to Django, I'm currently creating a web app that has a form that sends user input from the form to some other online tools, submits that data and then scrapes the results and shows the output in the form of a table on my web app like so: https://i.imgur.com/AVj3cJJ.png I've ended up using selenium with PhantomJS as the tools have javascript objects, I was using mechanicalsoup before which was working well but got stuck when I got to the javascript elements hence switching to selenium. I've ran into a problem, currently I run the scraper via a function I've created and call it in my view like so: if form.is_valid(): crisporDF = crispor(form.cleaned_data['dnaSeq'], form.cleaned_data['species']) This function takes the user data and feeds it into the scraper and then produces the table as can be seen in the screenshot above, all works fine, however I have 5 tools I need to scrape and produce 5 tables, so I've created another similar function for another tool and this is the result I get: https://i.imgur.com/qDXVR7s.png As you can see it kinda works, the results in the second table are fine but using the same input data from the user the first … -
Rendering queryset on template without <QuerySet [<User:>]>
I am rendering a ManyToManyField in my template but it is shown like this : <QuerySet [<User: Guido>]> And I just want to print out the username without the function. My views.py class HotelListView(LoginRequiredMixin,ListView): model = Hotel def get_queryset(self): return self.model.objects.filter(collaborateurs=self.request.user) My template {% for Hotel in object_list %} {{ Hotel.collaborateurs.ALL }} {% endfor %} Thanks. -
Django '__proxy__' object is not callable
I face a problem in sending a verification email in SignUp class # UserProfile views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView, CreateView, UpdateView from django.urls import reverse_lazy, reverse from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.utils.functional import lazy from django.http import HttpResponse # imports for user activation from django.contrib.auth import login from django.conf import settings from django.utils.encoding import force_bytes from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.core.mail import EmailMultiAlternatives from django.contrib.auth.tokens import default_token_generator from django.template.loader import render_to_string from django.http import HttpResponse, HttpRequest from django.contrib.sites.shortcuts import get_current_site # UserProfile forms and models from . import forms from .models import User # Create your views here. class SignUp(CreateView): form_class = forms.UserSignUp success_url = reverse_lazy('UserProfile:activation_email_sent') template_name = 'UserProfile/sign-up.html' def form_valid(self, form): user=form.save() user.save() mailhost={'scheme':self.request.scheme,'host':get_current_site(self.request)} lazy(send_account_activation_email(mailhost,user)) return HttpResponse(self.success_url()) class UpdateProfile(LoginRequiredMixin,UpdateView): form_class = forms.UserProfileForm success_url = reverse_lazy('index') template_name = 'UserProfile/profile.html' def get_object(self): return self.request.user class LogStatus(TemplateView): template_name='UserProfile/log-status.html' def send_account_activation_email(request, user): text_content = 'Account Activation Email' subject = 'Email Activation' template_name = 'registration/user-activation.html' from_email = settings.DEFAULT_FROM_EMAIL recipients = [user.email] kwargs = { 'uidb64': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': default_token_generator.make_token(user) } activation_url = reverse('UserProfile:activate_user_account', kwargs=kwargs) activate_url = "{0}://{1}{2}".format(request['scheme'], request['host'], activation_url) context = { 'user': user, 'activate_url': activate_url } html_content = render_to_string(template_name, context) email = EmailMultiAlternatives(subject, … -
Convert UUID to string in Django queryset
I have a model with a UUID as primary key. class Books(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = ..... And I have a simple query: results = Books.objects.all() All is working fine in terms of saving and retrieving data, but part of the record editing process requires storing records in the session variables which means I get the 'UUID('…') is not JSON serializable' error. It seems to me, that the simplest answer is to convert the UUID objects to strings immediately after making the initial query, thus preventing multiple changes elsewhere. Does that sound logical? If so, I assume I could do it with some sort of list comprehension. Could someone help with the syntax please? Or direct me on the approach if preferred! Many thanks. -
How do I create a delivery model with products and amounts?
I am trying to do some sort of shop. The user gets a delivery (delivery model) with some products (product model). The user can choose the quantity of the products. The models have a structure like so: class Delivery(models.Model): some stuff... class Product(models.Model): products = models.ManyToManyField(Product,related_name="deliveries", blank=True, null=True) some stuff... But now I am really confused how to solve this seemingly simple problem. Where do I specify the amount of a product in each delivery. Obviously, the amounts vary per delivery, so I can hardly specify a field with amount on the product ... I am really confused about this ... -
issue with Django tutorial lesson 4 : NoReverseMatch at /enquete/2/
I'm having the following error Reverse for 'vote' with arguments '(2,)' not found. 1 pattern(s) tried: ['enquete\/\ This is the traceback I'm having Internal Server Error: /enquete/2/ Traceback (most recent call last): File "/home/johnl/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/johnl/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/johnl/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 154, in _get_response response = response.render() File "/home/johnl/.local/lib/python3.6/site-packages/django/template/response.py", line 106, in render self.content = self.rendered_content File "/home/johnl/.local/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content content = template.render(context, self._request) File "/home/johnl/.local/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/johnl/.local/lib/python3.6/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/johnl/.local/lib/python3.6/site-packages/django/template/base.py", line 163, in _render return self.nodelist.render(context) File "/home/johnl/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render bit = node.render_annotated(context) File "/home/johnl/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated return self.render(context) File "/home/johnl/.local/lib/python3.6/site-packages/django/template/defaulttags.py", line 442, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/home/johnl/.local/lib/python3.6/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/johnl/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 622, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'vote' with arguments '(2,)' not found. 1 pattern(s) tried: ['enquete\\/\\<int\\:question_id\\/vote\\/$'] [02/Mar/2019 17:18:39] "GET /enquete/2/ HTTP/1.1" 500 112049 ^C% This is my view, view.py class DetailView(generic.DetailView): model = Question template_name = 'enquete/detail.html' This is my URL, url.py app_name = 'enquete' urlpatterns = [ path('',views.IndexView.as_view(), name='index'), path('<int:pk>/',views.DetailView.as_view(),name='detail'), path('<int:pk>/results',views.ResultsView.as_view(),name='results'), … -
Bootstrap : Is there a relatively simple way to make my pages workable on mobile?
I am working on my first "handmade" (i.e. not WordPress) site. Building it with Django/Python and Bootstrap 4. Even though I wrote in the contract that I am not obligated to make the site mobile friendly, the client is demanding that it work on mobile (client... amirite?). I am looking for some fairly simple ways to make the site work better on mobile. I am going to focus on one page, our login screen. It's kind of hard to describe, so I am including a few screenshots to show you what happens as the viewport gets smaller. So... I feel that there's a solution to be had between (1) making the top navbar switch to a mobile-style navbar at some break point and (2) programming it to preserve the padding at the top of the main div, so that the navbar "pushes the content down" rather than covers it over. Can you help? Here is the pertinent code: /*navbar:*/ .brand { margin-bottom: 0px; } h5.brand { color: #e3f2fd; font-family: "Arial"; } .navbar { background-color: #2c3b4b; } a.nav-link { color: white; } a.active { color: #808080; } .navbar .navbar-nav li a:hover { color: #808080; } /*Main container*/ .container-fluid { background-color: #fffef7; … -
Django filtering queryset with deserialized data from session
I want to implement an object-level permission system to my Entity model in Django. So I have a PermissionEntity model: class PermissionEntity(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) entity = models.ForeignKey(Entity, on_delete=models.CASCADE, null=True, blank=True) crud = models.ForeignKey(Crud, on_delete=models.CASCADE) # Create/Read/Update/Delete On my login page I store User permissions to session. Login view has the following code: permission_entity = PermissionEntity.objects.filter(user_id = user.id) permission_entity = serializers.serialize('json', permission_entity) request.session ['permission_entity'] = permission_entity And I want to get permitted entities list in my view: def entity_list(request): permission_entity = serializers.deserialize('json', request.session ['permission_entity']) entity_list = Entity.objects.filter(pk__in=permission_entity.entity_id) I know the current view isn't correct, but I have no idea what to do with deserialized objects in this case. Or maybe Im on the wrong way? -
X-Accel-Redirect feature does not work for external connections (inside docker network)
I'm trying to allow container with django to manage access to media files served from another container with nginx. Because of that despite of nginx documentation, I've removed the internal line from the location config: server { server_name nginx; //name of the container used for accessing from another containers charset UTF-8; client_max_body_size 32m; listen 80; location /protected/media/ { // internal; alias /data/djan,go/media/; } } With this config I'm able to use /protected/media urls from django containers so I've succeeded at doing wget http://nginx/protected/media/images/bank_credentials/H0grsrvgsBo.jpg from shell of container with django. But django's code response = HttpResponse() del response['Content-Type'] response['X-Accel-Redirect'] = 'http://nginx/protected/media/' + path # I'm sure that this url matches to url I've used succesfully with wget return response returning 404 Here is the django's url: path('media/<path:path>', media_access, name='media') Where I'm wrong? -
What should be the approach to make web frameworks and servers compatible?
I started web development with python's web development frameworks like flask and Django . Here , I saw that URL's are being mapped to functions which return HTML response called as views . However , I found that the servers provided by Django and flask and as a matter of fact , any other such web framework(save for maybe, cherrypy) are not robust enough to serve at production level . As such they need to be served by production level servers such as Apache , nginx or IIS . Then I got to know that to serve a python application , the server must have something called as "mod_wsgi" installed . WSGI , to my understanding , is a spec ,a division of duty for the server and the application . Both must do their side of the job so as to be arranged for request responding . Now I wondered how to generalize an approach for the problem of any server serving a web application written in any other language / So let's say there comes up a web framework in a language , let's say A and we have a production level server like Apache . Now the … -
Django Twitter API error: "code":215,"message":"Bad Authentication data."
I am making a bot detection system for Twitter. I am facing problem in getting user account info. I have successfully made twitter authentication but when requesting user account info, I am getting this error "code":215,"message":"Bad Authentication data." My views.py code from django.http import HttpResponse,HttpResponseRedirect from django.urls import reverse from django.shortcuts import render,redirect from werkzeug.utils import redirect from .forms import UserLoginForms from django.contrib.auth import authenticate, login, logout import requests def home(request): screenname = 'BarackObama' r = requests.get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' + screenname + '&count=2') print(r.text) return render(request,'home.html') def main_login_page(request): return HttpResponseRedirect('/accounts/twitter/login') def user_logout(request): logout(request) return HttpResponseRedirect(reverse(home)) I am new to Django. So please help me with that problem. Thanks -
Django restframework Error binding parameter
When trying to save the data in the DB I have this error: sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. models.py class Movie(Model): title = CharField(max_length=255) omdb = JSONField() slug = SlugField(max_length=255, unique=True, allow_unicode=True) views.py omdb_data = get_movie(title) # returns response.json() from external API call print(type(omdb_data['Title'])) # str print(type(omdb_data)) # dict movie = Movie(title=omdb_data['Title'], omdb=omdb_data, slug=slugify(title)) movie.save() # crashing here What could be wrong? I'm guess it's problem with title or omdb parameters (not sure if ID counts or not) but no idea whats wrong. -
Django get cleaned data from MultipleChoiceField
I can´t find the way to get cleaned data from a MultipleChoiceField in a form. I´m giving the user some options and then I want to concatenate the results in a string to compose the message body of an email. The form class EmailForm(forms.Form): contenidos_compartibles = ( ('1', 'Catálogo x Marca'), ('2', 'Catálogo x Producto'), ('3', 'Lista de precios x Marca'), ('4', 'Lista de precios x Producto'),) incluir = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(), choices=contenidos_compartibles, required=False) remitente = forms.EmailField() destinatario = forms.EmailField() cc = forms.EmailField(required=False) asunto = forms.CharField(required=False) mensaje = forms.CharField(required=False) firma = forms.CharField(required=False) The view def SendEmailView(request): if request.method == "POST": email_form = EmailForm(request.POST) if email_form.is_valid(): mensaje = email_form.cleaned_data["mensaje"] adjuntos = email_form.cleaned_data["incluir"] for incluido in adjuntos: mensaje = mensaje + incluido After sending the email I only get the original message but none of the options. It is supposed to be a simple list, but I can´t get it working and couldn´t get any clues on the webb. Thanks in advance. -
Loading a .csv file in d3.js inside django is not working
I am trying to load a csv file inside django in javascript but it gives me an error: http://127.0.0.1:8000/data.csv is not found , the data.csv location is inside the templates folder with the html page. My code: d3.csv("data.csv", function(d, i, columns) { for (var i = 1, n = columns.length; i < n; ++i) d[columns[i]] = +d[columns[i]]; return d; }, function(error, data) { if (error) throw error; } -
Catched except in django transaction.atomic() block rollbacks transaction
I have a block of code like this: with transaction.atomic(): for i in some_objects: stop_object(i) for i in some_objects: try: activate_object(i) except IntegrityError as e: pass Test is written with py.test. For some reason, when I catch IntegrityError all transaction is rolling back and I have the exact same state as before. I was sure transaction should rollback only on errors I don't catch. Am I missing something? Not sure also how I can debug it. If you have some ideas, please share them. -
Django filter between two date
My django model datetime field is string, in this case how get data between two date? models.py class asdf(models.Model): recordDate = models.CharField(max_length=20,blank=True) -
django PermissionRequiredMixin permission_required not working
Views.py class viewName(generic.TemplateView, PermissionRequiredMixin, AccessMixin): permission_required = 'accounts.action_all' def get(self, request, *args, **kwargs): #view logic print(self.request.user.has_perms('accounts.action_all')) accounts/models.py class User(AbstractBaseUser, PermissionsMixin): # some fields here class Meta: verbose_name = _('user') verbose_name_plural = _('users') permissions = ( ("template_all", "access to all template views"), ) The last line in the code in views.py returns the correct boolean value, however, the permission_required var has no effect, and the user is still able to see the page even when the print returns false. Help appreciated. -
Heroku build failed lockfile = json.load(f)
Heroku build is failing for my django app with the following error. `-----> Python app detected Python has released a security update! Please consider upgrading to python-3.6.8 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> Stack has changed from heroku-16 to heroku-18, clearing cache -----> Installing python-3.6.0 -----> Installing pip Traceback (most recent call last): File "/app/tmp/buildpacks/8790c95df2ef7b8917bda7b51cf284cfdb/vendor/pipenv-to-pip", line 24, in <module> main() File "/app/tmp/buildpacks/8790c95df255b386056eda7b51cf284cfdb/vendor/pipenv-to- pip", line 12, in main lockfile = json.load(f) File "/app/.heroku/python/lib/python3.6/json/__init__.py", line 299, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "/app/.heroku/python/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/app/.heroku/python/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/app/.heroku/python/lib/python3.6/json/decoder.py", line 355, in raw_decode` here is my link to the code - https://github.com/Thamizhvanan-R/Python-Backend -
Postgres data refresh in UI tables
I have data stored in postgres tables. I need the table in my UI to update and show the new data as soon as I do a new insert. I'm using react frontend and Django backend. -
How to resolve pyinstaller stack trace?
Attempting to build an executable for windows whilst on ubuntu from a Django project using pyinstaller. I have pip installed all required dependencies and look around at what hookfiles I might need to make, however the stack trace I get is not a common one that I can find in searches. for instance, there's a syntax error at the bottom of the trace. Trace: pyinstaller --onefile --name=alpha-server manage.py 45 INFO: PyInstaller: 3.4 45 INFO: Python: 3.6.8 46 INFO: Platform: Linux-4.15.0-45-generic-x86_64-with-Ubuntu-16.04-xenial 46 INFO: wrote /home/timi95/Desktop/AlphaServer/alpha-server.spec 49 INFO: UPX is not available. 50 INFO: Extending PYTHONPATH with paths ['/home/timi95/Desktop/AlphaServer', '/home/timi95/Desktop/AlphaServer'] 50 INFO: checking Analysis 50 INFO: Building Analysis because Analysis-00.toc is non existent 50 INFO: Initializing module dependency graph... 51 INFO: Initializing module graph hooks... 53 INFO: Analyzing base_library.zip ... 3385 INFO: running Analysis Analysis-00.toc 3421 INFO: Caching module hooks... 3426 INFO: Analyzing /home/timi95/Desktop/AlphaServer/manage.py 3475 INFO: Processing pre-find module path hook distutils 7791 INFO: Processing pre-safe import module hook setuptools.extern.six.moves 8281 INFO: Processing pre-find module path hook site 8281 INFO: site: retargeting to fake-dir '/home/timi95/.local/lib/python3.6/site-packages/PyInstaller/fake-modules' 12103 INFO: Loading module hooks... 12103 INFO: Loading module hook "hook-django.core.management.py"... 12119 INFO: Import to be excluded not found: 'IPython' 12119 INFO: Import to be excluded not … -
How can i limit the post view for unauthenticated user in class based view django
I am new to django. In my project I want to make home page which views some of the post.But if user get registered or authenticated then they can view all the post available on the website. so far I have created the view which renders all the post on home page but I want to limit them. I am using class based view. -
Template syntax error. Could not parse the remainder (Django)
Can someone point me to the right direction? Below is what I have been doing <p>{{article.snippet}}</p> <p>{{article.date}}</p> <p>{{article.retrieve_by_category("web")}}</p> I have no problems getting the date or the snippet but I keep getting the following error when trying to run article.retireve_by_category. Could not parse the remainder: '("web")' from 'article.retrieve_by_category("web")' Below is the code for the model: class Article(models.Model): category = models.CharField(max_length=100) title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) #add in thumbnail def __str__(self): return self.title def snippet(self): return self.body[:500] + "..." def retrieve_by_category(self,category): """retrieves blogs based on their category""" if (str(self.category) == category): return self.category return '' -
Django ORM raw delete query not deleting records
I am using raw_sql queries for my convenience for keeping my database minimal I am deleting extra records. By this query #d is from a loop and has values res=MyModel.objects.raw("DELETE FROM mydb_mymodel WHERE mydb_mymodel.s_type = '%s' and mydb_mymodel.barcode = '%s' and mydb_mymodel.shopcode = '%s' and mydb_mymodel.date = '%s'" ,[d.s_type,d.barcode,d.shopcode,d.date]) It is not deleting records in database but when I do res.query and run it from postgres console it works! what I am missing -
Why Chartkick says loading and never visualise the data?
I am trying to use chartkick to visualise data on template by following this. However, it says "loading" and do not display. What is the reason? Did I miss anything? Please look at the codes bellow. view.py def analyticView(request): template = 'survivors/analysis.html' exchange = {'2001-01-31': 1.064, '2002-01-31': 1.1305, '2003-01-31': 0.9417, '2004-01-31': 0.7937, '2005-01-31': 0.7609, '2006-01-31': 0.827, '2007-01-31': 0.7692, '2008-01-31': 0.6801, '2009-01-31': 0.7491, '2010-01-31': 0.7002, '2011-01-31': 0.7489, '2012-01-31': 0.7755, '2013-01-31': 0.7531, } browser_stats = [['Chrome', 52.9], ['Firefox', 27.7], ['Opera', 1.6], ['Internet Explorer', 12.6], ['Safari', 4]] sizes = [['X-Small', 5], ['Small', 27], ['Medium', 10], ['Large', 14], ['X-Large', 10]] areas = {'2013-07-27 07:08:00 UTC': 4, '2013-07-27 07:09:00 UTC': 3, '2013-07-27 07:10:00 UTC': 2, '2013-07-27 07:04:00 UTC': 2, '2013-07-27 07:02:00 UTC': 3, '2013-07-27 07:00:00 UTC': 2, '2013-07-27 07:06:00 UTC': 1, '2013-07-27 07:01:00 UTC': 5, '2013-07-27 07:05:00 UTC': 5, '2013-07-27 07:03:00 UTC': 3, '2013-07-27 07:07:00 UTC': 3} return render(request, template, locals()) analytic.html {% extends 'survivors/base.html' %} {% load chartkick %} {% block content %} {% line_chart exchange with min=0.4 id='rates' %} {% pie_chart browser_stats with library={"title":"Browser Statistics, May 2013"} %} {% column_chart browser_stats %} {% bar_chart sizes with id='sizes' %} {% area_chart areas with id='areas' %} {% endblock %} base.html <!DOCTYPE html> <html lang="en"> <head> …