Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return render methd does not working in django
Hi I am very new to the Django and trying to learn going through the vidoes&docs but stuck return the html page from templates. Though posts/index.html exists, getting the error "TemplateDoesNotExist at /posts/" not sure where did I wrong, please advise. here are my directory structure djangoproject/urls.py from django.contrib import admin from django.conf.urls import url, include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^posts/', include('posts.urls')), ] and Django app called "posts" posts/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index') ]; posts/views from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'posts/index.html') posts/templates/posts/index.html <h3>message from index.html</h3> -
Status code: 302 Found - Ajax is Failing to Load the Content
I'm working on a blog on which users can read post & write a comment on it. I'm using Waypoints to load more content as user reaches the bottom of page & ajax to load the comments after user submits a new comment. Problem is that comments are being submitted but ajax is failing to load them back! Here's my code, {% extends 'base.html' %} {% block content %} <div class="infinite-container"> {% for post in posts %} <div class="infinite-item">{{ post }}</div> <div class="comm_update" action="{% url 'comment:create_comment' post.id %}"> <form class="comm_form" action="{% url 'comment:create_comment' post.id %}" method="post" enctype="multipart/form-data"> # Comment Form </form> {% for comment in post.comment_set.all %} <div>{{ comment }}</div> {% endfor %} </div> </div> {% endfor %} </div> {% if post.has_next %} <a class="infinite-more-link" href="?page={{ post.next_page_number }}">More</a> {% endif %} <div class="loading" style="display: none;">Loading...</div> {% endblock %} Waypoints & ajax call: <script> $(document).on("submit", ".comm_form", function(t) { t.preventDefault(); var o = $(this), e = $.post(o.attr("action"), o.serialize()), n = o.attr("action"); e.done(function(t) { var e = $(t).find(".comm_update[action='" + n + "']"); o.closest(".comm_update").html(e), o[0].reset() }) }); var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); </script> So, as user requests the webpage … -
I want to change string date time to django date time
Hello everyone I am new to django and using newsapi to get some news, the api returns a json object having a dateTime attribute like this 2018-04-22T11:38:05Z I want to serialize it into django DateTimeFieldField I have tried .date() but it did'nt worked any help will be appreciated. -
How to Customize django bootstrap form
I am using boostrap forms but I need to customize it in my design. When I simply write <form class="firstform" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} its showing nice form but I want to edit this form as my design what can be the best way to do so? -
App not compatible with buildpack:python.tgz
when I tried to deploy my app to Heroku, I got App not compatible with buildpack, my python version is 3.6.5 and put runtime.txt file with that version, but when I deploy I got that version is not compatible with Heroku as Heroku supports till 3.6.4, what is the best solution for my situation , should i downgrade my python with all the dependencies ?!! -
Docker Compose Django, Webpack and building static files
I’m trying to figure it out how to build static files using Node and Webpack during production build and mount them as volume which is going to be served for Django webapp and used for Django collectstatic. I’ve got all services separated to its own containers and each has own Dockerfile. Current problem is that i can’t access generated access files generated by webpack inside Django app. Question is, can I achieve this using separate Dockerfiles for Node and Django, or shall this be done in one Dockerfile? Node Dockerfile FROM node:alpine WORKDIR ./code COPY ./package.json ./yarn.lock /code/ COPY ./webpack.base.config.js ./webpack.prod.config.js /code/ RUN yarn install --production ADD static /code/static/ RUN yarn run prod Python app Dockerfile FROM python:3.6.2-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ && apk add \ bash \ curl \ build-base \ postgresql-dev \ postgresql-client \ libpq \ tzdata WORKDIR /code ADD requirements.txt /code RUN pip install --upgrade pip RUN pip install -r requirements.txt ADD ./ /code ENV TZ=Europe/London EXPOSE 8000 Docker Compose production version: '3' services: frontend: build: docker/services/node volumes: - static_files:/code/static webapp: build: . env_file: - .env expose: - "8000" volumes: - ./public:/code/public/ - static_files:/code/static command: ["./docker/scripts/wait-for-it.sh", "database:5432", "--", "./docker/services/webapp/run-prod.sh"] depends_on: - frontend - database … -
Django Admin,trouble setting user.is_active to FALSE(banning) through admin action button
I am looking to ban users from an action button in Django admin by setting user.is_active = False, for the selected users. class MyUserAdmin(UserAdmin): list_display = ('username', 'first_name', 'last_name' , 'email') readonly_fields = ('first_name' , ('last_name') , ('email') , ('username')) actions = ['ban_users'] #USER BANNING FUNCTION def ban_users(self, request, queryset): user_obj = User.objects.get(username= 'username') user_obj.update(is_active = False) user_obj.save() admin.site.unregister(User) admin.site.register(User, MyUserAdmin) I've tried a few ways,and It either ends up banning all the users including super users or gives the error : User matching query does not exist. Its a simple function I am trying to implement I know,but any help would be appreciated. -
Is there any way I could change parameters of render using redirect in Django?
I want to change render parameters in Django but, by calling a redirect method. def abc(request): theatre = Theatre.objects.all() return render(request, 'book_tickets/post_list.html', {'theatre':theatre, 'flag': False}) And I want to do something like this: def xyz(request): if (something): return redirect('post_list', 'flag':True) -
Django search using Search Vector using multiple words or partial words
For search I want to use the search vector from PostgreSQL; I wrote a custom query method: def search(self, text): search_vectors = ( SearchVector('name', weight='A', config='english') + SearchVector('short_description', weight='B', config='english') + SearchVector('description', weight='C', config='english') ) search_query = SearchQuery(text) search_rank = SearchRank(search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1]) return self.annotate(rank=search_rank).filter(rank__gte=0.2).order_by('-rank'). There are 2 'issues'. For example for the name 'Eric', if I search: 'eric' I get the correct results 'eric john' I get not result 'eri' I get no results I kind of understand why it fails, but I don't how to implement the fixes. -
docker django elasticsearch Connection refused
I'm running ES with django in docker: version: '2' volumes: postgres_data_local: {} postgres_backup_local: {} es_data: {} services: django: &django build: context: . dockerfile: ./compose/local/django/Dockerfile depends_on: - postgres - elasticsearch volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres - ./.envs/.local/.celery ports: - "8000:8000" command: /start.sh postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile volumes: - postgres_data_local:/var/lib/postgresql/data - postgres_backup_local:/backups env_file: - ./.envs/.local/.postgres elasticsearch: image: elasticsearch:5.6.9 ports: - "9200:9200" volumes: - es_data:/usr/share/elasticsearch/data ES working fine. curl -XGET http://localhost:9200 Returns response. But Django don't see it. When I trying to create index: def indexing(self): obj = Blog( meta={'id': self.id}, name=self.name, created_at=self.created_at ) obj.save() return obj.to_dict(include_meta=True) I get an error: ConnectionError(: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(: Failed to establish a new connection: [Errno 111] Connection refused) -
Submitting variable checkbox form selection in django when choice options are not hardcoded
I am hoping someone can help on this. I am trying to POST submit a checkbox selection in a django template, the only difference that the number of checkbox options is variable, i.e not predefined in the django form. Could you please help me how to do this? thanks so much: views.py: if request.method == 'POST': list_of_files=request.POST.getlist('filetouse') print(list_of_files) else: template: <td> <form action="" method="post"> <div class="form-check"> <input type="checkbox" name="filetouse" class="form-check-input" id="file-{{ key }}"> <label class="form-check-label" for="FileSelect1">Select</label> </div> </form> </td> so I have a variable ID for each checkbox (from the key object attribute that I handed over to the template, my plan being to then do something such as: if request.method == 'POST': #gives list of id of inputs list_of_input_ids=request.POST.getlist('filetouse') but I cannot figure out how to do this POST submission, thanks so much for your help ! -
How to know which model instance is committed in Django function transaction on_commit?
I want to do somethings after the a model instance is committed to database. But the transaction on_commit() does not have any variable related to the instance was saved? Is there any way to know that? Thnkas -
Change href of modal based on button click
Clicking this button opens the modal <button type="button" id ="soldBtn" class="btn btn-info" data-toggle="modal" data-target="#myModal">This laptop has been sold</button> This is the modal <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <p>Confirmation</p> </div> <div class="modal-body"> <p>Are you sure you want to do this?</p> </div> <div class="modal-footer"> <a class="btn btn-outline-success" id="confirmBtn" href="#" >Yes</a> <a class="btn btn-outline-danger" id="cancelBtn" data-dismiss="modal">No</a> </div> </div> </div> </div> </div> I could just have a different modal for different buttons, but I'd rather follow the DRY principle. I'd like the href of the confirmBtn to change based on which button to open the modal was clicked. I've tried this so far but not even sure if I'm on the right track. <script type="text/javascript"> if(jQuery('#soldBtn').data('clicked')) { document.getElementById("confirmBtn").href="{%url 'laptops:sale'%}"; } </script> -
Showing all models in Django admin panel in development
When I am developing I constantly need to access data from the admin panel but I do not wish to add all models in admin.py since I do not want them to be accessed in production. Is there a way to show all models in the admin panel in the development environment and hide (part of) them in production automatically? -
Testing an ImageField in DRF
I am using Django Imagekit in models.py: from imagekit.models import ProcessedImageField class AltroUser(models.Model): first_name = models.CharField(_('first name'), max_length=30) image = ProcessedImageField(upload_to='media/path', default='user_default.jpg', processors=[ResizeToFill(640, 640)], format='JPEG', options={'quality': 60}) serializers.py: class UserRegistrationSerializer(Serializer): first_name = serializers.CharField() image = serializers.ImageField() I am trying to test the image field. I have tried following methods: def get_test_image(): try: image = DjangoFile(open(os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg'), mode='rb')) return image except (OSError, IOError) as e: return None def get_test_image1(): file = io.BytesIO() image = Image.new('RGBA', size=(100, 100), color=(155, 0, 0)) image.save(file, 'png') file.name = 'test.png' file.seek(0) return SimpleUploadedFile('abc.jpg', file.read()) def get_test_image2(): path = os.path.join(django_settings.MEDIA_ROOT, 'user_default.jpg') file = File(open(path, 'r+b')) return SimpleUploadedFile('abc.jpg', file.read()) I have tried calling the above three methods to set the value of the image key but none of them worked. For get_test_image(), I get a response "The submitted file is empty." For get_test_image1() and get_test_image2(), I get a response "The submitted file is empty." with an exception before in the data image field '_io.BytesIO' object has no attribute 'encoding'. I don't understand what am I missing. Please help. -
Custom Search using DjangoFilterBackend
DjangoFilterBackend uses http://localhost:8000/api/v1/contacts/?first_name=Clair&last_name=Test I want to customize this pattern as, http://localhost:8000/api/v1/contacts/?query[first_name]=Clair&query[last_name]=Test How can I customize DjangoFilterBackend? Thanks in advance. -
Django - Print only errors when running all tests
We're using python - Django 1.10. We have more than 1000 tests. When running all the tests we're getting tons of logs to stdout. It mainly hurts on deployments - we're creating a docker instance and run all our tests (with python manage.py test). I would like to somehow print only errors when running all tests. Is there a way to do such thing? -
Django form is being cleaned unintentionally
I have created a view that renders a template, and upon submitting the form, updates two models. I am only validating one form for the moment (is_valid()), but the other form is also being cleaned, even though I have not called the is_valid() or 'clean() methods on them. My view: def update_two_models_at_once(request): if request.method == "POST": form1 = Form1(request.POST) form2 = Form2(request.POST) if form1.is_valid(): #form1.save() #post = form2.save(commit=False) #post.save() return HttpResponseRedirect(reverse('stock:forms')) else: form2 = Form2() return render(request, 'update_models.html', {'form2': form2}) I have a print statement in Form2 and it gets executed every time I submit the form, even though I'm trying to validate Form1 only. Is there something I'm doing wrong or appear to be missing? The trace back is linking back to this line here: return render(request, 'update_models.html', {'form2': form2}) It appears when I first render the page, it's fine. But once I submit the page, Form1 doesn't validate (I have purposely made it not validate), and when it renders the template again, it invokes the clean method for Form2. What's the go with this? I only want to validate and clean Form1 at this time. -
Add application blog to my Django project
Django = 2.0 I want this app to add to my project - https://github.com/pythonsd/test-driven-django-development/tree/master/myblog It works for me, but I don't need comments. And I can't figure out how to delete these comments. In HTML I know how to remove it, but I want to remove comments from models and views, I want to have clean code in my project. https://github.com/pythonsd/test-driven-django-development/blob/master/myblog/blog/models.py - I am to delete class Comment(models.Model) , right? I think yes. https://github.com/pythonsd/test-driven-django-development/blob/master/myblog/blog/views.py - But what I need to remove from the file, if I do not have the comments in my blog-app? Thank you very much. -
Variables in Django template are showing in double quotes
I fetch the data from my Post model and simply passed into the template. But the output is showing in double quotes. I have html tags in my Post model, which is not rendering but showing as codes. views.py # It display the single post def single_post(request,cat,post_id,post_title): single_post = Post.objects.get(pk = post_id) return render(request, 'blog/single_post.html', {'single_post': single_post}) single_post.html <h1>I'm single post page</h1> {{single_post.title}} <br> <br> {{single_post.content}} Browser Output Browser Output Rendered Page -
permissionError while requesting url on chrome
I am Arkadeb Misra. I am making a web app on Django...But when I am requesting the url in Chrome I am getting an error - PermissionError at /learning_logs/ [Errno 13] Permission denied: 'C:\Users\Arka\learning_log\learning_log\learning_logs\templates\learning_logs\index.html'. Can anyone help me! my cmd is showing this contents = self.get_contents(origin) File "C:\Users\Debaleena\d_project\11_env\lib\site-packages\django\template\loaders\filesystem.py", line 23, in get_contents with open(origin.name, encoding=self.engine.file_charset) as fp: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Arka\\learning_log\\learning_log\\learning_logs\\templates\\learning_logs\\index.html' [22/Apr/2018 10:53:39] "GET /learning_logs/ HTTP/1.1" 500 98751 And chrome is showing this.... PermissionError at /learning_logs/ [Errno 13] Permission denied: 'C:\\Users\\Arka\\learning_log\\learning_log\\learning_logs\\templates\\learning_logs\\index.html' Request Method: GET Request URL: http://127.0.0.1:8000/learning_logs/ Django Version: 2.0.4 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'C:\\Users\\Arka\\learning_log\\learning_log\\learning_logs\\templates\\learning_logs\\index.html' Exception Location: C:\Users\Debaleena\d_project\11_env\lib\site-packages\django\template\loaders\filesystem.py in get_contents, line 23 Python Executable: C:\Users\Debaleena\d_project\11_env\Scripts\python.exe Python Version: 3.6.4 Python Path: ['C:\\Users\\Arka\\learning_log\\learning_log', 'C:\\Users\\Debaleena\\d_project\\11_env\\Scripts\\python36.zip', 'C:\\Users\\Debaleena\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Debaleena\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Debaleena\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Debaleena\\d_project\\11_env', 'C:\\Users\\Debaleena\\d_project\\11_env\\lib\\site-packages'] Server time: Sun, 22 Apr 2018 05:23:39 +0000 -
Display aggregated sum in django html template using Model and Views
I have created a model.py as below class overallAccountDetail(models.Model): accountId = models.IntegerField(primary_key=True, unique=False, blank=False, auto_created=True, null=False, editable=False) accountName = models.CharField(max_length=100) countryName = models.CharField(max_length=100) marketName = models.CharField(max_length=100) Alarm_Count = models.CharField(max_length=255,default='',blank=True) TT_Count = models.CharField ( max_length=255 , default='' , blank=True ) Views.py def displayAlarmCount(request): totalAlarmCount=overallAccountDetail.objects.filter(marketName='Market1', accountName= 'Account1').aggregate(Sum('Alarm_Count')).values() ctx = { 'totalAlarmCount': totalAlarmCount } return render_to_response('overallaccountdetail_filter.html', ctx, context_instance=RequestContext(request)) In HTML template {% block content %} <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> filter.qs.totalAlarmCount<br> totalAlarmCount <p><strong>Total Alarm_Count:</strong>{{totalAlarmCount}}</p> <ul> {% for overallAccountDetail in filter.qs %} <li>{{ overallAccountDetail.Alarm_Count }}</li> {% endfor %} </ul> Now the issue is when i am executing the below query in shell, i am getting the sum of all alarm count of Account1 corresponding to Market 1. But when i am displaying same on html .. it is showing nothing. Please advise what's the problem in my code. The below query shows the exact value in shell that i want to present on the webpage totalAlarmCount=overallAccountDetail.objects.filter(marketName='Market1', accountName= 'Account1').aggregate(Sum('Alarm_Count')).values() -
sphinx is showing the django base views instead of my own views.py
The view being shown when using Sphinx on a Django site is: The beginning of my views.py is: import os from django.shortcuts import render, redirect from django.urls import reverse from django.http import HttpResponse, HttpResponseRedirect from django.utils import timezone from . forms import PlayForm, RollForm, checkBoard, BossForm from random import randint from . templatetags.playExtras import translateDice from .models import Board, Winner, Boss def getFirstFolder(req): """ return the string between first two / - this is a hack, find out how to do it with the object """ r = req.split("'") loc = r[1].find('/',1) x = r[1][1:loc] return(x) def loadBoard(request,context,location=''): ''' Load the board from the database into context. Add a hyperlink for available squares. :param context: context for template :type context: dictionary :param location: Comma seperated string of available locations or empty string so no links included. :type location: str :return: 'not on the board' or 'all taken' or comma seperated string of location options such as 'A0,B0' :rtype: str ''' req = request.__str__() I was getting errors if I didn't show Sphinx where the Python was located. The path additions I made in the Sphinx's conf.py are: ourPaths = [ '/game/', '/game/game', '/game/play', '/game/play/templatetags' ] for p in ourPaths: abspath … -
Can I get django model object by pk which is string?
Is it okay if I get model object by string pk? I'm using basic model's pk. What I mean is like: str_pk = str(21) object = ExampleModel.objects.get(pk=str_pk) Is it possible and working well? -
Import CSS styles in pdf view in website
I am trying to develop a website using django framework, where i have to show some information to the user as a pdf. For this reason i design a view page and convert this page to pdf with xhtml2pdf library in python. But the problem is, when i import the style sheets like this it is not working <link href="http://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> but if i write any style directly in between style tag then it works.But it is not a suitable solution for me. How can i solve the problem ? <style type="text/css"> </style>