Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Call function from another file with Django
Good morning everybody, I would like to execute a Celery task by calling my function from a file. Up to now, my function is not called because I don't overcome to write this very good. I receive a post_save signal when a new entry is added inside a specific table named Thread. This post_save signal calls my view which will call the Celery task. In my model, I have : # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db.models.signals import post_save from django.dispatch import receiver from simple_forums.models import Thread from ..views import CeleryThreadNotification @receiver(post_save, sender=Thread) def get_new_thread(sender, instance, **kwargs): CeleryThreadNotification() In my views, I have : from .tasks import thread_notification class CeleryThreadNotification(View): def get(self, request): print('x') self.celery_thread_notification() return render(request, 'knowx/index.html') def celery_thread_notification(self, request): print('y') thread_notification.delay() return render(request, 'knowx/index.html') And in my tasks.py file : # -*- coding: utf-8 -*- from celery import shared_task from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ User = get_user_model() @shared_task(bind=True, time_limit=3600, soft_time_limit=3600) def thread_notification(self): print('Celery task executed') return ['success_message', _('Celery task ended')] I know my issue comes from my models file : CeleryThreadNotification() I tried : CeleryThreadNotification.get() But it doesn't work -
django react social auth
I am trying to setup a django,react social authentication setup. I plan on having a client side oauth2 flow, which gets the access_token from google authorization server, and passes it to the django backend. I am looking at how the backend should be designed for such a flow. All the resources available are directed towards a backend authoriazation. any help of direction on what needs to be done. would be greatly helpful. -
Non-relational field given in select_related: ' '. Choices are: (none)
I have two models from different apps: class Measure(models.Model): date = models.DateTimeField(default="2018-01-23 15:55") average = models.FloatField(default=0) class Sensor(models.Model): measure=models.ForeignKey(Measure, on_delete=models.CASCADE) value= models.FloatField(default=0) I'm calling all data coming from sensors as follow: new_context = Sensor.objects.select_related('measure__date') However, I receive this error: django.core.exceptions.FieldError: Non-relational field given in select_related: 'date'. Choices are: (none) from documentation, I should be using select_related instead of prefetch_related, and the call seems to be coherent. Am I missing something? -
Saving data Django Channels 2
I am trying to save the data which i am receiving from my client using the Django Channels. I have read the documentation but its not very clear. Here is my code of consumer.py def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) # Receive message from room group def chat_message(self, event): message = event['message'] # Send message to WebSocket message2 = message[1] database_sync_to_async(DeviceLogs.save(message2)) self.send(text_data=json.dumps({ 'message': message2 })) As you may have noticed that i just want to save message2 in database. -
How to let not all the data show up using a choice field but only the ones related to the choice field in Django?
I have this website which has one purpose which is viewing data out of a database according to the related topic chosen by the user. I have managed to make the data show up, but all the data found in the database is showing up when I click on the viewing button paying no attention to the chosen topic. I am not sure if it is because of how I have organized the database or if the problem is with my forms. This is the model that I am using: from django.db import models from home.choices import * # Create your models here. class Topic(models.Model): topic_name = models.IntegerField( choices = question_topic_name_choices, default = 1) def __str__(self): return '%s' % self.topic_name class Image (models.Model): image_file = models.ImageField() def __str__(self): return '%s' % self.image_file class Question(models.Model): question_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) question_description = models.TextField() question_answer = models.ForeignKey( 'Answer', on_delete=models.CASCADE, blank=True, null=True) question_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' % self.question_type class Answer(models.Model): answer_description = models.TextField() answer_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) answer_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' % self.answer_description This is the views file: from django.shortcuts import render, render_to_response, redirect … -
Django static file is not loading in my computer (windows 10) but its working on others computer (windows 10)
I've run my project in various computer (windows 10), python 3.7.2, django 2.1.7 In every computer its working properly except mine. Only in my computer bootstrap files is not loading from static directory. when I use CDN link its loads .css and working as my expectation. I've unstall python and django, cleaned python directory from appData and reinstalled python and django. but its still not working. What should I do? N.B: I've tested my project in various computers of similar configuration. -
Paginator for TabularInline models in Django admin
I checked this Paginator for inline models in django admin question but none of answers doesnt work for me. I use django 1.11 . Are there any other solution? -
How to list out all the api in an Django application?
I have an Django application which is around 4 years old. I want list out all the api in order to remove all inactive api's from the codebase. Is there any way to figure out all the API? The application is based on Djnago. We are using javascript for the frontend part. -
Retrieving thumbnailPhoto from Active directory and storing it in db
I was trying to save img retrieved from Active Directory and display it on django template.The image is in bytes looks somethin like this: b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00\x00\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t. Views.py: obj = { ... my_image=associate_details['pic'], } associate.append(obj) ldap.py 'pic':attributes['thumbnailPhoto'] Error: AttributeError at /save_information 'bytes' object has no attribute0 '_committed' -
How to create front-end to a prediction model using django
I created a time series prediction model(i.e. sarima.py) using python now I want to create a frontend for non-technical background people to use this model. My question is Using DJANGO how could I proceed to make a frontend which receives upload dataset from the user) the dataset which should feed into model and prediction results should return back to the user. How, could I call the sarima.py logic to respond for the request. -
TextField object is not Callable | Python Django & Auth | Default files not working
I am trying to run manage.py runserver, but am getting stuck with this error. "\Python37-32\lib\site-packages\social\apps\django_app\default\models.py", line 30, in class AbstractUserSocialAuth(models.Model, DjangoUserMixin, on_delete =models.SET_NULL): File "\Python37-32\lib\site-packages\social\apps\django_app\default\models.py", line 35, in AbstractUserSocialAuth extra_data = JSONField() TypeError: 'TextField' object is not callable Here is the code class AbstractUserSocialAuth(models.Model, DjangoUserMixin, on_delete =models.SET_NULL): """Abstract Social Auth association model""" user = models.ForeignKey(USER_MODEL, related_name='social_auth', on_delete =models.SET_NULL) provider = models.CharField(max_length=32) uid = models.CharField(max_length=UID_LENGTH) extra_data = JSONField() objects = UserSocialAuthManager() Other than feeding the class on_delete=models.SET_NULL, this is the default code that was installed. -
djnago url # and % cannot support
I was sending the get request like this http:121.0.0.1:8000/userlogin/userName=test&password=12345#% but accepted like this "GET /userlogin?username=admin&password=12345 HTTP/1.1" 403 2868 I cannot understand what happened here? -
Spring MVC and Django
I am an Engineer turned Web Developer with some experience in Django. Recently I got a work related to Spring MVC. My knowledge of Java is very limited. I know that Java is used at enterprise level applications more as compared to Python. What I would like to know is in web development when would it be preferable to use Spring MVC and when to use Django? What would be the basis for deciding the framework? If I should decide over either of these, apart from the fact that familiarity in either of these frameworks matters the most, what would be the parameters to decide? -
I am getting error while git pull in pythonanywhere bash console
error: Your local changes to the following files would be overwritten by merge: db.sqlite3 local/settings.py Please, commit your changes or stash them before you can merge. Aborting -
How to activate Anaconda environment tensorflow_p27 while running django application?
uwsgi.ini file [uwsgi] socket = /tmp/gist.sock chmod-socket = 777 chdir = /home/ubuntu/gist_web_api/portal-gist/ wsgi-file = wsgi.py pidfile = /tmp/gist.pid master = true processes = 5 stats = 127.0.0.1:9292 vacuum= true py-autoreload=3 logto=/home/ubuntu/logs/gist-uwsgi.log virtualenv=/home/ubuntu/anaconda3/envs/tensorflow_p27/ supervisor.conf file [program:server2] command=uwsgi --die-on-term --ini /home/ubuntu/configuration/gist-uwsgi.ini autorestart=true autostart=true stopwaitsecs=5 stopsignal=QUIT stdout_logfile=/home/ubuntu/logs/supervisor.log while checking uwsgi log file Traceback (most recent call last): File "wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/django/core/wsgi.py", line 2, in <module> from django.core.handlers.wsgi import WSGIHandler File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 8, in <module> from django import http File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/django/http/__init__.py", line 1, in <module> from django.http.cookie import SimpleCookie, parse_cookie File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/django/http/cookie.py", line 6, in <module> from django.utils.encoding import force_str File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/django/utils/encoding.py", line 10, in <module> from django.utils.functional import Promise File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/site-packages/django/utils/functional.py", line 1, in <module> import copy File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/copy.py", line 52, in <module> import weakref File "/home/ubuntu/anaconda3/envs/tensorflow_p27/lib/python2.7/weakref.py", line 14, in <module> from _weakref import ( ImportError: cannot import name _remove_dead_weakref unable to load app 0 (mountpoint='') (callable not found or import error) I am unable to run django application by activating anaconda tensorflow env I verified by running run after activating env and running and able to see that running successfully. The issue here while I use uwsgi and supervisor for running in prod … -
Adding logged in user in django model during creation and deletion fail
I have two django models in my app. A project model and another model to log the creation or deletion of projects. When a project is created, I'd like to fill in the created_by field in the projects model with the currently logged in user and at the same time create an instance of the logger model with source being the same logged in user. I'd like to also fill in the source in the logger model with the currently logged in user when they delete a project. My project model... class Projects(models.Model): title = models.CharField(max_length=40) description = models.TextField() budget = models.PositiveIntegerField() created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) @receiver(post_save, sender=Projects, dispatch_uid="update_logs") def update_logs(sender, **kwargs): instance = kwargs['instance'] created = kwargs['created'] if created: log_title = 'Project creation' comments = f'Project "{instance.title}" with a budget of ${instance.budget} was added' Logger.objects.create(title=log_title, comments=comments, source=instance.created_by) else: instance.save() @receiver(post_delete, sender=Projects, dispatch_uid="update_logs_deletion") def update_logs_deletion(sender, **kwargs): instance = kwargs['instance'] log_title = 'Project deleted' comments = f'Project "{instance.title}" with a budget of ${instance.budget} was deleted' Logger.objects.create(title=log_title, comments=comments) My Logger model... class Logger(models.Model): title = models.CharField(max_length=40) comments = models.TextField() source = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) Inside the admin.py file I have the following... class ProjectsAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, … -
Letting client download file from google cloud store using django
I have a django application with a google cloud storage backend that lets users upload and watch videos. I am trying to have the application also download a vtt file for each video. Currently, the client receives the url of the video (which contains authentication information) and the name of the vtt file in the google cloud storage. It is unclear to me why django sends the "proper" url for the video but not the vtt file. The vtt file path and video file path are stored in the same table and when looking at the output of the database query, there is no difference between how the video file path and the vtt file path are saved. The data flow is as follows: The user uploads a video The video is processed The Vtt file is uploaded The client loads the page and is able to get the video but not the vtt I suspect there is some sort of django middleware that I need to configure but I am unsure. class Video(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_uploaded = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) video = models.FileField(storage=GoogleCloudMediaStorage()) vtt = models.FileField(blank=True,storage=GoogleCloudMediaStorage()) def save(self, *args, **kwargs): super().save() -
Sorting in Django PostgreSQL is too slow
I have two Django models joined using a one-to-one link. Django generated this query for sorting and limit (PER_PAGE=20) objects in ChangeList: SELECT "test_model_object"."id", "test_model_object"."sorting_field_asc", "test_model_object"."sorting_field_desc", ... about fifteen fields ... "test_model_one_to_one_element"."id", "test_model_one_to_one_element"."number" FROM "test_model_object" INNER JOIN "test_model_one_to_one_element" ON ("test_model_object"."test_model_one_to_one_element_id" = "test_model_one_to_one_element"."id") ORDER BY "test_model_object"."sorting_field_asc" ASC, "test_model_object"."sorting_field_desc" DESC LIMIT 20; But execution is very slow in PostgreSQL for 1.5 million objects (about six second). I assumed uuid introduced some unwanted adjustments to sorting process, but test model with int indexes shows that's not it. What are some solution (maybe postgres settings) to speed up this Django PostgreSQL query? -
How to show pstree output in a Django webpage?
I've created a Django webapp. On clicking a button in webpage I have to print the output of the pstree in webpage. How do I do that? I'm using subprocess module to get the output. -
how to pass extra tags in success message mixin
I tried this in the views.py by passing the extra_tags but it did not work for me .please suggest suggest another approach for this views.py class CustomPasswordResetConfirmView(SuccessMessageMixin, PasswordResetConfirmView): success_message = "Your password has been set. You may go ahead and log in now. " extra_tags = 'alert-success' def get_success_message(self, cleaned_data): return (self.success_message, self.extra_tags) login.html {% if messages %} {% for message in messages %} {% if message.extra_tags == 'alert-success' %} <!-- alert-warning-green --> <div class="alert-bx alert-warning-green mt-3"> <i class="icon-checked b-6 alert-icon mr-2"></i> {{message}} </div> <!-- alert-warning-green END --> {% endif %} {% if message.extra_tags == 'alert-danger' %} <!-- error-alert --> <div class="alert-bx error-alert mt-3"> <i class="icon-warning-triangle alert-icon mr-2"></i> {{message}} </div> <!-- error-alert END --> {% endif %} {% endfor %} {% endif %} -
Django: Email isn't sent in built-in PasswordResetView
I'm overriding the built-in PasswordResetView but the email isn't sent. I'm currently using django.core.mail.backends.console.EnailBackend but the email's content doesn't show up on console. My code is like this class CustomPasswordResetView(PasswordResetView): email_template_name = 'accounts/password_reset_email.html' form_class = CustomForm template_name = 'accounts/password_reset.html' subject_template_name = 'accounts/password_reset_subject.txt' title = 'Custom Title' success_url = reverse_lazy('accounts/password_reset_done') It redirects to the password_reset_done as expected but the email doesn't show on concole. Is there something I missed? As long as I see the Django's code, I cannot find the part handling with sending email in PasswordResetView Do I have to write email functionality manually? -
Django Reverse Instance
Although my models are a lot complicated, It can be broken down to the classical book example. In django admin I can add multiple instances of a book while filling the form using the inline feature But I would like to have the reverse of it. Say, I received 100 books of the same publication penguin but of different book names. So, How do I go on adding the same book instance to many books. It would be tedious task to go on adding Pengiun Publication to 100 books separately.(Although it can be done using a separate model, Could it be done in the same book_instance model. -
Django forms.ValidationError not displayed in template and submit not working
In my Django application, I have a contact us template with fields: company name, contact number, email address. I have defined a def clean() to validate the email address and phone number as follows: class ContactForm(forms.Form): def clean(self): super(ContactForm, self).clean() email_address = self.cleaned_data.get('email_address') contact_no = self.cleaned_data.get('contact_no') if validate_email(email_address): pattern = re.compile('^[2-9]\\d{9}$') if bool(pattern.match(contact_no)): return self.cleaned_data else: # error not displayed raise forms.ValidationError( "Please enter a valid phone number") else: # error not displayed raise forms.ValidationError( "Please enter a valid email address") return self.cleaned_data In the 'contact_us' template, I am correctly rendering the errors as well: <form method="post" action="{% url 'contact' %}"> {% csrf_token %} {{contact_form.as_p} <input type="submit" value="Submit"> </form> {% if contact_form.errors %} {% for field in contact_form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% endif %} In views.py, even if the form is valid and an email is sent successfully, the form is not rendering again(as a fresh new form) on the template. def contact(request): contact_form = ContactForm() if request.method == 'POST': contact_form = ContactForm(request.POST) if contact_form.is_valid(): company_name = contact_form.cleaned_data.get('company_name') contact_no = contact_form.cleaned_data.get('contact_no') email_address = contact_form.cleaned_data.get('email_address') # send mail code contact_form.save() contact_form = ContactForm() return … -
Django monitor DataBase and Email as alert, if DB had reach an conditions
I apologies if I'm asking something stupid. Need some advice on design factor; I had this Django Apps ready and now I want add in available to monitor DB, to compare and check on condition I require, and send email if condition is fit in requirement. Example: (DB use space = 80%) => (limit DB use space = 70%) send email to alert user and I do not wish to open the webapp to be able send the email to user. I'm using Django 2.1 postgreSQL 9 and cloud server AWS Now summarize my question will I be do this on django, or I had to do on DB side? and do point me some link or codes where I could start working this. Applicate the help and really exited to hear the answer. -
Populate Random Image Python/Django using staticfiles
Application: Price is Right Game I'm trying to populate a random image from my static assets folder(I am using assets for images and css files) into one of my templates. The code is working however I'm getting a 404 image not found error. I have a feeling the problem lies within my path. Another question I have, I also have a random number function, am I able to have both functions in the same file (my_templatetag.py)? I'm getting errors when I have both functions in the same file. I have the random_int number working fine however when I'm trying to work the random_image function, I get a lot of errors. Thanks for the help my_templatetag.py (random numbers & images defs) import random, os from django import template from django.conf import settings register = template.Library() @register.simple_tag def random_int(a, b=None): if b is None: a, b = 0, a return random.randint(a, b) #Generate random img function register = template.Library() @register.simple_tag def random_image(): path = r"/assets/img/" random_image = random.choice([ x for x in os.listdir(path) if os.path.isfile(os.path.join(path, x)) ]) return random_image() retailPrice_start.html {% extends 'base_layout.html'%} {% load my_templatetag %} {% load static from staticfiles %} {% block content %} <h1>Actual Retail Price!</h1> <img src="{% …