Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pdf report genrate in python 2.7
https://dpaste.de/RosE check this link. i write a code for pdf file report genrate. but face error.Kindly check my code. Any solution for me tell me Thanks -
Celery & Django: calling completed_count() floods workers?
I'm trying to get the progress of a Celery task group, called like so in consumers.py: searches = [s.strip() for s in query.split(',') if s.strip()] task_group = group([refresh_func.s(user_profile, search, dont_auto_add) for search in searches]) result = task_group.apply_async() result_waiting = result.waiting() This is all happening inside a Django channels, utilizing daphne and websockets, but that shouldn't matter too much. In order to poll the current task-group completed count, and return it to the client, I'm doing this later in consumers.py: while result_waiting: result_dict = { 'type': 'results_update', 'completed': result.completed_count(), 'total': search_len, } Group(user_profile).send( { 'text': json.dumps(result_dict), } ) if result.completed_count() == len(searches): result_waiting = False It's working fine, except that relative to the time the mission itself takes - it's also painfully slow. The tasks in the group are completed in seconds, but .completed_count() takes from 20-50 seconds to show the right completed tasks count. If I add time.sleep(0.1) at the end of the while loop above, The results update much faster, but that seems like an anti-pattern. What is going on here? Am I utilizing completed_count wrong? Is it overloading the workers, the websocket? -
Job completing in Celery terminal but returns false in Django
I have the following code in my Ajax View: def ajax_view(request, task_id): results = convert_to_nightcore.AsyncResult(task_id) print(task_id) if results.ready(): return render_to_response('download_ready.html', {'results': results.get()}) return render_to_response('not_ready.html', {}) This is in my urls.py url(r'^result/(?P<task_id>.*)$', views.ajax_view, name='result') This is the result of my task in celery: [2017-12-16 09:08:38,534: INFO/MainProcess] Received task: nightcore.tasks.convert_to_nightcore[cd1b19fd-f721-4fa1-b9db-1ce01738d030] [2017-12-16 09:08:38,536: INFO/ForkPoolWorker-2] Task nightcore.tasks.convert_to_nightcore[cd1b19fd-f721-4fa1-b9db-1ce01738d030] succeeded in 0.00173856299989s: '/home/student/PycharmProjects/tonightcore/media/uploads/The_Skeptic_in_the_Room-OPs_j1EEplI_3O4k7JT.mp3' The task prints out the value it is supposed to print. This is the printed out value of print(task_id) in my Ajax View: [16/Dec/2017 09:11:19] "GET /result/cd1b19fd-f721-4fa1-b9db-1ce01738d030 HTTP/1.1" 200 22 cd1b19fd-f721-4fa1-b9db-1ce01738d030 As you can see the values are the same, but when I query http://127.0.0.1:8000/result/cd1b19fd-f721-4fa1-b9db-1ce01738d030, it returns the not_ready.html while it is supposed to return download_ready.html -
Django: Unknown column 'last_login' in 'field list'
I did look through other topics but I couldn't find anything useful or that would help me. All I did was doing python manage.py inspectdb > models.py and then edit the file a bit, the user model and then did migrate. Now when I try to create a super user I get this error D:\Programming\Web\blaine county\website>python manage.py createsuperuser --username=andrei --email=andreigames9@gmail.com Password: Password (again): This password is too short. It must contain at least 8 characters. Password: Password (again): Traceback (most recent call last): File "D:\Programming\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "D:\Programming\Python\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute return self.cursor.execute(query, args) File "D:\Programming\Python\lib\site-packages\MySQLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "D:\Programming\Python\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "D:\Programming\Python\lib\site-packages\MySQLdb\cursors.py", line 247, in execute res = self._query(query) File "D:\Programming\Python\lib\site-packages\MySQLdb\cursors.py", line 411, in _query rowcount = self._do_query(q) File "D:\Programming\Python\lib\site-packages\MySQLdb\cursors.py", line 374, in _do_query db.query(q) File "D:\Programming\Python\lib\site-packages\MySQLdb\connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1054, "Unknown column 'last_login' in 'field list'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "D:\Programming\Python\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "D:\Programming\Python\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Programming\Python\lib\site-packages\django\core\management\base.py", line 288, … -
email field for authentication in django2.0
i create new project on Django 2.0 and DRF, my need use email field for users authentication. How better do it, write authentication backend or use similar code class MyUser(AbstractUser): USERNAME_FIELD = 'email' email = models.EmailField(_('email address'), unique=True) thanks in advance -
Custome model creation for user details
I want to create a custom verification process in my application.Below is the steps 1 User signup and activates accounts 2 After new user logs in, user needs to fill in the organisation details -type of orgainsation -type of service they provide 3 An organisation can include many department or address, here they should be able to fill details like -name -type -number of employees 4 User also should have an option to enter there detail like -email -phone -sate,zip etc Please let me know how can I design the Django Model for this. -
GET request the django way
I am playing with Django and have the following question. I have a search form in some template: <form role="search" method="get" action="{% url 'polls:search' %}"> .... <\form> which, for example, forms the following request: http://127.0.0.1:8000/search/?text=dog&year=2017 The corresponding function in the view.py file works well with this request. At some point in other template i need to make a link which leads to http://127.0.0.1:8000/search/?text=&year=2017 I do the following: <a href="{% url 'polls:search' %}?text=&year=2017"> It looks a little bit ugly and maybe incorrect. Is there another way? For example, is it possible to form the get request in the Django way: http://127.0.0.1:8000/search/dog/2017 So in the other template, one can write <a href="{% url 'polls:search' %} text='' year=2017"> -
Does my Django app have to be the same name as the project directory?
I've pulled my django repo from bitbucket onto my digital ocean server. My project folder name in my server is project whereas my initial app from my repo (the one with settings.py is called app. Does this cause any problems? Because I know when you create a django project offline, the first directory is always the same as the parent directory. -
Django get request via ajax making two requests
I am working on passing data from ajax to a Django view. However, ajax somehow is making 2 GET requests: one with the query string and the other without it. In the view when I try to get the query string its empty. Ajax code: <script> $( document ).ready(function() { var query = "{{ item.ipv4_address }}"; $("#clickid").click(function() { $.ajax({ url: "/reserve/run/?ip=", type: "GET", data: {ip:query}, success:function(data){ console.log(data); } }); }); }); </script> Django view: def run_script(request): if request.GET: ip = request.GET['ip'] print ip return render_to_response('test.html',{'item':ip}) Two urls: [16/Dec/2017 07:03:56] "GET /reserve/get/?ip=198.18.101.123 HTTP/1.1" 200 1355 [16/Dec/2017 07:03:58] "GET /reserve/run/ HTTP/1.1" 200 1 Please let me know where I am going wrong. Also, let me know if you need any more info. Any pointers is appreciated. -
Error 500 - After configuring angular frontend and django backend with apache in ubuntu 16.04 server
usr/sbin/apache2' [Sat Dec 16 06:39:39.071803 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] mod_wsgi (pid=28509): Target WSGI script '/var/www/project/project/wsgi.py' cannot be loaded as Python module. [Sat Dec 16 06:39:39.071866 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] mod_wsgi (pid=28509): Exception occurred processing WSGI script '/var/www/project/project/wsgi.py'. [Sat Dec 16 06:39:39.072683 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] Traceback (most recent call last): [Sat Dec 16 06:39:39.072728 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] File "/var/www/project/project/wsgi.py", line 18, in [Sat Dec 16 06:39:39.072732 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] application = get_wsgi_application() [Sat Dec 16 06:39:39.072737 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] File "/var/www/project/projectenv/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Sat Dec 16 06:39:39.072740 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] django.setup(set_prefix=False) [Sat Dec 16 06:39:39.072744 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] File "/var/www/project/projectenv/lib/python3.5/site-packages/django/init.py", line 22, in setup [Sat Dec 16 06:39:39.072747 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Sat Dec 16 06:39:39.072751 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] File "/var/www/project/projectenv/lib/python3.5/site-packages/django/conf/init.py", line 56, in getattr [Sat Dec 16 06:39:39.072753 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] self._setup(name) [Sat Dec 16 06:39:39.072757 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] File "/var/www/project/projectenv/lib/python3.5/site-packages/django/conf/init.py", line 41, in _setup [Sat Dec 16 06:39:39.072759 2017] [wsgi:error] [pid 28509] [remote 49.248.67.206:17340] self._wrapped = Settings(settings_module) [Sat Dec 16 06:39:39.072763 2017] … -
How to create different model database for different user in Django
I am trying to create a todo website. In that all the users will have their own list of Todos. But it is showing the same list to all the users and also, other users can edit,delete and add to the todo-list which is again visible to all the users. models.py from django.db import models from django.contrib.auth import get_user_model from django.conf import settings class todo (models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete="models.CASCADE") todo_topic = models.CharField (max_length = 50) todo_description = models.TextField(max_length=100) todo_date = models.DateTimeField(null = True) date_added = models.DateTimeField(auto_now = True,) completed_or_not = models.CharField(choices=(('Done', 'Done'), ('Not Done', 'Not Done')), default = 'Not Done', max_length=10) views.py from django.shortcuts import render from .models import todo from .forms import addTodo_form, edit_form from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required def dashboard(request): if request.user.is_authenticated: todo_list = todo.objects.order_by('-date_added') template = 'customers/dashboard.html' return render (request, template, {'todo_list' : todo_list}) else : return render (request, 'customers/home.html') @login_required def addTodo(request): if request.method == 'POST' : form = addTodo_form(request.POST) if form.is_valid(): topic = form.cleaned_data['topic'] des = form.cleaned_data['description'] date = form.cleaned_data['todo_date'] #user = User.objects.get(username=request.user.username) user=request.user gta = user.todo_set.create(todo_topic = topic, todo_description = des, todo_date = date) message = 'Item Added To Your Todo List' … -
Django Admin, how to populate select options depending on another select
My scenario: I'm having three tables, Category, Subcategory, Products. While inserting new product, there are two select boxes 1)1st select is for Category (its working) 2) 2nd is for Subcategory, which should be relevant to the 1st select. Needs to fetch the data from subcategory table. Subcategory table has category id as a foreign key. I am a beginner, please somebody help. -
Get absolute file path of FileField of a model instance in Django
I have a page where people can upload files to my server. I want to do something with the file in Celery. So, I need to know the absolute filepath of the uploaded FileFiled of my Model. Let's say I queried the model and got the instance. Now I need to get the absolute file path including the filepath. obj = Audio.objects.get(pk=1) I'm currently trying obj.filename and it's only printing the file name and not the absolute path. I know I can get the upload path I input into upload_to and media directory, but I was wondering if there was a more DRY and automatic approach. How do I get the absolute path of file which is a file filed in obj? -
Django signals not working with channels in multicontainer setup
I have django app and implementing websocket support with channels and channels api. I am using demultiplexer with bindings to my models. For example when i save a model it will send the change to my open websocket connection. Everything works OK if i run ./manage.py runserver 0:80 and have all in one container. But if i separate my app to UWSGI, daphne and the worker containers using docker the signals are not triggered. For example i want any celery worker (task) to trigger the signal and send update via the websocket. In my multicontainer setup the websocket connection is established OK and web works OK, but nothing triggers that signals. How the signals are defined you can see here on github. I am using django 1.9.12, python 2.7, docker and build on debian stretch. docker-compose.yml web: build: . ports: ["8001:80"] daphne: build: . command: daphne -b 0.0.0.0 -p 8000 --access-log - -v 2 my_proj.asgi:channel_layer ws_worker: build: . command: ./manage.py runworker -v 2 celery_worker: build: . command: /usr/local/bin/celery -A my_proj worker nginx.conf upstream django { server unix:/home/docker/app.sock; } server { listen 80; server_name 127.0.0.1; charset utf-8; client_max_body_size 1000M; location /static/ { alias /home/docker/static/; } # proxy to other container location … -
Django form used multiple times in single HTML and avoid duplicate id
Python 3.6.3, Django 1.11.8, Chrome Version 63.0.3239.108 (Official Build) (64-bit) I have a create project form. Which is added multiple modals in html code. I used prefix attribute in form class, with this can avoid duplicate ID from other forms same name fields. But how to deal with same name multiple ID created by one form used multiple time in single html ? form.py class CreateProjectForm(forms.ModelForm): prefix = 'create_project' class Meta: model = Project fields = ['project_name', 'project_type', 'description'] widgets = {'description': forms.TextInput(attrs={'placeholder': 'description'})} My Form is working fine. but I am keep getting this error in Chrome Developer console: [DOM] Found 2 elements with non-unique id #id_create_project-description: <input type="text" name="create_project-description" placeholder="description" maxlength="200" id="id_create_project-description"> <input type="text" name="create_project-description" placeholder="description" maxlength="200" id="id_create_project-description"> (index):1 [DOM] Found 2 elements with non-unique id #id_create_project-project_name: <input type="text" name="create_project-project_name" maxlength="50" required id="id_create_project-project_name"> <input type="text" name="create_project-project_name" maxlength="50" required id="id_create_project-project_name"> (index):1 [DOM] Found 2 elements with non-unique id #id_create_project-project_type: <select name="create_project-project_type" required id="id_create_project-project_type">…</select> <select name="create_project-project_type" required id="id_create_project-project_type">…</select> -
In EmailMultiAlternatives attach and attach_alternative both at time is not working
from django.core.mail import EmailMultiAlternatives subject, from_email, to,bcc = request.POST['sub'],'fulfillment@***.com', lead.mailid,email_ccaddress msg = EmailMultiAlternatives(subject, "", from_email, [to]) filepdf = open("Plan.pdf",'rb').read() msg.attach("Plan.pdf",filepdf,'application/pdf') msg.attach_alternative(request.POST['bodyofmail'], "text/html") msg.content_subtype = 'html' msg.send() using Django 1.11.3 python3 EmailMultiAlternatives Individually both are working fine but once we run this code with attachment and attach_alternative HTML only pdf attachment is receiving in an email server -
Update view using function based view
How can I pass an object into a model form to pre-populate the field when the page is rendered? I want to do something similar to the build in Django UpdateView class based view but with a function based view. -
django error: 'subjects' object has no attribute 'get'
I'm working in my first django project. Unfortunately, I'm facing an issue that should be straightforward. my scenario: models.py from django.db import models # Create your models here. ## 1. Model for user registration class subjects(models.Model): description = models.CharField(max_length=500) def __Str__(self): return self.description views.py from django.contrib.auth import login , authenticate from django.shortcuts import render , redirect from poc_teaching.models import subjects # Create your views here. def list_subj(request): subj = subjects.objects.all() return render (request,'subjects.html',{'subjects': subj}) urls.py from django.conf.urls import url #from . import views from poc_teaching import views as poc_views urlpatterns = [ url('subjects/$',poc_views.subjects,name ='subjects'), ] html <head> "hello world" </head> <div> {{ subjects }} </div> I'm getting the error: 'subjects' object has no attribute 'get' I've gone thru the admin console to add objects. So, I'm pretty sure I should get results. I have gone thru many documents but really I dont understand where is my issue. I appreciate your help. thanks. -
Django adding basic search in navbar
In process of adding basic search bar for searching the menu titles in my menu list I am getting this error django.core.exceptions.FieldError: Cannot resolve keyword 'title_icontains' into field. Choices are: id, menu_title, price, title_content my views.py from django.shortcuts import render from django.http import HttpResponse,Http404,HttpResponseRedirect,HttpResponseNotFound from resturant.models import Carousel from resturant.models import Menu from django.db.models import Q from django import forms def search(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] menu_item = Menu.objects.filter(title_icontains = q) return render(request, 'sources/search_results.html',{'menu_item':menu_item, 'query': q}) else: return HttpResponse('Please submit a search term.') my search_results.html {% if menu_item %} <p>Found {{ menu_item|length }} item{{ menu_item|pluralize }}.</p> <ul> {% for s in menu_item %} <li class="wow fadeInUp" data-wow-duration="300ms" data-wow-delay="300ms"> <div class="item"> <div class="item-title"> <h2>{{ s.menu_title }}</h2> <div class="border-bottom"></div> <span>$ {{s.price}}</span> </div> <p>{{s.title_content}}</p> </div> </li> {% endfor %} </ul> {% else %} <p>No Menu_Items matched your search criteria.</p> {% endif %} And my urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login urlpatterns =[ url(r'^$', views.index , name= "index"), url(r'^menu/$', views.menu , name= "menu"), url(r'^check/$',views.check,name='check'), url(r'^search/$',views.search, name='search') ] -
What is the logic for a blog when we already have predefined CSS tags and need to upload multiple images and videos in same file?
Am creating one blog for my website. I have predefined CSS for all images, videos, code etc. Example: <div class="post-title">TITLE</div> <div class="col-md-12 blog-post">MY CONTENT</div> <div class="post-image"></div> ... When I fetch data from database, if the data is in correct tags then only get the CSS style. So when I save into db should I save it with these tags? i.e with <div class="post-image">/images/img.png</div> I know this is not the way it should be. When I thought about dynamic loading like this in django, {{ image_url }} But how would I know when I should append '' , if it is not in db! Example content: Hello world <IMG src='images/img1'> Hellow again. AM pretty happy. <IMG src='images/img2'> <CODE 1> So for each image tag, should I save it inside <div class="post-image">/images/img.png</div> ? Which free editor can I use in my website to add content to blog ? If I use an editor will it be possible to keep my CSS content same? In database, for a 'content' field, if I want to add images and video links, should it be a new columns or it should be a html tag inside content itself? -
django Keyerror password
I am trying to create a edit user profile feature which allows users to edit their profile info. When I click on submit in the form it is showing as keyerror password at albums/profile/edit. Error Screen Shot Views.py: from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib.auth.models import User from django.contrib.auth.forms import PasswordChangeForm from django.views.generic import View from albums.models import Album, Song from .forms import Userforms, EditProfileForm class Profile_edit(View): form_class = EditProfileForm template_name = 'accounts/edit_profile.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): form.save() return redirect('profile') return render(request, self.template_name, {'form':form}) forms.py: from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm from django import forms class EditProfileForm(UserChangeForm): class Meta: model = User fields = {'email', 'first_name', 'last_name', 'password'} urls.py url(r'^profile/edit/$', views.Profile_edit.as_view(), name='Profile_edit'), edit_profile.html: {% extends 'albums/base.html' %} {% block title %}Sign Up{% endblock %} {% block albums_active %}active{% endblock %} {% block body %} {% extends 'albums/base.html' %} {% block title %}Sign Up{% endblock %} {% block albums_active %}active{% endblock %} {% block body %} <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% … -
How to fetch table data to dropdownlist and save it to another table
I have two tables one is height and another is register in my mysql database..now I want to insert height table values to my drop-down list and after selecting that values it should be inserted into register table with value not with id...need help.. -
SMTPAuthenticationError; Username and Password not accepted
I'm following along with this book and in chapter 18 part of the current assignment involves sending an email via Django. I have a yearly domain I use for testing, and rather than pay an additional 5$ a month I figured I'd just have the emails forwarded to an existing address, using these instructions. I then went ahead and set it up so I could send mail using an alias via the Sending mail from your forwarded email address section However, I'm unable to get it working using the generated app password + alias. When I try to send an email from the page it only works if 2FA is disabled and I use my actual gmail credentials, say for example: EMAIL_HOST_USER = 'bob@gmail.com' EMAIL_HOST_PASSWORD = 'bobswife123' It works as intended. However, lets say I wanted to use my generated app password and alias, something like: EMAIL_HOST_USER = 'alias@bob.com' EMAIL_HOST_PASSWORD = 'bobsmistress123' Then I'll get the following error: Was able to make any use of the support article from the URL in the above screenshot, but here it is for the sake of convenience: https://support.google.com/mail/?p=BadCredentials Anyways, these are the exact steps I'm taking: From terminal on macOS 10.13.1, I run … -
Integration of Datastax(Spark, Cassandra, Solr) with a Django website
I am looking for options for Integration of Datastax(Spark, Cassandra, Solr) with a Django(python) website.Has anyone done this implementation and if possible can you please let me know the steps? Thanks, DP -
Best practices for GeoDjango Models
I have a classic GeoDjango model from django.contrib.gis.db import models class Location(models.Model): vessel = models.ForeignKey(Vessel, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, blank=True) point = models.PointField() However usage seems quite clumsy; >>> foo = somevessel.location_set.create(point=Point(5, 23)) >>> foo.point.x 5.0 I still want to store the location as a point but would prefer to interact with the model with more native looking code, something like >>> foo = somevessel.location_set.create(latitude=5, longitude=12) >>> foo.latitude 5.0 Is this against best practices? And is there a simple way to achieve this in Django?