Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django recursive relationship nesting in template question
First off, I want to say thank you to all of you here at stack-overflow. I have researched and been able to find many of the answers to the questions I had on recursive relationships in Django; all the way from# Model creation, to views, to now the template. I am new to Python, therefore, new to Django. So I thank you for the detailed examples in response to questions others have had. I am trying to create a "report" (for lack of a better term) app. It has a table of contents, introductory, however many sections you would like, bibliography, footnotes, index, glossary etc. I also have an app for for questions that can be asked along with the ability to answer said questions, this is where I am having an issue and the basis for my question. My code for Models, View and Template will be added below. (if I can figure out how to post code). I have a Subject model and a Body model. The Subject model is what the topic of the question is about. The Body model is where the text of the questions are stored. Each question may or may not have a … -
Djano form multiselection - Cannot assign QuerySet, must be user instance
I'm attempting to build a basic Job/To Do List. In the Job create form, I'm trying to add the ability for the "author" to assign additional personnel to the job via a multiple select field from a list of registered users. So far, it seems to work via the admin form. But when I do the same on the "Job create page" I get the following ValueError: Cannot assign "QuerySet [CustomUser: testuser1, CustomUser: testuser2]": "Job.personnel" must be a "CustomUser" instance. I'm not sure what I'm doing wrong in the view, I've seen similar topics but those options either didn't work or I just didn't understand the solution (I'm very new to Django/Python in general). Any help, or suggestions on how this could be better implemented, would be greatly appreciated! The Job Model from the job app from django.conf import settings from django.db import models from user.models import CustomUser class Job(models.Model): """A model for active jobs""" job_title = models.CharField(max_length=200) author = models.ForeignKey( CustomUser, null=True, on_delete=models.SET_NULL, related_name = 'authors' ) personnel = models.ForeignKey( CustomUser, null=True, on_delete=models.SET_NULL, related_name = 'addition_personnel' ) job_text = models.TextField() created_date = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(null=True, auto_now=True) close_date = models.DateField(null=True, blank=True) # Job status choices OPEN = 'Open' CLOSED … -
How to force jobs executing immediately after being scheduled in RQ scheduler
I'm using django-rq for scheduling offline jobs in my Django backend. I expect that that following code starts background jobs with scheduled_func immediately after calling schedule, but actually it seems to happen only after interval seconds. import django_rq import datetime scheduler = django_rq.get_scheduler('default') scheduler.schedule( scheduled_time=datetime.datetime.utcnow(), func=scheduled_func, interval=100, repeat=None ) What is the right way to force jobs start immediately right after invoking scheduler.schedule? -
Django get data from ajax post
I want to send array from javascript to django view to do some manipulations with it. For now I'm just trying to display that array via httpresponse to make sure everything works fine. Here's function that sends array function sendDistances(distances){ $.ajax({ url:'/distances/', type:'POST', //dataType: 'json', data:{distances : distances, csrfmiddlewaretoken: '{{ csrf_token }}'}, success:function () { console.log("Distances sent and this is success:function") }, error:function () { console.log("Distances not sent and this is error:function") } }); } Here I call it var distances = []; points.on('data:loaded', function () { console.log("Points.addTo(map)") points.addTo(map); console.log("Get distances"); getAllRoutes(); //this function add some values in distances array console.log("sendDistances"); sendDistances(distances); console.log("The end"); }); And now I want to get this array. I'm not jsoning it now because I guess I can send it that way and get error on python's side but I'll know I sent and got it correctly. In my urls.py: from .views import * urlpatterns=[ path('distances/', getDistances) ] And views.py def getDistances(request): if request.method == 'POST': text = "Good" return HttpResponse(text) elif request.method == 'GET': text = "Bad" return HttpResponse(text) As I can see in logs on javascript side it works fine and I get success message from sendDistances function. But then I try to … -
Django - Server only works in one browser until I restart it
I have a Django project (it's a big project meanwhile) and I can only connect to it via localhost using one browser (Chrome, Opera, Firefox, it doesn't matter which browser I use). When I connect to it once, Django is "locked" in this browser. When I try to connect to Django using another browser, it gets timed out. When I restart it I can again choice which browser I would like to use. But then Django gets "locked" again in this browser. Example: Django Server starts; I use Chrome; I can't use Opera, Firefox or any other browser anymore. Django Server restarts; I use Opera; I can't use Chrome, Firefox or any other browser anymore. I know this isn't a question about code but I don't know where this question fits except for Stackoverflow. Do you have any idea? -
new objects don't replace with deleted objects in Postgres
I'm new on Django and I use PostgreSQL with it. I added some objects to server and deleted them and now understood that id of new objects don't replace with deleted objects and they continue. for example when I deleted 4th object, next new objects is 5. I get objects IDs by: path('<int:blog_id>/', views.detail, name='detail'), in urls.py then I try to get the related object by: def detail(request, blog_id): detailblog = get_object_or_404(Blog, pk=blog_id) return render(request, 'blog/detail.html', {'blog': detailblog}) in views.py it works for objects that now are in DB. but for deleted objects for example 4th object here is the error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/4/ Raised by: blog.views.detail No Blog matches the given query. -
How to authenticate an insert or return error
im implementing a simple API CRUD using Django + Django rest and have a doubt. I have two models: class Shoe(models.Model): _id = models.AutoField(primary_key=True) description = models.CharField(max_length=100, null=False, blank=False) provider = models.CharField(max_length=100, null=False, blank=False) type = models.CharField(max_length=2, choices=TIPO_CHOICES, null=False, blank=False) cost_price = models.DecimalField( max_digits=6, decimal_places=2, verbose_name = 'Preço de Custo', null=False, blank=False ) sale_price = models.DecimalField( max_digits=6, decimal_places=2, verbose_name = 'Preço de Venda', null=False, blank=False ) class Stock(models.Model): _id = models.AutoField(primary_key=True) id_shoe = models.ForeignKey( Shoe, on_delete = models.CASCADE, verbose_name = 'shoe', related_name = 'stock') size = models.IntegerField(choices=NUMERACAO_CHOICES, null=False, blank=False) amount = models.IntegerField(null=False, default=0) What I am wanting is, when someone tries to make an insertion of stock of a size (of a certain shoe) that already exists it returns error. I can not just be 'unique' in the parameters of size. Any suggestions on how to do this? -
How can I generate download link in massage by usung youtube-dl?
I am new in not only in Django, even in programming. So now I want to download an mp3 file from a youtube video and send in massage a link to download to users message. I download and convert it, but now I can not make a link to put in the message to download in one click. I do not know how to do it. views.py import os import sys from .task import * from datetime import datetime from .models import Downloader from .forms import DownloadForm from django.shortcuts import render def main_page(request): if request.method == 'POST': form = DownloadForm(request.POST) if form.is_valid(): video_url = form.cleaned_data.get('link') email = form.cleaned_data.get('email') try: convert_load.delay(video_url) Downloader.objects.create(url=video_url, email=email) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' Type:{} Filename:{} Line:{}ERROR: {}'. format(exc_type, fname, exc_tb.tb_lineno, e)) return render(request, 'download_link.html') else: form = DownloadForm() return render(request, 'main_page.html', {'form': form}) def history(request): return render(request, 'history.html', {'instance': Downloader.objects.all()}) def download_link(request): link_location = 'media/{}'.format('skjdskdj') print(link_location, '\n\n\n\n') return render(request, 'download_link.html', {'link': link_location}) task.py from __future__ import unicode_literals import youtube_dl from celery import task from django.core.mail import send_mail import converter from converter.models import Downloader from django.utils.timezone import now @task def convert_load(video_url): # Mp3 format options ydl_opts … -
Fusioncharts Getting Started Guide page remains empty
I have just installed FusionCharts Suite XT v3.13.4 to use in my (Python) Django application. I have done the Getting Started Guide (https://www.fusioncharts.com/dev/getting-started/django/your-first-chart-using-django#installation-2), but I can't seem to get it to work. I don't get an error, but my page remains completely empty. I don't know what I did wrong, I followed the tutorial exactly. dash.html <!-- Filename: app_name/templates/index.html --> <!DOCTYPE html> <html> <head> <title>FC-python wrapper</title> {% load static %} <script type="text/javascript" src="{% static "https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js" %}"></script> <script type="text/javascript" src="{% static "https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js" %}"></script> </head> <body> <div id="myFirstchart-container">{{ output|safe }}</div> </body> </html> views.py from django.shortcuts import render from django.http import HttpResponse from collections import OrderedDict # Include the `fusioncharts.py` file that contains functions to embed the charts. #from fusioncharts import FusionCharts from vsdk.dashboard.fusioncharts import FusionCharts def myFirstChart(request): #Chart data is passed to the `dataSource` parameter, like a dictionary in the form of key-value pairs. dataSource = OrderedDict() # The `chartConfig` dict contains key-value pairs of data for chart attribute chartConfig = OrderedDict() chartConfig['caption'] = 'Countries With Most Oil Reserves [2017-18]' chartConfig['subCaption'] = 'In MMbbl = One Million barrels' chartConfig['xAxisName'] = 'Country' chartConfig['yAxisName'] = 'Reserves (MMbbl)' chartConfig['numberSuffix'] = 'K' chartConfig['theme'] = 'fusion' # The `chartData` dict contains key-value pairs of data chartData = … -
Django get result of javascript function in view
I have array created and modified in javascript function. I want to send it to view and do something with it (for now I'm just trying to display it via httpresponse). I followed this instruction and this is my code now: index.html // I have points on map. I collect distances between one point and another and store it in array that has to be sent to view later // array that I want to return to view var distances = []; // this is main function. I put some console logs to trace what is going on points.on('data:loaded', function () { console.log("points.addTo(map)") points.addTo(map); console.log("getAllRoutes"); getAllRoutes(); console.log("sendDistances"); sendDistances(distances); console.log("The end");//this log never displays }); //Function getAllRoutes return array with some digits in it. //and here I try to send this array function sendDistances(distances){ $.ajax({ url:'/distances', type:"POST", data:{distances : distances}, success:function () { console.log("Distances sent and this is success:function") }, complete:function () { console.log("This is complete:function") }, error:function () { console.log("Distances not sent and this is error:function") } }); }; urls.py from .views import * urlpatterns=[ ... path('distances/', getDistances ] views.py def getDistances(request): if request.method == 'POST': x = request.POST.get('data') return HttpResponse(x) elif request.method == 'GET': text = "Something's wrong" return … -
What is best way to fill out a related table after processing the parent field , DRF
I have a class like bellow: class News(models.Model): description = models.TextField(verbose_name="Description", max_length=50, blank=True, null=True, default="") timestamp = models.DateTimeField(auto_now_add=True) it has a text field.Now I am supposed to list the entities that are in this text, so I defined a related table as bellow: class Entity(models.Model): news = models.ForeignKey( News, related_name='entities4thisnews', on_delete=models.CASCADE) entity = models.TextField(verbose_name="Entity", max_length=100, blank=True, null=True, default="") timestamp = models.DateTimeField(auto_now_add=True) As an example I have this text in first table news1ID, " France is in Europe". so one user posts it second table should be filled with entityID2,news1ID, France entityID2,news1ID, Europe when the user posts a news, my question is that where is the best place to process the text(finding entity in this case), and post the processed results accordingly to the next table? An issue right of the bat is that, newsID1 is not determined before any post for the news. here are also my views. class NewsList(generics.ListCreateAPIView): queryset = News.objects.all() serializer_class = NewsSerializer name = 'news-list' def perform_create(self, serializer): pass class EntityList(generics.ListCreateAPIView): queryset = Entity.objects.all() serializer_class = EntitySerializer name = 'entity-list' Thanks for your help! -
how do I add template conditions in the ListView class?
I have a ListView class in views.py, I want to add a condition if the authenticated user displays another template urls.py from django.urls import path, include from django.contrib.auth import views as auth_views from .views import ( PostListView, ) urlpatterns = [ path('', PostListView.as_view(), name='index'), ] Views.py rom django.shortcuts import render, get_object_or_404 from django.views.generic import ( ListView, ) from .models import Post from django.contrib.auth.models import User from django.contrib.auth import authenticate class PostListView(ListView): model = Post template_name = 'page/index.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 7 i want to add if request.user.is_authenticated: template_name = 'page/index.html' else: template_name = 'page/home.html' Django 2.2.x -
Get the full path of uploaded/selected file in django
I do not want the user uploading a file, but with the "File Browser" (which is used for file upload) to read the path to the file. Example: With the File Browser, I select through my file system and select a file to upload. Click it. It is not the file to be uploaded, but the whole path of the file to be read and saved. How would this be possible? I have no code example found for this problem. -
How to send mp3 audio in django rest framework to frontend for audio playback?
I have a chatbot in django. Front end is react native. Now I want to integrate aws polly for text narration. How can I send aws polly mp3 file to front end from django restframework. Right now I send all of my data in a json. But how to send a file that is not json serializable like mp3 file. Should I send bytes and let frontend create a mp3 file out of bytes? What if the file is bigger than a couple of mega bytes? -
Programming Error: "user_id of relation APP_MODEL does not exist"
I've set User as a foreign key on my Video model. I am using the default django auth User model, and have managed to create a user using the serializer and view that I set up for it. The problem is that whenever I try to create a video entry I hit the title error. I've tried clearing the database, redoing the migrations, but there aren't any migrations for the app that handles the user serializer. The Model from django.contrib.auth.models import User class Video(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True ) map_marker = models.ForeignKey(MapMarker, on_delete=models.CASCADE) created = models.DateTimeField() ip_addr = models.TextField() file_id = models.TextField() class Meta: ordering = ('created',) The entry should be saved with the key of the user I selected on the API view. -
Django git changes to master branch not working on live site
In my Django project, when I push changes to my branch, ml-develop and then merge them into master. The changes work on my local site, but on the live server when I pull from the master branch only some of them work and I am really not sure why. I am not sure what to show you guys as I haven't a clue what the error could actually be, but if you need me to show anything, I am more than happy to show them e.g, server info? If anyone can help that would be great. -
How to get a celery task to save a django model right away?
I have a celery task that runs for five minutes and pings an external service for updates every second. If it detects an update, it should save the update to a django model immediately. My problem is that the model.save() does not occur immediately. Instead, it only occurs when the five minutes are up and the celery task ends. How can I force the save to occur immediately? My task code is below. I have tried using atomic transactions, and this still has not worked. class CheckForUpdates(PeriodicTask): run_every = 300 def run(self, queue_name='unique_queue'): end_task_time = _at_five_minutes() while time.time() < end_task_time: _wait_for_one_second() result = _check_for_update() if _update_was_found(result): update = json.loads(result.body) logger.info("response body: ", update) with transaction.atomic(): model.save() What do I need to add to ensure the model.save() occurs immeidately? -
I get 'django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint' when I try to publish a new post
--This is my first ever question on StackOverflow. So if I violate any community rules/standards, I apologize. Though there are similar questions around, no answer helped me solve the problem I am encountering. I would say I am not good enough a programmer to figure out the solution--- When I hit publish to add a new post, I get the following error "django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (18, s, s, 2019-05-26 15:39:10.466636+00, null)" I have tried passing ....ForeignKey('auth.User') and ...ForeignKey(get_user_model() on Post model (not knowing how it could even be of help to my problem. I migrated the database from sqlite to PostgreSQL and then checked the Post table on PgAdmin to see if user_id (previously named author_id) was there...and it was. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() published_date = models.DateTimeField(auto_now=True) def __str__(self): """String representation""" return self.title def get_absolute_url(self): """Returns the url to access a detailed post""" return reverse('post-detail', kwargs={"pk": self.pk}) class Meta: ordering = ['-published_date'] unique_together = ('user',) and the views … -
Django annotate average query not showing decimal places
I'm working with Django and I'm taking an average for some column values, however the result is rounded up and I'd like to make it one or two decimal places. My goal is to see the result look like 3.5 instead of 4. My model is named Application and the columns have an IntegerField model type. My database is PostgreSQL. Here's the query that I'm using to currently take the average of my column values: ratings = Application.objects.filter(id = review.id).annotate(rate = (F('col_1')+F('col_2')+F('col_3')+F('col_4')+F('col_5')+F('col_6'))/6) I've already tried playing with FloatFields, but maybe I did it wrong. Any suggestions? Thanks in advance! -
Python Django Short Guide: how do I learn to create RESTful APIs?
What I would like to learn Right now, I'm in a project where I need to create an API that would fetch a specific HTTP request (with a json), feed it to a Data Science service and then retrieve the answer as another json file with the location of the results on a DB once the service has been completed. My Django Problem It has been recommended to me that I use Django in Python because our project may become bigger and Django might come in handy later (Flask would be simpler, but it is limited. However, Django is so overwhelming to learn quickly that it's starting to become quite the nuissance and bottleneck, since I have other projects on the line too. So I come here to humbly ask if anyone knows what I need to learn and focus on in order to just build a sort of fetch and request API for a Data Science service, without having to sort through the million other web features Django has. -
How to return fields of both related models in a Django ManyToMany relation?
I have two models: class P(mdoels.Model): name = models.CharField(null=False,max_length=120) ... class F(mdoels.Model): name = models.CharField(null=False,max_length=120) ... p = models.ManyToManyField(P) I need a query like this: SELECT p.name, f.name FROM f JOIN f_p ON f.id = f_p.f_id JOIN p ON p.id= f_p.p_id I can use the f.objects.filter(), but it doesn't returns the fields of p and I need just to show a list with the both names. In psql the query works like I need. How can I do this in Django? -
Can I use crontab django in Heroku?
I have crontab-django task, which works very well in localhost. When I want to start this crontab task on Heroku - I get error: sh: 1: /usr/bin/crontab: not found. How I can fix this? It is my cron task: CRONJOBS = [ ('0 0 * * * /app', 'file_sharing.cron.delete_unuseful') ] -
Django: How to delete any foreign key object that is no longer referenced
I have nested data in my Django Rest Framework app, something like this: class Student(models.Model): studyGroup = models.ForeignKey(StudyGroup, on_delete=models.SET_NULL, blank=True, null=True, related_name='studyGroup') Each student may have a study group; a student may have no study group. Many students can have the same study group. I would like to automatically delete any StudyGroup that is not referenced by any students, either because the student was deleted or because it was updated. I think this can be done by customising the 'save' and 'delete' methods for Student, checking whether their StudyGroup is referenced by any other Student, and deleting it if is not referenced. Or perhaps more elegantly by using signals. But it feels like there should be a simpler way to do this - like an inverse of on_delete=models.CASCADE. Is there a way to tell the database to do this automatically? Or do I need to write the custom code? -
Django: infinite loop in cleanse_setting
I am currently using Heroku CI to run my django tests: python3 manage.py test --fail-fast However upon running these on the heroku CI i get an infinite loop when the django system tries to render the settings: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/investorsuite/middleware.py", line 11, in middleware response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 95, in response_for_exception exc_info=sys.exc_info(), File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/log.py", line 228, in log_response exc_info=exc_info, File "/app/.heroku/python/lib/python3.6/logging/__init__.py", line 1337, in error self._log(ERROR, msg, args, **kwargs) File "/app/.heroku/python/lib/python3.6/logging/__init__.py", line 1444, in _log self.handle(record) File "/app/.heroku/python/lib/python3.6/logging/__init__.py", line 1454, in handle self.callHandlers(record) File "/app/.heroku/python/lib/python3.6/logging/__init__.py", line 1516, in callHandlers hdlr.handle(record) File "/app/.heroku/python/lib/python3.6/logging/__init__.py", line 865, in handle self.emit(record) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/log.py", line 120, in emit message = "%s\n\n%s" % (self.format(no_exc_record), reporter.get_traceback_text()) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/debug.py", line 340, in get_traceback_text c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/debug.py", line 306, in get_traceback_data 'settings': get_safe_settings(), File "/app/.heroku/python/lib/python3.6/site-packages/django/views/debug.py", line 80, in get_safe_settings settings_dict[k] = cleanse_setting(k, getattr(settings, k)) File "/app/.heroku/python/lib/python3.6/site-packages/django/views/debug.py", line 58, in cleanse_setting cleansed = {k: cleanse_setting(k, v) for k, v in value.items()} File "/app/.heroku/python/lib/python3.6/site-packages/django/views/debug.py", line 58, in <dictcomp> cleansed = {k: cleanse_setting(k, v) … -
Overriding model save method does not allow assignment of values
I am attempting to override a model's save method and assign a value to the field when the field is saved: My models.py: def NewInviteCode(): import secrets print(secrets.token_urlsafe(16)) class Invitation(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=300, default='', blank=True) email = models.EmailField(max_length=100, default='') mobile = models.CharField(max_length=15, default='', blank=True) last_sent = models.DateTimeField(default=timezone.now) num_invitations = models.IntegerField(default=1) uniqcode = models.CharField(max_length=300, default='', blank=True) def save(self, *args, **kwargs): if not self.uniqcode: self.uniqcode = NewInviteCode() print(f"Saved new unique code: {self.uniqcode}") if self.num_invitations: self.num_invitations = self.num_invitations + 1 print(f"Sending invitation to {self.email}..") SendInviteActual(self.email) print(f"Parameters to be saved are: Code:{self.uniqcode} Name: {self.name} Email: {self.email}") super().save(*args, **kwargs) # Call the "real" save() method. Unfortunately, on my code execution: fktewVPm63tV-YqXxWPNxQ Saved new unique code: None Sending invitation to joel@domain.com. Mail sent Parameters to be saved are: Code:None Name: joel Email: joel@domain.com 2019-05-26 20:04:48,972 django.request ERROR Internal Server Error: /clinic/sendinvites What's the problem with the following lines of code? if not self.uniqcode: self.uniqcode = NewInviteCode() print(f"Saved new unique code: {self.uniqcode}")