Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django Styling Issue - Can't get icons to display
I'm using a custom set of icons from a template from themeforest. I can't get them to display using Django and I'm not sure why. The styling is setup with static files, the rest of the site loads, and i assume it's to do with the styling linking to a bunch of .svg, .eot, .ttf, .woff files. I can include code if needed but I feel like there's a more simple solution to this. Cheers! And i'm using Canvas template, being single page app template. -
Getting the error 'Credentials' object has no attribute 'revoke'
I'm using Google Calendar OAuth2 login. Now once the user is successfully logged in, I'd like to revoke the credentials token on clicking a link. The official documentation here says that the code below revokes the token credentials.revoke(httplib2.Http()) However, I'm getting the error - 'Credentials' object has no attribute 'revoke' Could someone help figure this out? Thank you! -
How to change format of a field value in model serializer keeping the field name same in both display and create?
I have a model called Task with field delay which is a duration field. class Task: delay = models.DurationField(timedelta(seconds=0)) and a serializer as below. class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ('id', 'delay') On creation of instance using serializer, i pass data such as {delay: 30} expecting seconds to be passed. Instance is created as expected. However on retrieval, I get below result. [ { "delay": "00:00:00.000060", }, { "delay": "00:00:00.000050", }, { "delay": "00:00:00.000060", } ] I am trying to get delay value in serializer in integer format only. For example: [ { "delay": 60, }, { "delay": 50, }, { "delay": 60 } ] I am not willing to change field name "delay" in either write or read serializer. How can I achieve the requirement ? -
OperationalError at /accounts/login/ attempt to write a readonly database
I have just setup my server and uploaded all my files for amy Django project. I am currently debugging all the errors it is giving me and I came across this one, which I have never seen before and can't seem to find very much on: OperationalError at /accounts/login/ attempt to write a readonly database I understand what it means, I just have no idea how to fix it nor do I know why it is happening. I am using a Digital Ocean droplet as my server. I had just gotten the homepage (login page) to work and upon logging in I came across this. Here is the traceback: Traceback Switch to copy-and-paste view /usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _legacy_get_response response = self._get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = self.process_exception_by_middleware(e, request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/generic/base.py in view return self.dispatch(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in _wrapper return bound_func(*args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/views/decorators/debug.py in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/decorators.py in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) ... ▶ Local vars … -
Ordering listview with get_queryset
Two models : Post and Author This view displays the last Post for each Author (author is a ForeignKey) I want to have these posts in a descending order, but it does not work. The template keeps displaying these in a ascending way. I try this following: views.py class LastestListView(ListView): context_object_name = 'posts' model = models.Post ordering = ['-date'] paginate_by = 10 def get_queryset(self): return self.model.objects.filter(pk__in= Post.objects.values('author__id').annotate( max_id=Max('id')).values('max_id')) or: class LastestListView(ListView): context_object_name = 'posts' model = models.Post paginate_by = 10 def get_queryset(self): return self.model.objects.filter(pk__in= Post.objects.order_by('-date').values('author__id').annotate( max_id=Max('id')).values('max_id'))