Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django File Upload Button working but files storing in Project File(VSCode)
I'm trying to make a file upload system in django. My file upload button is working but files storing in project file. Also, i'm using MongoDB and my uploaded files displaying there too. Is this a database issue or is there something wrong about the views.py, models.py? So this is my code, view.py def link1(request): if request.method == "POST": uf=UploadFileForm(request.POST,request.FILES) if uf.is_valid(): uf = FileUpload(file = request.FILES['file']) uf.user = request.user uf.save() else: uf=UploadFileForm() return render (request,'blog/links/Link1.html',{'uf': uf}) models.py from djongo import models from django.contrib.auth.models import User class FileUpload(models.Model): file = models.FileField() user = models.ForeignKey(User, on_delete = models.CASCADE) forms.py from django import forms from .models import FileUpload class UploadFileForm(forms.ModelForm): class Meta: model= FileUpload fields = ['file'] -
Django ListView works but DetailView not displaying Model Data
I am helping my daughter with her computing Project for school. It is a simple generic forum type application. She has a ListView for a model which works fine: {% extends 'users/main.html' %} <!-- Here is where our content will begin --> {% block content %} <h1>This is posts.html!</h1> <br/> {% for obj in object_list %} <h2>{{ obj.topic }}</h2> {{ obj.date_posted }} <br/> {{ obj.content }} <br/> Author: {{ obj.author }} <br/><br/> {% endfor %} {% endblock %} She then added a DetailView which is simply the same code with the loop removed: {% extends 'users/main.html' %} <!-- Here is where our content will begin --> {% block content %} <h1>This is posts.html!</h1> <br/> {{ obj.id }} <h2>{{ obj.topic }}</h2> {{ obj.date_posted }} <br/> {{ obj.content }} <br/> Author: {{ obj.author }} <br/><br/> {% endblock %} This is then called with a '....post/1/' (post id = 1 does exist (checked via DB Browser and in the ListView) and the path and naming of the template is correct. Frustratingly, this displays the page but not the details inside the django temp language brackets (object.topic etc)! When I look at the page source for the section dealing with the detail, I get: … -
django orm filter and exclude by related date field
models.py class Model(models.Model): ... class RelatedModel(models.Model): date = models.DateField() I want to filter objects realted by a DateField by month and year. first I do Model.objects.all() and I see 3 instances second I filter like this: Model.objects.filter(related_model__date__month=6, related_model__date__year=2021) the result is just 1 instance out of 3 third and last, I filter like this Model.objects.exclude(related_model__date__month=6, related_model__date__year=2021) and the result is empty, I was so sure that the result will be the opposite to the second query, like 2 out of 3 instances. any explanation? thanks. -
Django admin inline change fields on new record
Background I'm customizing the admin pages for an inventory system with a lot of ManyToMany relationships and other complex data. I want to display these relationships using Inlines, but I don't like the default drop-down field that Django uses for ManyToMany relationships in an Inline so I customized the field set. My custom fields are relatively simple, an ID field that links to the related record, readonly text fields with data from the related record since the Inline can't get fields from the related record by default; that sort of thing. Problem The issue is that in order to use custom fields in these inlines, I've had to make them all read-only. Normally that's fine, because of the linked ID field, but it's impossible to add a new record via the button on the Inline because I can't enter any of the necessary information. My IDs aren't even auto-incremented since this data needs to sync up with another Database, so the new row doesn't link to a newly created record. Basically, what I want to do is have a different set of writable fields on newly added rows so that required fields, like the ID, can be filled. Issues I've … -
Erro 500 / in handle / in handle_request / required 'SEND' - Django ASGI + Gunicorn + Nginx
I have a serious problem that made me lose a couple of hours and nothing solves. Below the installed modules: Package Version ---------------------------- --------- asgiref 3.3.4 attrs 20.3.0 autobahn 21.3.1 Automat 20.2.0 certifi 2020.12.5 cffi 1.14.5 channels 3.0.3 chardet 4.0.0 constantly 15.1.0 cryptography 3.4.7 daphne 3.0.2 Django 3.1.7 django-appconf 1.0.4 django-bootstrap-modal-forms 2.1.0 django-compressor 2.4 django-crispy-forms 1.11.2 django-drf-filepond 0.3.0 django-extensions 3.1.2 django-filter 2.4.0 django-mathfilters 1.0.0 django-model-utils 4.1.1 django-pandas 0.6.4 django-redis 4.12.1 django-stdimage 5.3.0 django-storages 1.11.1 django-widget-tweaks 1.4.8 djangorestframework 3.12.4 geographiclib 1.50 geopy 2.1.0 gunicorn 20.1.0 hyperlink 21.0.0 idna 2.10 importlib-metadata 3.10.1 incremental 21.3.0 Markdown 3.3.4 numpy 1.20.2 pandas 1.2.4 Pillow 8.2.0 pip 21.0.1 psycopg2 2.8.6 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycparser 2.20 PyHamcrest 2.0.2 pyOpenSSL 20.0.1 python-dateutil 2.8.1 pytz 2021.1 rcssmin 1.0.6 redis 3.5.3 requests 2.25.1 rjsmin 1.1.0 service-identity 18.1.0 setuptools 54.1.2 shortuuid 1.0.1 six 1.15.0 sqlparse 0.4.1 Twisted 21.2.0 txaio 21.2.1 typing-extensions 3.7.4.3 urllib3 1.26.4 uvloop 0.15.2 wheel 0.36.2 zipp 3.4.1 zope.interface 5.4.0 When running the server on 'python3 manage.py runserver' or 'python3 manage.py runserver 0.0.0.0:8000', everything is perfect! However, when running the system with gunicorn + nginx, I have the following error output: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2021-04-15 … -
Problem in the integration of django and react
I have a problem integrating my template with django. I have set up the webpack w and babel correctly and I ran the run dev webpack but I don't get any result in the server. [enter image description here][1] Index.html ``` Diet {% load static %} <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}" /> <script src="{% static "frontend/main.js" %}"></script> </body> </html>``` this is my index.js ``` import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { BrowserRouter } from 'react-router-dom'; import reportWebVitals from './reportWebVitals'; // Css import '../node_modules/animate.css/animate.css'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import '../node_modules/slick-carousel/slick/slick.css'; import '../node_modules/slick-carousel/slick/slick-theme.css'; import '../node_modules/magnific-popup/dist/magnific-popup.css'; import '../node_modules/react-select2-wrapper/css/select2.css'; import '../node_modules/leaflet/dist/leaflet.css'; import './assets/fonts/flaticon/flaticon.css'; import './assets/fonts/font-awesome/css/all.min.css'; import './assets/css/style.css'; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById('app') );``` [1]: https://i.stack.imgur.com/UDFik.png -
django.db.utils.DatabaseError with Django and Djongo
I keep running into the django.db.utils.DatabaseError error with trying to migrate the database changes in a Django project. Terminal Output: Running migrations: Not implemented alter command for SQL ALTER TABLE "project_name_user" ALTER COLUMN "age" TYPE double Applying project_name.0002_auto_20210415_1452...Traceback (most recent call last): File "...\.venv\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 783, in __init__ self._query = self.parse() File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 875, in parse raise e File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 856, in parse return handler(self, statement) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 888, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 425, in __init__ super().__init__(*args) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 84, in __init__ super().__init__(*args) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse self._alter(statement) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "project_name_user" ALTER COLUMN "age" TYPE double',) Params: ([],) Version: 1.3.4 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "...\.venv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "...\.venv\lib\site-packages\djongo\cursor.py", line 59, in execute raise db_exe from e djongo.database.DatabaseError The above exception was the direct cause of the following exception: Traceback (most recent call … -
Django user uploadind files without forms, button doesn't work
I'm trying to make a file upload page in my web site but I want to make this page without forms. I wrote my models.py and views.py files. When I click on "Choose File" button it doesn't gives error but it doesn't work either. So, I'm this is my codes, views.py def link1(request): if request.method == "POST": if request.POST.get('submit') == 'Upload': file_info = request.POST, request.FILES['file_info'] if not file_info.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') return redirect('/mainpage') file_info = FileUpload(file = request.FILES['file_info']) file_info.user = request.user file_info.save() return render (request,'blog/links/Link1.html') models.py from djongo import models from django.contrib.auth.models import User class FileUpload(models.Model): file = models.FileField() user = models.ForeignKey(User, on_delete = models.CASCADE) -
UnboundLocalError when submitting form in Django App
I am trying to submit a form but receiving an error: UnboundLocalError at /create/ local variable 'spr' referenced before assignment Below is the section of my views.py file that is highlighted in the error, specifically: return HttpResponseRedirect("/%i" %spr.id) def create(response): if response.method == "POST": form = CreateNewSprint(response.POST) if form.is_valid(): n = form.cleaned_data["name"] spr = Sprint(name=n) spr.save() response.user.sprint.add(spr) return HttpResponseRedirect("/%i" %spr.id) else: form = CreateNewSprint() return render(response, "main/create.html", {"form": form}) I am unsure of why this is happening, any pointers in the right direction would be greatly appreciated. If any other code/information is needed please let me know. -
Reduce Intial Server Response Time On Django Nginx
I have deployed a django 3.1 peoject on nginx 1.18 and gunicorn. I'm trying reduce website server response time (TTFB). The trouble i'm facing right now is that the webpage first renders all the data then display the webpage. Please refer the screenshot. Image 1 Image 2 -
Django, i can't put function form inside generic.UpdateView
I am making a app for one kindergarten in my city. I have kids model and payment model. For updating kid I am using class based view generic UpdateView and for creating a payment i am using form and function view. I have not problems with payment form when I am using a different template but when I try to put it on the same template, payment form is not showing up and it's not working. Is it possible to have payment form on same template as UpdateView class ? I am using UpdateView class as profile page and I would like to have payment form on the same page. Please help. Thanks models: class Kids(models.Model): name = models.CharField(max_length=100, blank=True, null=True) city_birthday = models.CharField(max_length=100, blank=True, null=True) custom_id = models.CharField(max_length=100 ,blank=True, null=True) gender = models.CharField(max_length=100, choices=gender_choices, null=True, blank=True) address = models.CharField(max_length=250, null=True, blank=True) contact_phone = models.CharField(max_length=100, blank=True, null=True) family_size = models.IntegerField(null=True, blank=True) living_with = models.CharField(max_length=100, choices=living_choices, null=True, blank=True) number_of_preschool_kids_in_family = models.IntegerField(null=True, blank=True) kid_already_been_in_kindergarten = models.CharField(max_length=100, choices=preschool_choices, null=True, blank=True ,default=False) father_name = models.CharField(max_length=100, blank=True, null=True) father_education_level = models.CharField(max_length=200, blank=True, null=True) father_company = models.CharField(max_length=200, blank=True, null=True) mother_name = models.CharField(max_length=100, blank=True, null=True) mother_education_level = models.CharField(max_length=200, blank=True, null=True) mother_company = models.CharField(max_length=200, blank=True, null=True) parent_notes = … -
Can't get a combination of if and elif to work in django
I have two variables, date1 and date2, both DateField. Here's what I'm trying to write: if date1 and date2 have values, display "Datation évaluée entre date1 et date2". if date1 have value but not date2, display "Datation évaluée vers date1". if date2 have value but not date1, display "Datation évaluée vers date2". if neither date1 nor date2 have values, don't display anything. Here is my code: {% if 'date1' and 'date2' %} Datation évaluée entre {{ object.date1 }} et {{ object.date2 }}. {% elif not 'date1' %} Datation évaluée vers {{ object.date2 }}. {% elif not 'date2' %} Datation évaluée vers {{ object.date1 }}. {% elif not 'date1' or 'date2' %} Datation inconnue. The first condition appears indeed, but not the others. When there's a value only on one side, I get "Datation évaluée entre value1 et None.", and when there are no values, I get "Datation évaluée entre None et None." Any ideas what's wrong in the code? Thanks for your help. -
Django url regex no longer matching
My django web app is trying to reverse match a url with a token. It's no longer matching the tokens that are passed in, but I can't spot why. This is the error it's spitting out at me: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments '{'uidb64': b'MTI5', 'token': '5pt-37c661de5cbc044ba699'}' not found. 1 pattern(s) tried: ['account\\/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] I might not have had enough coffee, but it looks like it should match to me. What am I missing? -
Construct a django queryset with inner join and order by
I am trying order table with external field Table1 Field_id Field_Name Field_Comment Field_Table2FieldID Table2 Field_id Field_date and the SQL do it : SELECT Table1.* From Table1, Table2 WHERE Table1.Field_Table2FieldID = Table2.Field_id ORDER BY Table2.Field_date Thank you very much -
Django handling cookie gdpr
Quick question for django devs in Europe, how do you handle the cookie law in Europe in your django app? I have seen a lot of solutions for an example cookiebot.com but I'm not sure if I want to use it. Also any other solution alternatives is appreciated. All the best -
Django rest Framework: How to create a custom, auto-generating string field?
I'm using the generic Django Rest Framework classes for an application, but I'd like to be able to auto-generate a short customer order ID whenever a new order instance is created. The generic classes are awesome, but small tweaks can get messy fast. I'm wondering if there's a way to do the auto-generation in models.py, in the spirit of classes like AutoIncrement or the way the primary key integer is created (but not as a primary key). Let's say I have a model class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) details = models.CharField(null=True, max_length=200) @property def title(self): return f"{self.user.first_name}'s, order" and I want to add a new field, order_reference. And lets say I want to add some custom logic, like @before_createish_thing def order_reference(self): # Return something like XYZ2021-000-23 return f"XYZ-{datetime.now().year}-000-{self.order_id}" somewhere. I don't suppose there's anything like a before_create decorator along the same lines as the @property decorator? My view is as simple as class OrderList(generics.ListCreateAPIView): queryset = Order.objects.all() serializer_class = OrderSerializer hence my reluctance to hack it apart just to get to the create() method. Is there any way to do this, ideally by somehow placing the logic in the model file? -
Django Channels Authentication
I am using Django Channels to serve a video stream from a raspberry pi to users' web browsers. I have this working great, but the problem is that the URL is essentially public. So anyone with some simple python or javascript can connect to the websocket and view the stream on their browser. Is there a way to authenticate on connection to the websocket? From the docs I followed the suggested: "websocket": AuthMiddlewareStack( URLRouter([ url(r"^stream/(?P<device_id>[\d\-]+)/$", StreamConsumer.as_asgi()) ]) ), }) But this appears to do nothing? I can open this HTML file (below) in chrome and see the video stream, no credentials or session authentication (ensured I logged out and cleared cache): <html> <head> <title>Client</title> </head> <body> <div class = "videoStream"> <img id="live-video-feed" src="" /> </div> <script> let feed = document.getElementById("live-video-feed"); const WS_URL = `ws://myip_address/stream/1924/` let ws; function setupWebsocket() { ws = new WebSocket(WS_URL); ws.onopen = () => console.log(`Connected to ${WS_URL}`); ws.onmessage = (message) => { // set the base64 string to the src tag of the image try { if (message.data === 'ping') { ws.send('pong'); return; } } catch {} responseCount = 0; feed.src = URL.createObjectURL(message.data); }; ws.onclose = () => { console.log('closed, reconnecting...') setupWebsocket() } } setupWebsocket(); </script> </body> … -
Django REST Framework API request with bad parameters returns all objects
When someone requests: 127.0.0.1:8000/api/current_metadata?SOME_FIELD_THAT_DOESNT_EXIST=1 this code returns everything. I want it to return nothing. Some kind of strict setting? class GetCrtMetadata(generics.ListAPIView): permission_classes=[IsAuthenticated] serializer_class = CurrentDeploymentSerializer queryset=deployment.objects.all() filter_backends = [DjangoFilterBackend] filter_fields = [field.name for field in deployment._meta.fields] -
what shuld i use for image fields or Boolean filds chaackbox in django forms widgets?
class CreateProductForm(ModelForm): class Meta: model = Product fields = ['name', 'price', 'category', 'description', 'image'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'price': forms.NumberInput(attrs={'class': 'form-control'}), 'category': forms.Select(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), 'image': forms.ImageInput(attrs={'class': 'form-control'}), } -
what is saved in django_session by default?
I have seen several guides on how to set/get sessions, but I cannot find any documentation of what is in the session as default i.e what is logged? Furhter more is there a better/more easy way of seing the current keys instead of creating a view, a template, set the url and then visitting the page? -
Django set data for form field after post
I have a formset with an FK to the form instance I edit: OrderForm (Basic Customer Datas) ItemFormSet (Just Items and FK to OrderForm) now I want set the field OrderID after I click on "create order" button and tried this methode: if Orderform.is_valid(): edit_form = Orderform.save() edit_order_id = edit_form.pk request.session['edit_order_id'] = edit_order_id Formset.OrderNo = Orders.objects.get(ID=edit_order_id).ID print(Formset.errors) instances = Formset.save(commit=False) for instance in instances: instance.OrderNo = Orders.objects.get(ID=edit_order_id).ID instance.save() because now I have the PK of the order form and can set it to the field OrderNo (which means OrderID) But the form.errors says I did not have set data to this field, is ther another way or much cleaner way todo it? The OrderForm saves fine so the FK should not be a problem, maybe the save methode. Edit: forms: class OrderItemsForm(forms.ModelForm): Quantity = forms.IntegerField(widget=forms.TextInput( attrs={'class': 'form-control', 'autofocus': True, 'data-toggle': 'touchspin', 'value': 1, 'data-bts-max': 100})) Price = forms.DecimalField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True})) OrderNo = forms.ModelChoiceField(widget=forms.Select(), queryset=Orders.objects.filter(), empty_label=None) class Meta: model = OrderItems fields = ['Item', 'Price', 'OrderNo', 'Quantity'] def __init__(self, user, *args, **kwargs): super(OrderItemsForm, self).__init__(*args, **kwargs) self.fields['Item'] = forms.ModelChoiceField(widget=forms.Select( attrs={'class': 'form-control select2 mb-3', 'data-toggle': 'select2'}), queryset=Products.objects.filter(UserID=user), empty_label=None) models: class OrderItems(models.Model): ID = models.AutoField(primary_key=True) Item = models.ForeignKey('Products', on_delete=models.DO_NOTHING) Quantity = models.IntegerField('Quantity') Price … -
Unable to render choices types in django template
views.py from .models import posts, TYPES //posts is a model def TypePostListView(request, type): posts = post.objects.filter(type=type).order_by('-date_posted') context = { 'posts': posts, 'p_types':TYPES } return render(request, 'blog/home.html', context) models.py TYPES = ( ('Food', 'Food'), ('Fashion', 'Fashion'), ('Fitness', 'Fitness'), ('Finance', 'Finance'), ('Travel ', 'Travel '), ('Music', 'Music'), ('Lifestyle', 'Lifestyle'), ('Music', 'Music'), ('Sports', 'Sports'), ('Political', 'Political'), ('Gaming', 'Gaming'), ) home.html <div class="type-selection"> <a href="{% url 'blog-home' %}">all</a> {% for t in p_types %} <a href="{% url 'type-posts' 't.0' %}">{{t.0}}</a> {%endfor%} </div> I am unable to render any text on the Django template. I am trying to print all the types of posts i have on the template. -
Erro Django ASGI + Gunicorn + Nginx + Python 3.7 - 500 / in handle / in handle_request / required 'SEND'
Estou com um sério problema que me fez perder alguns pares de horas e nada resolve. Abaixo os módulos instalados: Package Version ---------------------------- --------- asgiref 3.3.4 attrs 20.3.0 autobahn 21.3.1 Automat 20.2.0 certifi 2020.12.5 cffi 1.14.5 channels 3.0.3 chardet 4.0.0 constantly 15.1.0 cryptography 3.4.7 daphne 3.0.2 Django 3.1.7 django-appconf 1.0.4 django-bootstrap-modal-forms 2.1.0 django-compressor 2.4 django-crispy-forms 1.11.2 django-drf-filepond 0.3.0 django-extensions 3.1.2 django-filter 2.4.0 django-mathfilters 1.0.0 django-model-utils 4.1.1 django-pandas 0.6.4 django-redis 4.12.1 django-stdimage 5.3.0 django-storages 1.11.1 django-widget-tweaks 1.4.8 djangorestframework 3.12.4 geographiclib 1.50 geopy 2.1.0 gunicorn 20.1.0 hyperlink 21.0.0 idna 2.10 importlib-metadata 3.10.1 incremental 21.3.0 Markdown 3.3.4 numpy 1.20.2 pandas 1.2.4 Pillow 8.2.0 pip 21.0.1 psycopg2 2.8.6 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycparser 2.20 PyHamcrest 2.0.2 pyOpenSSL 20.0.1 python-dateutil 2.8.1 pytz 2021.1 rcssmin 1.0.6 redis 3.5.3 requests 2.25.1 rjsmin 1.1.0 service-identity 18.1.0 setuptools 54.1.2 shortuuid 1.0.1 six 1.15.0 sqlparse 0.4.1 Twisted 21.2.0 txaio 21.2.1 typing-extensions 3.7.4.3 urllib3 1.26.4 uvloop 0.15.2 wheel 0.36.2 zipp 3.4.1 zope.interface 5.4.0 Ao rodar o servidor em 'python3 manage.py runserver' ou 'python3 manage.py runserver 0.0.0.0:8000', tudo ocorre perfeito! Entretanto, ao rodar o sistema com gunicorn + nginx, tenho a seguinte saída de erro: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2021-04-15 … -
Django Login not redirecting to homepage
I'm trying create a login and registration form with Django. The registration portion of my program works fine. My issue is that when I give credentials to login, my program doesn't redirect me to the homepage. I've tried looking at similar problems people had and tried to work a solution and no luck. LOGIN <body> <div class="login-registration-div"> <div class="logo"> <img src = "{% static 'Logo.svg' %}"> </div> <form method="POST"> {% csrf_token %} <div class="form"> <div class="username"> <input type="text" placeholder="Username"> </div> <div class="password"> <input type="password" placeholder="Password"> </div> <button class="signin-btn" type="submit">SIGN-IN</button> </div> </form> <div class="sign-up"> <a href="{% url 'register' %}">Need an account? Sign-up here!</a> </div> </div> </body> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='coursebuddyapp-home'), path('register/', views.register, name='coursebuddyapp-register'), path('login/', views.login, name='coursebuddyapp-login'), ] views.py from django.shortcuts import render from django.shortcuts import redirect from django.contrib import messages from .forms import UserRegisterForm from django.contrib.auth import authenticate,login # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('login') else: form = UserRegisterForm() return render(request,'users/register.html', {'form': form}) def signin(request): if request.user.is_authenticated: return render(request, 'home.html') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] … -
Django - Why does this TableView has two paginators?
In my Django project I have a view that has two paginators, and I can't identify where each of them comes from. They look like this: I want to delete one of them, but I realized they are not working the same way. The one above to the right always paginates 25 results (10 on the first, 10 on the second and 5 on the third page. The one below seems to be dividing the whole queryset in sets of 25, which then the other paginator iterates over. So, for example, if I have 100 rows, the paginator below says there's 4 pages. If I select the number 2 in that paginator, the paginator on the right iterates over those 25 rows, and not the whole queryset. My view looks like this: class ClientTableView(AdminPermissionsMixin, PagedFilteredTableView): model = Client table_class = ClientTable template_name = 'users/client/client_table.html' filter_class = ClientFilter formhelper_class = ClientFormHelper exclude_columns = ('actions',) export_name = 'regiones' def get_context_data(self, **kwargs): context = super(ClientTableView, self).get_context_data(**kwargs) context['allows_user_creation'] = self.request.user.users_permission == '2' return context def get_queryset(self, **kwargs): qs = super(ClientTableView, self).get_queryset() qs = qs.filter(allows_credit=False) return qs The template client_table.html looks like this: {% extends "table.html" %} {% load staticfiles %} {% block users_active %}active{% …