Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Validationerror: "choose a valid option" on related field in ModelForm
I have a Model Inserzione related to a Model Servizio: class Inserzione(models.Model): servizio = models.OneToOneField( 'hub.Servizio', on_delete=models.CASCADE, null=True, default=None, related_name='+' ) In my InserzioneModelForm I want to restrict the choices of Servizio, I don't want all Servizio instances to be included. So in my InserzioneModelForm __init__ method: query = self.fields['servizio'].queryset self.fields['servizio'].queryset = query.filter(# my condition) This works correctly, when the user is submitting a form only the Servizio instances I want are available in the form field. The problem is that the form_valid() method returns False. It return a ValidationError {'servizio': [ValidationError(["Choose a valid option. The selected option is not between the available ones"])]} But it's actually an existing and valid Servizio instance. Here the incriminated form field in my template: <div class="controls "> <select name="servizio" class="select form-control" required="" id="id_servizio"> <option value="" selected="">---------</option> <option value="1">Corso Sicurezza sul Lavoro</option> <!--other options--> </select> </div> Any help is really aprreciated, thanks. -
Getting the error: This field is required when update user
I'm trying to update a user profile using two forms the problem is that when I click to update I get the following error: “<ul class="errorlist"> <li>username<ul class="errorlist"><li>This field is required.</li> </ul> ” My model module is the following: # user.models from django.contrib.auth.models import AbstractUser from django.db import models from model_utils.models import TimeStampedModel from localflavor.br.models import BRPostalCodeField, BRStateField, BRCNPJField, BRCPFField class User(AbstractUser): class Roles(models.IntegerChoices): SUPER = 0 COMPANY = 1 UNITY = 2 STAFF = 3 picture = models.ImageField(blank=True, null=True) role = models.IntegerField(choices=Roles.choices, default=Roles.STAFF) class Staff(TimeStampedModel): user: User = models.OneToOneField(User, null=True, on_delete=models.CASCADE) unity = models.ForeignKey(Unity, related_name="staff", on_delete=models.CASCADE) cpf = BRCPFField("CPF") class Meta: verbose_name: str = 'Staff' verbose_name_plural: str = 'Staff' ordering = ("-created",) def __str__(self): if f"{self.user.first_name} {self.user.last_name}".strip(): return f"{self.user.first_name} {self.user.last_name}" return str(self.user.username) And my user forms looks like: #user.forms class UserModelForm(forms.ModelForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'is_active'] class StaffModelForm(forms.ModelForm): class Meta: model = Staff fields = ['cpf', 'unity'] widget = { 'cpf': forms.TextInput(attrs={'class': "form-control", 'placeholder': 'Primeiro Nome', }), 'unity': forms.EmailInput(attrs={'class': "form-control", 'placeholder': 'meu@email.com', }), } with the following view: #views … def update_staff(request: HttpRequest, pk: int) -> HttpResponse: instance: Staff = get_object_or_404(Staff, pk=pk) # get staff instance template_name = 'pages/staff_update_form.html' # use this … -
Date label in JavaScript chart doesn't display properly
I'm doing a Django project. In my chart.html file, I created a javascript bar chart. The data and the label of the chart have been defined in my views.py file. This is my JavaScript bar chart: (I'm drawing this chart to display the order numbers in the most recent 7 days) var ctx = document.getElementById("BarChart7d"); var BarChart7d = new Chart(ctx, { type: 'bar', data: { labels: [{{date7}}, {{date6}}, {{date5}}, {{date4}}, {{date3}}, {{date2}}, {{date1}}], datasets: [{ label: "orders: ", backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', "#e74a3b", "#f6c23e", "#9B59B6", "#D68910"], hoverBackgroundColor: ['#353F8C ', '#17a673', '#2c9faf', "#9C4545", "#9C8545", "#4A235A", "#784212"], borderColor: "#4e73df", data: {{value7day}}, }], }, options: { maintainAspectRatio: false, layout: { padding: { left: 10, right: 25, top: 25, bottom: 0 } }, scales: { xAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { maxTicksLimit: 6 }, maxBarThickness: 80, }], yAxes: [{ ticks: { callback: function(value, index, values) { return number_format(value); } }, gridLines: { color: "rgb(234, 236, 244)", zeroLineColor: "rgb(234, 236, 244)", drawBorder: false, borderDash: [2], zeroLineBorderDash: [2] } }], }, legend: { display: false }, tooltips: { titleMarginBottom: 10, titleFontColor: '#6e707e', titleFontSize: 14, backgroundColor: "rgb(255,255,255)", bodyFontColor: "#858796", borderColor: '#dddfeb', borderWidth: 1, xPadding: 15, yPadding: 15, displayColors: false, caretPadding: 10, callbacks: … -
TypeError: background() got an unexpected keyword argument 'repeat' [closed]
I have the below Django background tasks code that I want to run after 60 seconds. However, I am getting the above error @background(repeat=60) def checkAccountBalances(): print(" working on it") -
Free realtime stockprice data and how to add charts like a real trading app chart
I currently planning for build a stock trading app using react for study purpose. Is there is any api that can give realtime stock price data and if you can please suggest a good charting package for my peoject. -
How to add custom Post Form in Django Admin below Model Records
I need some guidance! How to Create Custom Form in this Area? I will be thankful for Help. Thanks enter image description here -
How to do reverse URL with keyword argument in Jinja2?
In a view function we can do the following: from django.http import HttpResponseRedirect from django.urls import reverse def SomeView(request): return HttpResponseRedirect( reverse('blog:specific-topic', kwargs={'topic':'python'}) ) In a template, without keyword argument, we can do this: <a href="{{ url('home-page') }}">Home Page</a> But how to do reverse URL in Jinja2 with keyword arguments? I am developing a programming blog, so I need to organize articles into topics including Python, Dajngo, Jinja2, Designing Relational Databases, and so forth. I wrote the following: <a href="{{ url('blog:specific-topic', topic.slug) }}" class="topic">{{ topic.name }}</a> But it did not work. -
Django. How to not repeat yourself using class based views?
I'm new to Django. I wonder if it is considered 'repeating yourself' when I use generic views such as CreateView, ListView and etc. in different apps and they differ in values for attributes like 'model', 'fields' or 'template_name' only? Do I repeat myself in this case or I shouldn't be worried? -
Django - Group by and do ArrayAgg
I have a model: class Deviation(models.Model): deviation_number = models.SmallIntegerField() day_of_calculation = models.SmallIntegerField() And I'd like to group records of the model by day_of_calculation and get list of deviation_numbers: deviations = Deviation.objects \ .values('day_of_calculation') \ .annotate(deviation_numbers=ArrayAgg('deviation_number')) But Django incorrectly creates sql: SELECT "deviation"."day_of_calculation", ARRAY_AGG("deviation"."deviation_number" ) AS "deviation_numbers" FROM "deviation" GROUP BY "deviation"."day_of_calculation", "deviation"."deviation_number" Grouping by deviation_number should not happen. What do I do wrong? -
Unwanted fields appear on the template (Django)
I give the products to the page with the loop in the template, but there is a problem. There is a gap on the page and I can't find the reason. Most likely because of HTML codes. I will be glad if you help. This gap in the middle products.html <!-- STORE --> <div id="store"> <!-- row --> <div class="row"> <!-- Product Single --> {% for product in products %} {% if product.available %} <div class="col-md-4 col-sm-6 col-xs-6"> <div class="product product-single"> <div class="product-thumb"> <div class="product-label"> <span>New</span> {% if product.sale %} <span class="sale">-{{product.sale}}%</span> {% endif %} </div> <button class="main-btn quick-view"><i class="fa fa-search-plus"></i> Göz At</button> <img src="{{product.main_image.url}}" alt=""> </div> <div class="product-body"> {% if product.sale %} <h3 class="product-price">{{product.discount}} AZN <del class="product-old-price">{{product.price}} AZN</del></h3> {% else %} <h3 class="product-price">{{product.price}} AZN</h3> {% endif %} <div class="product-rating"> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star"></i> <i class="fa fa-star-o empty"></i> </div> <h2 class="product-name"><a href="#">{{product.name}}</a></h2> <div class="product-btns"> <button class="main-btn icon-btn"><i class="fa fa-heart"></i></button> <button class="main-btn icon-btn"><i class="fa fa-exchange"></i></button> <button class="primary-btn add-to-cart"><i class="fa fa-shopping-cart"></i> Səbətə At</button> </div> </div> </div> </div> {% endif %} {% endfor %} <!-- /Product Single --> </div> <!-- /row --> </div> <!-- /STORE --> -
I have a problem with override title in admin when use TabularInline
I have a problem with title in admin, when i use TabularInline, the name of the fields is overwritten. This happens precisely with ManiToMany. How can i change it? Field name in admin "AdditionalCourseModel_course object (1)" block name in admin "ADDITIONALCOURSEMODEL" models.py class CoursesDescriptionModel(models.Model): ... class Meta: verbose_name = 'Курс' verbose_name_plural = 'Курсы' def __str__(self): return f'{self.name_courses}' class CourseDetailModel(models.Model): course = models.ForeignKey(CoursesDescriptionModel, on_delete=models.CASCADE, related_name='course') ... class Meta: verbose_name = "Что изучает курс" verbose_name_plural = "Что изучает курс" def __str__(self): return f'{self.detail}' class AdditionalCourseModel(models.Model): course = models.ManyToManyField(CoursesDescriptionModel, related_name='add_course', verbose_name='qwerty') name_course = models.CharField(max_length=100, verbose_name='название допа') ... class Meta: verbose_name = 'Доп к курсу' verbose_name_plural = 'Допы к курсу' def __str__(self): return f'{self.name_course}' admin.py class CoursesDescriptionInline(admin.TabularInline): model = CourseDetailModel fk_name = 'course' extra = 1 max_num = 10 class AdditionalCourseModelInline(admin.TabularInline): model = AdditionalCourseModel.course.through extra = 1 max_num = 1 verbose_name = 'допы к курсу' verbose_name_plural = 'Доп к курсу' @admin.register(CoursesDescriptionModel) class CourseAdmin(admin.ModelAdmin): fields = (...) list_display = (...) inlines = [CoursesDescriptionInline, AdditionalCourseModelInline] enter image description here -
django 4.0 Invalid path type: PurePosixPath but working on django 3.1
i tried to migrate from django 3 to django 4 my project based on wemake-django-template i have 2 virtual env, django 3.1 and django 4.0 the project working fine on venv django 3.1 but have this error on django 4.0 raise TypeError("Invalid path type: %s" % type(value).__name__) TypeError: Invalid path type: PurePosixPath ` from pathlib import PurePath from decouple import AutoConfig BASE_DIR = PurePath(file).parent.parent.parent.parent config = AutoConfig(search_path=BASE_DIR.joinpath('config')) ` the project still empty, i just wanna my default setting are working properly on django 4.0 -
How to create model instance with a button and no forms
I have a model with 2 fields, the first one is user and the second one is member. I want to create an instance just clicking a button without filling a form. I want to get the I want to get the user from the logged user and the member from the current block in the HTML This is my model: class Applicant(models.Model): member_proyect = models.ManyToManyField(Member, related_name=('vacancy')) user = models.ForeignKey(User, on_delete=models.CASCADE) I want to get the user from the logged user. I did this for loop to display all the members in the HTML {% for member in member_list %} {% if member.proyect_id == page.id %} {% with n=forloop.counter %} <div class="accordion-item"> <h2 class="accordion-header" id="heading{{n}}"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{n}}" aria-expanded="false" aria-controls="collapse{{n}}"> {{member.rol}} </button> </h2> <div id="collapse{{n}}" class="accordion-collapse collapse " aria-labelledby="heading{{n}}" data-bs-parent="#accordionExample"> <div class="accordion-body"> {{member.content |safe }} <form action="" method="post"> <!-- I want to click this button and create the instance --> {% csrf_token %} <input type="submit" value="Aplicar" class="btn btn-primary" /> </form> </div> </div> </div> {% endwith %} {% endif %} {% endfor %} In this case, there is no form, just a button and I am not sure how to do it. -
Django + DRF + Djoser: Unable to send api request to create a user due to Forbidden (CSRF cookie not set.) error
I am using dojser urls to create a user. However I am unable to send api request due to the following error shown in the terminal Forbidden (CSRF cookie not set.): /auth/users/ [28/Mar/2022 16:44:56] "POST /auth/users/ HTTP/1.1" 403 2870 Below is my set up urls.py urlpatterns = [ path('', include('home.urls')), path('admin/', admin.site.urls), path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_simplejwt', "corsheaders", 'djoser', 'account', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE' : True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL' : True, 'SET_USERNAME_RETYPE':True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL':'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL':'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL':'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SERIALIZERS':{ 'user_create': 'account.serializers.UserCreateSerializer', 'user': 'account.serializers.UserCreateSerializer', 'user_delete': 'djoser.serializers.UserDeleteSerializer', } } AUTH_USER_MODEL = 'account.CustomUser' The url at which I am sending the request to for creating a user is POST: http://127.0.0.1:8000/auth/users/ Please suggest me what should how to rectify the error. -
Why hide a django secret key?
I wanted to ask, why should I hide the secret key in a Django application? Why not just commit it to public source control? I understand the effects of an attacker finding out the secret key (from here). But if I just upload the code to github and ask people to download it, run python manage.py runserver and go to 127.0.0.1:8000, I don't need to hide it, right? Don't those effects of revealing the secret key apply for when you run the code on your device using your device as a server, and have them visit it at a public URL? If they're running it on their own device, that doesn't pose a security risk to me, right? I read that knowing the secret key can allow them to bypass form validations, etc. But they would just be messing up the db of their own local installation of the app so why should I care? -
Displaying table x's fields in GET request of table y that has foreign key of table x (Django)
I could use some help please, been stuck on this for awhile. I have two tables, Share and Fund. Share.py class Share(models.Model): ShareName = models.CharField(max_length=100, unique=True, default="N/A") ISINCode = models.CharField(max_length=100, primary_key=True, default="N/A") Fund.py class Fund(models.Model): FundID = models.AutoField(primary_key=True) FundName = models.CharField(max_length=100, default="N/A", unique=True) FundIdentifier = models.CharField(max_length=100, default="N/A") PercentOfFundNetAssets = models.DecimalField(decimal_places=2, max_digits=5, default=0.00) ISINCode = models.ForeignKey(Share, to_field='ISINCode', related_name="toshares", on_delete=models.CASCADE) class Meta: unique_together = ('FundIdentifier', 'ISINCode') Individually they has been no issue for GET/POST/PUT etc. Its important now though that on GET requests to fetch the fund table while also retrieving the relevant share fields that fall under each fund row. See below: What fund JSON looks like now upon GET request [ { "FundName": "Some fund", "FundIdentifier": "FND001", "PercentOfFundNetAssets": "3.82", "ISINCode": "SHR001" }, ] What I want fund JSON to look like upon GET request [ { "FundName": "Some fund", "FundIdentifier": "FND001", "PercentOfFundNetAssets": 3.82, "ISINCode": "SHR001", "share": [ { "ISINCode": "SHR001", "ShareName": "Some share" } ] } ] I'd also settle for something like this though. [ { "FundName": "Some fund", "FundIdentifier": "FND001", "PercentOfFundNetAssets": 3.82, "ISINCode": "SHR001", "ISINCode": "SHR001", "ShareName": "Some share" } ] Either way, each fund json object will only have one share object within with its relevant fields … -
Does acccessing nested FK relation's field value downgrade performance?
I have various models which are interconnected through Foreign key relations, does doing this make any performance downside. I want to know how does django perform this internally. PriceSheet.objects.select_related('query').filter(id=pricesheet_id).values('query__campaign_name', 'query_id', 'query__campaign_status', 'query__lead_id', 'query__lead__legal_name', 'query__lead__brand_name' # nested 'query__lead__working_capital', 'query__lead__payment_terms', ) # 7 -
Running docker container: iptables failed
im moving a django app and dependencies (redis & celery) from docker containers hosted on VM to Azure app service but get the below error 2022-03-28T10:15:36.671Z ERROR - Container start failed for testoms_application_0_6c28f745 with System.AggregateException, One or more errors occurred. (Docker API responded with status code=InternalServerError, response={"message":"driver failed programming external connectivity on endpoint testoms_application_0_6c28f745 (a92233c6cf84a60789ac7fb71e71e3b1fbc358c4694917ce4210a73ebf412c05): (iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 127.0.0.1 --dport 3062 -j DNAT --to-destination 172.16.4.3:0: iptables v1.6.1: Port 0' not valid\n\nTry iptables -h' or 'iptables --help' for more information.\n (exit status 2))"} ) (Docker API responded with status code=InternalServerError, response={"message":"driver failed programming external connectivity on endpoint testoms_application_0_6c28f745 (a92233c6cf84a60789ac7fb71e71e3b1fbc358c4694917ce4210a73ebf412c05): (iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 127.0.0.1 --dport 3062 -j DNAT --to-destination 172.16.4.3:0: iptables v1.6.1: Port 0' not valid\n\nTry iptables -h' or 'iptables --help' for more information.\n (exit status 2))"} ) docker compose file points to port 8080 for django image, added WEBSITE_PORTS under configuration-> application settings. i have also set env variables under application settings. How do i fix this please -
django-grpc-framework: correct way to serialize/deserialize JSONFields?
what is the proper way to handle Django JSONFields in the django-grpc-framework ? How can I check, what kind of data is actually sent (Evans throw the same error) = When I try to receive a serialized JSONFiled with the django-grpc-framework, the following error is thrown in my data_grpc_client.py: python data_grpc_client.py Traceback (most recent call last): File "/my_data/data_grpc_client.py", line 8, in for datum in stub.List(my_data.lara_data_pb2.DataListRequest()): File ".../python3.9/site-packages/grpc/_channel.py", line 426, in next return self._next() File .../lib/python3.9/site-packages/grpc/_channel.py", line 826, in _next raise self grpc._channel._MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with: status = StatusCode.UNKNOWN details = "Exception iterating responses: Failed to parse data_JSON field: expected string or bytes-like object." debug_error_string = "{"created":"@1648155177.535827174","description":"Error received from peer ipv6:[::1]:50051","file":"src/core/lib/surface/call.cc","file_line":905,"grpc_message":"Exception iterating responses: Failed to parse data_JSON field: expected string or bytes-like object.","grpc_status":2}" I would be very happy for any help - thanks a lot in advance ! Elain Here are my python/proto modules - to reproduce the error: I have a django (4.0.3) model with a JSON field: # models.py class Data(models.Model): data_id = models.AutoField(primary_key=True) data_JSON = models.JSONField(blank=True, null=True, help_text="JSON representation of the data") My serializer.py looks like this: from my_data.models import Data from django_grpc_framework import proto_serializers from rest_framework import serializers import my_data.my_data_pb2 class DataProtoSerializer(proto_serializers.ModelProtoSerializer): class Meta: … -
Does render in Django obfuscate the HTML cord that it loads?
I am using render in Django to load an HTML file that contains different calculators/simulators. I would like to use render because I believe it may help obfuscate the HTML to code to prevent people from doing right click view source? Is this accurate? Are there other ways to achieve my goal of not having my HTML code be viewable? -
TypeError: render() missing 1 required positional argument: 'template_name'
I created simple form register user but something is wrong. This is my django project: settings.py account/urls.py forms.py views.py Directories: error: I don't understand this issue. I use render(request, 'name_template', {}) but django request name_template. What did I do wrong? Sorry for my english but I still learn ;) -
Django - grouping in serializer
I'm struggling to create a serializer that groups the result, I can make it my "dirty" way but i am curious what is the proper way my models: class Station(models.Model): type = models.ForeignKey(StationType, on_delete=models.SET_NULL, null=True) line = models.CharField(max_length=1) number = models.CharField(max_length=3) bool1= models.BooleanField( null=True, blank=True, default=False) bool2= models.BooleanField( null=True, blank=True, default=False) def str(self):return self.number my serializer: class mySerializer(serializers.ModelSerializer): class Meta: model = Station fields = ['line', 'number','bool1', 'bool2'] result: [ { "line": "1", "number": "001", "bool1": false, "bool2": false }, { "line": "1", "number": "001", "bool1": false, "bool2": false }, { "line": "3", "number": "013", "bool1": false, "bool2": false } ] expected result (more or less): [ {"line": "1",{ "number": "001", "bool1": false, "bool2": false }, { "line": "1", "number": "001", "bool1": false, "bool2": false }}, {"line": "3", { "number": "013", "bool1": false, "bool2": false }} ] I would be grateful for all kinds of help ;) If you could give me the source where I could learn more about serializers I would be even more grateful -
django Form, MultipleChoiceField and circular import
I try to setup a ModelForm Formset - with Checkbox fields... But if I set a queryset for my MultipleChoiceField I get an "ImportError" ImportError: cannot import name 'Event' from partially initialized module 'ferienspiel.event.models' (most likely due to a circular import) How can I make a queryset for my MultipleChoiceField-Fields in `forms.py? to avoid a circular import Error? My setup: - app --- model.py (contains Model and Formhandler, for Wagtail Page `def serve()` ) --- form.py (formset setup) --- ulrs.py --- views.py forms.py class ChildForm(ModelForm): def __init__(self, *args, **kwargs): super(ChildForm, self).__init__(*args, **kwargs) self.fields["event"].widget = CheckboxSelectMultiple() self.fields["event"].queryset = Event.objects.all().order_by("date", "time") class Meta: model = Child fields = ("first_name", "last_name", "date_of_birth", "text") widgets = { ... ... model.py class Event(Page): location = models.TextField(max_length=500, null=False) date = models.DateField(null=False) time = models.TimeField(null=False) class EventRegistrationPage(Page): intro = models.TextField(blank=True) def serve(self, request): if request.method == "POST": parent_form = ParentForm(request.POST, request.FILES) childs_form = ChildFormSet(request.POST, request.FILES) if all([parent_form.is_valid(), childs_form.is_valid()]): for child in childs_form: # print(f"child {child.cleaned_data}") if child.is_valid(): new_child = child.save(commit=False) new_child.parent = new_parent new_child.save() new_child.event.set( child.cleaned_data.get("event") ) child.save_m2m() childs_data.append(new_child) -
Django Select2 ModelSelect2TagWidget Problem
I followed the documentation on how to use the ModelSelect2TagWidget from the django-select2 library, but when I submit the form I get "Select a valid choice error" on the tag field regardless the tag is saved in the database. models.py class FromTo(models.Model): from_to = models.CharField(max_length=100) class Course(models.Model): from_to = models.ForeignKey( FromTo, null=True, on_delete=models.SET_NULL) forms.py class FromToWidget(s2forms.ModelSelect2TagWidget): queryset = models.FromTo.objects.all() search_fields = ['from_to__icontains'] def value_from_datadict(self, data, files, name): values = super().value_from_datadict(data, files, name) queryset = self.get_queryset() pks = queryset.filter( **{'pk__in': [v for v in values if v.isdigit()]}).values_list('pk', flat=True) cleaned_values = [] for val in values: if represent_int(val) and int(val) not in pks or not represent_int(val) and force_text(val) not in pks: val = queryset.create(from_to=val).pk cleaned_values.append(val) return cleaned_values class CourseModelForm(forms.ModelForm): from_to = forms.ModelChoiceField( models.FromTo.objects.all(), widget=FromToWidget(model=models.FromTo)) -
Issue with Django redirect to previously visited page
I am trying to update the login view. For now, if someone will try to enter http://127.0.0.1:8000/articles/ then the user is redirected to http://127.0.0.1:8000/ (login page) and after successful log, it is redirected to http://127.0.0.1:8000/home. What I want is to redirect users to the page they tried to visit before logging in. So if someone will try to visit http://127.0.0.1:8000/articles then after log in the website should redirect him to the articles page, not to home. This is what I tried: views.py class UpdatedLoginView(LoginView): form_class = LoginForm template_name = 'user/login.html' redirect_field_name='main/homepage.html' def post(self, request): form = self.form_class(request.POST) if form.is_valid(): if 'next' in request.POST: return redirect(request.POST['next']) login.html <form method="post" class="login-form background" novalidate> {% csrf_token %} {{ form|crispy }} {% if request.GET.next %} <input type="hidden" name="next" value="{{request.GET.next}}" /> {% endif %} <button type="submit" class="text-center mx-auto border-0 join-btn col-sm-12 col-md-6 main-btn">Login</button> <a href="{% url 'login' %}?next={{request.get_full_path|urlencode}}">Login test</a> // this is just a test element, I want to have button in my form </form> My question is how to modify UpdatedLoginView and form in order to redirect users to previously visited page. The code I tried is taken from here.