Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have performance issue with apex charts
I have 3 async charts on one page and total number of data on the page is about 15k, but the chart is lagging a lot. Data is from the backend I use Django templates to iterate over specific data and add that data to the chart. First chart: var options = { series: [{ name: 'Fed Fund Rate', data: [ {% for int in interest %} { x: "{{int.interest_date}}", y: ["{{int.strategy_interest}}"], }, {% endfor %} ] }, ], chart: { id: 'chart_1', group: 'social', height: 300, type: 'line',`your text` animations: { enabled: false }, zoom: { type: 'xy' }, }, dataLabels: { enabled: false }, yaxis: { type: 'numeric', }, xaxis: { type: 'datetime', }, }; var chart = new ApexCharts(document.querySelector("#chart-int"), options); chart.render(); Second: var options = { series: [{ name: 'OHLC', data: [ {% for stock in stocks %} { x: "{{stock.date}}", y: ["{{stock.open|floatformat}}", "{{stock.high|floatformat}}", "{{stock.low|floatformat}}", "{{stock.price|floatformat}}"], }, {% endfor %} ] }, ], chart: { height: '100%', id: 'chart_2', group: 'social', type: 'candlestick', animations: { enabled: false }, }, dataLabels: { enabled: false }, title: { text: '{{ticker}}', align: 'center', style: { fontSize: '24px', fontFamily: 'calibri' } }, yaxis: { type: 'numeric', }, xaxis: { type: 'datetime', … -
Setup an email notification when consumer: Connection to broker lost in celery
I want to implement an email system which will send an email whenever my celery worker lost connection with my Redis server. Whenever it lost connection it gives warning: [2023-03-02 21:33:48,272: WARNING/MainProcess] consumer: Connection to broker lost. Trying to re-establish the connection... And starts reconnecting with the server [2023-03-02 21:33:48,286: ERROR/MainProcess] consumer: Cannot connect to redis://127.0.0.1:6379//: Error 61 connecting to 127.0.0.1:6379. Connection refused.. Trying again in 2.00 seconds... (1/100) I am using django 3.2.8 and celery 5.2.7. I went through the whole celery docs and source code I get to know there is a method on_connection_error_after_connected in the celery.worker.consumer.connection which get's triggered when it lost connection. -
Data not rendering in Cytoscape.js in the Django template
I am trying to display the data in the Django template in the form of graph. I am getting the data from Neo4J and for querying I am using neomodel. First I am serializing the data in the form of JSON accepted my Cytoscape.js. This is my template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Graph View</title> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.23.0/cytoscape.min.js" integrity="sha512-gEWKnYYa1/1c3jOuT9PR7NxiVI1bwn02DeJGsl+lMVQ1fWMNvtjkjxIApTdbJ/wcDjQmbf+McWahXwipdC9bGA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>--> <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.8.4/cytoscape.min.js" integrity="sha512-gn5PcEn1Y2LfoL8jnUhJtarbIPjFmPzDMljQbnYRxE8IP0y5opHE1nH/83YOuiWexnwftmGlx6i2aeJUdHO49A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <style> #cy { width: 300px; height: 250px; display: block; background-color: #fff; } </style> </head> <body> {{data}} <div id="cy"></div> <div id="test"></div> <h2>Hello</h2> <script> var my_graph_data = JSON.parse('{{ data|escapejs }}'); var cy = cytoscape({ container: document.getElementById('cy'), elements: '{{data}}', style: [ { selector: 'node', style: { 'label': 'data(label)', 'width': '60px', 'height': '60px', 'color': 'blue', 'background-fit': 'contain', 'background-clip': 'none' } }, { selector: 'edge', style: { 'text-background-color': 'yellow', 'text-background-opacity': 0.4, 'width': '6px', 'target-arrow-shape': 'triangle', 'control-point-step-size': '140px' } } ], layout: { name: 'circle' } }); </script> </body> </html> This is the format of my data when I print my json [{'data': {'movieName': 'Matrix', 'director': 'John', 'rating': 9.0}}, {'data': {'movieName': 'John Wick', 'director': 'Bill', 'rating': 8.0}}] When I try the different data with same format I get the graph [ { 'data': { id: 'a', name: 'Sheraton … -
Running django migration gives "Wait for backup lock" in mysql
I am trying to run a django migration that creates 3 models and deletes 1 model with 350k rows. However, after running the migration, my mysql database is waiting for backup lock. <id> <admin> <ip>:<port> database_test Query Waiting for backup lock CREATE TABLE `table` (`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, `column1` double precision NOT NULL, `column2` bigint NULL, `column3` bigint NULL) How can I resolve waiting for backup lock and what does it mean? -
{% if {club.c_type} == 'Tech' %} is giving error Code is working perfectly without it. Want to filter data on basis or Tech and Non Tech in same Page
{% for club in clubs %} {% if {club.c_type} == 'Tech' %} SOME CODE {% endif %} {% endfor %} def clubs(request): clubs_data = Clubs.objects.all() return render(request, 'clubs.html', {'clubs': clubs_data}) CLUBS_TYPE = {('T', 'Tech'), ('NT', 'Non-Tech')} class Clubs(models.Model): club_id = models.CharField(primary_key= True, max_length=5) c_name = models.CharField(max_length=50) c_logo = models.ImageField(upload_to='clubimg') c_type = models.CharField(choices=CLUBS_TYPE, max_length=2) -
I want to run "python manage.py makemigrations ". Got error "password authentication failed""No changes detected"
I want to run: (venv) ubuntu@ip-172-31-44-136:~/easy_django_repo$ python manage.py makemigrations And got this error: /home/ubuntu/venv/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:143: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "diEvaR6s52EqJv" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "diEvaR6s52EqJv" warnings.warn( No changes detected I changed password for user and os: (venv) ubuntu@ip-172-31-44-136:~/easy_django_repo$ sudo -u postgres psql Password for user postgres: psql (14.6 (Ubuntu 14.6-0ubuntu0.22.04.1)) Type "help" for help. postgres=#ALTER USER diEvaR6s52EqJv WITH PASSWORD '#####'; (venv) ubuntu@ip-172-31-44-136:~$ sudo passwd postgres New password: And I ran: (venv) ubuntu@ip-172-31-44-136:/etc/postgresql/14/main$ sudo -u postgres psql Password for user postgres: (venv) ubuntu@ip-172-31-44-136:/etc/postgresql/14/main$ psql -U postgres Password for user postgres: Got error: psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: password authentication failed for user "postgres" I can't understand what do I have to do. Can anyone give me some advice? Almost struggling for a week. -
Django logging - logger from a module?
According to documentation I have to specify the LOGGING variable in settings.py Is it possible to pass logger from my custom module in django instead? For example, I have a following module: import logging import os class CustomFormatter(logging.Formatter): grey = "\x1b[38;20m" blue = "\x1b[1;34m" yellow = "\x1b[33;20m" red = "\x1b[31;20m" bold_red = "\x1b[31;1m" reset = "\x1b[0m" logging_message_format = "\n%(asctime)s - (%(filename)s:%(lineno)d) - %(name)s - %(levelname)s - %(message)s" FORMATS = { logging.DEBUG: blue + logging_message_format + reset, logging.INFO: grey + logging_message_format + reset, logging.WARNING: yellow + logging_message_format + reset, logging.ERROR: red + logging_message_format + reset, logging.CRITICAL: bold_red + logging_message_format + reset } def format(self, record): log_fmt = self.FORMATS.get(record.levelno) formatter = logging.Formatter(log_fmt) return formatter.format(record) LOGGING_LEVEL = os.environ.get('LOGGING_LEVEL', 'INFO').upper() logger = logging.getLogger("api") logger.setLevel(LOGGING_LEVEL) ch = logging.StreamHandler() ch.setLevel(LOGGING_LEVEL) ch.setFormatter(CustomFormatter()) # Set to False if too much output in container logger.propagate = True logger.addHandler(ch) I'm using it for logging in tests, as well as database and intending to use the same module for celery logging (probably modifying it a little bit). Is it possible to re-use the module for Django's runserver logging as well? -
Django built-in template tag to convert UTC to datetime?
Is there any way to convert a UTC, defined with models.CharField, to datetime using a built-in filter template tag? Or must i use a custom function (see below)? I have found nothing on this specific topic online. Here is an example Inside models.py: ... boarding_time_utc = models.CharField(max_length=15, default="14:00") ... def show_boarding_time(self): date_time = datetime.fromtimestamp(int(self.boarding_time_utc)) reable_date_time = date_time.strftime('%H:%M') return str(reable_date_time) Inside example.html: <td>{{ entry.show_boarding_time}}</td> Thats pretty much it. Thanks in advance! -
What are some ways to display images on server for a Django project? I keep getting 404 errors
A current miniproject that I am working on is a personal cocktail "cookbook" website, where I display different drinks, their recipes, my personal notes, images, etc. I configured the code in that when someone clicks on one of the many drinks that are displayed under a base alcohol category, they will be navigated to that one specific drink and be shown its attributes. The only thing that I haven't been able to do is having the server correctly display the image associated with the drink. Whenever I run the server and click on a specific drink, that entries' contents are shown in the correct format, but the image only appears as an icon and the server console keeps giving a 404 not found error. On Django admin, I am able to save images whenever I create a new entry, and VScode shows the correct location as to where the images are stored. I made sure that libraries like Pillow and Whitenoise have been downloaded. I also checked the MEDIA and STATIC section of my settings.py file to check the path configuration of where the images can be stored and served. But, so far, the server keeps giving a 404 error … -
phonenumber field authentication error in django
i am making a login function in django where user will input their phone number and password, they can access the account. but when i run the server, i get error that invalid phone number and password, but i registered proper phone number and password. I did some troubleshooting and come to know that phone number data is not showing. here's my code models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from phonenumber_field.modelfields import PhoneNumberField from .manager import MyUserManager # Create your models here. class MyUser(AbstractBaseUser, PermissionsMixin): username= models.CharField(max_length=50, null=True) phone_number = PhoneNumberField(unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) email = models.EmailField(unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = MyUserManager() def __str__(self): return self.phone_number.as_e164 def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm from phonenumber_field.formfields import PhoneNumberField from .models import * class MyLoginForm(AuthenticationForm): phone = PhoneNumberField() password = forms.CharField(label='Password', widget=forms.PasswordInput) views.py from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from .forms import MyLoginForm # Create your views here. def my_login(request): if request.method == 'POST': form = MyLoginForm(request, request.POST) if form.is_valid(): phone_number = … -
Choosing a right size for e-commerce platform images (grid-item, item, full-size item?)
I'm now a bit lost and can't find the right way or the best practice of choosing the right size of the image. I know that the image sizes should be optimal and not too big or small. So I've read and found that optimal size should be 800x800? So let's start with the things that I will be using in the front-end. So first of all I will have a grid in which I will display from 1 to 4 items in a row. The grid item has a max-width:574px; max-height:409px;. Let's continue to the main item page. I wish to display a slider in which the image should be centered and not full-width. Two things here, I don't really know what the wrapper should look like. This image has 700x109 but it does stretch to fill all the width, I would love to prevent it from happening. Another question is how should I process user uploaded images? Should I prevent users from uploading images that are smaller than 800x800 or something? How should I resize them, what resolutions should I save in our server? This is the grid-item with the visible size: f -
How to customise Folium html popups in a for loop in Django views?
I am trying to change the standard popups provided with Folium and make these work with a for loop. I am using Django. I succeeded on change the html, following a few tutorials. However I am struggling to understand how to call the variables in the html. Quite simply I have a map with a list of locations. If the user click on the locations the popup appear and would display logo, name and a few other things specific to the location. what I tried I tried different iteration including adding {{venue.name}} but clearly this doesnt work if I am not in the template.py. The current one """.format(venue.name)+""" is an example I found on a tutorial. However I must be missing something as this is not working for me. (https://towardsdatascience.com/use-html-in-folium-maps-a-comprehensive-guide-for-data-scientists-3af10baf9190) my question I suppose my question would be to know how I can call a variable in the for loop of my views.py where I am also trying to render the HTML from. In my particular case, how can I call {{venue.name}} in a format views.py is going to understand (I haven't added the files, as I didn't think it is necessary for this problem. I am obviously happy to … -
Django UpdateView does not validate form fields, and does not update
I have created the following Django UpdateView: class ProfileSettingsView(SuccessMessageMixin, UpdateView): template_name = "accounts/settings/profile_settings.html" form_class = ProfileSettingsForm success_message = "Your profile has been successfully updated." success_url = reverse_lazy("accounts:profile_settings") context_object_name = "staff_member" def get_object(self, queryset=None): staff_member = get_object_or_404(StaffMember, user=self.request.user) return staff_member The ProfileSettingsForm is defined as follows: class ProfileSettingsForm(forms.ModelForm): class Meta: model = StaffMember fields = ["profile_image"] And finally, the StaffMember model looks like this: class StaffMember(models.Model): user = models.OneToOneField( "auth.User", on_delete=models.PROTECT, related_name="staff_member" ) profile_image = models.ImageField( upload_to=get_profile_image_upload_path, blank=True, default="none.png", help_text="A profile image for this staff member. Must be square, and be in .png format.", validators=[FileExtensionValidator(["png"]), validate_img_square], ) My UpdateView renders correctly. I select an image from my local machine and press submit. The form posts successfully, and I see the success message. However, the validators, as defined on the StaffMember profile_image field have not been run. Also, the profile_image field is not updated. Why is validation not being called on my form fields, and why are they not being updated? What am I missing? Thank-you. -
How to do a Django list in list query
I have a list of lists filter items as this: [['3aa', '1ss', '2bb'], ['4aa', '5bb'], ['3nn', '9mm', '6cc']] My database table has a field with a field(category) holding a list as value: ['4aa', '5bb'] How can I query to fetch items whose category is in the filter list? Something like: Table.objects.filter(category__in=[['3aa', '1ss', '2bb'], ['4aa', '5bb'], ['3nn', '9mm', '6cc']]) -
How to make Django admin write LogEntry (history) for inline objects?
I have a model that is registered as a ModelAdmin, but for convenience is also an inline in another model. When creating or editing this related model, changes to the inline objects are not saved to Django's LogEntry, only the main object being edited. An example of this configuration is as follows: class Manufacturer(models.Model): ... class Car(models.Model): manufacturer = models.ForeignKey(Manufacturer) ... Then, in admin: @admin.register(Car) class CarAdmin(admin.ModelAdmin): ... class CarInline(admin.StackedInline): model = Car class ManufacturerAdmin(admin.ModelAdmin): inlines = [CarInline] ... Currently, when editing a Manufacturer, even if I only add / remove cars, the only LogEntry added by Django is a change to Manufacturer (and the change message sucks by the way). ModelAdmin has methods called log_addition, log_change, and log_deletion, which I can use to create LogEntry objects, but how do I determine if an inline object has been added / changed / removed? -
Django model property does not working - Django
class Offers(models.Model): @property def flag_from(self): return self.country.country_flag status = models.BooleanField() .....other_normal_fields So when i'm trying to get one row, and print my custom field Doesn't shows only when print it directly: line=Offers.objects.get(pk=1) print(line) ### here shows only normal fields print(line.flag_form) ### now ok also when i convert line to dict custom models dissappears, but i need it there How it can be fixed? -
Django server calls Google pay API refund
I can't find an open API for Google Pay that I can interact with from my Django server to make automated refunds for my customers who have bought some items but want a refund. I am investigating Google Pay API, but I can't find an open API that I can interact with from my django server. What I need is to make an automated refund for my customer, who have bought an item but wants a refund. -
Django rest framework error when trying to loggin(Authenticate) via post request
Anytime I make a post request to this login route at http://127.0.0.1:8000/api/login/ I keep getting this error in postman, despite providing the right credentials. "detail": "CSRF Failed: Origin checking failed - chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop does not match any trusted origins." Same post request from an android app also gives me cors errors. I use these decorators @api_view(['GET','POST']). It works well without the decorators though. This is also my path declaration : path('login/',csrf_exempt(api_views.login),name='api_login'), How can I login? I expect a login success with user information as response -
How to save an in memory Excel file to a Django models.FileField
I am trying to save an Excel file that is built in memory to a Django models.FileField but get the error message: "'XlsxWriter' object has no attribute 'read'". Here are the steps I follow: Data are first extracted from Django models. The data is saved temporarily in a pandas DataFrame. When completed, the Dataframe is transferred to an Excel file. The final step would be to save the Excel file to a models.FileField. This is the last step I have a problem with. Here are the problematic lines of code with the error message I get: file = File(excel_file) doc.document.save(file_name, file, save=True) 'XlsxWriter' object has no attribute 'read' I suspect the solution might lie with the usage of io.BytesIO but I cannot figure out how. Here are more details on my code: models.py class DocuPlan(models.Model): plan = models.ForeignKey(Plan, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.DO_NOTHING, null=True) doc_type = models.IntegerField( _('Document type'), choices=DocuPlanType.choices, default=DocuPlanType.OTHER ) date_order = models.DateField(null=True, blank=True) date_published = models.DateField(null=True, blank=True) is_public = models.BooleanField(_('Public document'), default=False) **document = models.FileField( upload_to=docu_plan_directory_path, max_length=100, null=True, blank=True)** date_filed = models.DateTimeField(auto_now_add=True) file_name = models.CharField(max_length=150, null=True, blank=True) views.py def dataExtraction(request, pk): template = 'basic/form_data_extraction.html' plan = Plan.objects.get(pk=pk) context = {} form = DataExtractionForm(request.POST or None, request=request, plan=plan) … -
AttributeError: module 'rest_framework.serializers' has no attribute 'Booleanfield'
I'm trying to create a boolean field serializer and i get this error i tried to make it default is false and did not work is_follower = serializers.Booleanfield(default=False) -
ModuleNotFoundError: No module named 'timescale.fields'
I have downloaded django-timescaledb but when i run server, the following error is displayed in terminal: ModuleNotFoundError: No module named 'timescale.fields' from django.db import models from django.contrib.auth import get_user_model import uuid from datetime import datetime from django.utils import timezone from django.db.models import F from django.utils.timezone import now from timescale.fields import TimescaleDateTimeField User = get_user_model() class TimescaleModel(models.Model): """ A helper class for using Timescale within Django, has the TimescaleManager and TimescaleDateTimeField already present. This is an abstract class it should be inheritted by another class for use. """ time = TimescaleDateTimeField(interval="1 day") class Meta: abstract = True Terminal error message -
NoReverseMatch at / Reverse for 'athlete_profile' with keyword arguments '{'pk': ''}' not found
i'm trying to make a page where i can display an athlete's profile to them by using their primary key as a refernce but i get an error as follows: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.7 Python Version: 3.11.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'events', 'userty'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\SHRUTI\SEM_6\PROJECT\COMBAT_CON_F\templates\base.html, error at line 81 Reverse for 'athlete_profile' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['users/profile/athlete/(?P<pk>[0-9]+)/\\Z'] 71 : </head> 72 : <body> 73 : <nav> 74 : <div> 75 : <a href="{% url 'home' %}">Combat-Con</a> 76 : </div> 77 : <div> 78 : <a href="{% url 'events:event_list' %}">Events</a> 79 : {% if user.is_authenticated %} 80 : {% if user.is_athlete %} 81 : <a href=" {% url 'userty:athlete_profile' pk=athlete.pk %} ">Athlete Profile</a> 82 : {% elif user.is_host %} 83 : <a href="{% url 'userty:host_profile' pk=user.host.pk %}">Host Profile</a> 84 : {% endif %} 85 : <a href="{% url 'userty:user_logout' %}">Logout</a> 86 : {% else %} 87 : <a href="{% url 'userty:register' %}">Register</a> 88 : <a href="{% url 'userty:login' %}">Login</a> 89 : {% endif %} 90 : </div> 91 : </nav> Traceback (most … -
Django - Moving from one category post to the next and back
There is a model and posts attached to it. I can not figure out how to make the transition from the active post to the next and back. I read many articles, but I did not find the right one for me. Here is my code. How can this be done? HTML <div class="bootons-navigation"> <span class="span__bootons-navigatiom"><a href="#" title="previous">previous</a></span> <span class="span__bootons-navigatiom"><a href="#" title="next">next</a></span> </div> Models class home(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('URL')) title = models.CharField(max_length=250) top_description = models.TextField(max_length=700, blank=False) class Meta: verbose_name = 'Главная' verbose_name_plural = 'Главная' def __str__(self): return self.title class category(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('URL')) description = models.TextField(max_length=700, blank=False) def __str__(self): return self.slug def get_absolute_url(self): return reverse('category', kwargs={'category_slug': self.slug}) class post(models.Model): slug = models.SlugField(max_length=266, unique=True, db_index=True, verbose_name=('URL')) description = models.TextField(max_length=700, blank=False) cat = models.ForeignKey('category', on_delete=models.PROTECT, null=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse('post', kwargs={'post_slug': self.slug}) Views def content_category(request, category_slug): categorypost=category.objects.filter( slug=category_slug) get_list_or_404(categorypost, slug=category_slug) return render(request, 'content/season.html',{ 'category':categorypost, }) def content_post(request, category_slug, post_slug): postpages = post.objects.filter(slug=post_slug, cat__slug=category_slug) get_object_or_404(postpages, slug=post_slug, cat__slug=category_slug) return render(request, 'content/post.html', { 'post': postpages, }) URLS path('', views.ContentHome.as_view(), name='homepage'), path('\<slug:category_slug\>', views.content_category), path('\<slug:category_slug\>/\<slug:post_slug\>', views.content_post)` -
How to start with no formsets and generate form whenever a button / dropdown item is clicked?
Given the following form: class MyForm(forms.Form): my_field = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'My field', 'class': 'form-control'} ), label='', ) When used with a formset_factory in this way, it generates a minimum of 1 form which is visible whenever the corresponding url is access. def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) match self.request.method: case 'GET': context['formset'] = formset_factory(MyForm)() case 'POST': context['formset'] = formset_factory(MyForm)(self.request.POST) return context and this is how the template looks like: <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form.my_field }} {% endfor %} <button class="btn btn-success" type="submit">Create</button> </form> results in: What do I need to modify if I don't need the form to show up at all, without explicitly hiding it? I want to start with something like this / a dropdown menu with different form types: <button class="btn btn-success" type="button">Generate form A</button> <button class="btn btn-success" type="button">Generate form B</button> and each button generates a different form. I don't want any initial forms to show up, just the buttons, what would be a clean way to do it? -
Periodic tasks in Django are not called
I use django_crontab to periodically call my tasks. The problem is that periodic tasks are not called. I created a test function that sends me a message and I can understand that the task is done: def test_crj(): send_message("Test cronjobs!") I set it to run once every five minutes: # in settings.py INSTALLED_APPS = [ ... , "django_crontab", ] CRONJOBS = [ ("*/5 * * * *", "project.cronjob.test_crj", '>> /tmp/test.log'), ] crontab sees it: > docker exec container python3.9 manage.py crontab show # Currently active jobs in crontab: # a35573388f4e46c33f88fc825f0a1d8f -> ('*/5 * * * *', 'project.cronjob.test_crj', '>> /tmp/test.log') > docker exec container crontab -l # */5 * * * * /usr/local/bin/python3.9 /app/manage.py crontab run a35573388f4e46c33f88fc825f0a1d8f >> /tmp/test.log # django-cronjobs for project But nothing happens! Meanwhile, when I run the function independently, everything works fine. And when I run it the way the system crontab should run (as I understand it), it works too. > docker exec container python3.9 manage.py crontab run a35573388f4e46c33f88fc825f0a1d8f # it works What could be the error and who is to blame - django_crontab or the system crontab? Or where and how do I look at the logs, why it doesn't work?