Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authentication with Django channels using Tokens - How do I use this mixin
My website hosts a lot of APIs(CRUDs) using DJR. I am using DJR Token based authentication and for testing I would add this header to postman Key : Authorization value : Token 826fdf3067b07afdf9edd89a6c9facd9920de8b8 and Django Rest Framework would easily be able to authenticate the user. Now I inlcuded Django channels constantly 1.1.5 and wanted to know how I could do token based authentication. I read this post and it suggests that I copy this mixin to the project. I just started with Django-channels and am not sure how to include that mixin to my code. Currently I have something like this @channel_session_user_from_http def ws_connect(message): user = message.user message.reply_channel.send({"accept": True}) #Send back Acceptance response. @channel_session_user def chat_join(message): user = message.user #Get authenticated user I have the following two questions 1-How do I include that mixin in my current project ? I know you include mixins in classes using class classname(SomeMixin). How would I go about including this mixin into my code ? 2-Will my join json message have an authentication token in it ? Any suggestions would be great. ` -
Django display limited images in grid row
As mentioned in the title. Is it possible to display a specific number of photos in a particular grid-container? For example, a maximum of 3 columns with a card in the row using a loop? I was able to achieve the effect of displaying all the photos from the defined model,but I don't know how to set the limit. Below I present fragments of the code responsible for displaying the created model forms.py class ProductsForm(forms.ModelForm): class Meta: model = Product fields = ('name', 'description', 'image', 'file_type') models.py class Product(models.Model): name = models.CharField(max_length=20, default='') description = models.CharField(max_length=100, default='') file_type = models.CharField(max_length=256, choices=[('image', 'image'), ('thumbnail', 'thumbnail')], default='') image = models.ImageField(upload_to='products', default='') def __str__(self): return self.name views.py def gallery(request): image = Product.objects.filter(file_type='image') thumbnail = Product.objects.filter(file_type='thumbnail') return render(request, 'products/fruits.html', {'img': image, 'thumb': thumbnail}) fruits.html <!DOCTYPE html> {% load staticfiles %} {% load thumbnail %} {% block body_block %} <div class="grid-container"> <div class="card-deck"> {% for i in thumb %} {% thumbnail i.image "150x150" crop="center" as im %} <!-- Card --> <div class="card mb-4"> <!--Card image--> <div class="view overlay"> <img src="{{ im.url }}" alt="Card image cap"> <a href="#!"> <div class="mask rgba-white-slight"></div> </a> </div> <!--Card content--> <div class="card-body"> <!--Title--> <h4 class="card-title">Card title</h4> <!--Text--> <p class="card-text">Some quick example … -
How to pass args into a serializers is_valid() in Django DRF?
I am trying to create a flag called unique as you can see below class RecordSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('name',) def is_valid(self, raise_exception=False, unique=None): if hasattr(self, 'initial_data'): if unique is True: # if obj already exists raise if Record.objects.filter(name=self.initial_data['name']).exists(): raise RecordExists("This Record already exists") return super().is_valid(raise_exception) I basically want to call is_valid(unique=true) to trigger that block in is_valid() RecordExists returns a 202 status, so that is the expected result here but instead I am just getting a generic 500 and I know it is related to the code above. Is it possible to pass in args like how I'm doing here? -
JSfiddle javascript works for django stripe application, but doesn't work when moved to project
So, I have a django project that is attempting to run stripe ach payments. I've set up the basic page. When I use jsfiddle and submit the form with the placeholders as values, I get a success response for the stripe token: However, when I add the same code to my django project (see below) nothing happens upon submit. The console doesn't say anything is wrong. I'm not sure how to trouble shoot it any further. Thoughts? {% extends 'base.html' %} {% block content %} <script src="https://js.stripe.com/v3/"></script> <div class='col-10 col-md-6 mx-auto' class='ach-font'> <!-- <form action="//httpbin.org/post" method="POST"> --> <form method="POST" class='ach-form'> {% csrf_token %} <input type="hidden" name="source" /> <div class="group" class='ach'> <label class='.ach-label'> <span>Name</span> <input id="name" class="field" placeholder="Jenny Rosen" /> </label> <label class='.ach-label'> <span>Type</span> <select id="type" class="field"> <option value="individual">Individual</option> <option value="company">Company</option> </select> </label> <label class='.ach-label'> <span>Routing number</span> <input id="routing-number" class="field" placeholder="110000000" /> </label> <label class='.ach-label'> <span>Account number</span> <input id="account-number" class="field" placeholder="000123456789" /> </label> </div> <button type="submit" class='.ach-button'>Submit</button> <div class="outcome"> <div class="ach-error"></div> <div class="ach-success"> Success! Your Stripe token is <span class="token"></span> </div> </div> </form> </div> <script> var stripe = Stripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh'); var elements = stripe.elements(); function setOutcome(result) { var successElement = document.querySelector('.ach-success'); var errorElement = document.querySelector('.ach-error'); successElement.classList.remove('visible'); errorElement.classList.remove('visible'); console.log(result) if (result.token) { // … -
Apply CSS to Django Form Wizard
I´m working with the Form Wizard which is alright but right now its not really pretty. My Views.py is based on the docs: class ContactWizard(SessionWizardView): form_list = [DurationForm, ContactForm2] def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) My done.html contains: {% extends "base.html" %} {% block content %} <h1> Done! </h1> {% endblock %} My forms are defined in forms.py: from django import forms class DurationForm(forms.Form): Duration_in_secounds = forms.IntegerField() class FrequencyForm(forms.Form): Frequency_in_time_interval = forms.IntegerField() Now i wonder how the forms even render because i never load them the way i used (for example with {{form.as_p}} Because whatever i change in my done.html doesnt affect the forms created with the wizard i have no idea how to add css to them. Could any of you help me get whats going on here? (sorry if the question is stupid/ already asked - its quite late here and i couldn´t find anything for the last two hours) -
How do I get a post save to increment a hidden field in django python for a unique row?
How do I get a post save to increment the hidden vote field in django python for a unique row? My model is a table of unique pastries that has a vote field that should increment with each post save when user submit a vote for their favorite pastry. If two people submit muffins as their favorite pastry muffin should only be on 1 row with vote field equal to count of 2. Thanks. MODELS.PY from django.db import models from django.utils import timezone from django.urls import reverse class Pastry(models.Model): pastry = models.CharField(max_length=20, default="muffin",unique=True, choices=( ("muffin", "Muffin"), ("cupcake", "Cupcake"), ("brownie", "Brownie"), ("cake", "Cake"), ("fruittart", "Fruit Tart"))) vote = models.IntegerField(default=0) def get_absolute_url(self): return reverse("pastry_detail", kwargs={'pk': self.pk}) def __str__(self): return self.pastry VIEWS.PY from django.shortcuts import render from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from myapp.models import Pastry from myapp.forms import PastryForm from django.db.models import F class PollsListView(ListView): model = Pastry def get_queryset(self): #order by descending Date return Pastry.objects.all() class PollsDetailView(DetailView): model = Pastry class PollsCreateView(CreateView): success_url = reverse_lazy('pastry_list') form_class = PastryForm model = Pastry def add_poll(request): if request.method == 'POST': Pastry.objects.filter(pk=Pastry.pk).update(vote=F('vote')+1) class PollsUpdateView(UpdateView): success_url = reverse_lazy('pastry_list') form_class = PastryForm model = Pastry class PollsDeleteView(DeleteView): model = Pastry success_url = reverse_lazy('pastry_list') … -
django permission error /admin/fonts/Roboto-Regular-webfont.woff
I get permission error. Permission denied for /admin/fonts/Roboto-Regular-webfont.woff on my docker container. I got this error by getting inside the docker container by the command docker exec -it /bin/bash and running curl -XGET 'http://localhost' It is displaying error on the line {% stylesheet 'style' %} on my base.html. The docker is inside ubuntu machine which is on aws. I am running this application with nginx and uwsgi. Please help me in fixing this issue. With many thanks, Bharath AK -
Django Website Background not functioning when running server using my IP
Problem: When I attempt to run the Django website, the background only shows when I don't run it with the IP. Running it with the IP is needed to allow other people on my network to connect. Running server with IP (python manage.py runserver my.v.4.ip:8000) - https://gyazo.com/d149b93f4c87bcd74fc0aa12588aeced Running server without IP (python manage.py runserver) - https://gyazo.com/7965448c296daffc57fb862cf1385e83 style.css script: li a { color: blue; } body { background: white url("images/background.gif") no-repeat; } Code inside of website: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" /> System Information: Django Version: 2.0.5, Processing system: Windows 10, Python Version: 3.6.3 -
Django - get id of posted form in post method of view that contains list of forms
I have a view that display a list of Lecture object each lecture has a file select button that automatically submits the selected file. The relevant part in html template: {% for lecture in past_lectures %} <form method = "post" id=upload_{{lecture.pk}} action=""> {% csrf_token %} <input type="file" onchange="$('#upload_{{lecture.pk}}').submit();" value="Upload Audio..."/> </form> {% endfor %} The view class: class LectureListView(ListView): model = Lecture ordering = ('name', ) context_object_name = 'past_lectures' template_name = 'professor/home.html' def get_queryset(self): professor = self.request.user.professor lecture_queryset = Lecture.objects.filter(course__professor = professor) return lecture_queryset def post(self, request,): pk = int(request.POST['id'].split('_').[-1]) #return the pk portion of the id of the form lecture = Lecture.objects.get(pk=pk) lecture.audio = request.FILES['audio'] #audio is the name of the filefield in Lecture model lecture.save() return reverse('professor:home') The problem is that request.POST['id'] does not return the id of the form but rather looks for any element with the name 'id' which doesn't exist. How do I get the lecture.pk value based on the form submitted? -
Kubernetes Pod Object crashing in infinite loop when trying to deploy Dockerized Django application with PostgreSQL DB
I am working on my Django project and I am trying to deploy it on Kubernetes cluster ( Google Cloud Provider ). I've managed to create all the files I need for configuring the cluster: Django App Deployment + Service .yml files Postgres DB Deployment + Service + PersistentVolumeClaim ( which dynamicly creates PersistentVolume object and uses PD storage on cloud nodes by default )+ Secret .yml files Docker File + Docker Compose ( I dont have much experience with docker so there might be something wrong with them, maybe that is the issue but I cannot figure it out ) For some reason when i try to apply them my PODs, specifically Django Application PODs, are Crashing in an infinite loop. Also my Postgres Pod is not crashing but it is not running eather. Can anyone help me figure out what am I doing wrong? Here is my github repo: https://github.com/…/mast…/agents/config/kubernetes/postgres My best guess is that I did not set DATABASES configuration in settings.py file correct, and that my Django Application cannot find DATABASE HOST specified in settings.py. If anyone has any suggestions please leave a comment. -
nginx configuration to leverage browser caching in Django app
I have recently deployed my first django app on DigitalOcean. My nginx configuration looks very much similar to this, taken from here server { listen 80; server_name your_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /root/djtrump/static/; } location / { include proxy_params; proxy_pass http://your_ip:8030; } } How can I modify this configuration to leverage browser caching? -
After integrating django channels in django app. I am getting a lot of 404 page not found on local host
I currently have a Django website which is running on my local host 127.0.0.1 The website uses Django Rest Framework and hosts a bunch of REST apis. I just added Django channels to the website and now 2 in 5 calls to an api on my local host would return back a 404 page not found error. I have to try the same api multiple times to get a response. Any idea why this might be happening.The way I integrated channels into my app was by installing redis and adding channels to my installed apps and then adding an interface layer like this #Redis config redis_host = os.environ.get('REDIS_HOST', 'localhost') # Channel layer definitions # http://channels.readthedocs.org/en/latest/deploying.html#setting-up-a-channel-backend CHANNEL_LAYERS = { "default": { # This example app uses the Redis channel layer implementation asgi_redis "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6379)], }, "ROUTING": "main.routing.channel_routing", # We will create it in a moment }, } Any suggestions on why my CRUD apis are returning back 404 page not found results and not being reached even though they are running on my local machine right now ? -
How to get help_text on a custom Django ModelChoiceField
I'm creating a custom ModelChoiceField so I can display custom labels for my foreign key, but in doing so Django no longer displays the help_text on the form. How can I get the help text back? models.py class Event(models.Model): title = models.CharField(max_length=120) category = models.ForeignKey(Category, default=Category.DEFAULT_CATEGORY_ID, on_delete=models.SET_NULL, null=True, help_text="By default, events are sorted by category in the events list.") forms.py class CategoryModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return "%s (%s)" % (obj.name, obj.description) class EventForm(forms.ModelForm): category = CategoryModelChoiceField( queryset=Category.objects.all(), ) class Meta: model = Event fields = [...] -
Django Template Section Dependent on Block Presence
Is it possible in django version 2.x to conditionally render HTML only if block is present? {% if block content %} <tag> {% block content %} {% endblock %} </tag> {% endif %} <tag></tag> should not be displayed unless content block is in extending template. -
Annotate non-modal data in query
I have a model Event which has a ManyToManyField named users. I want to get all the events with an extra attribute which denotes whether a specific user belongs to this event or not. user = User.objects.get(id=1) events = // Event query print events[0].your_event // It should be True or False Here is the working solution which I tried from django.db.models import Case, When, BooleanField user = User.objects.get(id=1) Event.objects.annotate(your_event=Case(when(users=user, then=True), default=False, output_field=BooleanField())) I believe a better solution can exist for this purpose. -
Cannot create form field as model is not loaded
Here is my model class AbstractSubnet(TimeStampedEditableModel): subnet = NetworkField(default="10.0.0.0/24") description = models.CharField(max_length=100, blank=True) master_subnet = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name="child_subnets") class Meta: abstract = True def __str__(self): return str(self.subnet) And the form: class AbstractSubnetAdminForm(forms.ModelForm): class Meta: model = AbstractSubnet fields = '__all__' This is giving me the following error, and I guess it's quite obvious as well, ValueError: Cannot create form field for 'master_subnet' yet, because its related model 'django_ipam.Subnet' has not been loaded yet Any solution to this problem? -
Run Django tests against an existing database with custom testrunner
I've got an application that is running Django 2 that connects to a Microsoft SQL Server backend. We're in a big environment where things are pretty tightly controlled - a user account has access to the database that houses all the tables for my django application. So I have found through various posts that I need to create a testrunner for my application - which is fine. I can override the setup_databases function - but I'm not sure exactly how to do that. My TestRunner(DiscoverRunner) looks like this: class ExistingDbTestRunner(DiscoverRunner): """ A test runner to test without database creation """ def setup_databases(self, **kwargs): """ Override the database creation defined in parent class """ # force Django to connect to the correct db for tests connection = self.connections['default'] db_conf = connection.settings_dict connection.connect() def teardown_databases(self, old_config, **kwargs): """ Override the database teardown defined in parent class """ pass But this fails with AttributeError: 'ExistingDbTestRunner' object has no attribute 'connections' I'm just trying to get this to use the 'default' database that I have set in the settings for testing purposes. It's worth noting - the default database specified in settings is a duplicate copy of the production database with a different name. … -
FOREIGN KEY constraint failed when creating a new user
I'm a beginner at django and decided to build one of my projects using the new and upcoming react + django combo's and am using django-rest for my backend as a REST api. I've built my models and everything is working fine except after including all the walls of code below I try to register my user but end up getting a foreign key constraint. I am unable to figure out what is causing this error. I've built a custom user model using django-rest-auth on my django app which uses django-rest-framework, the user model is: class User(AbstractBaseUser): username = None email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=100) college = models.CharField(max_length=100) date_of_birth = models.DateField(default=datetime.date.today) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser is_participant = models.BooleanField(default=True) is_mentor = models.BooleanField(default=False) is_sponsor = models.BooleanField(default=False) is_end_user = models.BooleanField(default=False) contested_challenges = models.IntegerField(default=0) mentored_challenges = models.IntegerField(default=0) mentored_won_challenges = models.IntegerField(default=0) sponsored_challenges = models.IntegerField(default=0) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [ 'date_of_birth' ] objects = UserManager() def sponsor_challenge(self): new_sponsor_count = self.sponsored_challenges + 1 setattr(self, 'sponsored_challenges', new_sponsor_count) self.save(update_fields = ["sponsored_challenges"] ) def mentor_challenge(self): new_mentor_count = self.mentored_challenges + 1 setattr(self, 'mentored_challenges', new_mentor_count) self.save(update_fields = ["mentored_challenges"] ) def contest_challenge(self): new_contest_count = self.contested_challenges … -
Render/Load context one by one when it's ready in Django
I have a generic.ListView class to take care of the content on this page class SspView(generic.ListView): template_name = 'page.html' context_object_name = 'result_list' def get_context_data(self, **kwargs): context['a'] = ... context['b'] = ... context['c'] = ... ... return context Each context will call some function to calculate some result, and some of them will a few seconds. In this structure, what's the best option to load context a, b, c on the web page when they are ready instead waiting for everything to be ready. Thank you -
Large set of data, DataTables render time awful
I have a view that displays a set of data of about 3000+ records (multiple objects combined into a QuerySet. The result is rendered into a table using DataTables but the render time is terrible - 15 seconds at least. I dug deeper into DataTables and found deferRender API option together with AJAX thing. As I never used it before I'd like to ask for guidance on how to approach in my particular case. Below are views.py and template with DataTables. views.py: def index(request): clients = Client.objects.all().prefetch_related('loan_set', 'loan_set__case_set') return render(request, 'app/index.html', {'clients': clients}) index.html: <table id="case_list" class="display"> <thead> <tr> <td>Imię i nazwisko</td> <td>Edycja</td> </tr> </thead> <tbody> {% for c in clients %} <tr> <td>{{ c.firstName }}&nbsp;{{ c.lastName }}</td> {% if c.editLock %} <td><i class="fas fa-lock fa-lg" style="color:Red" title="W edycji przez:&nbsp;{{ c.lockedBy }}"></i>&nbsp;{{ c.lockedBy }}</td> {% else %} <form method="post"> {% csrf_token %} <td><a href="/edit/{{ c.pk }}" name="c_id"><i class="fas fa-pen-square fa-2x" style="color:green"></i></a></td> </form> {% endif %} </tr> {% endfor %} </tbody> </table> <script type="text/javascript"> $(document).ready(function(){ $('#case_list').DataTable( { deferRender: true } ); }); </script> -
open() "/root/project/static/*.css" failed (13: Permission denied) nginx
I have gotta my project setup with uwsgi, django, nginx Everything seems to be working fine but somehow I keep on getting the error on getting static files I have been reading through online and tried all the possible ways but I keep on getting this permission denied error on my static folder. Can someone please let me know what I have done wrong with the permission and how I should change it? this is my /var/log/nginx/error.log open() "/root/project/static/*.css" failed (13: Permission denied), client: 2xx.xx.xx.xxx, server: _, request: "GET /static/*.css HTTP/1.1", host: "1xx.xx.xx.xxx" This is my nginx site-available config server { listen 80 default_server; listen [::]:80 default_server; # root /var/www/html; # Add index.php to the list if you are using PHP # index index.html index.htm index.nginx-debian.html; server_name _; #location = /favicon.ico { access_log off; log_not_found off; } #location /media { # root /root/project/mediafiles; #} location ^~ /static/ { allow all; # this is from one of the posts but no luck auth_basic off; # this is from one of the posts but no luck root /root/project; } location / { include uwsgi_params; uwsgi_pass unix:/tmp/uwsgi/project.sock; } } as my folder permission for project folder it's drwxr-xr-x 23 www-data www-data for static … -
What IP to use with Redis in production?
I am using Redis for Caches and as Celery broker in my project. So these are my local settings: CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", ......... } } CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' Now I am deploying my project and used this tutorial to set Redis in prod. But when I run redis-cli in prod console - I see that it runs on 127.0.0.1:6379. The question is - how should I change my prod_settings to make Redis work with my project? If I have my_prod_ip - should I change somewhere in the Redis settings to my_prod_ip: 6379 and next in my prod_settings something like this: CELERY_BROKER_URL = 'redis://my_prod_ip:6379' Or should I leave Redis running on "prod localhost" and it will communicate with my my_prod_ip somehow? -
function object has no attribute 'get extra action'
I'm learning show to work with rest-framework and using this tutorial: https://medium.com/quick-code/crud-app-using-vue-js-and-django-516edf4e4217 Codes: Serializers.py from rest_framework import serializers from .models import Category class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('name',) viewsets.py from .models import Category from rest_framework.viewsets import ModelViewSet from .serializers import CategorySerializer # Create your views here. #APRENDEND SOBRE SERIALIZER def CategoryViewSet(ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() rounters.py from rest_framework import routers,viewsets from app.viewsets import CategoryViewSet router = routers.DefaultRouter() router.register(r'category/',CategoryViewSet,base_name='queryset') urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from django.conf import settings from django.conf.urls.static import static from .routers import router urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('navegar/',include('app.urls')), path('',include('accounts.urls')), ] And at this point this error shows up: extra_actions=viewset.get_extra_actions() Attribute Error: 'function' object has no attribute 'get_extra_actions' -
Redirects and Sessions
I have a ReactJS component inside a Django template, where a user clicks on a checkout button and posts the item_code: onCheckout = () => { fetch("/onCheckout/", { method: "POST", body: JSON.stringify({'item': this.props.item_info.code}) }) } A Django view receives the request and stores it in a session. def onCheckout(request): if request.method == "POST": items = request.session.get('items', []) new_item = json.loads(request.body.decode('utf-8'))['item'] items.append(new_item) request.session['items'] = items return redirect('checkout_page') For some reason the redirect doesn't work, even though Django logs the correct redirect: [23/May/2018 17:30:53] "POST /onCheckout/ HTTP/1.1" 302 0 [23/May/2018 17:30:53] "GET /checkout/ HTTP/1.1" 200 611 Now besides for the redirect issue, I am having a issue with the session. After the first item gets stored correctly in the array, and I then checkout on a second item, the items array starts acting up: (Pdb) items ['15130BC.ZZ.8042BC.01'] (Pdb) new_item '5213G-001' (Pdb) items ['15130BC.ZZ.8042BC.01'] (Pdb) items ['5213G-001'] I am fairly new to Django, any help would be appreciated. -
Why does DRF custom exception raise 500 instead of 202?
exception class CustomExcep(APIException): def __init__(self, obj): self.obj = obj self.status_code = 202 self.default_detail = 'This {} already exists.'.format(self.obj) self.default_code = 'accepted' in serializers def duplicate_check(self): if Person.objects.filter(name=name, age=age).exists(): raise CustomExcep('Person') return True This results in a generic 500 error with no other information. If I remove the init method and just raise CustomExcep without passing anything in, it returns 202 as expected. What am I doing wrong?