Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django Forms Validation message not showing
I'm trying to restrict file type, size and extension that can be uploaded in a form. The functionality seems to work, but the validation error messages are not showing. I realize that if file._size > 4*1024*1024 is probably not the best way - but I'll deal with that later. Here's the forms.py: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'description', 'url', 'product_type', 'price', 'image', 'image_url', 'product_file'] labels = { 'name': 'Product Name', 'url': 'Product URL', 'product_type': 'Product Type', 'description': 'Product Description', 'image': 'Product Image', 'image_url': 'Product Image URL', 'price': 'Product Price', 'product_file': 'Product Zip File', } widgets = { 'description': Textarea(attrs={'rows': 5}), } def clean(self): file = self.cleaned_data.get('product_file') if file: if file._size > 4*1024*1024: raise ValidationError("Zip file is too large ( > 4mb )") if not file.content-type in ["zip"]: raise ValidationError("Content-Type is not Zip") if not os.path.splitext(file.name)[1] in [".zip"]: raise ValidationError("Doesn't have proper extension") return file else: raise ValidationError("Couldn't read uploaded file") ...and here's the view I'm using for that form: def post_product(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ProductForm(data … -
Making EMail address unique in DJango authentication system
I need to make the EMail field of the DJango authentication system unique. I am using Python 3.6.3 and DJango 1.11.7 In order to do so, I found this: Making email field unique with Django User admin When following it, I add the code below to __init__.py under the application folder that represents the authentication. I have also tried adding it to the __init_-.py file for the project. from django.contrib.auth.models import User User._meta.get_field("email")._unique = True Either way, I still get the same error (which is listed below). How do I solve it? TIA C:\WORK\Software\Python64bitv3.6\python.exe manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001F9D03BCEA0> Traceback (most recent call last): File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\WORK\Software\Python64bitv3.6\lib\site-packages\django-1.11.7-py3.6.egg\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\WORK\Software\Python64bitv3.6\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen … -
Docker container stops responding to network calls
I've my django application running using gunicorn inside docker container. Randomly, the container stops responding to network calls. Container is up and running. I've checked the stats too for cpu or memory usages and they seem to be fine. My docker version: Client: Version: 1.13.0 API version: 1.25 Go version: go1.7.3 Git commit: 49bf474 Built: Tue Jan 17 09:50:17 2017 OS/Arch: linux/amd64 Server: Version: 1.13.0 API version: 1.25 (minimum version 1.12) Go version: go1.7.3 Git commit: 49bf474 Built: Tue Jan 17 09:50:17 2017 OS/Arch: linux/amd64 Experimental: false Curl command response: * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 8001 (#0) > GET /api/health/ HTTP/1.1 > User-Agent: curl/7.35.0 > Host: localhost:8001 > Accept: */* > No response for above is received. Although ping inside the container works fine. If it's a known problem, solution would be great otherwise what all other parameters / tools I should look into to debug this or fix this ? -
Django celery worker to send real-time status and result messages to front end
In a django app I'm running async tasks and would like to show progress, errors etc to the user. If there are errors, the user should be redirect to a page where additional input or some action is required to fix the problem. What is the best way to communicate from the celery work back to the front end? Here's a basic structure in pseudo code: # views.py from tasks import run_task def view_task(): run_task.delay() return render(request, 'template.html') # tasks.py from compute_module import compute_fct @shared_task def run_task(): result = compute_fct() # how to catch status update messages from compute_module while compute_fct is running?? if result == 'error': handle_error() else: handle_succes() # compute_module import pandas as pd def compute_fct(): # send message: status = loading file df = pd.read_csv('test.csv') # send message: status = computing val = df['col'].mean() if val is None: return {'status':'error'} else: return {'status':'success','val':val} What I would ideally want: compute_module.py module uses python native logger. By separation of duties I want to keep the logging as generic as possible and use the standard python/django loggers. But they don't seem to be designed to send messages to front end. celery task somehow handles the logs and instead of displaying …