Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the autofocus field in Django PasswordChangeForm?
I'm looking through the Django documentation and found this line of code I don't get, specifically the autofocus part class PasswordChangeForm(SetPasswordForm): """ A form that lets a user change their password by entering their old password. """ error_messages = { **SetPasswordForm.error_messages, 'password_incorrect': _("Your old password was entered incorrectly. Please enter it again."), } old_password = forms.CharField( label=_("Old password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'autofocus': True}), ) field_order = ['old_password', 'new_password1', 'new_password2'] def clean_old_password(self): """ Validate that the old_password field is correct. """ old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return old_password in the widget=forms.PasswordInput(attrs={'autocomplete': 'current-password', 'autofocus': True}) part, I don't get what the autofocus field is and what it does when it says it's True. What is the purpose of this?? -
why double underscore and single =, instead of . and == in django?
I thought this was python. Why doesn't the upper one work then? CMD -
Django ListView not showing up in frontend
I am trying to create a gym workout basic app in Django, and wish to have my workouts displayed as a list on my home page, using Django's built-in list view. For some reason, my home page template is rendering, with the proper headers and nav bar, but my list is not showing. Here is my code: Models.py from django.db import models STATUS = ( (0,"Draft"), (1,"Publish") ) class Workout(models.Model): workout_number = models.AutoField(primary_key=True) name = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) content = models.TextField() description = models.TextField(blank=True, default='') time_cap = models.TimeField(auto_now=False, auto_now_add=False, blank=True) rounds = models.IntegerField(blank=True, default='') weight = models.FloatField(blank=True, default='') status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.name Views.py from django.shortcuts import render from django.views import generic from .models import Workout class WorkoutList(generic.ListView): model = Workout template_name = 'home.html' context_object_name = 'workout' queryset = Workout.objects.filter(status=1).order_by('-created_on') Template home.html (part of) <div class="container"> <div class="row"> <div class="col-md-8 mt-3 left"> {% for workout in workout_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ workout.name }}</h2> <p class="card-text text-muted h6">{{ workout.created_on}} </p> <p class="card-text">{{workout.content|slice:":200" }}</p> </div> </div> {% endfor %} </div> </div> Workout/Urls.py from django.urls import path from . import views app_name='workout' urlpatterns = [ path('', views.WorkoutList.as_view(), name='home'), ] -
ModelForm has no model class specified Error at Django
I tried to build a simple registration from using django, but somehow it does not work here's my model : class User(models.Model): name = models.CharField(max_length=200,unique=True) email = models.CharField(max_length=200,unique=True) verified = models.BooleanField(default=False) voted = models.BooleanField(default=False) def __str__(self): return self.name Here is my Form : class User_data(forms.ModelForm): class Meta(): form = User fields = ("name", "email") Here's my View.py : def register(response): form = User_data if response.method == 'post': form = User_data(response.POST) if form.is_valid(): form.save(commit=True) return index(response) return render(response,'voting/voting.html', { 'form': form, }) what did I miss? Thank you -
Cannot click button to dismiss the message
I have this code on my template which shows an alert message on the screen when user is logged in and it contains a dismiss button. I've managed to center it in the screen. However, I cannot click on the button - probably because of the header, but I cannot figure out how to fix it. How do I make the button clickable? {% if user.is_authenticated %} <div class="container-fluid"> <div class="row"> <div class="col-lg-6" style="float:none;margin:auto;padding:15px"> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button> <p><i class="fa fa-check"></i> <strong>Hello {{ user.username }}! You have successfully logged in!</strong></p> </div> </div> </div> </div> {% endif %} Thank you. -
Django: Return queryset and string
In Django, is it possible to make a HttpResponse which is a combination of a queryset and a text string? I imagine something like this objs = ModelName.objects.all() text = "Some text" allData = ??? #Some kind of operation (json.dumps, serializers, or ...) that combines the two return HttpResonse(allData,content_type="application/json") -
Django Can I change the Response Charset only in a specific View?
settings.py DEFAULT_CHARSET = 'UTF-8' views.py class OrderResult(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): payload = request.data print(payload) <<---- ....do something i'd like to receive data with 'euc-kr' only in the above View. (Korean is mixed in the data for that part.) -
Why my ArrayField(models.ImageField()) is always getting null value?
I am trying to create an article with multiple images,but i am facing with a problem. class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') MediaImageArray = ArrayField(models.ImageField(upload_to='images',null=True,blank=True),size=8,null=True) When i am posting list of images named as p1.jpg , p2.png,it is always returning null like this: Using Postman: { "id": "34d75f5e-bd82-45a1-9c86-10e3f260311d", "author": "d39d29c8-4807-41c5-a3fa-e9cb117fdb2d", "MediaImageArray": [ null, null ], } Does anybody know the reason? -
Django webapp hosted on Azure DISALLOWED HOST error after creating custom domain
I have a fully working django project hosted on Azure App Service plan and I created a custom domain for my project to go from example.azurewebsites.net to simply example.com. After that I get a following error: DisallowedHost at / Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS. Of course this still happens when I do add example.com to ALLOWED_HOSTS, I have also tried using simply ['*'] which should allow any host but I still get the same error. -
tawk.to chat widget not working with django?
I am trying to add tawk.to chat widget to my django site. I used the Django-tawkto package from https://pypi.org/project/django-tawkto/. But still, it's not showing the widget on the page. Here is the output of my page: My Django template for where I want to use tawk.to chat widget I did check the page source and I can see the tawk.to script over there. But it's not working. I don't know why? page source for above Django template Please help me out here. Thanks in Advance. -
Erratic Login Behavior for a regular user
For a user who is registered, I am trying to log into the web application. Sometimes it will login immediately after inputting the credentials (username and password), and other times it will redirect to the same login page with this error: __all__: Please enter a correct username and password. Note that both fields may be case-sensitive. It is quite erratic in nature so can't pinpoint what really can be the issue. Sometimes it will log in after each attempt to log in a user. And sometimes it will keep failing 4-5 times before it logs me in. I do input the correct credentials. These users are just our regular user and not a superuser and I don't need them to be super users. -
Having trouble linking bootstrap css into my Django page
I am trying to make a user registration template for my future projects and have run into a problem. I attempt to link the style sheets that come with template form but I don't understand how to write the path that will link it all together. Here is the base.html file I am working with. base.html {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>Bare - Start Bootstrap Template</title> <link href= "{% static 'R_form/vendor/bootstrap/css/bootstrap.min.css' %" rel="stylesheet" type="text/css"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark static-top"> <div class="container"> <a class="navbar-brand" href="#">Start Bootstrap</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </div> </nav> <!-- Page Content --> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h1 class="mt-5">A Bootstrap 4 Starter Template</h1> <p class="lead">Complete with pre-defined file paths and responsive navigation!</p> <ul class="list-unstyled"> <li>Bootstrap 4.5.3</li> <li>jQuery 3.5.1</li> </ul> </div> </div> </div> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.slim.min.js"></script> … -
How to open different-2 drop-down using Collapse in Django?
I have a collapse drop-down in my Django project, When I am clicking on button it's opening all the accordion, Please let me know how i can open single single accordion. Suppose if I click on first accordion then only first drop-down should be open, but currently all accordion opens. here is my project.html code... <div class="row"> {% for i in project.projectfloorplan.all %} <div class="col-sm-6"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="false" aria-controls="collapseOne"> <ul class="floor-list"> <li style="color: #2f9cda;">Floor Plan &nbsp;<i class="fas fa-angle-down"></i></li> {% if i.size %} <li><span>{{i.size}} Sq.Ft</span></li> {% endif %} {% if i.bhk %} <li>Rooms : <span>{{i.bhk}}</span></li> {% endif %} {% if i.price %} <li>Price : <span>{{i.price}} </span></li> {% endif %} </ul> </button> </h5> </div> <!-- show --> <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne"> <div class="card-body"> <div class="masonry"> <div class="brick"> <a href="{{i.floorplan_image.url}}" class="js-img-viwer" data-caption="{{i.name}}" data-id="koala" data-group="nogroup" data-index="0"> <img src="{{i.floorplan_image.url}}" alt="{{i.name}}" style="height: 290px; width: 100%;"> </a> </div> </div> </div> </div> </div> </div> {% endfor %} </div> -
Python, Django float() argument must be a string or a number, not 'NoneType
I get an error when run the server: "float() argument must be a string or a number, not 'NoneType" The site worked fine, but after I deleted the database this error appeared views.py def home(request): today = datetime.date.today() tomorrow = today + datetime.timedelta(days=1) service_check = Service.objects.filter( date_of_treatment__gte=today, date_of_treatment__lt=tomorrow) total_service_today = service_check.count() total_price = service_check.aggregate(Sum('price')) total_price_today = float(total_price['price__sum']) context = {'service_check': service_check, 'total_price_today': total_price_today} return render(request, 'main/dashboard.html', context) models.py class Service(models.Model): patient = models.ForeignKey( Patient, related_name='patient', null=True, on_delete=models.SET_NULL) attending_doctor = models.ForeignKey( Doctor, related_name='attending_doctor', null=True, on_delete=models.SET_NULL) treatment = models.ForeignKey( Treatment, related_name="treatment", on_delete=models.SET_NULL, null=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) date_of_treatment = models.DateTimeField() -
How should I get facebook/twitter insights for different projects
Am working on a project that involves getting facebook and twitter insights for multiple companies,,, should I create a developer's account for each and every company or there's a simpler way to get the information. -
Is there a standard way of configuring a mapping from model field names to JSON keys on Django Rest Framework?
I have a Django backend with conventional snake_case model fields. In the frontend, however, they expect another notation. Is there a simple way of configuring a serializer so that every field (e.g. field_name) gets automatically converted to the frontend notation (e.g. fieldName or even something completely different)? I couldn't find any simple way of doing this. I know I can manually declare each field and use source, but besides being a lot of extra work, it still only works for readonly fields if I remember correctly. Besides, it also forces me to declare fields like fieldName = serializers.CharField(source="field_name", ...), and it makes it impossible to use keys like field-name in the frontend. Is there any better way of doing it? -
How to access subcclass attributes in super class methods, without passing them in
How does one access a derived class'es property (static variable in other languages), in its base classes method? I.e. class Base: @classmethod def set_foo(cls): return [1, 2, cls.x] class Derived(Base): x = 3 foo = Base.set_foo() Derived.foo # Hope to have it set to [1, 2, 3] I wish to not pass x directly to the base class, i.e. foo = Base.set_foo(x) because I have a lot of methods to be called with the same variables. EDIT The comments have asked for context. I tried to make a minimum reproducible example to spare you guys the details. Here's the full context: So its actually todo with Django Admin. I have a abstract model. Then I have various admin interfaces for the various concrete implementation of the abstract model. As you can guess I created an asbtract admin model to handle the common logic. A part of handling the common admin logic, e.g. generating properties on the dervived admin model. So for example the list display, heres the logic to create the list display: class FactAdmin(admin.ModelAdmin): @classmethod def build_list_display(cls, *custom): return ( 'created_utc', *custom, 'foo__bar__abbreviation', 'foo__baz__name', 'foo__caz__name', 'foo__daz__description', 'foo__eaz__code', ) @admin.register(FooEntry) class FoopEntryAdmin(FactAdmin): fieldsets = FactAdmin.build_list_display('cannon_ball', 'pogo_stick') So in the base … -
which is best choose for online game back-end (Laravel vs django)?
I want to create a database for a popular online game. Which is better for server-side code between Laravel and django frameworks? -
How to Authenticate Django REST API with HTTP only cookie?
i use django rest framework and react js environment for my project, to store jwt token local-storage, cookie is unsafe so i decided to save httponly cookie, how do i achieve authenticate how pass token in http header -
JSONDecodeError Exception Value Expecting value: line 1 column 1 (char 0)
I am trying to add products in to the cart but whenever I try to add to the cart product added in the cart successfully but whenever I try to see json data I get this error Here is my Views.py for Cart: def updateCart(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) customer = request.user.customer_name product = ProductModel.objects.get(pk= productId) order, created = OrderModel.objects.get_or_create(customer=customer, complete=False) return JsonResponse('Item added to cart', safe=False) Here is my Cart.js var updateBtn = document.getElementsByClassName('update-cart') for(var i = 0; i < updateBtn.length; i++){ updateBtn[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:',productId, 'action:',action) console.log('USER:',user) if(user === 'AnonymousUser'){ console.log('Please Login to Order!') } else { updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('Product added to cart!') var url = '/update_item/' fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({'productId': productId, 'Action':action}) }) .then((response) => { return response.json() }) .then((data) => { console.log('data:',data) // location.reload() }) } I am really new here so please help me I am wrong. And I am stuck here don't know what to do ? :( -
Django Retrive data after a specific number or index
i have two rendered contexts in my view: def PostHomeView(request): RecentPost = Post.objects.order_by("-date").all()[:5] AllOtherPosts = Post.objects.order_by("-date").all() template_name = 'lista_post.html' context = {**strong text** 'recentposts' : RecentPost, 'allposts' : AllOtherPosts } return render(request,template_name,context) in the second one ('allposts') i would like to get all objcects without the first fve how can i do it? -
Huey task not running from django view but works from shell
I am running into a problem and wondering what might be wrong. Problem Huey task is not running when called from web view. But when called from shell command from same VM it runs fine. The task is registering fine with huey. The task in question is handshake. VM: Web, Using View: Not working VM: Web, Using Shell: Working VM: Worker, Using Shell: Working Setup I am running an application in docker. Running two instances of same image with exactly same settings connecting to same redis and same postgres. I have verified that both instances are connected to same Redis. The two instances are: web.1: Running gunicorn web application in normal thread mode. worker.1: Running python manage.py run_huey Settings INSTALLED_APPS += ['huey.contrib.djhuey'] HUEY = { 'name': 'myapp', # Use db name for huey. 'results': True, # Store return values of tasks. 'store_none': False, # If a task returns None, do not save to results. 'utc': True, # Use UTC for all times internally. 'blocking': True, # Perform blocking pop rather than poll Redis. 'consumer': { 'workers': 2, 'worker_type': 'thread', 'initial_delay': 0.1, # Smallest polling interval, same as -d. 'backoff': 1.15, # Exponential backoff using this rate, -b. 'max_delay': 10.0, # … -
How to manually turn off a condition thru frontend javascript
I have a function on my django app that automatically executes when certain conditions are met. Now I want to happen is, the user have the ability to turn on/off that automatic feature on a toggle button. @views.py def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', created_gt=now() - timedelta(days=3), sms_sent=False, ) if responses.count() >= 50: send_sms() responses.update(sms_sent=True) @urls.py urlpatterns = [ path('send_sms/', send_sms, name='send_sms'), ## To execute this, call the API endpoint from vue path('auto_sms/', auto_sms, name='auto_sms'), ## There must be a toggle button for on & off. ] How to do it? I mean what logic or condition. I'm using DRF-VueJS Thanks! -
how to compare uploaded file in already exist in django model
I am getting a file from the user and filter data from the model if the user uploaded file exists or not, but I am getting "None" while filtering. from .models import SomeModel uploaded_file = request.FILES.get('upload_file') model_data = SomeModel.objects.filter(my_file=uploaded_file) if model_data == None: someModel.objects.create(my_file=uploaded_file) else: print('file already exist.') print(model_data) # prints None I have uploaded the same file too many times but it always creates new data in the model. I know every time when uploaded file Django creates a new file in the media folder. how can I filter if uploaded_file already exists in the model? -
multiple inline formset in django
Hi everyone this is Dilip here, i am an intermediate to django. I want multiple form to be saved at the same time. where one table is independent and other two tables are linked as ForeignKey to first one. I want to add data to all three tables at the same time and I should get an option to open and close new fields. like django default admin panel TabulorInline form. Here i am able to do with single table which is having ForeignKey with another, but what if there are two foreignkey associated a single table?