Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Advanced Python Scheduler running multiple times in production (Django on DigitalOcean)
I have a simple use of Advanced Python Scheduler to run some django code overnight everyday. The code itself works fine, and locally using manage.py runserver with the --noreload flag everything is spot on. My problem is in production where the APS code is being executed three times; as an example, I receive a status update by email at the end of the process each night, and this email is delivered 3 times within a 10 second period. Where should I be looking to replicate the protections of the --noreload flag in a production set up? -
How to apply different permission classes for different http requests
I have a UserViewSetthat supports get, post, patch, and delete HTTP requests. I have admins with different roles, some of them can delete users, and others cannot. I want to edit my UserViewSet to support this feature. I tried to do something like this: class UserViewSet(ModelViewSet): queryset = User.objects.all() http_method_names = ['get', 'post', 'patch', 'delete'] def get_serializer_class(self): if self.request.method == 'PATCH': self.permission_classes = [CanEdit] return UpdateUserSerializer elif self.request.method == 'DELETE': self.permission_classes = [CanDelete] return UserSerializer I am not sure if this is the best practice to do this. -
Page Not Found for urls - openwisp-radius
I'm new to Django, I am following this guide to setup openwisp-radius https://openwisp-radius.readthedocs.io/en/latest/developer/setup.html#setup-integrate-in-an-existing-django-project When I go to the browser for any path from urlpatterns besides admin/ I get Page not found (404). When I go to admin/ I get: ModuleNotFoundError: No module named 'openwisp_users.backends' My django version is 3.0, os is Ubuntu 20.04, I installed openwisp-radius-0.2.1 I created a new django project with django-admin startproject testapp, and added code from the guide to settings.py and urls.py this is my settings.py: import os # 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/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$_u-k638-9hprxb8lhx96+q+yo97be1uriik_86*t3my(s8ux3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', # openwisp admin theme 'openwisp_utils.admin_theme', # all-auth 'django.contrib.sites', 'allauth', 'allauth.account', # admin 'django.contrib.admin', # rest framework 'rest_framework', 'django_filters', # registration 'rest_framework.authtoken', 'dj_rest_auth', 'dj_rest_auth.registration', # openwisp radius 'openwisp_radius', 'openwisp_users', 'private_storage', 'drf_yasg', ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') PRIVATE_STORAGE_ROOT = os.path.join(MEDIA_ROOT, 'private') AUTH_USER_MODEL = 'openwisp_users.User' SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'openwisp_users.backends.UsersAuthenticationBackend', ) OPENWISP_RADIUS_FREERADIUS_ALLOWED_HOSTS … -
Navbar sliding to the right
<nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <div class="container-fluid"> <span class="navspacing"></span> <a class="navitems hover" href="{% url 'home' %}">Home</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar"> <span style="margin:5px;" class="navbar-toggler-icon"></span> </button> <div class=" collapse navbar-collapse topnav" id="collapsibleNavbar"> <ul class="navbar-nav" > {% if user.is_authenticated %} <li class="nav-item navitems"> <a class="nav-link hovering" href="{% url 'light_novel:characters_page' %}">Characters</a> </li> <li class="nav-item navitems"> <a class="nav-link " href="{% url 'light_novel:moves_page' %}">Moves</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:chapters_page' %}">Chapters</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:outfits_page' %}">Outfits</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:sights_page' %}">Sight</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:timelines_page' %}">Timeline</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:scratchpads_page' %}">Scratchpad</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'light_novel:statistics' %}">Statistics</a> </li> <li class="nav-item navitems"> <a class="nav-link" href="{% url 'logout' %}">Logout</a> </li> {% else %} <li class="nav-item navitems"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> {% endif %} </ul> </div> </div> </nav> When I click on burger icon in navbar the Home button along with the burger icon slides to right side of the screen which I don't want it to do. I tried several solutions but the button keeps sliding no matter what I tried. Can anyone help me with this? -
Django Docker media files save and restore
Hi there I am trying to deploy a project in docker with django and django rest framework. According to the documentation I successfully able to deploy it and it is working fine with media files. I am able to upload media files (images) and it also shows the right file at the right side. But the problem is for some changes I need to re-build the container with new code ... after re-deploying It can not able to found out the previously uploaded media files(images). I badly need help on it.enter image description here this is my docker-compose file. enter image description here and dockerfile -
Overriding is_valid in Nested serializer to be able to process child model with same information during update()
I'm trying to make my nested serializer to be able to process updating when I'm only updating for the parent model. The default action in drf is that the serializer cant tell if ur child model is trying to updating or create, there's a solution where you just turn off the validation, which I don't think is ideal for the database and iots implication. I've scour about this topic for like 2 days and I think the ideal approach to this is to override the is_valid method to be able to just return the object. Idea from : Django REST Framework ModelSerializer get_or_create functionality from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned class MyModelSerializer(serializers.ModelSerializer): def is_valid(self, raise_exception=False): if hasattr(self, 'initial_data'): # If we are instantiating with data={something} try: # Try to get the object in question obj = Security.objects.get(**self.initial_data) except (ObjectDoesNotExist, MultipleObjectsReturned): # Except not finding the object or the data being ambiguous # for defining it. Then validate the data as usual return super().is_valid(raise_exception) else: # If the object is found add it to the serializer. Then # validate the data as usual self.instance = obj return super().is_valid(raise_exception) else: # If the Serializer was instantiated with just an object, and no # … -
table app_shop_boughtitem has no column named buyer_id Django
Can you explain me, why I have this error? I think migration should solve this problem, but it doesn't. How can I solve this problem? My model: class BoughtItem(models.Model): name = models.CharField(max_length=100, verbose_name='Название товара или акции', blank=True) price = models.IntegerField(verbose_name='Цена', blank=True) created_at = models.DateTimeField(auto_now_add=True) buyer = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='Покупатель') This migration: class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('app_shop', '0002_item'), ] operations = [ migrations.CreateModel( name='BoughtItem', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=100, verbose_name='Название товара или акции')), ('price', models.IntegerField(blank=True, verbose_name='Цена')), ('created_at', models.DateTimeField(auto_now_add=True)), ('buyer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='Покупатель')), ], ), ] -
Django orm latest data
reference class Board(model.Model): master = models.ForeignKey(User, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) status = models.PositiveIntegerField(default=0) class MSG(models.Model): Board= models.ForeignKey(Board, on_delete=models.CASCADE) writer = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=True) How can I get the following values from this relationship? i'm using PostgreSQL response = { master="USER1", member="USER2", status=0, master_latest_MSG="master last_msg" master_latest_date="2020.03.21", member_latest_MSG="member last_msg" member_latest_date="2020.03.22", } Is there any better way instead of subquery? -
Reduce the time consumed by api in Django Rest Framework
These are the models that I created i.e. Video, Tag, Category, Exercise and Package_Exercise respectively. and i want to fetch data based on the object in package exercise and fetch all the data from the Exercise i.e. video url, tag and category of each exercise. I wrote the code but its taking too much time how do I reduce the time taken by the code? What should be the best approach to handle these kind of situations? What would be the best approach based on the time complexity. class Video(models.Model): video = models.FileField(upload_to='videos_uploaded',null=False,validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])]) name = models.CharField(max_length=100) thumbnail = models.ImageField(upload_to="video_thumbnails",null=False) description = models.TextField(max_length=200) created_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='videos_created_by') updated_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='videos_updated_by') def __str__(self): return self.name class Tag(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): title=models.CharField(max_length=200) created_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='catagoery_created_by') updated_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='catagoery_exercise_updated_by') def __str__(self): return self.title class Exercise(models.Model): name=models.CharField(max_length=100,null=False) description=models.TextField(max_length=300,null=False) video=models.ForeignKey(Video,on_delete=models.CASCADE,null=False) category=models.ForeignKey(Category,on_delete=models.CASCADE,null=False) tag=models.ManyToManyField(Tag,null=False) created_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='exercise_created_by', null=False) updated_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='exercise_updated_by', null=False) def __str__(self): return self.name class Package_Exercise(models.Model): package = models.ForeignKey(Package,on_delete=models.CASCADE,related_name='package') exercise = models.ForeignKey(Exercise,on_delete=models.CASCADE) repetition = models.IntegerField() number_of_sets = models.IntegerField() rest_time = models.IntegerField() created_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='packages_exercise_created_by') updated_by = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='packages_exercise_updated_by') Here is the serializer takes 2.3s for ~30 objects of … -
Django retain order of product when displayed
Suppose I want the order of my products in my Django webshop to be displayed in a certain order. How can I achieve that? I have simplified the below example to show the problems that I am experiencing. In my webshop models I have the below 2 models. class TakeawayWebshop(models.Model): name = models.CharField(max_length = 255, help_text = 'name of takeaway restaurant') products = models.ManyToManyField(Product) class Product(models.Model): name = models.CharField(max_length = 50, unique=True) description = models.TextField() price = models.DecimalField(max_digits=9, decimal_places=0, default=0.00) class Meta: ordering = ['-created_at'] In the admin.py I have class TakeawayWebshopAdmin(admin.ModelAdmin): form = TakeawayWebshopAdminForm list_display = ['name'] ordering = ['name'] filter_horizontal = ('products',) admin.site.register(TakeawayWebshop, TakeawayWebshopAdmin) Now from the admin, I am adding 3 products in the exact product A, product B and product C to the webshop using the filter_horizontal. . Upon saving the TakeawayWebshop model object, the products in the filter_horizontal box automatically rearanged, so the order becomes product C, product B and product A. When from the views.py if I get a list of all the products I have added to the webshop such as webshop = TakeawayWebshop.objects.filter(name = 'my webshop name')[0] products = webshop.products.all() The queryset returned is <QuerySet [<Product: Product C>, <Product: Product B>, <Product: … -
How to collect data from google form and store in jsonfield in django?
How to collect data from google form and store in JsonField in Django? I am expecting to collect all the responses and save them in my database in JsonField Any help would be appreciated. Thanks in advance :) -
Redirect http url to https for django application served by Apache without virtualHost
I have a django application running on http://localhost:8081 I want to redirect it to https://localhost:8081 I have following in my settings.py: SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True httpd.conf file has been modified to: WSGIScriptAlias / /path/to/django/application/wsgi.py #WSGIPythonHome /python3.9 WSGIPythonPath /path/to/django/application:/python3.9/lib/python3.9/site-packages <Directory /path/to/django/application> <Files wsgi.py> Require all granted </Files> </Directory> When I am trying to execute my django application with command: /python3.9/bin/python3 manage.py runserver 8081 it gives this error on webpage: This site can’t provide a secure connection localhost sent an invalid response. ERR_SSL_PROTOCOL_ERROR I have not configured virtual environment and have default python2.7. Installed python3.9 at different location on machine to serve django. Any thoughts what I'm missing to make it work. -
How do you pass multiple kwargs to reverse_lazy in django?
I could pass one kwargs for reverse_lazy as follows, but I don't know how to do 2 or 3 kwargs. return reverse_lazy('next-url', kwargs={'pk': variable}) Is there a way I can easily do this? Is the following line of code functional? return reverse_lazy('next-url', kwargs={'pk': variable, 'pk2': variable_two}) -
Django check if time is in an object's timefield range
How do I check if a time is in the range of two timefields? #appointmentApp.models Appointment #Appointments class Appointment(models.Model): ... date_selected = models.DateField(blank=True, default='2001-12-1') time_start = models.TimeField(blank=True) total_time = models.IntegerField(blank=False, null=False, default=0) end_time = models.TimeField(blank=True, null=True) appointment_accepted = models.BooleanField(blank=False, default=False) Total_time and end_time are calculated after the object is created because it requires an attribute from a many to many field In my views where I want to check if there is an object that exists #appointmentApp.views def appointment_view def appointment_view(request): ... #form is submitted else: form = AppointmentForm(request.POST) if form.is_valid(): cd = form.cleaned_data date = cd.get('date_selected') #this is a datetime field start = cd.get('time_start') #appointments = Appointment.objects.filter(date_selected=date, start_time__range=()) #form needs to save first because total time and end time don't have values until after the object is saved form.save() new_appointment = Appointment.objects.filter(date_selected=date, time_start=start, appointment_accepted=False) for apps in new_appointment: new_app_starttime = apps.time_start new_app_endtime = apps.end_time appointments = Appointment.objects.filter(date_selected=date, appointment_accepted=True) #if the start time #my question is here for app in appointments: if app.time_start__range(new_app_starttime, new_app_endtime): print('another appointment begins/ends during this time slot!') return render(request, 'home.html') How can it check if its time falls in between two timefields? -
How to call two urls with one submit button to get form data
I am trying to perform two different functions with single submit button, the below script shows the example of what I am trying to get. Thank you for helping me. Expected solution --> when I click on submit button file has to upload along with map2 has redirect to mapRedirect url. from flask import flask, render_template, flash, request, redirect,url_for @app.route('/map2') def map_2(): return render_template('map2.html') @app.route('/mapRedirect', methods = ['POST', 'GET']) def onMap(): if request.method == 'POST': name = request.form['nm'] return redirect(f"map2") @app.route('/proc') def upload_file(): ## file upload script return render_template('proc.html') map2.html <iframe name = "Ifrmp", id='mp', src="map2" > proc.html <form method="post" enctype="multipart/form-data" target="Ifrmp"> <input type="submit" id='btn' name="nm" value="submit> -
How to reduce the time for this code in django rest framework
class Category: title = models.CharField(max_length=50) class Tag: name = models.CharField(max_length=50) class Video: video = models.FileField(upload_to='xxx/') class Exercise: name = models.CharField(max_length=50) video = models.ForeignKey(Video) description = models.CharField(max_length=250) category = models.ForeignKey(Category, on_delete=models.CASCADE) tag = models.ManyToManyField(tag, on_delete=models.CASCADE) class Data: relation = models.ForeignKey(Relation, on_delete=models.CASCADE) exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE) The code for getting data accordingly this is taking too much time how do I reduce this or what are the ways to handle these kind of situations for each in Data: sam.append( { "name": each.exercise.name, "url": each.exercise.video.video.url, "description": each.exercise.description, "category": each.exercise.category.title, "tag": each.exercise.tag.name } ) -
VirtualEnv don't save django installation
I'm learning about Django from "Python Django 7 Hour Course" mady by Traversy Media on YT. I'm doing exactly the same things as he and everything works fine. But, every time I'm deactivating venv, after reentering, I can't use django-admin and pip freeze is not showing any installation of django. Do I need to save it somewhere? I'm using pip 22.0.3 and django 4.0.3 -
django 3.2 inline_formset with related models many to one
I'd like to make my form look like this enter image description here but my following this approach my output looks like this enter image description here Here are my models class Question(models.Model): id = models.BigAutoField(primary_key=True) question = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=False) class Declaration(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='declarations', on_delete=models.CASCADE) created_at = models.DateTimeField(verbose_name='created', auto_now_add=True) class Checklist(models.Model): id = models.BigAutoField(primary_key=True) declaration = models.ForeignKey(Declaration, related_name='checklist_declarations', on_delete=models.CASCADE) question = models.ForeignKey(Question, related_name='checklist_questions', on_delete=models.CASCADE, limit_choices_to={'is_active': 'True'}) is_yes = models.BooleanField() forms class ChecklistInlineFormSet(BaseInlineFormSet): def clean(self): if any(self.errors): #Don't bother validating the formset unless each form is valid on its own return questions = [] for form in self.forms: question = form.cleaned_data.get('question') if question in questions: raise ValidationError(_('Question must be distinct'), code='invalid') questions.append(question) class HorizontalRadionRenderer(forms.RadioSelect): def render(self): return mark_safe(u'\n'.join([u'%s\n' % w for w in self])) class ChecklistForm(forms.ModelForm): ANSWER_CHOICES = [ (True, 'Yes'), (False, 'No') ] is_yes = forms.TypedChoiceField( choices=ANSWER_CHOICES, coerce=lambda x: x == 'True', widget=forms.RadioSelect, required=True ) class Meta: model = Checklist fields = ['question', 'is_yes'] views declaration.views def checklist(request): FS_PREFIX = 'question_fs' user = request.user result = "" if request.method == 'POST': # Use your custom FormSet class as an argument to inlineformset_factory formset = inlineformset_factory(Declaration, Checklist, form=ChecklistForm, fk_name='declaration', formset=ChecklistInlineFormSet) declaration = Declaration() … -
How to get id of a dynamic input field in javascript
I want to create a dynamic form where I also apply JavaScript to the dynamic elements. What I want to do right now is figure out which field (stored in array or whatever data structure) in JavaScript has been clicked so that I can apply the script to that particular field. The HTML looks like this: <div class="triple"> <div class="sub-triple"> <label>Category</label> <input type="text" name="category" id="category" placeholder="Classes/Instances" required/> <ul class="cat-list"></ul> </div> <div class="sub-triple"> <label>Relation</label> <input type="text" name="relation" id="relation" placeholder="Properties" required/> <ul class="rel-list"></ul> </div> <div class="sub-triple"> <label>Value</label> <input type="text" name="value" id="value" placeholder="Classes/Instances" required/> <ul class="val-list"></ul> </div> </div> This "triple" div is dynamic and I want to create as many "triples" as the user wants, that also means the input fields of inside the "triple" section increase as well. I'm confused on how to add javascript to one element of the input. For example I have inputs: category, relation and value and the user wanted 2 or more triples then the input ids could look like category2, relation2 and value2 or something similar to that. let category = document.getElementById("category"); category.addEventListener("keyup", (e) => { removeElements(); listDown(category, sortedClasses, ".cat-list") }); If I lets say clicked on category2 for instance how do I tell that to … -
django how to call view function to template via button
I want to download a csv file and my form is not working. when I try to enter in the URL http://xxx.xx.xx.x:8080/report/ it downloads the file my index.html <table id="tb1" border=1 align="center"> <tr> <th>Permanent Male Staff</th> </tr> <tr> <td><form action="/report/" method=""> <input type="button" value="{{perma_male_staff}}"/> </form></td> </tr> </table> views.py def some_view(request): response = HttpResponse( content_type='text/csv', headers={'Content-Disposition': 'attachment; filename="somefilename.csv"'}, ) perma_male_staff = HsHrEmployee.objects.filter(emp_status=1, emp_gender=1, eeo_cat_code=2).select_related('job_title_code') t = loader.get_template('my_template_name.txt') c = {'data': perma_male_staff} response.write(t.render(c)) return response url.py from rms.views import some_view urlpatterns = [ path('admin/', admin.site.urls), path('report/', some_view) ] -
How to dynamically set the sorting parameter order with null last in django API?
I am receiving sort_by and sort_order as query parameters into our Django API. I have the logic originally like this: class Users: queryset = ... sort_by = self.request.query_params.get('sort_by') sort_order = self.request.query_params.get('sort_order') if sort_order == "desc": sort_by = "-" + sort_by def get_queryset(self): return queryset.order_by(sort_by, "id") The issue I ran into is that when I sort by descending order by a specific parameter, the null values will show up first. I want all null values to be last no matter if I'm sorting asc or desc. I saw that there's a function from the Django docs here but that would mean that I have to have a different function call for whether it's ascending or descending which would make it not elegant: if sort_order == 'desc': return queryset.order_by(F(sort_by).desc(nulls_last=True), "id") else: return queryset.order_by(F(sort_by).asc(nulls_last=True), "id") Is there a better way of doing this? -
Prefetch not working for ForeignKey's related_name? (Results in n + 2 queries)
# models.py class Author(models.Model): name = CharField() class Book(models.Model): title = CharField() author = ForeignKey(Author, related_name="books") # serializer.py class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ["id", "title"] class AuthorSerializer(serializers.ModelSerializer): books = serializers.SerializerMethodField() class Meta: model = Author fields = ["id", "name", "books"] def get_books(self, obj): qs = obj.books return BookSerializer(qs, many=True).data # views.py class AuthorList(generics.ListAPIView): queryset = Author.objects.all().prefetch_related("books") serializer_class = AuthorSerializer Seems relatively straightforward but I'm still getting n + 2 queries? I would expect to get just 2 queries - one for all the authors and one for all the books? If I actually simplify my view's queryset to just Author.objects.all(), I get n + 1 queries. -
Choosing a nested serializer from a dropdown in Django REST Framework
I want to be able to POST / PUT a nested serializer related to an already existing other resource by choosing that other resource from a drop-down button. My current situation, which works but is not ideal to me is the following: I have the following models, with a Dataset existing for a given Project and a given Datasource. Project is a Model which exists independently of Datasource and of Dataset. Its url is projects/projectid/ Datasource is a Model which exists independently of Project and of Dataset. Its url is datasources/datasourceid/ Dataset needs a Project and a Datasource to be created. Its url is projects/projectid/datasets/datasetid class Project(models.Model): """Class that models analytical projects""" title = models.CharField(max_length=300) description = models.TextField(null=True) def __str__(self): return self.title class Datasource(models.Model): """Class that models datasources under projects""" title = models.CharField(max_length=300) description = models.CharField(max_length=300) def __str__(self): return self.title class Dataset(models.Model): """Class that models datasets under projects""" title = models.CharField(max_length=300) project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='datasets') datasource = models.ForeignKey(Datasource, on_delete=models.CASCADE, related_name='datasources') (...) def __str__(self): return self.title Here are the serializers I first created for Datasource and Dataset: class DatasourceSerializer(serializers.ModelSerializer): class Meta: model = Datasource fields = ['id', 'title', 'description'] class DatasetSerializer(serializers.ModelSerializer): queryset = Datasource.objects.all() # datasource = DatasourceSerializer(many=False, read_only=False) , … -
How to fix heroku command not found error
So i've been working on a prject and I'm about to deploy it.I don't get any errors while building but and i get asked to view app after but when i do the web page shows a heroku Application error. I tried running heroku logs --tail --app appname and it shows me the logs and i can see this error which i can't seem to fix. bash: gunicorn: command not found I have my Procfile and with the following command web: gunicorn MFLS.wsgi If any other information is needed I ill be happy to provide. -
Is is possible to order queryset by last word in CharField?
Say I have a Person object with a fullname CharField. Is it possible to filter a queryset by the LAST word in fullname? (And if fullname is just one word, then just use that one word.) E.g. Person.objects.create(fullname="Zoey Aardvark") Person.objects.create(fullname="Brian") Person.objects.create(fullname="Aaron Christopher") Is ordered as Aardvark, Brian, Christopher: Zoey Aardvark Brian Aaron Christopher Or would it frankly be more efficient to just sort the serialized JSON data on my frontend via JavaScript?