Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dokku: how to change heroku stack to heroku-20 or heroku-22 (from heroku-18)
I have been working on a Django (Python) project using Dokku (thus Heroku) for deployments. Up until today, all deployments worked just fine, but since this morning, I get this error message: Requested runtime 'python-3.10.12' is not available for this stack (heroku-18). I know that python-3.10.12 is available on heroku-18 so I assume I (finally) have to change stack since heroku-18 is deprecated. I have tried using this command on Dokku: dokku buildpacks:add --index 1 {APP-NAME} https://github.com/heroku/heroku-buildpack-python.git, but it doesn't solve my problem (heroku-18 is still being used). Any help would be greatly appreciated -
Need Clarification on Correctly Saving Uploaded File Data to Default Storage using Django-minio-storage?
I've received a response that has been helpful so far, and everything has been functioning as expected. However, I've encountered some confusion when attempting to save uploaded file data to the default storage. In my current implementation, I have a method named _save_uploaded_file_data, which ideally should handle the task of saving uploaded file data to the default storage. This comes after successfully uploading the file to MinIO using a presigned URL. Here's the relevant excerpt of my code: Although my code appears straightforward, I'm uncertain about the accuracy of my approach, particularly when it comes to saving the uploaded file data to the default storage, which could potentially be local storage. I would greatly appreciate guidance, insights, or suggestions on the proper way to handle this situation. If you could provide any tips, relevant code snippets, or best practices related to this scenario, it would be immensely helpful. Thank you. models.py class FileModel(models.Model): uploaded_file = models.FileField(upload_to='uploads) minio.py class MinioUploader: def __init__(self, file): self.client = default_storage.client self.bucket_name = settings.MINIO_STORAGE_MEDIA_BUCKET_NAME self.file = file self.put_presigned_url = self._get_put_presigned_url() def _get_put_presigned_url(self): return self.client.presigned_put_object( self.bucket_name, self.tus_file.filename, expires=timedelta(minutes=2), ) def upload_file(self, file_path): file_data = self._read_file_data(file_path) response = self._upload_to_presigned_url(file_data) if response.status_code == 200: self._save_uploaded_file_data(file_data) return response def _read_file_data(self, … -
Annotate using primary key in Django
Consider a model with some stuff and a method property: class MyModel(models.model): blah blah @property def func(self): blah blah Suppose now I want to annotate MyModel objects with the value of the function: MyModel.objects.annotate(func_value=MyModel.objects.get(pk=Subquery(OuterRef('pk'))).func) but this throws the following error: OuterRef object has no attribute 'clone'. How do I properly annotate the function values to the query set? -
Conflict when using django-simple-history with django-computedfields libraries together
In my django app I have a model with some computed fields, i have used django-computedfields to achive that. Now i am trying to add django-simple-history to my model, but aparently there is a conflict when using these two django libraries. When making migrations I am getting the following error. computedfields.resolver.ResolverException: <class 'arbolsaf.models.HistoricalSpeciesModel'> is not a subclass of ComputedFieldsModel This is my code (I am not showing all fields in the model): from computedfields.models import ComputedFieldsModel, computed, compute from simple_history.models import HistoricalRecords class SpeciesModel(BasicAuditModel, ComputedFieldsModel): history = HistoricalRecords() VALUES_CHOICES = ( ("ninguno", "Ninguno"), ("bajo", "Bajo"), ("medio", "Medio"), ("alto", "Alto"), ) cod_esp = models.CharField(_("Código especie"), max_length=50, unique=True) taxonid_wfo = models.CharField(_("Taxon ID WFO"), max_length=50) nombre_comun = models.CharField(_("Nombre común"), max_length=255) nombre_cientifico = models.CharField(_("Nombre científico"), max_length=255) nombre_cientifico_completo = models.CharField(_("Nombre científico completo"), max_length=255) familia = models.ForeignKey("arbolsaf.FamilyModel", verbose_name=_("Familia"), on_delete=models.RESTRICT) genero = models.ForeignKey("arbolsaf.GenderModel", verbose_name=_("Género"), on_delete=models.RESTRICT) epiteto = models.CharField(_("Epíteto"), max_length=50) variedad_subespecie = models.CharField(_("Variedad/Subespecie"), max_length=50, blank=True, null=True) autor = models.CharField(_("Autor"), max_length=255, blank=True, null=True) nativa = models.BooleanField(_("Nativa?")) class Meta: db_table = 'arbolsaf_species' managed = True ordering = ["nombre_cientifico"] verbose_name = 'Especie' verbose_name_plural = 'Especies' -
Djago - Access related_name in queryset using as_manager
I am having some difficulty figuring out how to use foreign key (related_name) in a queryset using as_manager() Below is the mode and queryset. Everything works except the `get_powerbars()' method. I cannot seem to find any information about how to access the reverse foreign key lookup. Anything I try gets me the error (or similar) 'PowerbarQuerySet' object has no attribute 'outlet' What am I missing? If 'related_name' is not available in a queryset, how would one go about returning all the powerbars and their outlets in a simple fashion. import logging from django.db import models logger = logging.getLogger(__name__) class PowerbarQuerySet(models.QuerySet): """Additional queryset functions""" def get_powerbar_ips(self): try: all_bars = ( self.all().values_list("ip", flat=True).order_by("ip") ) return list(all_bars) except self.model.DoesNotExist: return None def get_powerbars(self): try: all_outlets = ( self.all().outlet ) return all_outlets except self.model.DoesNotExist: return None class Powerbar(models.Model): objects = PowerbarQuerySet.as_manager() name = models.CharField(max_length=200) building = models.CharField(max_length=200) group = models.CharField(max_length=200) ip = models.GenericIPAddressField() def __unicode__(self): return f'{self.name} @ {self.ip}' def __str__(self): return f'{self.name}' class Meta: base_manager_name = 'objects' class PowerbarOutlet(models.Model): powerbar = models.ForeignKey(Powerbar, on_delete=models.CASCADE, related_name='outlet') number = models.PositiveIntegerField() label = models.TextField(blank=True, default="") class Meta: unique_together = ("powerbar", "number") ordering = ("powerbar", "number") def __unicode__(self): return f'{self.number} @ {self.powerbar}' def __str__(self): return f'{self.powerbar}' I have … -
HTMX / Django List Of Forms - CSRF Token Issue?
I've got an application where I'm listing out a bunch of forms - it loads a csrf_token into each form. Each form is a simple dropdown for choosing a 'color' for each item in the list. I have a ListView that returns a list of placement objects like so: {% for placement in placements %} {% include 'placements/snippets/placement_update_form.html' %} {% endfor %} The placement_update_form.html looks like this: <form id="placementUpdateForm" action="{{ placement.get_update_url }}" method="post" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}'> <input type="hidden" name="id" value="{{ placement.id }}"> <label for="color">Color</label> <select name="color" id="color{{ placement.pk }}" class="form-select" hx-post="{% url 'placements:placement-update' placement.pk %}" hx-target="closest #placementUpdateForm"> <option value="" {% if not placement.color %}selected{% endif %}>Default</option> {% for value, display_name in placement_colors %} <option value="{{ value }}" {% if value == placement.color %}selected{% endif %}>{{ display_name }}</option> {% endfor %} </select> </form> I am using HTMX to POST the data to an UpdateView on my backend; which redirects to a success_url that is a DetailView that simply returns the placement_update_template and replaces that exact item in the DOM. It works - once. The first POST works and saves the color as expected. The template is replaced in the DOM, but if you choose a different color (triggering a second … -
instead of the username django value, I get "<django.db.models.query_utils.DeferredAttribute object at 0x0000017E365030D0>" (i see in SQLiteStudio)
I wanted to create a user without entering username and password, but only first_name, last_name and phone_number and so that username when creating a user was equal to phone_number models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): image = models.ImageField(upload_to='images/', null=True, blank=True) phone_number = models.CharField(max_length=11, help_text="Введите номер телефона пользователя", verbose_name="Номер телефона") class Meta(AbstractUser.Meta): pass def save(self, *args, **kwargs): self.username = User.phone_number super().save(*args, **kwargs) def __str__(self): return self.last_name forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from users.models import User class UploadImageForm(forms.ModelForm): class Meta: model = User fields = ['image'] class UserCreateForm(UserCreationForm): username = forms.CharField(label='username', max_length=100) phone_number = forms.CharField(label='phone_number', max_length=11) class Meta(UserCreationForm.Meta): model = User fields = ('username', 'phone_number') def save(self, *args, **kwargs): self.username = self.phone_number super().save(*args, **kwargs) admin.py from django.contrib import admin from django.contrib.admin import ModelAdmin from django.contrib.auth.admin import UserAdmin from django.utils.translation import gettext_lazy as _ from .forms import UserCreateForm from .models import * @admin.register(User) class CustomUserAdmin(ModelAdmin): add_form = UserCreateForm list_display = ('last_name', 'phone_number', 'is_staff') list_display_links = ('last_name', 'phone_number') search_fields = ('last_name', 'phone_number') ordering = ['last_name'] add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("username", 'phone_number'), }, ), ) fieldsets = ( (_("Personal info"), {"fields": ("first_name", "last_name", "phone_number", 'image')}), ( _("Permissions"), { "fields": ( "is_active", … -
Django:- Identification and Access Control
I'm working in an intelligence agency. Each and every agent of that agency has to provide their generated number on a certain page before they can access some pages. In our CustomUser model, we have a field that asks the user for their full name. We want the name to appear in the 'name' field of the Access model in real-time. What we want is that when someone types their number in the Access model, their full name in the CustomUser model should appear in the 'name' field of the Access model in real-time. My signals: @receiver(post_save, sender=User) def generate_number(sender, instance, created, **kwargs): if created: random_number = ''.join(random.choices(string.digits, k=10) Account.objects.create(user=instance, secret_number=random_number) My models: class Account(models.Model): user = models.ForeinKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) secret_number = models.IntegerField() Class Access(models.Model): user = models.ForeinKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.IntegerField() name = models.CharField(max_length=50) Note: We don't want to use the current user, which means that we want to allow someone on the platform to use another agent number to log in. I don't know if this is possible in django, that's why I'm asking this question. Thanks. -
Django allauth login isnt working. It was working but I am getting a ratelimit issue
Here is the login view def login(request): if request.method == 'POST': try: form = UserLoginForm(request.POST) if form.is_valid(): print('form is valid') email = form.cleaned_data.get('login') password = form.cleaned_data.get('password') try: user = authenticate(request, username=email, password=password) except Exception as e: print(str(e)) messages.success(request,str(e)) if user: #auth_login(request, user) messages.success(request, 'Sign in successful!') print('Login successful') return redirect('/dashboard') else: print(form.errors) print() except Exception as e: print(str(e)) else: form = UserLoginForm() return render(request, 'account/login.html', {'form': form}) When trying to login, I am getting File "\lib\site-packages\allauth\ratelimit.py", line 58, in consume if request.method == "GET" or not amount or not duration: AttributeError: 'NoneType' object has no attribute 'method Is this a known issue ? Please help -
Change Django to use EmailMultiAlternatives instead of send_mail() by default (all-auth)
So I am using django-all-auth for my authentication and using its in-built functionality for mailing reset passwords, confirmations of registration, etc. I have designed templates that include images. For the regular emails, I am explicitly using functions that use EmailMultiAlternatives instead of send_mail() since that allows inline images and background images. Django-all-auth however automatically uses send_mail() and my emails are arriving with the images missing. How can I override it so it uses EmailMultiAlternatives? -
Collapsed field in Django Admin's change view
The table Content has a field compressed_string that stores a very long string in the compressed form. This is what I have to display the original decompressed string in the Django Admin's change view: class ContentAdmin(admin.ModelAdmin): fields = ( [f.name for f in Content._meta.fields if f.name not in ['compressed_string']] + ['original_string']) readonly_fields = ['original_string'] list_display = [f.name for f in Content._meta.fields] def original_string(self, obj): return pickle.loads(brotli.decompress(obj.compressed_string)) I would like original_string to be displayed collapsed, with the possibility to expand and view the whole string. How can I accomplish this? -
I am getting "NoReverseMatch" error for my 'results' page
I am creating a quiz website. After the user answers all the questions he is redirected to the results page. But if he clicks the back button in Chrome he goes back to the questions in the quiz. But since the quiz is submitted i don't want him to go there. Instead It should redirect him into the home page where a list of all quizzes is available. So in the templates of the results page I included the following JavaScript code. <script> window.onload = function() { // Check if the referring URL matches the results page URL console.log('Referrer:', document.referrer); var expectedReferringURL = '{% url "quizquestions" %}'; // Check if the referring URL contains the expected URL pattern name if (document.referrer.includes(expectedReferringURL)) { // Replace the current history entry with the home page URL window.history.replaceState(null, null, '{% url "quizlist" %}'); } }; </script> The url pattern of the name "quizquestions" is path('quizzes/<int:quiz_id>/question/<int:question_id>',user_views.quizquestions,name='quizquestions') But when I go to the results page it shows this error Reverse for 'quizquestions' with no arguments not found. 1 pattern(s) tried: ['quizzes/(?P<quiz_id>[0-9]+)/question/(?P<question_id>[0-9]+)\\Z'] Any thoughts on why is this happening? -
Update Django via settings to new domain
I'm new to Django and nginx. I have built a default Django app and my setup uses a nginx server as a reverse proxy. My application was previously reached via https://myapplication.intranet and every internal link referred to this link (e.g. href "/" points to "https://myapplication.intranet/" and href points to "/test" "https://myapplication.intranet/test") - so everything worked. Now nginx changed the domain link to "https://myapplication.intranet/new/", and everything broke: redirect (e.g. in view.py) href (in html templates. For example href "/test" incorrectly points to "https://myapplication.intranet/test" instead of "https://myapplication.intranet/new/test") css sheets not found My question is the following: What adjustments have to be made (for Django) in order to make the application work again? Is there an easier (and more general) way than rewriting all links in all files to make the urls specific? Thank you very much. -
Invoke Django reload manually
I would like to force a reload of Django similar to when Django reloads after a file has changed. e.g. Watching for file changes with StatReloader This answer has the desired result but it involves a reload on "file changing": https://stackoverflow.com/a/43593959/12446456 However, I would specifically like to invoke the reload behaviour manually after a get request has been handled by Django. -
Basic Django image runs locally but fail inside Kubernetes?
I created a bare minimal Django project using django-admin startproject I then dockerized it using the following Dockerfile FROM python:3 ENV PYTHONUNBUFFRED=1 COPY . . RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I built and pushed the image to ACR. I am able to run it locally using docker run -p 8000:8000 <image_name> and I am able access the site at localhost:8000. However, when I try to deploy it inside a Kubernetes deployment with the following yml file, it just crashed and restart over and over. apiVersion: apps/v1 kind: Deployment metadata: name: demodjango-deployment labels: app: demodjango spec: replicas: 1 selector: matchLabels: app: demodjango template: metadata: labels: app: demodjango spec: containers: - name: demodjango image: djangonba.azurecr.io/demodjango:latest imagePullPolicy: "Always" ports: - containerPort: 8000 --- apiVersion: v1 kind: Service metadata: name: demodjango-service spec: type: LoadBalancer selector: app: demodjango ports: - protocol: TCP port: 8000 targetPort: 8000 I am unable to access the page through the external IP address of the service demodjango-service either even at time where it somehow didn't crash. I already made the following modification ALLOWED_HOSTS = ['*'] I believe there is something fundamentally wrong with my approach? Can anyone tell me theoretically why it works … -
How can i raise a message error when introducing the same company and username
Hi guys I'm creating a django form I'm introducing companies and users to create a license, I would like that you cannot register the same user with the same company class UserForm(forms.Form): """User form model.""" company = forms.ModelChoiceField( queryset=models.CompanyInfo.objects.all(), empty_label=None, error_messages={"required": "Please enter customer company."}, ) user_name = forms.CharField( error_messages={"required": "Please enter username."}, empty_label=None, ) full_name = forms.CharField( error_messages={"required": "Please enter customer full name."} ) email = forms.EmailField(required=True) I would like to create the validaton here, I've been trying to use "unique" direct to de field in the form but i noticed i cannot use it, how can i create that kind of validation directly in the form? -
How to solve django.db.utils.OperationalError: (1060, "Duplicate column name 'country_id'")
I was trying to delete some of the fields of my model and I tried to migrate them, but I got the error: Operations to perform: Apply all migrations: admin, auth, contenttypes, leads, order, sessions Running migrations: Applying leads.0023_auto_20230823_0043...Traceback (most recent call last): File "/web/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/web/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/web/.local/lib/python3.6/site-packages/pymysql/cursors.py", line 148, in execute result = self._query(query) File "/web/.local/lib/python3.6/site-packages/pymysql/cursors.py", line 310, in _query conn.query(q) File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 548, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 775, in _read_query_result result.read() File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 1156, in read first_packet = self.connection._read_packet() File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 725, in _read_packet packet.raise_for_error() File "/web/.local/lib/python3.6/site-packages/pymysql/protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "/web/.local/lib/python3.6/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1060, "Duplicate column name 'country_id'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/web/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/web/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/web/.local/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/web/.local/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/web/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res … -
Django ModelForm: how do I pre-populate data for a ModelForm overriding a field's widget? (Some working, some not.)
I have a model form with a number of fields that need to use widgets other than the default widget for the model data type. Loading the update form before adding custom widgets, all the data pre-populates for the current object correctly. As soon as I add a custom widget for any field, the pre-population for that field breaks. For example, this works as expected: class ChecklistForm(forms.ModelForm): class Meta: model = Checklist fields = [ "expected_time", #TimeField "completed", #BooleanField, nullable ] But I want control over the widgets used. I'd like the boolean completed field to render as a checkbox even though it is nullable, so I add: class ChecklistForm(forms.ModelForm): class Meta: model = Checklist fields = [ "expected_time", #TimeField "completed", #BooleanField, nullable "date", #DateField ] widgets = { 'expected_time': forms.TimeInput(format='%H:%M',attrs={'type': 'time'}), 'completed': forms.CheckboxInput(), 'date': forms.DateInput(format=('%m/%d/%Y'), attrs={'placeholder':'Select a date', 'type':'date'}), } When I load an update form, completed pre-populates correctly, while expected_time and date do not. Why? And is there a way to pre-populate these fields automatically? -
Memory never releases on Heroku, slow memory leak from models in Django?
I have been troubleshooting memory leak issues on my Django application deployed to Heroku. Basically, when the app is deployed/dyno restarted RAM hovers around 40% then as soon as someone gets on, it goes to 80% usage then stays there and never goes back down. Here is a screenshot of my last 24 hours: Things I have tried: Caching expensive things that are called often (using @cached_property), like checking a users subscription that is tied to their organization. Optimizing my queries, so far the biggest queryset I bring back is ~20 rows and isn't particularly big. Ran a memory profiler (pympler) that has a tab on Django Debug Toolbar. Admittedly am unsure of what I am looking at. Lowered gunicorn workers to 2 instead of 4 Checked that database connections weren't going haywire (currently 2 connections) Some other ideas of what it could be but unsure how to properly troubleshoot: I have middleware where I check for a subscription that runs on most pages, could this be somehow leaking/storing data? If I hit a 3rd party API (which isn't that often in this app) do I have to actively run del to get it out of memory? Has anyone else … -
How to remove `b'\x80\x05\x95\x08\...` from the contents of cache in Django?
I set 4 cache values with LocMemCache as shown below: from django.core.cache import cache cache.set("first_name", "John") cache.set("last_name", "Smith", version=2) cache.set("age", 36, version=3) cache.set("gender", "Male") Then, I tried to see the contents of the cache with cache._cache as shown below: from django.core.cache import cache print(cache._cache) # Here But, each key's value contains b'\x80\x05\x95\x08\... as shown below: OrderedDict([(':1:gender', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04Male\x94.'), (':3:age', b'\x80\x05K$.'), (':2:last_name', b'\x80\x05\x95\t\x00\x00\x00\x00\x00\x00\x00\x8c\x05Smith\x94.'), (':1:first_name', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04John\x94.')]) And, I tried to see the contents of the cache with cache._cache.items() as shown below: from django.core.cache import cache print(cache._cache.items()) # Here But again, each key's value contains b'\x80\x05\x95\x08\... as shown below: odict_items([(':1:gender', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04Male\x94.'), (':3:age', b'\x80\x05K$.'), (':2:last_name', b'\x80\x05\x95\t\x00\x00\x00\x00\x00\x00\x00\x8c\x05Smith\x94.'), (':1:first_name', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04John\x94.')]) Lastly, I tried to see the contents of the cache with locmem._caches as shown below: from django.core.cache.backends import locmem print(locmem._caches) # Here But again, each key's value contains b'\x80\x05\x95\x08\... as shown below: {'': OrderedDict([(':1:gender', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04Male\x94.'), (':3:age', b'\x80\x05K$.'), (':2:last_name', b'\x80\x05\x95\t\x00\x00\x00\x00\x00\x00\x00\x8c\x05Smith\x94.'), (':1:first_name', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04John\x94.')])} My questions: How can I remove b'\x80\x05\x95\x08\... from the contents of the cache? What is b'\x80\x05\x95\x08\...? -
Django admin: displaying computed property when viewing a single item
I store compressed strings in the database. I would like to see the actual string when in Django Admin. Since the strings are very long, I don't want them to appear in the list view, but only when viewing a single item (row). So, I can define: @property def short_my_field(self): return pickle.loads(brotly.decompress(self.my_field))[:80] @property def original_my_field(self): return pickle.loads(brotly.decompress(self.my_field)) I will then put short_my_field into list_display. But how do I cause original_my_field to display when viewing a single item? -
Got an lint error while running a dockerised project on github actions
I don't understand the error and I tried any times (https://i.stack.imgur.com/xNs3G.png) Here is my setup for github actions: --- name: Checks on: [push] jobs: test-lint: name: Test and Lint runs-on: ubuntu-20.04 steps: - name: Checkout uses: actions/checkout@v2 - name: Test run: docker-compose run --rm app sh -c "python manage.py wait_for_db && python manage.py test" - name: Lint run: docker-compose run --rm app sh -c "flake8" -
How to display the chapters of the Bible from django-bible package?
I'm trying to display the chapters of the bible from the bible package available here https://github.com/davisd/django-bible. Some of the codes are deprecated and I have refactored some. Now, I have the JSON file of the bible loaded in my database. I'm also able to display a list of the books of the Bible. The problem I'm facing is how to display the chapters of each book from my database. I have tried the following: models.py from django.db import models from .managers import BookManager class Book(models.Model): """ Book of the Bible """ number = models.PositiveIntegerField(primary_key=True, unique=True, db_index=True) slug = models.SlugField(unique=True) name = models.CharField(max_length=64, db_index=True) is_new_testament = models.BooleanField() objects = BookManager() def get_absolute_url(self): """ Returns the absolute url """ return reverse('book_detail', [self.slug,]) def __unicode__(self): return self.name class Meta: ordering = ['number',] class Chapter(models.Model): """ Chapter of the Bible """ book = models.ForeignKey(Book, related_name='chapters', on_delete=models.CASCADE) number = models.PositiveIntegerField(db_index=True) def __unicode__(self): return '%s %s' % (self.book.name, self.number) def get_next_chapter(self): try: return Chapter.objects.filter( book=self.book,number__gt=self.number).order_by( 'number')[0] except IndexError: return None def get_previous_chapter(self): try: return Chapter.objects.filter( book=self.book,number__lt=self.number).order_by( '-number')[0] except IndexError: return None def get_absolute_url(self): """ Returns the absolute url """ return reverse('chapter_detail', [self.book.slug, self.number]) class Meta: ordering = ['number',] unique_together=(('book','number',),) views.py from django.http import HttpResponse, Http404 from … -
Python Libraries (Twisted, regex, cryptography, hiredis)
These are all the libraries I used in my project. aioredis==1.3.1 alabaster==0.7.12 amqp==2.6.0 appdirs==1.4.4 Arpeggio==1.9.2 asgi-redis==1.4.3 asgiref==3.2.7 async-timeout==3.0.1 atomicwrites==1.4.1 attrs==19.3.0 autobahn==20.4.3 autoflake==1.3.1 Automat==20.2.0 autopep8==1.5.2 Babel==2.8.0 backcall==0.2.0 backports.shutil-get-terminal-size==1.0.0 bandit==1.6.2 billiard==3.6.3.0 black==19.10b0 bleach==3.1.5 boto3==1.17.0 botocore==1.20.0 bumpversion==0.5.3 celery==4.4.5 certifi==2020.4.5.2 cffi==1.15.1 channels==2.4.0 channels-redis==2.4.2 chardet==3.0.4 Click==7.0 colorama==0.4.6 colour==0.1.5 constantly==15.1.0 coverage==5.0.3 coveralls==1.10.0 cryptography==41.0.3 daphne==2.5.0 decorator==4.4.2 distlib==0.3.0 Django==3.0.7 django-admin-inline-paginator==0.3.0 django-admin-logs==1.0.1 django-admin-sortable2==0.7.6 django-ckeditor==5.9.0 django-cors-headers==3.11.0 django-debug-toolbar==2.2 django-dotenv==1.4.2 django-environ==0.4.5 django-fernet-fields==0.6 django-impersonate==1.9.1 django-js-asset==1.2.2 django-mapper==1.1.11 django-modelclone==0.7.1 django-mysql==3.7.1 django-pagination-bootstrap==2.3.0 django-redis==5.2.0 django-safedelete==1.0.0 django-silk==4.1.0 django-slack==5.17.6 django-solo==1.1.3 django-storages==1.11.1 djangorestframework==3.12.1 doc8==0.8.0 docopt==0.6.2 docutils==0.15.2 docxcompose==1.4.0 docxtpl==0.16.5 EasyProcess==0.3 entrypoint2==0.2.1 entrypoints==0.3 enum34==1.1.10 et-xmlfile==1.0.1 filelock==3.0.12 flake8==3.7.9 flake8-2020==1.5.0 flake8-bandit==2.1.2 flake8-broken-line==0.1.1 flake8-bugbear==20.1.4 flake8-builtins==1.4.2 flake8-comprehensions==3.2.2 flake8-debugger==3.2.1 flake8-fixme==1.1.1 flake8-isort==2.8.0 flake8-logging-format==0.6.0 flake8-mutable==1.2.0 flake8-polyfill==1.0.2 flake8-variables-names==0.0.3 flower==0.9.7 future==0.18.2 gitdb==4.0.5 GitPython==3.1.3 gprof2dot==2019.11.30 gunicorn==20.0.4 hiredis==2.2.3 humanize==3.9.0 hyperlink==19.0.0 idna==2.9 imagesize==1.2.0 importlib-metadata==1.6.1 incremental==17.5.0 ipython==7.15.0 ipython-genutils==0.2.0 isort==4.3.21 jdcal==1.4.1 jedi==0.17.0 jeepney==0.4.3 Jinja2==2.11.2 jmespath==0.10.0 keyring==21.2.1 kombu==4.6.10 lxml==4.9.3 MarkupSafe==1.1.1 mccabe==0.6.1 more-itertools==8.3.0 msgpack==0.6.2 msgpack-python==0.5.6 numpy==1.23.5 olefile==0.46 openpyxl==3.0.4 packaging==20.4 pandas==1.5.2 parso==0.7.0 pathlib2==2.3.5 pathspec==0.8.0 pbr==5.4.5 pep8-naming==0.9.1 pexpect==4.8.0 pickleshare==0.7.5 Pillow==9.4.0 pillow-heif==0.13.0 pkginfo==1.5.0.1 platformdirs==3.10.0 pluggy==0.13.1 prometheus-client==0.8.0 prompt-toolkit==3.0.5 ptyprocess==0.6.0 py==1.8.1 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.5.0 pycparser==2.20 pydocstyle==5.0.2 pyflakes==2.1.1 Pygments==2.6.1 PyHamcrest==2.0.2 pyOpenSSL==19.1.0 pyparsing==2.4.7 pypdf2==3.0.1 pytest==5.3.5 pytest-cov==2.8.1 pytest-runner==5.2 python-dateutil==2.8.1 python-dev-tools==2020.2.5 python-docx==0.8.11 pytz==2020.1 pyunpack==0.2.1 pyupgrade==1.26.2 pywin32-ctypes==0.2.2 PyYAML==5.3.1 readme-renderer==26.0 redis==2.10.6 regex==2023.8.8 requests==2.23.0 requests-toolbelt==0.9.1 restructuredtext-lint==1.3.1 s3transfer==0.3.4 scandir==1.10.0 SecretStorage==3.1.2 sentry-sdk==0.17.0 service-identity==18.1.0 simplegeneric==0.8.1 six==1.16.0 smmap==3.0.4 snowballstemmer==2.0.0 Sphinx==2.3.1 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==1.0.3 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.4 sqlparse==0.3.1 stevedore==2.0.0 testfixtures==6.14.1 textX==2.1.0 tokenize-rt==4.0.0 toml==0.10.1 tornado==6.1 tox==3.14.3 … -
How to notify a User whenever an object is Created in Django model
I would like to tell a user automatically whenever a new game or a movie is uploaded or published on the website. below is my models. #games model GAME_TYPE=( ("action", "action"), ("adventure", "adventure"), ("racing", "racing"), ("puzzle", "puzzle"), ) MOV_TYPE=( ("action", "action"), ("adventure", "adventure"), ("sci-fi", "sci-fi"), ("horror", "horror"), ("drama", "drama"), ) GAME_OS=( ("Windows", "Windows"), ("Android", "Android"), ) class Games(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=GAME_TYPE) os=models.CharField(max_length=15, choices=GAME_OS) img=models.ImageField() developer=models.CharField(max_length=50) version=models.CharField(max_length=10) ratings=models.CharField(max_length=10) description=models.TextField() def __str__(self) -> str: return self.name class Movies(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=MOV_TYPE) description=models.TextField() released=models.DateField() def __str__(self) -> str: return self.name I need direct me on how to create an function to send or notify a user automatically whenever a game is published but l don't know how to do it. Anyone to solve me