Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Django test throwing an error complaining about a column size that is incorrect when I try to run tests?
I have an old project that I'm resurrecting that was built with Python 2. I'm getting it going with a more current version of Python and Django (v3.9 and v4.1.2 respectively). I have the app basically up and running and I just tried to get the automated testing going. But I'm getting this error: django.db.utils.OperationalError: (1074, "Column length too big for column 'body' (max = 16383); use BLOB or TEXT instead") Unfortunately, I have the 'body' column in multiple objects in my models.py, AND each of them is defined as a TextField (e.g. body = models.TextField()). I'm not sure how to post the offending code since the error doesn't specify the exact object. My test is simple as I'm just trying to get testing going: from django.test import TestCase class Test_Countries(TestCase): def setUp(self): pass def test_basicCompare(self): self.assertEqual(1, 1) Before running the test (python manage.py test IFSServices/tests), I've ensured that makemigrations and migrate have succeeded. Any help that anybody could provide to help (incl how to ask a more useful question) would be greatly appreciated. -
django filter: How to filter results with multiple values
I am working on Django and I need to filter records eg: table: Person name age David Abraham Benj 18 so, if I run this, Person.objects.filter(name__icontains="David Abraham") it is working but if I run this, Person.objects.filter(name__icontains="David Benj") it is not working any idea how it works? framework: Django and SQL: Postgres -
Django huey file not processing all tasks
This is very strange. I don't want to setup a Redis service and since my queue has only very little requirements file or sqlite would work just fine. The both work fine on localhost, but when I deploy it to a docker container there are the following issues: SQLite compains that there is an I/O error. The path is set to /tmp, which has read/write permissions. I read that there are issues with CIFS filesystem, not sure if this is the case. Fact it, it doesn't work. Filesystem queue. Tasks are created in the folder, the consumer is starting to process them, but then just stops. Consumer is still running, but not processing any files anymore. Any advice on where to start looking would be appreciated. -
DJango-How to merge two variables together and send them as an argument to the url?
url: 127.0.0.1:8000/name/ url has one parametr, name but name is first_name + last_name in template we resive first_name and last_name How to merge two variables (first_name and last_name) together and send them as an argument (name) to the url??? -
Annotate results from related model method onto model Queryset?
I'm trying to figure out the best / most efficient way to get the 'progress' of a Summary object. A Summary object has X Grade objects - a Grade object is_complete when it has a Level chosen and has 1 or more related Evidence objects. I am trying to tie that Summary 'progress' to a Person. The models.py look like this: class Summary(models.Model): id = models.BigAutoField(primary_key=True) person = models.ForeignKey( Person, on_delete=models.PROTECT, related_name="summaries" ) finalized = models.BooleanField(default=False) class Meta: verbose_name = "Summary" verbose_name_plural = "Summaries" def progress(self): """Return the progress of the summary.""" grades = self.grades.all() finished_grades = ( Grade.complete.all().filter(summary=self).count() ) try: progress = (finished_grades / grades.count()) * 100 class Grade(models.Model): id = models.BigAutoField(primary_key=True) summary = models.ForeignKey( Summary, on_delete=models.PROTECT, related_name="%(class)ss" ) level = models.ForeignKey( Level, on_delete=models.PROTECT, null=True, blank=True, related_name="%(class)ss", ) class Meta: verbose_name = "Grade" verbose_name_plural = "Grades" @property def is_complete(self): if 0 < self.evidences.count() and self.level: return True return False class Evidence(models.Model): id = models.BigAutoField(primary_key=True) grade = models.ForeignKey( Grade, on_delete=models.PROTECT, related_name="%(class)ss" ) comment = models.TextField() My views.py looks like this: class PersonListView(ListView): model = Person template_name = "app/person_list.html" context_object_name = "person_list" def get_queryset(self): people = Person.objects.all().prefetch_related("summaries", "summaries__grades", "summaries__grades__evidences") # There should only be one non-finalized summary # or there will … -
Django back end not sending response message back to React front end
I am currently working on a e-commerce project using django and react. I finished building my create order route and it is working fine in terms of adding the order and orderItem to the database. (I am checking from the admin panel). However the issue is that for some reason I am not able to see the response on the front end even though I am returning it. This is my react component making the reuest PlaceOrder.jsx const handleCreateOrder = async () => { let body = {}; body.user = userContextEmail; body.totalPrice = totalPrice; body.shippingAddress = shippingAddressString; const items = {}; for (let i = 0; i < cart.length; i++) { let itemId = cart[i].id; let itemQuantity = cart[i].quantity; items[itemId] = itemQuantity; body.items = items; } let response = await fetch("http://127.0.0.1:8000/base/orders/create", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(body), }); let result = await response.json(); console.log(result.data); // NOTHING BEING DISPLAYED ON MY CONSOLE }; urls.py path('orders/create', order_views.createOrder) order_views.py @api_view(['POST']) def createOrder(request): data = request.data # print(data) profile = Profile.objects.get(username=data['user']) totalPrice = data['totalPrice'] shippingAddress = data['shippingAddress'] try: order = Order.objects.create( profile = profile, totalPrice = totalPrice, shippingAddress = shippingAddress ) except: message = {'detail': 'An error has occured during … -
show or know LDAP attributes in django
I have a project in django where i try to connect with ldap server. All seems works well, because when i login in django, the user is added to the django database. The problem is that I made a custom user with the department field in django and I want to get a concret attribute from ldap and assign with the field department, but when I login i see in django logs this line: search_s ('ou=xxx,o=xxx, 2 '(uid=%user)s)') returned 1 objects cn=usern_name,ou=xxx,o=xxx Creating Django user user_name Populating Django user user_name cn=user_name,ou=xxx,o=xxx does not have a value for the attribute aaeAppAdd Then I see in department field in Django user database that is empty. How I can see or get the user_object attributes (print, etc) that the LDAP offer when i login correct? These are my config files. settings.py # Config to authenticate with LDAP import ldap from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion, GroupOfNamesType AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) basedn = "ou=xxx,o=xxx" AUTH_LDAP_SERVER_URI = 'ldap://ldapserver:389' AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch(basedn, ldap.SCOPE_SUBTREE, "(uid=%(user)s)") AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "department": "aaeAppAdd" } AUTH_LDAP_ALWAYS_UPDATE_USER = True LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": {"console": {"class": … -
how to apply template for django ModelViewset class
hello i am stuck and i can't apply my html to this class please help class ProductViewSet(ModelViewSet): queryset = Product.objects.prefetch_related('images').all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter pagination_class = DefaultPagination permission_classes = [IsAdminOrReadOnly] search_fields = ['title', 'description'] ordering_fields = ['unit_price', 'last_update'] -
django.db.migrations.exceptions.MigrationSchemaMissing error Connecting Postgres to Django?
This is my first time that i am using other database than sqlite3 with django ,so i go ahead with postgres ,install it on my machine and created the user and db but after config the setting.py when i migrate i got this error # database config DB_NAME = 'django_chat_db' DB_USER = "django" DB_PASSWORD = "password" DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': DB_NAME, 'USER': DB_USER, 'PASSWORD': DB_PASSWORD, 'HOST': 'localhost', 'PORT': '5432', } } ERRORs Traceback (most recent call last): File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 87, in _execute return self.cursor.execute(sql) psycopg2.errors.InsufficientPrivilege: permission denied for schema public LINE 1: CREATE TABLE "django_migrations" ("id" bigint NOT NULL PRIMA... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\migrations\recorder.py", line 70, in ensure_schema editor.create_model(self.Migration) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\base\schema.py", line 447, in create_model self.execute(sql, params or None) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\base\schema.py", line 199, in execute cursor.execute(sql, params) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 103, in execute return super().execute(sql, params) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers( File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\rakib\OneDrive\Desktop\Real Time Messenger\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File … -
It is impossible to add a non-nullable field Error when extending Abstract User
I want to extend the Base Abstract User Model and this is the extended model: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=25) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = models.CharField(max_length=20) province = models.CharField(max_length=20) code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))]) address = str(street) + str(street_number) + str(city) + str(code) + str(province) But I get this message popup: It is impossible to add a non-nullable field 'password' to student without specifying a default. This is because the database needs something to populate existing rows. However I haven't added a new password field and all the existing password fields (for the superuser) already have a value. What should I do? When I add a default value and try to migrate it, it complains that there is no such table as 'mainApp_student'. -
Is there any way to overwrite the default operation id , tag, name ,description of generated drf api schema?
Is there any way to overwrite the default operationid,name,tag,type,summary, description of generated drf api schema? -
Learning Better Way of Doing It (Django Models)
I am doing Django and I have 4 models. District, Province, Schools and User. The District belongs to a Province, in the School model/table there are the foreign keys to which the school belong. In the User table, I have district, province and school foreign keys. these tuples were named province or district in the tables they are FKs. The error I was getting was a conflict and needed to add a related_name. I need someone to explain to me the value for related_name. From my reading, it is showing the table name, If the FK is in the Comments model then the related_name='comments'. In my case I have three FK in the User model so how do I manage this? I hope this tries to explain my query. -
Django python manage.py runserver TypeError: 'dict' object is not callable
''' Environment: Request Method: GET Request URL: http://127.0.0.1:8000/league/ Django Version: 4.1.2 Python Version: 3.10.0 Installed Applications: Traceback (most recent call last): File "/Users/km/Projects/tournament/Worldchamps/champ_env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) Exception Type: TypeError at /league/ Exception Value: 'dict' object is not callable ''' -
Specifying the display of a django DateField from the model, and not form/input/settings?
I have a Django model with a DateField, like so: production_date = models.DateField(null=True, blank=True) I am trying to have that field display as the default Python date format in templates, which looks like "2000-01-01". But in a Django template it displays as "Jan. 1, 2000." In a Python shell, the date displays properly: In [4]: resource.production_date Out[4]: datetime.date(2014, 4, 20) In [5]: str(resource.production_date) Out[5]: '2014-04-20' But in the template, when I call production_date, I get the other format. I have many templates that use this value, and many ways the data gets added to the database. So I do not want to go to each template and change the display. I do not want to change the input form because that is not the only way data gets added. I do not want to change my site settings. I just want the field to display the default Python value. How do I accomplish this? Thank you! -
Error: no such table when extending Abstract User Model
I wanted to extend the Base Abstract User Model within Django to have some other Fields: class Student(AbstractUser): birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=20) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = models.CharField(max_length=20) province = models.CharField(max_length=20) code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))]) address = str(street) + str(street_number) + str(city) + str(code) + str(province) def __str__(self): return f'Adresse: {self.address}' I added this into my settings.py file: AUTH_USER_MODEL = 'mainApp.Student' But I get an Error saying there is no such table "Student" when trying to load /admin/. I have made all the migrations using: python manage.py makemigrations mainApp python manage.py migrate mainApp Error: OperationalError at /admin/ no such table: mainApp_student If y'all need any more infos, please comment! -
How to use HTMX to send url to HTML audio element
This is what I've come up with so far. Where am I going wrong? <button hx-put="/link/to/file.mp3" hx-target="audio"> LOAD TRACK 1 </button> <audio controls> <source src="audio" type="audio/mpeg"> Your browser does not support the audio element. </audio> -
python Django get exact table filed value from JWT token
I'm coding a Django project with JWT token. 'email' is a field from user table. I want to get the exact user email by using: usereamil = request.user.email When I print it ,I got none. But if I use: username = request.user.username I can get a wired user name ,not exact one in the data base ,which I think it is a security way to protect the data. But I do want to get the exact email address of user ,so that can send email to the user. Any friend can help ? -
How can I pass in href a field of my model to put it after in the modal id
Im trying to do a dinamic list to create all the references that I already have saved. <div class="row"> <div class="col-2"> <div class="list-group" id="list-tab" role="tablist"> {% for reference in reference_list %} <a class="list-group-item list-group-item-action" id="list-home-list" data-bs-toggle="list" href={{reference.brand_manufacturer}} role="tab" aria-controls="list-home">{{reference.brand_manufacturer}}</a> {% endfor %} </div> </div> <div class="col-8"> {% for reference in reference_list %} <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show" id="{{reference.brand_manufacturer}}" role="tabpanel" aria-labelledby="list-home-list">{{reference.website_url}}</div> {% endfor %} </div> </div> </div> -
How to create a dropdown of foreign keys in a template?
Without crispy forms I can create a form as follows <form method="POST"> {% csrf_token %} <input type="text" id="name" name="name" value="{{ project.name }}"/> </div> However I do not know how to create a dropdown of foreign keys. I cannot use cripsy forms because I want to seperate the fields by headings. What is the correct methodology? -
python3.9 doesn't recognize Walrus operator :=
I created a virtual environment in python3.9. Then I installed django 4.0 framework by pip command. It's ok but surprise it seems python 3.9 doesn't recognize operator :=. This operator is been introduced in python 3.8. Why I get this error from django framework? I can't modify all files for using a normal syntax! These files are many. nicola@giustizia:/etc/apache2/sites-available$ sudo tail -f /var/log/apache2/myproj-error.log [Fri Oct 21 16:18:48.196449 2022] [wsgi:error] [pid 17067] File "/home/nicola/webgiustizia/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 12, in <module> [Fri Oct 21 16:18:48.196452 2022] [wsgi:error] [pid 17067] from django import forms [Fri Oct 21 16:18:48.196457 2022] [wsgi:error] [pid 17067] File "/home/nicola/webgiustizia/lib/python3.9/site-packages/django/forms/__init__.py", line 7, in <module> [Fri Oct 21 16:18:48.196461 2022] [wsgi:error] [pid 17067] from django.forms.fields import * # NOQA [Fri Oct 21 16:18:48.196475 2022] [wsgi:error] [pid 17067] File "/home/nicola/webgiustizia/lib/python3.9/site-packages/django/forms/fields.py", line 43, in <module> [Fri Oct 21 16:18:48.196479 2022] [wsgi:error] [pid 17067] from django.utils.dateparse import parse_datetime, parse_duration [Fri Oct 21 16:18:48.196494 2022] [wsgi:error] [pid 17067] File "/home/nicola/webgiustizia/lib/python3.9/site-packages/django/utils/dateparse.py", line 118 [Fri Oct 21 16:18:48.196501 2022] [wsgi:error] [pid 17067] if match := datetime_re.match(value): [Fri Oct 21 16:18:48.196519 2022] [wsgi:error] [pid 17067] ^ [Fri Oct 21 16:18:48.196544 2022] [wsgi:error] [pid 17067] SyntaxError: invalid syntax -
django.utils.datastructures.MultiValueDictKeyError: 'q'
When I try to filter content with tags I get the following error 2022-10-21 16:05:47,853: Internal Server Error: /tag/tag1/ Traceback (most recent call last): File "/home/app/.virtualenvs/venv/lib/python3.10/site-packages/django/utils/datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'q' **NO MATCH** During handling of the above exception, another exception occurred: **NO MATCH** Traceback (most recent call last): File "/home/app/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/app/.virtualenvs/venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/app/app/blog/views.py", line 28, in home q= request.GET['q'] File "/home/app/.virtualenvs/venv/lib/python3.10/site-packages/django/utils/datastructures.py", line 86, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'q' My views.py is def home(request, tag_slug=None): posts = Post.objects.all() # tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) #search q= request.GET['q'] if q is not None: multiple_q=Q(Q(title__icontains=q) | Q(content__icontains=q)) posts=Post.objects.filter(multiple_q) return render(request, 'blog/home.html', {'posts':posts}) my urls.py has this URLpatterns ... path('tag/<slug:tag_slug>/',views.home, name='post_tag'), The search system works as I intend to but for some reason this is affecting my tag filter. Do you have any idea how to solve this error? -
Redirecting my Login page to a new page and if user is remembered and already logged in show this new page
Setting.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' LOGIN_REDIRECT_URL = '/home1' LOGIN_URL = 'login' views.py def home(request): return render(request, 'users/home.html') class RegisterView(View): form_class = RegisterForm initial = {'key': 'value'} template_name = 'users/register.html' def dispatch(self, request, *args, **kwargs): # Redireccion a Home si ya esta logged if request.user.is_authenticated: return redirect(to='/users/home1') return super(RegisterView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}') return redirect(to='login') return render(request, self.template_name, {'form': form}) class CustomLoginView(LoginView): form_class = LoginForm def form_valid(self, form): remember_me = form.cleaned_data.get('remember_me') if not remember_me: # Expira 0seg self.request.session.set_expiry(0) # Cookies self.request.session.modified = True # Hasta que los cookies expriran return super(CustomLoginView, self).form_valid(form) urls.py urlpatterns = [ re_path('admin/', admin.site.urls), re_path('', include('users.urls')), re_path('login/', CustomLoginView.as_view(redirect_authenticated_user=True, template_name='users/login.html', authentication_form=LoginForm), name='login'), re_path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), re_path('password-reset/', ResetPasswordView.as_view(), name='password_reset'), re_path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), re_path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'), path('password-change/', ChangePasswordView.as_view(), name='password_change'), re_path(r'^oauth/', include('social_django.urls', namespace='social')), re_path('home1/', auth_views.LoginView.as_view(redirect_authenticated_user=True, template_name='users/home1.html'), name='home1'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) My templates Got 12 templates, home, home1, base, login, logout, register, profile, password reset, etc I continue to get a too many redirects error, or when I try and change the redirection with … -
Django Migration timed out
I have a logging table,which is being continuously written to,in which i want to add a column,it's migration works fine on local but it's getting timed out on deployment This is the migration file a have: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("request_log", "0004_requestlog2"), ] operations = [ migrations.AddField( model_name="requestlog2", name="request_type", field=models.PositiveSmallIntegerField( blank=True, choices=[(0, "Incoming"), (1, "Outgoing"), (2, "Internal")], help_text="State the type on request", null=True, ), ), ] This is the migration logs: Rendering model states... DONE Applying request_log.0005_requestlog2_request_type...django 21/Oct/2022:15:12:54,194347 +0000 [INFO] squadrun.sentry_helpers: thread=140715699507328 extra: exchash: b8ca65d21d0d448f8fe90658c0708923 detected Traceback (most recent call last): File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/elasticapm/instrumentation/packages/dbapi2.py", line 210, in execute return self._trace_sql(self.__wrapped__.execute, sql, params) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/elasticapm/instrumentation/packages/dbapi2.py", line 244, in _trace_sql result = method(sql, params) psycopg2.extensions.QueryCanceledError: canceling statement due to statement timeout The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 40, in <module> execute_from_command_line(sys.argv) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/storage/.pyenv/versions/3.5.9/envs/squadrun_python3.5/lib/python3.5/site-packages/django/db/migrations/executor.py", … -
Why isn't "SELECT" query run in Django?
I have person table as shown below: # "store/models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=30) And, I have test view with print(Person.objects.all()) as shown below: # "store/views.py" from django.http import HttpResponse from .models import Person def test(request): print(Person.objects.all()) # Here return HttpResponse("Test") Then, when I run test view, SELECT query is run as shown below: Now, I replace print(Person.objects.all()) with Person.objects.all() as shown below: # "store/views.py" from django.http import HttpResponse from .models import Person def test(request): Person.objects.all() # Here return HttpResponse("Test") Or, I replace print(Person.objects.all()) with persons = Person.objects.all() as shown below: # "store/views.py" from django.http import HttpResponse from .models import Person def test(request): persons = Person.objects.all() # Here return HttpResponse("Test") Then, when I run test view, SELECT query isn't run as shown below: So, why isn't SELECT query run in Django? -
Django queryset filter based on slug
I want to put a filter on a page which shows videos selecting an album shows up on album page not all the videos but my current filter is showing all the published videos. I couldn't find a way to put a filter based on slug that if an album's slug is matching with the current url then shows the video selecting that album. I am all confused help me. models.py from django.db import models from django.urls import reverse STATUS = ( (1, "Publish"), (0, "Draft") ) class WatchCategory(models.Model): title = models.CharField(max_length=20) slug = models.SlugField(max_length=2000, unique=True) def __str__(self): return self.title class Genre(models.Model): title = models.CharField(max_length=20) slug = models.SlugField(max_length=2000, unique=True) def __str__(self): return self.title class Album(models.Model): title = models.CharField(max_length=2000) slug = models.SlugField(max_length=2000, unique=True) image = models.CharField(max_length=2000, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('Watch:album', kwargs={ 'slug': self.slug }) class Video(models.Model): title = models.CharField(max_length=2000) slug = models.SlugField(max_length=2000, unique=True) thumbnail = models.CharField(max_length=2000, unique=True) updated_on = models.DateTimeField(auto_now=True) file = models.CharField(max_length=2000) time = models.CharField(max_length=2000, blank=True) about = models.TextField(blank=True) category = models.ManyToManyField(WatchCategory) album = models.ManyToManyField(Album) genre = models.ManyToManyField(Genre) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=1) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_absolute_url(self): return reverse('Watch:video', kwargs={ 'slug': self.slug }) views.py class Album(ListView): …