Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple images for a project in django
Am creating a web app in django where I have a model called projects which carries data of a project with an image. I have another model called ProjectImages which allows one to add multiple images to a project. I am trying to query the images related to a specific project but they are mot being rendered on the webpage. I will appreciate any help. Here are my models models.py class Projects(models.Model): title = models.CharField(max_length=100, null=True, blank=True) image = models.FileField(upload_to='media/images', null=True, blank=True) video = models.FileField(upload_to='media/videos', null=True, blank=True) description = models.TextField(null=True, blank=True) client = models.CharField(max_length=300, null=True, blank=True) completed = models.BooleanField(default=True) def __str__ (self): return self.title class Meta: verbose_name_plural = 'Projects' ordering = ('-id',) class ProjectImages(models.Model): project = models.ForeignKey(Projects, on_delete=models.CASCADE) image = models.ImageField(upload_to='media/images', blank=True, null=True) def __str__ (self): return self.project.title forms.py more_project_images = forms.FileField(required=False, widget=forms.FileInput(attrs={ 'class':'form-control', 'multiple':True })) class Meta: model = Projects fields = '__all__' views.py form = ProjectsForm() if request.method == "POST": form = ProjectsForm(request.POST, request.FILES) files = request.FILES.getlist('more_project_images') if form.is_valid(): project = form.save() for f in files: project_image = ProjectImages(project=project, image=f) project_image.save() projectdetails.html {% for project in project.projectimages_set.all %} <div class="col-md-3 p-2"> <img src="{{project.image.url}}" class="img-fluid" style="object-fit: contain;" alt=""> </div> -
Django REST framework unrecognized
I already have django rest framework installed in my project, as you see when I run pip freeze: However, when I try to import any module it does not recognize it, so it is not possible for me to go check the function or class or whatsoever I am importing. Who knows what the problem is? -
Send Event after Celery Signal call
I have a Django project and call a task named my_task and listen to different signals which are sent by the task. I am using django_eventstream inside my project to send to my eventstream. from django_eventstream import send_event when I listen for celery builtin signal after_task_publish the following way @after_task_publish.connect(sender='my_task') def task_sent_handler(sender=None, headers=None, body=None, **kwargs): print("task_sent") message = "task_sent" send_event("eventchannel", "my_event", message) the message is sent to my existing eventstream and is working as expected. print statement is printed into webserver console but when I listen to celery builtin signal task_success the following way @task_success.connect(sender=my_task) def task_success_handler(sender=None, result=None, **kwargs): print("task_success") message = "task_success" send_event("eventchannel", "my_event", message) send_event will not be sent to my eventstream print statement will print into celery worker console I am struggling to find the reason for that behavior. What is the difference between both signals or what is the difference between both functions which are triggered by the signals? Following Versions are used: Django=3.2.6 celery=5.1.2 redis=3.5.3 django-eventstream=4.2.0 -
UNIQUE constraint failed: post_author.href in django
I will create a different author table using the user table available in django and I want to combine this custom table I created with the column in the post model. Thus, I will have both the author table and the post table with the posts shared by these authors separately. And also, I will make the user models that I will create in the future with the ready user table. but I am getting the error I mentioned. How can I solve this, what are the alternative ways? from django.db import models from django.contrib.contenttypes.models import ContentType from django.db import models from django.urls import reverse from .utils import get_read_time from django.conf import settings from django.utils import timezone from markdown_deux import markdown from django.utils.text import slugify from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.utils.safestring import mark_safe class GENDER(models.TextChoices): Erkek = "Erkek" Kadın = "Kadın" Diğer = "Diğer" NONE = "Belirtmek İstemiyorum" class Category_Choices(models.TextChoices): BİLİNMEYENLER = '13İlinmeyenler' KİŞİSEL_GELİŞİM = 'Kişisel Gelişim' İLHAM_AL = 'İlham Al' YATIRIM_HABERLERİ = 'Yatırım Haberleri' GİRİŞİMCİLİK = 'Girişimcilik' ENGLİSH_NEWS = 'English News' BAŞARI_HİKAYELERİ = "Başarı Hikayeleri" class Color_Choices(models.TextChoices): INDIGO = 'indigo' green = 'green' yellow = 'yellow' RED = 'red' blue = 'blue' gray = 'gray' … -
Import "rest_framework" could not be resolved "django-rest-framework"
I have installed the Django framework but it always shows a yellow line under it as if the project is not defined Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_filters', 'rest_framework', 'rest_framework.authtoken', 'rest_framework.routers', 'hauptapp', ] views.py Zb Import "rest_framework" could not be resolved When i write pip freeze find Django==3.2.7 django-environ==0.7.0 django-filter==21.1 django-import-export==2.5.0 django-mssql-backend==2.8.1 django-mssql-backend-aad==0.2.1 django-pyodbc==1.1.3 django-rest-framework==0.1.0 djangorestframework==3.12.4 djangorestframework-csv==2.1.1 -
Django REST Framework - How to compare two given values?
at my Django API application, I have a serializer that should validate a given pin but I'm always running into: TypeError: string indices must be integers def validate_old_pin(self, value): user = self.context['request'].user if value['old_pin'] != user.pin: # <- Breakpoint raise serializers.ValidationError( ({'old_pin': _("Your old PIN was entered incorrectly. Please try again.")}) ) return value Why do I get this? What is the most effective way to simply check if the two pin field match? Thanks in advance. -
I would like to disable the clickable link only for an object in Django-admin
I would like to disable the clickable link in the django admin object so that the displayed link is only as plain text without <a href ... in HTML. The current code looks like this current situation in the code here is where I would like to disable the clickable link, which would be displayed as plain text e.g. in /csvinput/3c1927f2-9ef6-45b8-a9aa-0021ef64a46f/change/.(of course I would like to keep the functionality for uploading the csv file mean /csvinput/add/) display on page of instance object /csvinput/3c1927f2-9ef6-45b8-a9aa-0021ef64a46f/change/ Many thanks for every thought or idea. -
Django admin page if statements
I'm building a webpage to present sports results but on the admin page I want it, to when a certain sport is set, the points will change to be a certain number of points like this: sports = [ ('Voléi', 'Voleibol'), ('Fut', 'Futebol'), ] team_name = models.CharField(max_length=50, blank=False, null=False, default="") sport = models.CharField(max_length=20, blank=False, null=False, choices=sports) final_score = models.IntegerField(blank=False, default=0) game_date10 = models.DateField() game_description = models.TextField(blank=True, null=True) The Sport is a list of tuples to choose and when you choose, for example, voleibol the final_score field is supposed to change to 1 or 2 points and not infinite, can I do that? -
Cannot find pg_config executable
Having no idea what pg_config is, I searched online and it seems to be part of or connected to PostgreSQL. I don't have or use that though and never have but I suspect that I may be getting this because I recently started using azure libraries in Python (I never had this problem before). Here is one of the error messages: WARNING: Discarding https://files.pythonhosted.org/packages/aa/8a/7c80e7e44fb1b4277e89bd9ca509aefdd4dd1b2c547c6f293afe9f7ffd04/psycopg2-2.9.1.tar.gz#sha256=de5303a6f1d0a7a34b9d40e4d3bef684ccc44a49bbe3eb85e3c0bffb4a131b7c (from https://pypi.org/simple/psycopg2/) (requires-python:>=3.6). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Using cached psycopg2-2.9.tar.gz (379 kB) Preparing metadata (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'C:\Users\E\AppData\Local\Programs\Python\Python310\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\E\\AppData\\Local\\Temp\\pip-install-q50_w0n5\\psycopg2_b3e7f5e155154965bfc0d5340d85b1ff\\setup.py'"'"'; __file__='"'"'C:\\Users\\E\\AppData\\Local\\Temp\\pip-install-q50_w0n5\\psycopg2_b3e7f5e155154965bfc0d5340d85b1ff\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89' cwd: C:\Users\E\AppData\Local\Temp\pip-install-q50_w0n5\psycopg2_b3e7f5e155154965bfc0d5340d85b1ff\ Complete output (23 lines): running egg_info creating C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info writing C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\E\AppData\Local\Temp\pip-pip-egg-info-ufqtnd89\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with … -
Python class variable is None despite being set
I'm struggling with thread communication in Python. I'm clearly missing something, but I'm new to Python so I don't know very well what I'm doing. When the server gets a GET request, I want it to get two numbers (x and y coords) from a separate thread, which constantly updates those values and to return those numbers as a response. I have a simple Django project with the following structure: it is very basic, made according to tutorial. When the server starts, I start a thread that looks launches my coordinate generator in a separate thread: class GpsMockCoordsServiceConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'gps_mock_coords_service' def ready(self): if os.environ.get('RUN_MAIN', None) != 'true': _thread.start_new_thread(CoordsTracker.launch_recognition, ()) CoordsTracker class looks like so: coords = None class CoordsTracker: #coords = None #tried placin it here, but same effect - it is None when retreived from views.py logger = logging.getLogger("CoordsTrackerLogger") @staticmethod def draw_contours(mask, frame, color): ...... for stuff in stuffs: ...... CoordsTracker.set_coords((x, y)) ...... @staticmethod def launch_recognition(): ........ while True: ........ CoordsTracker.draw_contours(....) ........ @staticmethod def set_coords(new_coords): global coords CoordsTracker.logger.debug("setting coords " + str(new_coords)) coords = new_coords # here coords var is OK @staticmethod def get_coords(): CoordsTracker.logger.debug(coords) # Here it is OK if I call this method … -
In Django, what is the better way to pass arguments to a create view?
I need help with two questions. Number one: I have Orders model and generic create view for it and OrderDetails model with create view. After order is created the get_absolute_url method in Orders model redirects to a page with OrderDetails creation form. I want this OrderDetails create view to get arguments from order we just created such as order.pk, now I have to fill this field manually. So, is get_absolute_url method is what I need, or should I override dispatch method in my view, but may be I need to work on get_success_url method? Number two: when I go to Order creation page, how to automatically fill Employee field? E.g. I'm logged in system as Bob Smith and when I create new order I don't want to set myself there manually, I want system do it for me. Here's models: class OrderDetails(models.Model): order = models.OneToOneField('Orders', models.DO_NOTHING, primary_key=True) product = models.ForeignKey('products.Products', models.DO_NOTHING) unit_price = models.FloatField() quantity = models.SmallIntegerField() discount = models.FloatField() class Meta: managed = False db_table = 'order_details' unique_together = (('order', 'product'),) class Orders(models.Model): customer = models.ForeignKey('contractors.Customers', models.DO_NOTHING, blank=True, null=True) employee = models.ForeignKey('employees.Employees', models.DO_NOTHING, blank=True, null=True) order_date = models.DateField(blank=True, null=True) required_date = models.DateField(blank=True, null=True) shipped_date = models.DateField(blank=True, null=True) ship_via = … -
How To set edit / delete permissions for the creator only django
How To Give User Permission To Delete Or Edit It's Post @login_required(login_url="login") def editsell(request , pk): context= {} user = request.user if not user.is_authenticated: return redirect('login') sell_listing = get_object_or_404(listingsell , id=pk) if request.POST: form = UpdateSellForm(request.POST or None , request.FILES or None , instance = sell_listing) if form.is_valid(): obj = form.save(commit = False) editsell.user == user obj.save() context['success_message'] = "Updated" sell_listing = obj form = UpdateSellForm( initial = { "title" : sell_listing.title, "subtitle" : sell_listing.subtitle, "description" : sell_listing.description, "image" : sell_listing.image, "image2" : sell_listing.image2, "image3" : sell_listing.image3, "image" : sell_listing.image, "number_phone" : sell_listing.number_phone, "ville" : sell_listing.ville, } ) context['form'] = form return render(request , 'Swapdz/add_listing.html' , context) -
AttributeError: module 'speedtest' has no attribute 'Speedtest' test_get_server is not defined
!am trying to get the download and upload speed in python by using the "speedtest" module, but it gives me that error when I use the module: AttributeError: module 'speedtest' has no attribute 'Speedtest'. and I was only declaring the variable, that is my code : import speedtest test = speedtest.Speedtest() -
if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta'
A source Django 3 by examples Chapter 14 When I try to run python manage.py migrate --settings=educa.settings.pro Another files are copies and pastes from the book The result is File "C:\Python\educa\manage.py", line 22, in <module> main() File "C:\Python\educa\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 487, in add_field if field.many_to_many and field.remote_field.through._meta.auto_created: AttributeError: 'str' object has no attribute '_meta' Migration file: from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('account', '0005_contant'), ] operations = [ migrations.CreateModel( name='Contact', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=True, verbose_name='ID')), ('user_from', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rel_from_set', to=settings.AUTH_USER_MODEL)), … -
Is there any way to get the exact datatype of fields of csv file reading using pandas? [duplicate]
i have used dtypes of pandas to get the datatype of csv file, ``` with codecs.open(new_file_path_is, encoding="utf8") as csvfile: df = pd.read_csv(csvfile,nrows=100) print(df.dtypes) ``` Here the string fields are considered as object also the date field, I have appended field name and its datatype to a dictionary and the result is: {'First Name': 'object', 'Last Name': 'object', 'Date': 'object', 'Id': 'int64'} is there any method to get the exact datatype of fields?why its taken as object? -
How to get "HTTP_CF_IPCOUNTRY" with django python
I'm unable to get HTTP_CF_IPCOUNTRY from http meta data. I want to get country code. def register(request): country_code = request.META.get('HTTP_CF_IPCOUNTRY', 'N/A').strip() print("THIs is ",country_code) this prints --> N/A -
Django Please help me place a checkbox and a mail box with a send button on the html page
One of functionality in my training project: subscribe to the news by check-box and e-mail. Send newsletter daily. The user can unsubscribe from the mailing list in his profile by unchecking the checkbox. It so happened that first I set up a daily newsletter for users who have booleanfield = true. For it I marked the checkboxes in the admin panel. It works. Now it is necessary to add the checkbox and the mail field to the news page. I'm stuck on the simplest. Tired and confused. Please help me place a checkbox and a mail box with a send button on the news page models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) hr = models.BooleanField(default=False) subscribed_for_mailings = models.BooleanField(default=False) subscription_email = models.EmailField(default="") def __str__(self): return str(self.user) Forms.py class MailingForm(forms.ModelForm): class Meta: model = models.Profile fields = ('subscription_email', 'subscribed_for_mailings', ) widgets = { 'subscription_email': forms.EmailInput(attrs={"placeholder": "Your Email..."}), 'subscribed_for_mailings': forms.CheckboxInput, } views.py def all_news(request): today = date.today() today_news = models.TopNews.objects.filter(created__gte=today) return render(request, "news.html", {'today_news': today_news}) def mailing_news(request): if request.method == 'POST': mailing_form = forms.MailingForm(request.POST) if mailing_form.is_valid(): mailing_form.save() return HttpResponse('You will receive news by mail') else: mailing_form = forms.MailingForm() return render(request, "news.html", {'mailing_form': mailing_form}) urls.py ... path('news/', views.all_news, name='all_news'), ... news.html {% extends 'base.html' … -
Exe creation using pyinstaller for django rest app
I am trying to create an exe file using Pyinstaller for Django project having only REST api framework used. I am running manage.py runserver command by creating another file run.py and executing that file. run.py content: import os if name == 'main': os.system("python manage.py runserver 0.0.0.0:5000") I am trying to create exe file by giving command pyinstaller --onefile -w run.py manage.py (Giving two files by keeping in mind that it should analyze both the files but execute run.exe, I may be wrongly doing it) It is creating a run.exe file which is not giving any error or output. I tried --noreload option but still no error and no output at console while exe execution. I am running exe file as: run.exe --noreload (not giving runserver as it is already mentioned in run.py file) Could someone please help on how to create exe file in such scenario and as I am mentioning runserver inside another function? -
Django forms.PasswordInput() updated my application main password
On my Django app, I have a custom field rendered with the forms.PasswordInput() widget. This works as expected from a visual perspective. However, Chrome detects this as a password and then updates this field with the master password that a user might have set on his account on the app. Is there a way to get a forms.PasswordInput() field without Chrome messing passwords fields in it? -
How to put template into iframe?
The very similiar problem as mine I found here: Set URL to load iframe in a Django template but it doesn't help. Having a route in my urls.py written as (...) path('rejestracja/', views.rejestracja, name = 'rejestracja'),(...) where the view is to render page named rejestracja.html, I have to put the content of it into iframe. And I do it assigning src = "{% url 'rejestracja' %}". Unfortunatelly the iframe is showing me an error: "Page localhost is blocked" "Server localhost denied connection." ERR_BLOCKED_BY_RESPONSE The strange thing is, source of iframe shows me content of rejestracja.html. It means, I think, my code is ok, but somewhere I have any restrictions. But I have no idea which, how and where... Could someone tell me what is wrong, or at least, where to look for solution? -
Django creates a migration that seems already reflected in original postgresql schema
I've modified the foreign key calendar as nullable in my Django model CalendarAssign. \ # ---------------------------------------------------------------------------- # class Calendars(models.Model): id = models.CharField(primary_key=True, max_length=100) cms_id = models.CharField(max_length=100) default_program = models.ForeignKey(ControlPrograms, models.CASCADE, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = 'calendars' # ---------------------------------------------------------------------------- # class CalendarAssign(models.Model): device_mac = models.ForeignKey(Device, models.CASCADE) calendar = models.ForeignKey(Calendars, models.CASCADE, null=True) timestamp = models.DateTimeField(auto_now_add=True) class Meta: managed = True db_table = 'calendar_assign' When applying the migration generated by Django it gives me an error. operations = [ migrations.AlterField( model_name='calendarassign', name='calendar', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='smartbridge.Calendars'), ) Generated sql code uses unsupported feature 'WITH ORDINALITY'. It's because Django doesn't support the Postrges version we are using. WITH ORDINALITY appears in psql 9.4 but we use version 9.1. Both Postgres and Django cannot be upgraded right now. So I need to write the migration manually (without 'WITH ORDINALITY' feature). migrations.RunSQL("DO $$DECLARE r record;\ BEGIN\ FOR r IN SELECT table_name,constraint_name \ FROM information_schema.constraint_table_usage \ WHERE table_name IN ('calendars') AND constraint_name like '%calendar_assign_calendar_id%'\ LOOP\ EXECUTE 'ALTER TABLE calendar_assign DROP CONSTRAINT '|| quote_ident(r.constraint_name) || ';';\ END LOOP;\ ALTER TABLE calendar_assign ALTER COLUMN calendar_id DROP NOT NULL; \ ALTER TABLE calendar_assign \ ADD CONSTRAINT calendar_assign_calendar_id_fk_calendars_id FOREIGN KEY (calendar_id) REFERENCES calendars(id);\ END$$;") Migration … -
Making any changes to inline css of the HTML file inside DJANGO project is not woking
I have to make changes in my code that if approverFlag is "Approved" then display the record as green and if the approverFlag is "Not Approved" then display the record as red. Folllowing are the changes I have made in my HTML file:- {% if awp.approveFlag == "Approved" %} <td style = "color:green;" id=displayrecord >{{ awp.approveFlag }} </td> {% elif awp.approveFlag == "Not Approved"%} <td style = "color:red;" id=displayrecord >{{ awp.approveFlag}} </td> {% endif %} But it is not working. I have also tried writing class here as follows:- <td class = "approved" id=displayrecord >{{ awp.approveFlag }} </td> And then making changes in tag of the HTML file:- <style> .approved{ color:red; } </style> But nothing is working. Can anyone suggest any solution to make it work? -
Invalid block tag on line 7: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I am beginner in html-templates and Django. author_list.html {% extends "base_generic.html" %} {% block content %} <h1>All authors</h1> <ul> {% for author in author_list %} <li><a href="">{{ author.last_name }}:</a> {% for book in author.book_set.all %} {{ book.title }} {% if not forloop.last %}, {% endif %}{% endfor %}</li> {% endfor %} </ul> {% endblock %} Error: Invalid block tag on line 7: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? I have the block of code. It works without block if, but doesn't work with the conditional. How to fix it. Help! I should paste "," after each name of book. -
Can I change the django rate limiter timeout?
I'm building an API in Python and Django and have encountered the rate limits set by django. Now, I've adjusted the rate limits for users and anons accordingly but I was wondering if there was a way to change or reduce the time in the following error response. { "detail": "Request was throttled. Expected available in 7735 seconds." } Specifically I would like to reduce the 7735 seconds. Also, if I'm not mistaken, the timer counts down from 86400 seconds i.e. 1 day ? -
Better way of hiding entries not created by current user in Django?
Im pretty new to Django, and right now I have created a site that lets users register/login, make entries that are associated to that user via a "user" field in the entries database. Iv'e managed to get all the functionality of hiding other users entries by adding get_queryset() methods that only return the current users entries. But I feel like this is a bad way of doing this. I feel like im reusing a lot of code and that there could be backdoors to display other users entries. Is there a way to completely disable other users entries from the current user, not just not display it? views.py class EntryListView(LockedView, ListView): model = Entry def get_queryset(self): return super().get_queryset().filter(user=self.request.user).order_by("-date_created") class EntryDetailView(LockedView, DetailView): model = Entry def get_queryset(self): return super().get_queryset().filter(user=self.request.user) class EntryCreateView(LockedView, SuccessMessageMixin, CreateView): model = Entry fields = ["title", "content"] success_url = reverse_lazy("entry-list") success_message = "Your new entry was created!" def form_valid(self, form): user = self.request.user form.instance.user = user return super(EntryCreateView, self).form_valid(form) def get_queryset(self): return super().get_queryset().filter(user=self.request.user) class EntryUpdateView(LockedView, SuccessMessageMixin, UpdateView): model = Entry fields = ["title", "content"] success_message = "Your entry was updated!" def get_success_url(self): return reverse_lazy( "entry-detail", kwargs={"pk": self.object.pk} ) def get_queryset(self): return super().get_queryset().filter(user=self.request.user)