Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Virtual Environment Transfer
Currently I have learnt Django and have made many projects. So, I wanted to deploy my projects on heroku but I have not made my projects in virtual Environment. So, they are not able to get deploy So, my question is how to can I transfer my projects to virtual environment. Or I have to make all projects again in virtual Environment? -
How to fix a MultiValueDictKeyError
I am trying to get the time spent on each page in a Django project using Javascript. I keep getting an error so I am trying to fix it the error: MultiValueDictKeyError at /backendurl/ 'timeSpent' Highlighted line of error in views.py: timeSpent = request.POST['timeSpent'] Here is the javascript in template: <script> $(document).ready(function() { var startDate = new Date(); $(window).unload(function() { var endDate = new Date(); $.ajax({ type: POST, url: "backendurl", // be mindful of url names data: { 'timeSpent': endDate - startDate || 'none' // defaults to a string }, success: function(response) { // unpack response: status = response.status } }) </script> Here is the views.py: def my_view_function(request): timeSpent = request.POST['timeSpent'] response = json.dumps({ 'timeSpent' : timeSpent, }) return HttpResponse(response) Here is the url.py path('backendurl/', views.my_view_function, name='backendurl'), -
Django NoReverseMatch Reverse for 'new_proc' with arguments '(1,)' not found
Could anyone explain what is wrong here? view: class ProcessCreate(View): def get(self,request, appId, procId): context = {'appId': appId, 'subpage':1, 'procId': procId} return render(request, 'analysis/diagram.html', context) url: path('applications/<int:appId>/processes/<int:procId>/', login_required(login_url='/analysis/login')(process.ProcessCreate.as_view()), name="new_proc") html: href="{% url 'analysis:new_proc' row.id %} " Thanks for your help -
django-elasticsearch-dsl NestedFiled not working for ManyToManyField
I have successfully been able to declare, map, and populate all model fields to Elasticsearch Index except the Price field on the BookPrice model which is using through attribute. If I remove the Price field from the document then it works fine. However, I had successfully been able to build the Index in the past, but I think I made some changes and I lost the code integrity, and it's not working now. I tried all possible combinations I found on help forums and official documents, but with no luck. I am currently using Elasticsearch == 7.8.0 elasticsearch-dsl == 7.2.1 django-elasticsearch-dsl == 7.1.1 models.py class Publisher(models.Model): publisher_name = models.CharField(max_length=50) class BookType(models.Model): book_type = models.CharField(max_length=20) # Hard Cover, Soft Cover, Kindle Edition, Digital PDF etc. class Book(models.Model): book_title = models.TextField() book_types = models.ManyToManyField(BookType, through='BookPrice', through_fields=('book', 'book_type')) class BookPrice(models.Model): book_type = models.ForeignKey(Booktype, on_delete=models.CASCADE) book = models.ForeignKey(Book, on_delete=models.CASCADE) price = models.DecimalField(max_digits=7, decimal_places=2) documents.py @registry.register_document class BookDocument(Document): book_title = fields.TextField( attr='book_title', fields={ 'suggest': fields.CompletionField(), }) publisher = fields.ObjectField(properties={ 'publisher_name': fields.TextField(), }) book_types = fields.NestedField(properties={ 'id': fields.IntegerField(), 'book_type': fields.TextField(), 'price': fields.FloatField() }) class Index: name = 'books' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Report fields = [ 'id', 'slug', 'published_date', 'pages', … -
Elastic Beanstalk environment's health severe: Following services are not running: release
I deployed a Django application to Elastic Beanstalk (EB) Amazon Linux 2 Python 3.7 platform and everything seems to be working fine. However, the health of the environment is severe and I can't figure out why. The only information EB gives me is the following: Overall status: Degraded - Impaired services on all instances. (there is only one instance running) Instance status: Severe - Following services are not running: release. I found no information about what the "release" service is. From the full logs, the only errors I'm seeing are the following: daemon.log: F, [2020-11-07T04:03:03.891398 #5022] FATAL -- : /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/launcher.rb:432:in `block in setup_signals': SIGTERM (SignalException) from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/single.rb:117:in `join' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/single.rb:117:in `run' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/launcher.rb:172:in `run' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/puma-4.3.5/lib/puma/cli.rb:80:in `run' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/healthd-1.0.6/bin/healthd:112:in `block in <top (required)>' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/healthd-1.0.6/bin/healthd:19:in `chdir' from /opt/elasticbeanstalk/lib/ruby/lib/ruby/gems/2.6.0/gems/healthd-1.0.6/bin/healthd:19:in `<top (required)>' from /opt/elasticbeanstalk/lib/ruby/bin/healthd:23:in `load' from /opt/elasticbeanstalk/lib/ruby/bin/healthd:23:in `<main>' From what I've read here this SignalException is thrown to shut down a process, so I assume it's normal. There is no other error in any of the other logs. Turning the enhanced health check off would be the easy "solution" as stated here but I would like to keep them on. Any help is very much appreciated. -
Can I use XSLT with XML in Django
I have been trying to render an XML page in Django After Passing after going to link i get a blank page and my line is commented out automatically enter image description here -
Django Inconsistent Login Behavior
I have an app in Django wherein the user logs in and is redirected to a page. I have changed the redirect url for both login and logout in settings.py to ensure redirection happens. LOGIN_REDIRECT_URL='/' LOGOUT_REDIRECT_URL='/' Below is a small snippet from the server post log-in. Notice the two POST behaviour. The first one works accurately with 302 as the response code. If you notice the next POST, it is response code 200. This 200 response code keeps occurring multiple times before I am able to login with response code 302 (that is, login works as expected). Here is another image that shows the behavior: I am baffled by this behavior. Can someone help me understand why this is happening? Thank you! -
KeyError at /videos/compose/ 'items'
here i am working with youtube api and trying get youtube video titlt with json response but getting KeyError at /videos/compose/ 'items' can you guys tell me what is wrong here , i have printed video_id that is correct but getting error on retrieving title if a video. views.py class VideoCreateView(CreateView): model = Video form_class = VideoForm template_name = "videos/video_form.html" def form_valid(self, form): video = Video() video.url = form.cleaned_data['url'] parse = urllib.parse.urlparse(video.url) video_id = urllib.parse.parse_qs(parse.query).get('v') if video_id: video.youtube_id =video_id[0] response = requests.get(f'https://youtube.googleapis.com/youtube/v3/videos?part=snippet&id={video_id[0]}&key=[{ YOUTUBE_API_KEY }]') json = response.json() title = json["items"][0]["snippet"]["title"] video.title = title video.save() return super().form_valid(form) urls.py app_name = 'videos' urlpatterns = [ path('compose/',views.VideoCreateView.as_view(),name='new'), path('video/<str:slug>/',views.VideoDetailView.as_view(),name='video_detail'), ] if more code is require than tell me in a comment session , i will update my question with that information. -
Django hangs when i call js file from static folder
I use a template with parallax image and navigation bar in it. I've added news ticker like this: jQuery News Ticker: .remove() dom effect I use same code from link to animate my ticker: var leftMargin, scrollSpeed; var playScroll = true; scrollSpeed = 5; leftMargin = 0; function autoPlay() { if (playScroll) { $('.news-ticker-display').animate({ marginLeft: --leftMargin }, scrollSpeed, "linear", function () { var $first = $('.news-ticker-display li:first'); var width = $first.outerWidth(); if (leftMargin < -width) { $first.clone().appendTo('.news-ticker-display ul'); leftMargin = leftMargin + width; $first.remove(); $(this).css({marginLeft: --leftMargin}); } autoPlay(); }); } } autoPlay(); When i add it directly to the template it works fine. However when i try to call it from static <script src='{% static "scripts/textnews.js" %}'></script> my page starts to freeze. It doesn't happen every time. What is more frequency of freezes decrease after log out. -
django + javascript: issue with adding modelformset row
I have a template that renders a modelformset and I am trying to dynamically add rows to the formset upon the click of a button. Being a javascript ignorant, I am stucked on the following javascript problem: new_sale.html:331 Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. this is what my template looks like: <form method="POST" class="form-validate" id="formset"> {% csrf_token %} {{ formset.management_form }} <table id="formset" class="sale-form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> </div> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle row1 row2 %}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> <div id="emptyform_wrapper" style="display:none"> <table class='no_error'> {{ form }} </table> </div> </div> <br> <br> </form> <button class="btn btn-success" id="add-more">Add</button> <button id="Download"class="btn btn-primary" type="submit" form="formset">Save</button> </section> </div> </div> <footer class="footer"> <div class="footer__block block no-margin-bottom"> … -
Is it best if i use django-oscar for building a multi-vedor site?
I've been working with django for sometime now and i'm thinking about launching an ecommerce platform in my city as a startup. The thing is i can't decide whether to build it from scratch or should i use a preexisting framework like oscar... which is the best way to go if i want a multivendor site which is tailored to my specific idea? -
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()