Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels - Group name must be a valid unicode string containing only ASCII alphanumerics, hyphens, or periods
I need help in creating chat rooms, it works like I'm entering into specific room (like "Python Community", "DjangoDev", etc.). Packages that I use: Django==1.9.7, channels==1.1.8, asgi-redis==1.4.3 I use slug fields of group name, I filter this slug in Channels find group and call save every time new message is coming. So main reason of problem is Channels throws an error which says that the name of group is invalid: (venv) alibek@OverlorD:~/Desktop/my_porject/RedProject$ ./manage.py runworker 2018-03-17 13:59:51,607 - INFO - runworker - Using single-threaded worker. 2018-03-17 13:59:51,608 - INFO - runworker - Running worker against channel layer default (asgi_redis.core.RedisChannelLayer) 2018-03-17 13:59:51,608 - INFO - worker - Listening on channels chat-messages, http.request, websocket.connect, websocket.disconnect, websocket.receive Not Found: /home/ Not Found: /favicon.ico Traceback (most recent call last): File "./manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "/home/alibek/Desktop/my_porject/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/alibek/Desktop/my_porject/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alibek/Desktop/my_porject/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/alibek/Desktop/my_porject/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/alibek/Desktop/my_porject/venv/local/lib/python2.7/site-packages/channels/management/commands/runworker.py", line 83, in handle worker.run() File "/home/alibek/Desktop/my_porject/venv/local/lib/python2.7/site-packages/channels/worker.py", line 151, in run consumer_finished.send(sender=self.__class__) File "/home/alibek/Desktop/my_porject/venv/local/lib/python2.7/site-packages/django/dispatch/dispatcher.py", line 192, in send response = receiver(signal=self, sender=sender, **named) File "/home/alibek/Desktop/my_porject/venv/local/lib/python2.7/site-packages/channels/message.py", line 105, in send_and_flush sender.send(message, immediately=True) File "/home/alibek/Desktop/my_porject/venv/local/lib/python2.7/site-packages/channels/channel.py", line 88, … -
How to save the changed record in the database
I have two models: the participant model and the event model, admin creates a new event, in which case the participants create an application in the event and save it. Additionally, the participant can edit his application, but here I have problems, the changed save is not saved in the database, the record remains the same as when creating, help to find the error? Models: class Event(models.Model): creator = models.ForeignKey('auth.User') event_id = models.AutoField(primary_key=True) date = models.DateTimeField(blank=True, null=False, help_text='Date and time format is : dd.mm.yyyy hh:mm:ss') title = models.CharField(max_length=30, blank=True, null=False) created_date = models.DateTimeField(blank=True, null=True, default=timezone.now) approved_event = models.BooleanField(default=False) def approve(self): self.approved_event = True self.save() def __str__(self): return '%s' % self.title class Participant(models.Model): person = models.ForeignKey('auth.User') fullname = models.CharField(max_length=50) event = models.ForeignKey(Event, related_name='event') age = models.CharField(max_length=3) relationship_choices = (('with partner', 'with partner'), ('without partner', 'without partner')) drinks_choice = (('nothing', 'nothing'), ('wine', 'wine'), ('beer', 'beer'), ('vodka', 'vodka')) relationship = models.CharField(max_length=30, choices=relationship_choices) drink = models.CharField(max_length=10, choices=drinks_choice) approved_invite = models.BooleanField(default=False) created_date = models.DateTimeField(blank=True, null=True, default=timezone.now) def approve(self): self.approved_invite = True self.save() def __str__(self): return '%s' % self.event Views: def add_event(request): if request.method == "POST": form = AddEventForm(request.POST) if form.is_valid(): event = form.save(commit=False) event.creator = request.user event.created_date = timezone.now() event.save() return redirect('event_details', pk=event.pk) else: form … -
Django admin on saving Field doesn't have a default value
Try to save an object in admin but get an error Field 'site_id' doesn't have a default value user model: class User(AbstractUser): address = models.CharField(max_length=128, blank=True) site = models.ForeignKey(Site, related_name='users', default=1) review model: class Review(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='reviews') title = models.CharField(max_length=128, verbose_name='Review Title') text = models.TextField(verbose_name='Your Review') admin: @register(Review) class ReviewAdmin(admin.ModelAdmin): pass i user Django==1.6.11 and MySQL==5.7.14 -
generate select field in django form using model
I'm writing a Django application and building the form manually. <form method="post"> {% csrf_token %} <input name="name" class="form-control"> <textarea name="description"> <select name="teaching_language"> <option value="">Value 1</option> </select> </form> my models.py contains class TeachingLanguage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=250) modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class META: verbose_name_plural = 'teaching_languages' db_table = 'languages' def __str__(self): return self.title class Course(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=250) teaching_language = models.ForeignKey(TeachingLanguage, on_delete=models.CASCADE) description = models.TextField(blank=True) I have to fill <option> by the list of TeachingLanguage The view.py file contains class NewCourse(CreateView): model = Course fields = ['name', 'teaching_language', 'description'] def get_context_data(self, **kwargs): context = super(NewCourse, self).get_context_data(**kwargs) teaching_languages = TeachingLanguage.objects.all() context['teaching_languages'] = teaching_languages return context def form_valid(self, form): form.instance.created_by = self.request.user form.save() return super().form_valid(form) How to render the teaching_languages in select field to generate a dropdown list? -
How can I integrate linkedin login in Flask application?
I'm developing web apps using flask where the user can enter the app by signing up with LinkedIn. How can I do this? any documentation, example tutorial will be really helpful. I searched on google I didn't find suitable answer All I found is Flask-OAuthlib I didn't understand what it is, can anybody explain to me what is OAuthlib used for? thanks. -
How to consume rest apis more than one with django?
I want to get data from multiple api in django using request.get() method. Normally we fetched data django like this: response = requests.get('http://freegeoip.net/json/') Is it possible to get data from 3 different api like this. response=requests.get('http://freegeoip.net/json/','http://api.example.com','http://api.anotherexample.com'); -
Like/Unlike Button with jQuery
I'm trying to create a Like/Unlike button with jQuery! Here's what I did, Here's the HTML, <span class="like-button">{% if request.user in likes.all %}Unlike{% else %}Like{% endif %}</span> Here's the jQuery, $('.like-button').click(function(){ var x = $(this); x.toggleClass('like-button'); if(x.hasClass('like-button')){ x.text('Like'); } else { x.text('Unlike'); } }); When I press Like button it works fine & text changes into Unlike, but problem is after refreshing the webpage when I press Unlike button it takes 2 clicks to turn back into Like. How can we solve it or is there any other better way to do this? Thank You :) -
How to upload InMemoryUploadedFile to my S3 Bucket?
I have a simple upload form which includes an image as a FileField: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect('/home/') else: form_post = PostForm() context = { 'form_post': form_post, } return render(request, 'post/post.html', context) else: return HttpResponseRedirect("/accounts/signup/") When a user adds an image to the form, it fires this JS function: $('input#id_image').on('change', function(e) {...} which gives a preview of the image. This is the point where I want the image to be uploaded to my media folder directory (I'm using S3 storage). By default, the image is uploaded when the user submits the form, but I want it to be uploaded as soon as $('input#id_image').on('change' is triggered. What I've done so far is retrieve the image in InMemoryUploadedFile format in my views: $('input#id_image').on('change', function(e) { var formData = new FormData(); formData.append('image', $('input[type=file]')[0].files[0]); formData.append('csrfmiddlewaretoken', $("input[name='csrfmiddlewaretoken']").val()); $.ajax({ url: '/upload_image/', data: formData, type: 'POST', contentType: false, processData: false, ... }); ^ sends to views: def upload_image(request): if request.is_ajax(): img = request.FILES.get('image') print(img) #successfully prints the filename But I'm stuck in what to do next in terms of uploading this InMemoryUploadedFileto my S3 bucket. Any advice? -
Django ORM with Key/Value Table structure
I'm trying to get the django orm to replicate a call on a database for my current table structure: Tables: ServiceItems {Id, name, user, date_created} ServiceItemsProps {fk_to_ServiceItems Item_id, Id, key, value} I'm trying to select items from the ServiceItem table with multiple keys from the ServiceItemsProps table as columns. I can accomplish this with a query like the following: > select tbl1.value as bouncebacks, tbl2.value as assignees from > service_items join service_item_props as tbl1 on tbl1.item_id = > service_items.id join service_item_props as tbl2 on tbl2.item_id = > service_items.id where service_items.item_type='CARD' and > tbl1.key='bouncebacks' and tbl2.key='assignees' But I'm not able to figure out how to reproduce this in Django's ORM. I would like to not inject raw SQL into the statements here, because codebase portability is important. -
Linking todolist to a user
I am creating a web application that allows a user to create a todolist where they can add, delete, and edit todo list items (todos). I am using the django framework to do so and I have gotten it to work for the most part. So far, I have implemented adding, editing, and deleting todos from a todolist, I have created a superuser, and I am able to log in to the site using my superuser. However, I want to let each user have their own unique todolist. I don't want users to see each other's todolists. I am new to python and django and I am not sure how to go about doing this. I have created a test user using the admin site and when I log in using this test user, I am taken to the page with the same (and only) todo list. I have not yet implemented a registration page for new users and I want to be able to link users to their own todolists before I do that. This is what I have so far: // models.py class Todo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=255) text = models.TextField() created_at = models.DateTimeField(default=datetime.now, blank=True) … -
Django query of table with implicit join on itself
I've read the documentation and looked at other questions posted here, but I can't find or figure out whether this is possible in Django. I have a model relating actors and movies: class Role(models.Model): title_id = models.CharField('Title ID', max_length=20, db_index=True) name_id = models.CharField('Name ID', max_length=20, db_index=True) role = models.CharField('Role', max_length=300, default='?') This is a single table that has pairs of actors and movies, so given a movie (title_id), there's a row for each actor in that movie. Similarly, given an actor (name_id), there's a row for every movie that actor was in. I need to execute a query to return the list of all title_id's that are related to a given title_id by a common actor. The SQL for this query looks like this: SELECT DISTINCT r2.title_id FROM role as r1, role as r2 WHERE r1.name_id = r2.name_id AND r1.title_id != r2.title_id AND r1.title_id = <given title_id> Can something like this be expressed in a single Django ORM query, or am I forced to use two queries with some intervening code? (Or raw SQL?) -
haystack-django: how to implement search suggestions when user starts to type query?
I'm using Django==1.11.8, django-haystack==2.7.0, pysolr==3.7.0 and Solr==6.6.3 and Python3 Here is a model called MainData from which I want to show search results. from django.db.models import * from django.db import models as models class MainData(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) url = models.CharField(max_length=1000) title = models.CharField(max_length=250, blank=True, null=True) metadata = models.TextField(max_length=500, blank=True, null=True) meta_keywords = models.TextField(max_length=1000, blank=True, null=True) context = models.TextField(max_length=1000, blank=True, null=True) class Meta: ordering = ('-created',) def __str__(self): return str(self.title) def get_absolute_url(self): return self.url my search_index.py file: import datetime from haystack import indexes from .models import MainData class MainSearchIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) url = indexes.CharField(model_attr='url', null=True) title = indexes.EdgeNgramField(model_attr='title', null=True) metadata = indexes.EdgeNgramField(model_attr='metadata', null=True) meta_keywords = indexes.CharField(model_attr='meta_keywords', null=True) context = indexes.EdgeNgramField(model_attr='context', null=True) suggestions = indexes.FacetCharField() def get_model(self): return MainData def index_queryset(self, using=None): return MainData.objects.filter(created__lte=datetime.datetime.now()) def prepare(self, obj): prepared_data = super(MainSearchIndex, self).prepare(obj) prepared_data['suggestions'] = prepared_data['text'] return prepared_data Now, my question is that how can I implement auto-suggestions feature like Google when a user starts to type something. I also want to implement spelling check feature. Please help me. Thank you. -
using Django with Apache, mod-wsgi and mod-wsgi_httpd
(Sorry, my English may be not fluent.) I'm studying about Django, a module of Python, with Windows10, and have something to ask. I've learned tutorial of official website of Django. Now I want to try using it with apache and mod-wsgi, but a command "pip install mod-wsgi_httpd" wasn't accepted. Here is what I've done or checked. 1. python3.6 works with no problem. 2. installed apache, and successed indicating default page on port 80 on localhost. 3. the command "pip install mod_wsgi" wasn't accepted, so I installed 'whl' file from https://www.ifd.uci.edu/~gohlke/pythonlibs/#mod_wsgi but I've not checked whether it works well because I've not installed mod-wsgi_httpd. I'll the response of command prompt in the end of this question. These are what I want to ask. 1. What should I do to install mod-wsgi_httpd? 2. What can I do with mod-wsgi_httpd? (the official website of Django tells me about mod-wsgi, but doesn't about mod-wsgi_httpd. The official website of Python tells me too, but it was too abstract for me.) 3. Some websites tell me that apache doesn't work without APR, but apache enabled me the default page without installing APR. Is this information wrong? C:\Users\拓海>pip install mod-wsgi_httpd Collecting mod-wsgi_httpd Using cached mod_wsgi-httpd-2.4.27.1.tar.gz Complete output … -
how can i save data from multiple screens
I have a class called "Person" with this 4 fields: name, telephone, document, photo. In the first screen I have 2 fields: "name" and "telephone". In the second one I have 1 field: "document". In the third one I have 1 field: "photo". I´ve already saved fields "name" and "telephone" in database (table "Person"). I don´t know how i can save the others fields, "document" and "photo", at the same table "Person". -
Django and Rabbitmq Architecture
I want to use RabbitMQ with Django for message queuing. Currently I am having a new instance of RabbitMQ and celery with each Django app server. I wanted to know is this the best method? Or should I have a single cluster of RabbitMQ for queuing the messages and multiple celery for executing those tasks on the first come basis? -
Deploy django app on heroku has error: DisallowedHost at / Invalid HTTP_HOST header: 'ecommerceyy.herokuapp.com'
When I want to deploy my Django App on Heroku, I met an error as below: DisallowedHost at / Invalid HTTP_HOST header: 'ecommerceyy.herokuapp.com'. You may need to add 'ecommerceyy.herokuapp.com' to ALLOWED_HOSTS. However, I have code in production.py like: DEBUG = False ALLOWED_HOSTS = ['.herokuapp.com'] And my wsgi.py is like: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ecommerce.settings") application = get_wsgi_application() And encrypt ssl/tls https like: CORS_REPLACE_HTTPS_REFERER = True HOST_SCHEME = "https://" SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = 1000000 SECURE_FRAME_DENY = True So what's wrong with my app? -
The best way to divide card-deck into rows in django template
What I have(image) So i need to divide these cards into 4-5 cards per row. My solution is simple <div class="card-deck"> {% for book in books %} {% include 'books/book_element.html' %} {% endfor %} </div> And I have tried for a while and was doing some brainstorm {% for book in books %} {% if forloop.counter|divisibleby:"5" or forloop.counter == 1 %} <div class="card-deck"> </div> {% endif %} {% endfor %} How can I include a template into a div.card-deck? -
Django - DRF Delete/Retrieve/Patch Returns 404 { detail: "Not found" }
After intensive debugging for about 4-5 hours. I give up trying to find what's causing this, probably really simple, bug. Tried this with Update and Patch/Put Mixins, and didn't work as well. It is 100% because of the queryset, but I can't find the problem? Tried using .get() and everything else I could think of. My View is pretty straightforward: class RemoveModel3D(generics.DestroyAPIView): serializer_class = Model3DSerializer def get_queryset(self): user_pk = self.kwargs["pk"] return Model3D.objects.filter(owners__in=[user_pk]) P.S. That queryset is working perfectly fine with ListModelMixin. I read that List is for collections and Retrieve/Destroy/Update is for single model instance, but How do I get the queryset to be a single model instance? That I could not find anywhere -
Insure sequential request processing within a session on nginx + uWSIGI + Django
I am trying to fix some bugs in a Django www app that are caused by concurrent processing of http requests from a single user contending for session state. Is there an easy way to insure that a sequence of http requests from a single user are processed sequentially? I know I need to start by configuring the load balancer for "sticky sessions" to make sure they are routed to the same node, but is there a way to configure nginx + uWSGI + Django make sure they are processed in sequence thereafter? -
How to configure nginx for websocket. I have django for REST in backend. The standard configurations i found over net wont work for nginx websocket
I have nginx to server to browser. I want nginx to serve for websocket requests from browser. Nginx has internally proxy to django (gunicorn uwsgi) using proxy configs. I am not able to set up the config in nginx for websocket. Tried different configs from internet but no success. My default file in nginx config file : server { listen 80 default_server; listen [::]:80 default_server; root /usr/share/gmc/dist; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name _; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404 /index.html index.js; } location ~ /redfish.* { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://localhost:8000; } } -
User model other than AUTH_USER_MODEL in Django REST Framework
I have an architectural problem. I'm using Django (with admin panel) and DRF (api with stateless authentication using JWT). Django has Admin users represented by model which is more or less the same as default Django User Model. Admins work with Django Admin only and can't use DRF api. DRF has API users that are allowed to use only api through DRF and can't interact with Django Admin or Django Session etc. I know that the best approach is to use multi model inheritance, like: class User(DjangoUserModel): pass class Admin(User): pass class API(User): pass AUTH_USER_MODEL = "User" but the problem is that, those users are completly different. Eg: API user has complex composite key as an username field which is impossible in combination to simple Admin username field. And many other differences. .. The question is: may I use a user object that is not an AUTH_USER_MODEL instance in DRF? So self.request.user will store model instance that isn't connect in any way with AUTH_USER_MODEL. Has any of you done something similar? -
curl command doesn't work whereas python-requests does
I'm trying to replicate following code in data={ 'first_name':'test1', 'last_name':'test', } r = requets.post(url, data=data) to CURL I tried curl -X POST -H "Content-Type:application/json" url --data '{"first_name":"test1","last_name":"test2"}' This doesn't seem to be working. Why? -
Creating New Project Generated for other version of Django in Visual Studio
Why everytime I create a new project in Visual Studio it uses the 1.9.1 version of Django instead of 2.0.3 version? I have to create the project and then upgrade the versioin of Django to 2.0.3, because it cause me problems with MIDDLEWARE for having other version of Django. in my settings.py: """ Django settings for pruebadelaprueba project. Generated by 'django-admin startproject' using Django 1.9.1. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import posixpath # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '88069ed1-4820-4472-80e8-cdbd14c14b6b' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pruebadelaprueba.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, … -
How to use DRF auth on Django non-REST views?
I would like to use my current Django views in another project (which lives on another domain), so I will need token authentication. Is it possible to use Django Rest Framework, which has a good token authentication system, to authenticate users on Django non-REST views? I currently use the login_required decorator which doesn't work for Django Rest Framework token auth: from django.contrib.auth.decorators import login_required from django.http import JsonResponse @login_required def my_view(request): return JsonResponse({'status': 'ok'}) -
Upload file to media folder during AJAX instead of when the form is submitted
I've just got a simple upload form: def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect('/home/') else: form_post = PostForm() context = { 'form_post': form_post, } return render(request, 'post/post.html', context) else: return HttpResponseRedirect("/accounts/signup/") which derives from here: class PostForm(forms.ModelForm): class Meta: model = Post fields = [ 'title', 'image', 'user' ] and here's the models: class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=95) image = models.FileField(null=True, blank=True) When a user adds an image to the form, it fires this JS function: $('input#id_image').on('change', function(e) {...} which gives a preview of the image. This is the point where I want the image to be uploaded to my media folder directory (I'm using S3 storage). By default, the image is uploaded when the user submits the form, but I want it to be uploaded as soon as $('input#id_image').on('change' is triggered. How would I go about this?