Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rendering django tag in HTML not working
Hi guys I am trying to make my HTML work but it seems that I do not get something. My HTML is the following: {% extends 'base.html' %} {% block body %} <div class="container"> <div class="jumbotron"> <h2>Welcome to your Project {{ project.name }} Detail page</h2> </div> {% if not project.team_id and project.team_id.members.count() == 0 %} <div class="invite-teammembers"> <div class="jumbotron"> <div class="jumbo-text"> <h3>The team {{ project.team_id }} has beed created, we now need to add TeamMembers</h3> </div> <div class="jumbo-button"> <a href="{% url 'registration:team_register3' %}" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Add Team Members</a> </div> </div> </div> {% elif project.team_id == None %} <div class="invite-team"> <div class="jumbotron"> <div class="jumbo-text"> <h3>Your project has been created, It is time to link a team or create a new for your project</h3> </div> <div class="jumbo-button"> <a href="{% url 'website:link_team'%}" class="btn btn-default" role="button"><span class="glyphicon glyphicon-link"></span> Link an existing team</a> <a href="{% url 'website:add_team' %}" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span> Create a new team</a> </div> </div> {% else project.team_id.members.count() > 0 %} <h1>Youhouu</h1> {% endif %} </div> </div> {% endblock%} my HTML is not rendering like it is supposed to be I get : Could not parse the remainder: '()' from 'project.team_id.members .count()' the thing is using the shell … -
How to add click event on django-chatit chart
I have created a chart using django-chartit library. Once the chart it shown, I want a click action on my chart, upon which chart get enlarge. How can I do this. Moreover: it there any tutorial available to customize django-chartit charts? -
Celery can't autodiscover tasks
I can't figure out why Celery doesn't autodiscover tasks in Django apps (app called engine). The only discovered task is debug_task inside celery.py Celery v: v4.1.0 stilio/settings.py: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'stilio_auth', 'engine', 'django_extensions' ] ... stilio/__init__.py: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] stilio/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stilio.settings') app = Celery('stilio') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) engine/tasks.py: from datetime import timedelta from celery.app import shared_task from celery.task import periodic_task, task from utils import SpiderSupervisor @shared_task def tasks(): return @periodic_task(run_every=timedelta(minutes=1)) def ping_spider(): SpiderSupervisor().check() Do you have any ideas where is the problem? -
Django ERROR (EXTERNAL IP): Internal Server Error: /u/1/
I'm having the following issue, but I suspect that it is a configuration issue. The DJANGO app I'm using is open source (from GitHub). The serving components are DJANGO, NGINX and GUNICORN. Clicking on a user-profile page of the site produces the following web page error (all other site links appear fine -- no issues): Internal Error! Sorry about that. A detailed error report has been generated and has been sent to the managers. If the problem persists please contact the site owners. Underneath the covers, it looks like an error email is also constructed with the following subject: [Django] ERROR (EXTERNAL IP): Internal Server Error: /u/1/ Again, I haven't run into any other site link that produce this issue (but I am just starting with this). Looking at the logs, here is more information (where I substituted in example.com and 93.184.216.34 for the actual host/domain name and IP address), Both the host/domain name and it's IP address are specified in NGINX as well as in ALLOWED_HOSTS (live.deploy settings file). gunicorn uses a UNIX DOMAIN SOCKET to communicate with NGINX. MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Subject: [Django] ERROR (EXTERNAL IP): Internal Server Error: /u/1/ From: noreply@lvh.me To: admin@lvh.me … -
Django squash or eliminate migrations on production
I have an app on production. It has 251 migrations that take too much time when I run the tests, it is making development really slow. I need to do something about this and I'd like an advice. Is it recommendable to squash the 251 migrations? what if I erase then and then just fake initial? of course, I can't lose or change the database, it is on production. Thanks a lot for your help. -
Gunicorn does not work when try to launch Django application
I am following this tutorial, until up to this part. start.sh #!/bin/bash # Start Gunicorn processes echo Starting Gunicorn. exec gunicorn helloworld.wsgi:application \ --bind 0.0.0.0:8000 \ --workers 3 My directories is like this. awesome_app -awesome_app --__init__.py --celery.py --settings.py --urls.py --wsgi.py -awesome_app_to_do_list --a lot of stuffs here -manage.py -start.sh Here is the content of my wsgi.py. """ WSGI config for airport project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "airport.settings") application = get_wsgi_application() I adapted the launch code to this. #!/bin/bash # Start Gunicorn processes echo starting gunicorn exec gunicorn awesome_app.wsgi:application \ --bind 0.0.0.0:8080 \ --workers 3 After I make it executable and run the script from the root of the project awesome_app and not from awesome_app/awesome_app. I received this error, ImportError: No module named 'myproject'. I have looked at this SO discussion, but the error is still there. What should I do? -
Django - Oracle, How to connect to readonly db with user/pass provided for the User
I need to connect Django with a read-only Oracle database. The user and password to connect to that db is going to be provided by the User in a web form. Any hint to do that? Thanks is advance. -
Django filter based in joined table
I have two tables: class Client(models.Model): name = models.TextField() lastname = models.TextField() class Meta: managed = False db_table = 'client' class Clientreport(models.Model): id_client_home = models.ForeignKey('Client', models.DO_NOTHING, db_column='id_client_home', related_name='home_id_client_home') id_client_reported = models.ForeignKey('Client', models.DO_NOTHING, db_column='id_client_reported', related_name='client_id_client_home') class Meta: managed = False db_table = 'clientreport' And I'm trying to build a query similar to this: SELECT cr.*, cl.id, cl.name, cl.lastname FROM Clientreport cr INNER JOIN Client cl ON cr.id_client_reported = cl.id WHERE (LOWER(cl.name) LIKE LOWER('%jo%') OR LOWER(cl.lastname) LIKE LOWER('%jo%') ) I tried using: SQL queries But, now I'm trying to do it using django. How I can access to a joined model using django??? -
AttributeError: 'StatisticsSubmitView' object has no attribute 'request'
class StatisticsIndexView(StaffRestrictedMixin, TemplateView): model = Statistics() template_name = 'loanwolf/statistics/index.html' form_class = StatisticsBaseForm() def get_context_data(self, **kwargs): context = super(StatisticsIndexView, self).get_context_data(**kwargs) context.update({ ... 'statisticaltools': StatisticsSubmitView(), }) return context class StatisticsSubmitView(StatisticsIndexView): ... I would like to access the request (self.request) from StatisticsIndexView inside StatisticsSubmitView. I made the mistake of trying self.request.GET[...] inside StatisticsSubmitView. How could I do such thing? -
How to filter BooleanField in template in Django?
I am preparing a image gallery for my website using Django . I have basically a Gallery Model Foreign Key in my Image Model. I have a BooleanField in my Image model to make a cover photo. What I need is to get True value for the one in between images. {% for gallery in gallery_list %} <div class="grid-item {{ choices | random }}"> <a href="#" data-background="{{gallery.images}}#howtofilter?#" data-rel="lightcase:gal" title="Image Caption"></a> </div> {% endfor %} I checked the documents for custom filters trying to solve but I could not figure out. Can you help me ? Thanks -
django admin filter forein key model when creating
I have 2 models, one is fk of another. I want when creating model filter fk on username creating. I know how to do this in sql, but don't understand how to do in django. I thought about api, am I right? Or I can do it in models or admin interface? class Post_links( models.Model): post_id = ParentalKey('Post') username_can_see=models.CharField(max_length=30, default='') class Post( models.Model): some_link =models.CharField(max_length=50, default='') now on creating new post when I ll check links I want to see only the links can see current user. How can I write this& -
Django view adding parameter to response does not serialize correctly
I am following this tutorial, I tried to add a simple database call to return the number of Snippet objects. Python runs the server fine but says: System check identified 1 issue (0 silenced). Whhat is wrong with the line of code I added? @api_view(['GET']) def api_root(request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), 'snippets': reverse('snippet-list', request=request, format=format), #My example of db query 'num_snippets': len(Snippet.objects.all()) }) -
Running Python directly is much faster compared to when Django runs python
So I have a SQL query that takes really long to load using Django, 10000 rows takes about 30 seconds. If I run the exact same code directly using python it does this in 2 seconds. For some reason, the loop I built takes really long to execute when Django runs the code, does anyone know why that is? Can I do something to increase the performance and get rid of this inconvenience? -
Django form Data Retaliate and Display
I am getting this type of data in my template file , from forms.py . Now I want to get only data of sql_name field which is u'ag_pres . So how I can get this data ? kindly before down vote let me know what I am doing wrong ? <type 'list'>: [{'sql_name': u'ag_pres', 'type': 'string', 'name': u'Ag Pres', 'map_order': 0}, {'sql_name': u'abc', 'type': 'string', 'name': u'ABC', 'map_order': 0}] -
dump CSV file from Django query to Github
We want to automate a process through django admin where, whenever a user makes a change to a record (or adds/deletes a record), a CSV file is created and then dumped into a Github repository with a commit message specified by the person who made the change. Creating the csv file from a queryset is easy enough... But how would we go about then getting that csv file to a folder that is git initialized so that we can commit it to a repository? Any ideas would be great. Essentially we're looking for a way of tracking specific changes to the database. With CSV files in github, we can really easily follow the changes, and we want to leverage that. cheers -
What is the "path" mean in Django urls
When a read some new project on Django in one of urls.py files i find following code: from django.urls import path from . import views urlpatterns = [ path('buyers/embed/<int:id>/view', views.buyers_view), ] This is written in application that not used for now (Instead of this is used another application for buyers view). But i want to know what is this path. I can't find any information about it in documentation. Maybe this is some old style for url routing, or some mistakes. Thanks for any help! -
Django pass empty parameter
I'm trying to pass an empty parameter to render a template but I can not achieve this I do not know if the problem is in urls or views, I really appreciate a hand. Urls url(r'^hola/(\b[a-z\.-]+)$', views.hola, name='hola'), Views def hola(request, varr = ''): #val = val pregunta = Datos_usuario_DB.objects.all().order_by('-id').filter(activo="1")[:15] plantilla = {'': 'index.html', 'nosotros': 'nosotros.html'} return render(request, plantilla['%s' % varr], {'pregunta': pregunta}) When I accès to hola/ it the web site does not exist. -
Buttons with Django to choose items
I have 6 buttons which are options to buy something. You cannot make multiple choices but choose one and it automatically selects that item and reroutes you to checkout section. My question is, using Django, how do I embed the values of those buttons (ie. price, credits etc) into each button so they the ones used in the checkout. My initial method was that I created the items dynamically in Django.admin and instead of having a page in which you individually selected an item you had instead a checkboxes to select from whichever items I had created in the admin through a model (bono) I had created. However, I need the items to be hard coded into individual buttons rather than relying on Django.admin and the server. I've attached a sample html and pic showing the buttons and will add any other items upon request. I simply had no clue which items I should include: html: <div> <div class="row"> <!-- New set of columns, centered --> <div> <div class="row"> <div id="bonocredits3" class="col-xs-12 col-sm-12 col-md-4 col-lg-4 text-center bonoint" data-toggle="modal" data-target="#login-modal"> <a href="{% url 'home' %}"> <div class="circle" style="background: #0045ab" ><span style="font-weight:bold; font-size:60px;" >3</span><br> Credits</div> <div id="price">25€</div> <div id="savings"> {% trans 'You … -
use REST for DJango model instead of DB Access
I am looking to connect REST APIs to a DJango model. I want to do this because I have a database that is to work with Android, iOS and just regular HTML/CSS/Python. Instead of writing code to access a particular DB in Python directly (to support the CRUD functionalities), the goal is to map REST APIs to a Python Model instead. How can this be done? Below are some things that were found; however, is there a better approach? TIA http://www.django-rest-framework.org/api-guide/serializers/#modelserializer https://pypi.python.org/pypi/django-rest-models -
Django: get objects.all() with the related rows in another ManyToMany table
I have 3 models: The django normal User model Author model UserAuthor models which is considered as a many-to-many relationship between the previous two models, but with additional fields (is_follow, review) class Author(models.Model): name = models.CharField(max_length=50) class UserAuthor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='userauthors') is_follow = models.BooleanField(default=0) review = models.TextField(max_length=500, blank=True, null=True) My question is about how to get all the authors with a field inside each author to show that the authenticated user is following him or not. I know that I can use the related_name attribute, which returns the UserAuthor manager filtered by specific author, in some way to get it but how?! My trial is: class AuthorListView(ListView): model = Author def get_queryset(self): final_list = [] authors_list = list(Author.objects.all()) for author in authors_list: element = author.userauthors.filter(user=self.request.user) final_list.append(element) return final_list I don't like this solution for sure, but how to do it in a better way? -
How do you make a 1 on 1 (Like Twitter) messaging feature with django 1.11?
Would any of you know how to implement a 1on1 chat feature on Django 1.11? How would the views, models, templates .py look? Any recommendation's? Any python library for this kind of act? Thanks! -
Display datraframe into django template
I'm currently working on a stadistics portal with Django and i'm trying to display a Dataframe in my template with the next code: View.py: def tabla(request): engine = create_engine('postgresql://postgres:alphabeta@localhost:5432/escaladas') t='escalado 08/2017' sqltable = ps.read_sql_table(t,engine) sqltablehead = sqltable.head(n=10) table = sqltablehead.to_html(classes='table',index=False,escape=False) return render(request,'escalamiento.html',{'table':table}) I've tried display that table with a for on the template but doesn't show anything and writing {{table}} but gives me this https://ibb.co/bVpWw5 any ideas? -
Python Templates - Include/With - Passing parameters
So according to the Django docs, in python we can pass a parameter from one template to another. So at present I have a main html template (home.html) which my python program renders. It passes a username parameter as 'un'. To print this parameter in the home.html I do: {% if user_info %} {{ un }} {% endif %} //this works and prints the username Now I have another template that is included within the main.html. It is called user.html. I have included it as below wit using the 'with' statement to pass the parameter {% include 'sub_pages/user.html' with un=un %} The error I get: TemplateSyntaxError: expected token 'end of statement block', got 'with' Why is this happening? Also when and if the parameter does pass to the sub template do I print it in the same way as I'am printing on the main.html? -
django multiple search terms
I want to add all the columns in 1 algorithm for a search. If it is possible. Something like this: views.py def search_table(request, pk): table_name = Crawledtables.objects.get(id=pk) t = create_model(table_name.name) if 'q_title' in request.GET and request.GET['q_title']: q = request.GET['q_title'] title = t.objects.filter(id__icontains=q_id, title__icontains=q_title, url__icontains=q_url) return render(request, 'search/results_table.html', {'tbl_name': table_name, 'details': title, 'query': q}) else: return HttpResponse("Please submit a search term!") results_table.html <strong> {{ tbl_name }}</strong> <p> You searched for: <strong>{{ query }}</strong></p> {% if details %} <p> Found {{ details|length }}</p> <div class="row"> <table class="table table-bordered sortable"> <thead> <tr> <th>Id</th> <th>Title</th> <th>Url</th> </tr> </thead> <tbody> {% for lists in details %} <tr> <td>{{ lists.id }}</td> <td>{{ lists.title }}</td> <td><a href="{{ lists.url }}" target="_blank">{{ lists.url }}</a></td> </tr> {% endfor %} </tbody> </table> </div> {% else %} <p> No results found</p> {% endif %} {% endblock %} search_table.html {% if tbl_name %} <form action="/search/{{ tbl_name.id }}/results" method="GET"> {% endif %} <input type="text" name="q_id" placeholder="Id"> <input type="text" name="q_title" placeholder="Title"> <input type="text" name="q_url" placeholder="Url"> <input type="submit" value="Search"> </form> -
Django behind Apache transforms HEAD in GET
I'm managing an old django (1.4) application where the following is happening. In a function based view I receive a request, if it is a HEAD method then I just reply with an empty response if request.method == 'HEAD': return HttpResponse() This is just a simple method to check that the client (a script) has a correct configuration and the url is correct. Otherwise, if method is GET then proceed inside then view. This work in a local django debug server. When I deploy this behind Apache and wsgi, something is transforming my http HEAD method in GET. In the apache log I see that it correctly receives a HEAD method but then in my django application the same request is received as GET! Can Apache or wsgi be responsible for this? Where should I look for additional clues?