Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best Practices For Django Web App + REST API Architecture as one project
I am working on my Django project which is going to be a Web App and REST Api for the mobile app. I am using Django Rest Framework to build the API for the mobile app and it is going pretty good. I like it. For this part, I have a separate app within my Django project. Let's call it 'api'. What I also want to do, is a web app. Let's call it 'webapp' in my Django project. So basically, web version of the mobile app, with a few different functionalities (e.g. different user/account management) for a slightly different part of the audience. Obviously, the majority of the models that I need, as well as logic are already there in the 'api' app. Also, I want to use Angularjs for the front end of the web app. My question is what is the best path to take here? Should I create a separate app for my web app and copy the majority of views.py logic, which again will reference models and serializers from the 'api' app in the project? Or should I adjust my existing 'api' app to handle requests from both mobile phones and web app? Thank you. -
Django Bootstrap Grid all content breaks onto new line
I am building a website using the Django framework where it will display a grid of places (3 per row) however the code below, every place ends up going onto a new line within the column. <div class="site-container container-fluid"> <div class="row"> <div class="col-md-3 col-lg-2"> <div class="thumbnail"> <a href="{% url 'sites:details' site.id %}"> <img src="{{ site.site_picture}}" class="img-responsive"> </a> <div class="caption"> <h2>{{ site.site_name }}</h2> <h4>{{ site.site_street }}</h4> <!-- View Details --> <a href="{% url 'sites:details' site.id %}" class="btn btn-primary btn-sm" role="button">View Details&nbsp;<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span></a> </div> </div> </div> </div> </div> In my browser I see the content I want however every site is on a new line in the column, whereas I would like it to be in a row of three and break onto a new line and then begin another row of three. Screenshot -
Django REST - SearchFilter not filtering
I am using Django 1.10 and django-rest-framework 3.5.3. I would like to have a generic search query: search for a value on many fields. I Found the SearchFilter on the Docs. I tried to add the filter backend to the ViewSet, but it seems not to be working. Any search query response with all the objects. ViewSet: from rest_framework import filters class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer filter_backends = (filters.SearchFilter,) filter_fields = ['username', 'email', 'is_staff', 'groups'] Query url: http://localhost:8000/users/?search=something In addition, at the docs they show that a new button "Filter" added to the django rest web page. It does not in my case. Am I missing something? Thank you! -
Updating a Single Object Field in Django View
I am trying to update the value of a single field inside one of Django's objects. Here is the code: class TodoCompleteView(generic.edit.UpdateView): def get_queryset(self): Todo.objects.filter(id=self.kwargs['pk']).update(todo_completed=True) However, I keep getting an error: 'NoneType' object has no attribute 'filter' What am I doing wrongly? -
NoReverseMatch error after updating form in Django
from sites/models.py def get_absolute_url(self): return reverse('site-detail', kwargs={'pk':self.pk}) sites/urls.py from django.conf.urls import url from sites.views import SiteCreate, SiteUpdate, SiteDelete, IndexView, TestedView, DetailView, ApproveSite app_name = 'sites' urlpatterns = [ url(r'^$', IndexView.as_view(), name='site-list'), url(r'add/$', SiteCreate.as_view(), name='site-add'), url(r'(?P<pk>[0-9]+)/update/$', SiteUpdate.as_view(), name='site-update'), url(r'delete/$', SiteDelete.as_view(), name='delete'), url(r'tested/$', TestedView.as_view(), name='site-tested'), url(r'(?P<pk>[0-9]+)/$', DetailView.as_view(), name='site-detail'), url(r'approve/$', ApproveSite.as_view(), name='approve') ] from sites/views.py class DetailView(generic.DetailView): model = Site template_name = "sites/detail.html" context_object_name = "site" sites/forms.py from django import forms from sites.models import Site, Category class SiteForm(forms.ModelForm): class Meta: model = Site fields = '__all__' exclude = ('Status',) When I update a site using the form from my site update view, I want it to take me to the site detail view, but it throws a NoReverseMatch error. Specifically: NoReverseMatch at /sites/1/update/ Reverse for 'site-detail' with arguments '()' and keyword arguments '{'pk': 1}' not found. 0 pattern(s) tried: [] Why is this error happening and how can I get rid of it so that my app shows the detail view for my site record, after my form is submitted? -
Django quickly get latest in one to many relation
I have a model in Django like this class Artist(models.model): pass class Track(models.model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) I only have a couple hundred Artists that I want to display on a page alongside their latest Track. I can fetch all the Artists quickly, but fetching their latest Track, when there are thousands of tracks, is proving to be expensive. latest_track = artist.track_set.latest('when') # really expensive The way I add tracks to an artist allows me to easily set an artists latest track (i.e. I don't have to worry about multiple threads). This made me think I should just store a field Artist#latest_track, but I don't know how to model that because it's not really a OneToOneField, and that's the closest thing I could find. I also considered using cached_property, but I don't have a good way to invalidate the cache at the right time. Also, cached_property appears to only setup during runtime, so if I restart my app server, it will need to redo all the queries. What do I do here? -
NoReverseMatch at /sitemap-main.xml
I am trying to set up a sitemap for the blog portion and main static portion of my website. I have been digging through the docs but nothing I have done is fixing this. I am thinking I am implementing the namespace incorrectly in sitemap_main.py but this is how it looks in the docs. The blog portion is working fine and I am getting the sitemap index page that gives the links to both sitemaps. But the sitemap for the static portion of the website isn't working. I get a NoReverseMatch at /sitemap-main.xml. NoReverseMatch at /sitemap-main.xml Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Request Method: GET Request URL: http://127.0.0.1:8000/sitemap-main.xml Django Version: 1.8.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] website/urls.py from django.conf.urls import url from django.contrib.sitemaps.views import sitemap from .sitemap_main import StaticViewSitemap from . import views sitemaps = { 'static': StaticViewSitemap, } urlpatterns = [ url(r'^$', views.index, name='home'), url(r'index$', views.index, name='home'), url(r'^gallery$', views.gallery, name='gallery'), url(r'^contact$', views.contact, name='contact'), url(r'^about$', views.about, name='about'), url(r'^about/testimonial$', views.testimonial, name='about'), url(r'^about/faq$', views.faq, name='about'), url(r'^services$', views.services, name='services'), url(r'^services/design$', views.design, name='design'), url(r'^services/lawn-garden$', views.lawn, name='lawn'), url(r'^services/irrigation$', views.irrigation, … -
Suggestions for splitting up application?
I am making a site with Django 1.10 (Python 3). The purpose is to track what book I have and which ones i have read. I want to make simple CRUD pages for a few different models. The different models I have at the moment are: Books, Authors and Publishers. This list will probably grow. I have read about splitting your site into smaller apps. So one app for the books CRUD pages, one for the authors and one for the publishers. Is this the way intented by Django? If so a question arises. How do we seperate the models? The Books model has fields that depend on Author and Publisher. But since they are in their own app now, how am I supposed to access it? I am not liking the idea of just importing from another app since they are supposed to be seperate apps. -
Selenium can't access dead object/The element reference is stale
I am following guide to learn TDD with python. At some point, after doing migrations, the output of command python3 functional_tests.py should be (according to book): self.fail('Finish the test!') AssertionError: Finish the test! But I am getting error: selenium.common.exceptions.InvalidSelectorException: Message: Given css selector expression "tr" is invalid: TypeError: can't access dead object And after trying second (and more) time: selenium.common.exceptions.StaleElementReferenceException: Message: The element reference is stale. Either the element is no longer attached to the DOM or the page has been refreshed. I've been googling and searching SO for similar problems, but didn't find one that could help me solve the issue. I am using geckodriver, and adding it's path to PATH. Django==1.8.7 selenium==3.0.2 Mozilla Firefox 50.0.2 (X)Ubuntu 16.04 Should I switch to Chrome? It's not trivial, it would require some time from me, but can it work? Is more like Firefox or Selenium? I don't think it's code related - I cloned repo for chapter 5 and same crash is happening. -
Get error when install requirements.txt for Django
I am trying to follow the tutorial on Heroku for Django and get along till I come to pip install -r requirements.txt. While there is no problem with loading Django, dj-database and unicorn, loading psycopg2 stucks and get Error: pg_config executable not found. I have read over a few entries in SO like Getting Started with Python on Heroku and Can't figure out where Heroku app is failing. I have followed the answers and proposals there and I installed postgresql again via brew; all without success. My PATH is /usr/local/bin : /usr/bin : /bin : /usr/sbin : /sbin : /usr/local/lib/python2.7/site-pakages : /Applications/Postgres.app/Contents/Versions/9.6/bin : /Users/Martin/anaconda/bin : /usr/X11/bin and my pg_config is where it should be and is added to the PATH. But I still get the message Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. I am on OSSiera 10.12.2. Help is appreciated. -
Django, Nginx, Gunicorn 502
Help me, please :) I can't run server for this configuration: - site/ - env/ - src/ - PROJECT - setting.py - wsgi.py - ... - manage.py - static_content/ - static/ It's systemd gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=USERNAME Group=www-data WorkingDirectory=/home/USERNAME/site/ ExecStart=/home/USERNAME/site/env/bin/gunicorn --workers 3 --bind unix:/home/USERNAME/site/src/PROJECT.sock PROJECT.wsgi:application [Install] WantedBy=multi-user.target It's nginx site-available: server { listen 80; server_name ***.***.***.***; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/USERNAME/site/static_content; } location / { include proxy_params; proxy_pass http://unix:/home/USERNAME/site/src/PROJECT.sock; } And I get "502 Bad Gateway" -
Integrate documentation from sphinx to django
I have the documentation folder which is generated by sphinx from some other project in github and I want that documentation folder to be added with django project. So that when user login into django project he can see the project documentation on django web framework. Although this documentation is not related with the django application. I would be thankful if anyone give me step by step suggestions to do this task? -
Django ModelForm error
forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class meta: model = User fields = ['username','email','password'] view.py class UserFormView(View): form_class = UserForm template_name = "music/registration_form.html" # display blank form def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) # process form data def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) # cleaned normalized data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() # returns user object if credentials are correct user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('music:index') return render(request, self.template_name, {'form': form}) and thats django error ValueError at /music/register/ ModelForm has no model class specified. Request Method: GET Request URL: http://127.0.0.1:8000/music/register/ Django Version: 1.10.3 Exception Type: ValueError Exception Value: ModelForm has no model class specified. Exception Location: C:\Python34\lib\site-packages\django-1.10.3-py3.4.egg\django\forms\models.py in init, line 275 Python Executable: C:\Python34\python.exe Python Version: 3.4.0 Python Path: ['C:\Users\HP\desktop\projweb', 'C:\Python34\lib\site-packages\django-1.10.3-py3.4.egg', 'C:\Windows\SYSTEM32\python34.zip', 'C:\Python34\DLLs', 'C:\Python34\lib', 'C:\Python34', 'C:\Python34\lib\site-packages'] Server time: Sat, 17 Dec 2016 23:35:40 +0300 the error is in the def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) -
Django staticfiles not being updated in browser
this is a weird error. I'm working on a Django project in local. when I make changes to staticfiles (.css and.js), they don't appear in the updated version in browsers. So if I add new styles in a .css file, changes appear in Chrome but not in Firefox. Similarly .js files changes appear in firefox but not in chrome. First, I thought this a git branch issue, removed git, didn't work. I also tried cleaning browser cache and force refresh the website. What's wrong? -
PostgreSQL . Models.py is not transformed into database scheme
There were two issues. First was due to Django converting model class name with app name prefix, and as far as that part was solved 'Relation does not exist' error after transferring to PostgreSQL I suppose it may be right to make different question.I was getting such errors as relation "blog_userprofile" does not exist and found out by select column_name, data_type, character_maximum_length from INFORMATION_SCHEMA.COLUMNS where table_name = 'closer'; that there are no columns in existing database closer, so python manage.py migrate , python manage.py make migrations , python manage.py make appname, python manage.py syncdb all basically didn't works properly and didn't transform models.py into database scheme. Why? How do I solve this ? I'v tried deleting everything from models.py and running all commands again, but it still outputs errors on nonexisting fields (?) like django.db.utils.ProgrammingError: relation "blog_community" already exists . I tried to to use --fake initial and flush and 'reset' but neither of those helped. -
Django why to create superuser for custome user model
I am making a Django website and after reading the documentation there are certain things I do not understand. When creating a custom user model that is with BaseUserManager and AbstractBaseUser, why is it important to create a superuser? Since my only interest is to log users in and out and for them to update their settings, where does the superuser come into play? Also when creating a custom user model does that replace the Django built-in admin, that is, no Django-admin page or login? And only my website and apps will be shown accessible to login and function? Pleas bear with me, I am not use to this, somethings seem unclear, I will continue to read the documentation. -
How to configure the Database setting Django-MSSQL using django-pyodbc (ubuntu 16.04)?
I'm new to Django and currently trying to use another database to save my model (i.e. MS SQL). My database is deployed in a docker container: 903876e64b67 microsoft/mssql-server-linux "/bin/sh -c /opt/mssq" 5 hours ago Up 5 hours 0.0.0.0:8888->1433/tcp nauseous_williams I also create a new user for my login to the SQL Server. Username='kucing', password='Kucing@1234' With my user, I can use sqlcmd to access my DB as below: sqlcmd -S localhost,8888 -U kucing -P 'Kucing@1234' Therefore, I change my Django setting for my DB as shown here: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'videogame', #The DB name 'USER': 'kucing', 'PASSWORD': 'Kucing@1234', 'HOST': 'localhost', 'PORT': '8888', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', }, }, However when I run python manage.py migrate, I get an error related to authentication: Traceback (most recent call last): File "/home/luca/git/learnPython/DjangoTicTacToe/lib/python3.5/site-packages/django/db/backends/base/base.py", line 199, in ensure_connection self.connect() File "/home/luca/git/learnPython/DjangoTicTacToe/lib/python3.5/site-packages/django/db/backends/base/base.py", line 171, in connect self.connection = self.get_new_connection(conn_params) File "/home/luca/git/learnPython/DjangoTicTacToe/lib/python3.5/site-packages/sql_server/pyodbc/base.py", line 302, in get_new_connection timeout=timeout) pyodbc.Error: ('28000', "[28000] [unixODBC][Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Login failed for user 'kucing'. (18456) (SQLDriverConnect)") Did I wrongly set up my configuration? Should I update my setting? -
Django image checkbox field
In my form I want the user to select a couple of his favourite images just by clicking on the image, the selected images datas should be stored so it can later be compared, I'm using formtools and django +1.8. forms.py class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) class ContactForm2(forms.Form): ... #choice field linked to image ? class ContactForm3(forms.Form): company_name = forms.CharField(max_length=100) sender = forms.EmailField() views.py class ContactWizard(SessionWizardView): template_name = 'contact_form.html' def done(self, form_list, **kwargs): form_data = process_form_data(form_list) context = {'form_data': form_data} return render_to_response('done.html', context) def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] return form_data I thought about creating a checkbox field linked to an image field, I don't know if it's the good solution, any suggestions ? -
socket.emit working propely but socket.broadcast.emit not working.TypeError: socket.broadcast is undefined
I am trying https://github.com/mburst/django-realtime-tutorial github example. socket.emit send message to all connected client including sender.I want to exclude sender,for that i used socket.broadcast.emit.But it giving error TypeError: socket.broadcast is undefined.I am using Nodejs 0.9 Below is client side js code var socket = io.connect('localhost', {port: 4000}); socket.on('connect', function(){ console.log("connect"); }); var entry_el = $('#comment'); socket.on('message', function(message) { console.log(message) }); entry_el.keypress(function(event){ //When enter is pressed send input value to node server if(event.keyCode != 13) return; var msg = entry_el.attr('value'); if(msg){ console.log(socket) socket.broadcast.emit('send_message', msg, function(data){ console.log(data); });/* NOT WORKING */ socket.emit('send_message', msg, function(data){ console.log(data); });/* WORKING */ //Clear input value entry_el.attr('value', ''); } }); }); Below is server side js code var http = require('http'); var server = http.createServer().listen(4000); var io = require('socket.io').listen(server); var cookie_reader = require('cookie'); var querystring = require('querystring'); var redis = require('redis'); var sub = redis.createClient(); //Subscribe to the Redis chat channel sub.subscribe('Chat'); //Configure socket.io to store cookie set by Django io.configure(function(){ io.set('authorization', function(data, accept){ if(data.headers.cookie){ data.cookie = cookie_reader.parse(data.headers.cookie); return accept(null, true); } return accept('error', false); }); io.set('log level', 1); }); io.sockets.on('connection', function (socket) { //Grab message from Redis and send to client sub.on('message', function(channel, message){ socket.send(message); }); //Client is sending message through socket.io socket.on('send_message', function (message) { values … -
Sorting Outputs of a List Into Different <UL> Tags Django Template
I have the following code in one of my templates. As you can see, there is a lot of repetition going on. Hence, I am wondering if I can somehow use Django Template to consolidate this code while achieving the same (or closely comparable) result when it comes to HTML. Namely, I am interested if I can sort the todo entries into two different <ul> tags on the page, depending on the boolean value of todo.todo_completed. {% block content %} {% if todo_list %} <ul class="list-group"> {% for todo in todo_list %} {% if not todo.todo_completed %} <li class="list-group-item"> <div class="row"> <div class="col-sm-5"> <a href="{% url 'list:todo-detail' todo.id %}" >{{ todo.todo_name }}</a> </div> <div class="col-sm-6"> </div> <div class="col-sm-1"> <a href="{% url 'list:todo-complete' todo.id %}">{% bootstrap_icon "ok" %}</a> <a href="{% url 'list:todo-delete' todo.id %}">{% bootstrap_icon "remove-circle" %}</a> </div> </div> </li> {% endif %} {% endfor %} </ul> <ul class="list-group"> {% for todo in todo_list %} {% if todo.todo_completed %} <li class="list-group-item"> <div class="row"> <div class="col-sm-5"> <a href="{% url 'list:todo-detail' todo.id %}" class="text-muted">{{ todo.todo_name }}</a> </div> <div class="col-sm-6"> </div> <div class="col-sm-1"> <a href="{% url 'list:todo-complete' todo.id %}">{% bootstrap_icon "ok" %}</a> <a href="{% url 'list:todo-delete' todo.id %}">{% bootstrap_icon "remove-circle" %}</a> </div> </div> </li> … -
How i can get User id by student id?
How i can get the User id by using using student id. I have model named Student. described below. class Student(models.Model): user = models.ForeignKey(User) nationality = models.CharField(max_length=255, blank=True, null=True) -
Updating a variable length html list via ajax
I would like to update a list in my template based on a response from an ajax call. As far as I understand it is not possible to send a list directly back from the view and iterate over it. That is why I tried to come up with an alternative, but I am kind of stuck. Here's my current code: Template (shortened): {% for a in attributes %} <li> a.name </li> {% endfor %} Ajax: $.ajax({ url: "{% url 'main:next_attributes' %}", data: {'next':'abc'}, datatype : 'json', success: function (data) { console.log("Success");}}) console.log should be replaced by something which iterates over new values and updates the values in the list above. Tricky part here is, that the number of list items might be different (both lower or higher) than before. However, I am unclear how the response from the view might look, which is why this still has a placeholder (see next part). Views.py: def next_attributes(request): keyword = request.GET.get('next', None) next_attributes = Attributes.objects.filter(keyword=keyword) data = {'attributes':next_attributes} return JsonResponse(data) Problem here is, that I cannot return a query result via JsonResponse.. In summary: I want to get a new query result based on the filter given in the ajax request and … -
Debug python application running in Docker
I've just recently begun trying to wrap my head around Docker and have managed to get a development machine up and running. What i'm now trying to do is to be able to use the debugger in Visual Studio Code in my python application (specifically Django). I've tried following the limited documentation of the python extension for VS Code which explains the parameters for remote debugging. Dockerfile FROM python:3.5.2 RUN apt-get update \ --no-install-recommends && rm -rf /var/lib/apt/lists/* \ && mkdir -p /code \ EXPOSE 8000 WORKDIR /code COPY requirements.txt /code RUN /bin/bash --login -c "pip install -r requirements.txt" ADD . /code CMD [] docker-compose.yml version: '2' services: db: image: postgres web: build: . volumes: - .:/code ports: - "8000:8000" command: bash -c "./wait-for-it.sh db:5432 && python manage.py migrate && python manage.py runserver 0.0.0.0:8000 --noreload" depends_on: - db launch.json { "name": "Attach (Remote Debug)", "type": "python", "request": "attach", "localRoot": "${workspaceRoot}", "remoteRoot": "/code", "port": 8000, "secret": "debug_secret", "host": "localhost" } I've also added the line ptvsd.enable_attach("debug_secret", address = ('0.0.0.0', 8000)) to one of the project files The Issue When ever I start the debugger nothing happens and it looks like VS Code is waiting for a breakpoint to hit. But it … -
AWS BOTO : No handler After configuration
I'm deploying my Django application on ec2 on AWS. I did configuration setting up ~/.boto and finally succeed in 'python manage.py collectstatic'. If there is an error, then error is caused! (I know because I solved it by setting up ~/.boto configuration file!). But after configuration , when I query my image file at S3 mapped to my imageField model, it shows the error message below: No handler was ready to authenticate. 1 handlers were checked. ['HmacAuthV1Handler'] Check your credentials I think I made it authentication, but why is this message occuring? please help me! -
How to use Django, Elasticsearch and Graphql together?
I'm looking into develop a graphQL API. I have a django/elasticsearch/mysql backend and I'm figuring out how graphQL fits into this picture. I reading about the graphene-django project but it seems tightly coupled with the Django ORM, so I'm wondering is elastic search can fit in this recipe. I'm just starting this research so there is a chance that even this question is making no sense. Any clue about how to do this?