Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django_Password_Expiry_not_working
setting.py PASSWORD_RESET_TIMEOUT = 120 views.py def login(request): if request.method == 'POST': uname = request.POST['uname'] pwd = request.POST['pwd'] user = authenticate(username=uname, password=pwd) if user is not None: if user.is_active: auth.login(request, user) return redirect('home') else: return render(request, 'login.html') models.py class RegisterUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=100) password_expiry = models.TimeField(auto_now_add=True) def __str__(self): return self.user.username Does anyone know how to set password expiry in django for 2 minutes -
django drf not listing all data in models
I am testing to overwrite the object with same "user" value after posting the data, the django model is like below: class TestModel(models.Model): customer = models.CharField(max_length=128, verbose_name="Customer Name", help_text="Customer Name") account = models.CharField(max_length=20, verbose_name="Account Id", help_text="Account Id") role = models.CharField(max_length=64, verbose_name="customer Role", help_text="IAM Role") user = models.CharField(max_length=20, verbose_name="User Name", help_text="User Name") post_time = models.CharField(max_length=16, verbose_name="Post Time", help_text="Post Time", null=True) Serializer class: """ TestModel Serializer """ class Meta: model = TestModel fields = '__all__'``` def create(self, validated_data): user = validated_data.get('user') try: testobj = TestModel.objects.get(user=user) for key, value in validated_data.items(): setattr(testobj, key, value) testobj.save() return testobj except TestModel.DoesNotExist: return super().create(validated_data) Viewset: class TestViewset(viewsets.ModelViewSet): lookup_field = 'user' permission_classes = (permissions.IsAuthenticated,) serializer_class = TestModelSerializer queryset = TestModel.objects.all() Every time after post, the database record updated as expected, but when accessing via get api and using the user as lookup_field, it always return the stale(the old record values). Appreciate for any help. Thanks. -
DRF custom url for viewset method
I have a rating viewset for product per user as : class RatingViewSet(viewsets.ModelViewSet): queryset = models.Rating.objects.all() serializer_class = serializers.RatingSerializer # @action(detail=False, methods=['get'], url_path=r'(?P<user>\d+)/(?P<pizza>\d+)/') @action(detail=False, methods=['get'], url_path=r'<int:user>/<int:pizza>') def get_user_pizza_rating(self, request, *args, **kwargs): how can I define the url to call this method drf custom url actions -
Django Queryset filtering against list of strings
Is there a way to combine the django queryset filters __in and __icontains. Ex: given a list of strings ['abc', 'def'], can I check if an object contains anything in that list. Model.objects.filter(field__icontains=value) combined with Model.objects.filter(field__in=value). -
Change IP-address of django server [closed]
I'm currently trying to program a server that makes a series of files available for download within a network. I use Django to run the server on different PCs. My problem with this is that when I use python manage.py runserver 0.0.0.0:8000 the clients don't know what the IP address of the server is. Is it possible to change the IP address of the server so that the same address is always used everywhere, no matter what network or PC? -
How to dynamically generate optimal zoom on folium/leaflet?
I am using leaflet and folium to map out locations. These locations can be filtered out and therefore requires something a bit dynamic. I want to achieve two things: center the user on the map between the different locations (that works); Now I also want to regulate the zoom level to capture all the locations on the screen - sometime this zoom might be at street level, sometimes it might be at a country level. I feel my problem can be solved by using fitBounds, which according to documentation automatically calculates the zoom to fit a rectangular area on the map. That sounds ideal and this post here seems to be giving an answer about a similar question: pre-determine optimal level of zoom in folium Slight problem, I just don't understand it. I am thinking I should be able to use the min and max longitude and latitude to generate the rectangular area leaflet documentation refers to. But how does that translate in the zoom levels provided by leaflet? def function(request): markers = Model.objects.filter(location_active=True) #Max latitude & longitude min_latitude = Model.objects.filter(location_active=True).aggregate(Min('latitude'))['latitude__min'] min_longitude = Model.objects.filter(location_active=True).aggregate(Min('longitude'))['longitude__min'] #Min latitude & longitude max_latitude = Model.objects.filter(location_active=True).aggregate(Max('latitude'))['latitude__max'] max_longitude = Model.objects.filter(location_active=True).aggregate(Max('longitude'))['longitude__max'] sum_latitude = 0 # sum latitude … -
How to avoid similiar queries in for loop
I have json and i parse and filter that json literally in my template and for some reason i have 10 similiar queries bcs of that loop I tried to call my Model outside loop all_sections = CleanSections.objects.all() but it didnt help views.py class ShowProjectBudgetList(ListView): template_name = 'customer/customer_home.html' context_object_name = 'json_data' def get_queryset(self): response = session.get(url, auth=UNICA_AUTH) queryset = [] all_sections = CleanSections.objects.all() for item in response_json: my_js = json.dumps(item) parsed_json = ReportProjectBudgetSerializer.parse_raw(my_js) for budget in parsed_json.BudgetData: budget.SectionGUID = CleanSections.objects.filter(GUID=budget.SectionGUID) budget.СompletedContract = budget.СompletedContract * 100 budget.СompletedEstimate = budget.СompletedEstimate * 100 queryset.append(budget) return queryset template.html {% for info in json_data %} <tr> {% for section in info.SectionGUID %} <td>{{ section }}</td> {% endfor %} <td>{{ info.BudgetContract|floatformat:"2g" }} ₽</td> <td>{{ info.DiffContractEstimate|floatformat:"2g" }} ₽</td> <td>{{ info.СompletedContract|floatformat:0 }}</td> <td>{{ info.BudgetEstimate|floatformat:"2g" }} ₽</td> <td>{{ info.DiffEstimateAct|floatformat:"2g" }} ₽</td> <td>{{ info.СompletedEstimate|floatformat:0 }}%</td> <td>{{ info.SumAct|floatformat:"2g" }} ₽</td> </tr> {% endfor %} -
django-ckeditor5 server error 500 with AWS S3 bucket
I am attempting to use AWS S3 bucket for storage with a Django site. I am using django-ckeditor5 for some text fields in some models. I am allowing image uploads in the ckeditor fields. This works with local storage. However, when I attempt to upload an image while using the S3 bucket for storage, I get the following error in the terminal: OSError: [Errno 30] Read-only file system: '//bucketname.s3.amazonaws.com' [12/Apr/2023 13:33:58] "POST /ckeditor5/image_upload/ HTTP/1.1" 500 118977 For testing I have made the bucket policy completely open with the following policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "AddPerm", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": "arn:aws:s3:::bucketname/*" } ] } The relevant section from the settings.py file is: #S3 Bucket config AWS_ACCESS_KEY_ID = 'Key ID here' AWS_SECRET_ACCESS_KEY = 'secret key here' AWS_STORAGE_BUCKET_NAME = 'bucketname' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' #AWS S3 Settings AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ AWS_LOCATION = 'static' STATICfILES_DIRs = [ str(BASE_DIR.joinpath('static')), ] STATIC_ROOT = BASE_DIR / "static" STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL AWS_QUERYSTRING_AUTH = False # needed for ckeditor … -
Django DreamHost - Request exceeded the limit of 10 internal redirects due to probable configuration error
I have hosted Django project on DreamHost. Everything works perfectly when I visit the homepage, but when I try to access any other page, I receive the following error message: Example: www.example.com (Working) www.example.com/foo/ (Getting error) 'Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.' I have tried to solve this issue, but I have been unable to do so. Following is my .htaccess file in /home/username/example.com/public folder. RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /electiondata_private/$1 [L,QSA] AddHandler wsgi-script .wsgi And my passenger.wsgi file in /home/username/example.com import sys, os INTERP = "/home/analyzethevote/atv/electiondata-private/venv/bin/python3" #INTERP is present twice so that the new python interpreter #knows the actual executable path if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv) cwd = os.getcwd() sys.path.append(cwd) sys.path.append(cwd + '/electiondata-private') #You must add your project here sys.path.insert(0,cwd+'/venv/bin') sys.path.insert(0,cwd+'/venv/lib/python3.9.16/site-packages') os.environ['DJANGO_SETTINGS_MODULE'] = "electiondata_private.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application() PS. I am using django 4. Any help would be appreciated. -
Django build Models with duplicating data is a correct way?
I'm new to Django. But have a doubt now regarding building Models within one Django app with certain relations. For example I have an accounts app with defined model User(AbstractUser) which works fine. I've created a new Django app records with a model Bill which suppose to handle a certain service records with following fields: year_due service_name cost To link User with a Bill I've created an additional model Payment which contains: user_id bill_id service_name year_due Is this example a good practice to define models or better to incapsulate such a fields within one class? I want to make it clear to see the relevant data. The main idea is to clearly see to which service_name a certain bill or payment belong. The raw example of my code I haven't yet migrate: class Bill(models.Model): service_name = models.CharField(max_length=30) fixed_cost = models.BooleanField(default=False) unit = models.CharField(max_length=5, null=True, blank=True) current_counter = models.DecimalField(max_digits=15, decimal_places=2, null=True, blank=True) consumption = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) cost_per_unit = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True) payed_amount = models.DecimalField(max_digits=8, decimal_places=2) is_paid = models.BooleanField(default=False) class Payment(models.Model): bill_id = models.ForeignKey(Bill, on_delete=models.CASCADE) user_id = models.ForeignKey(User, on_delete=models.CASCADE) record_date = models.DateTimeField(auto_now_add=True) service_name = models.CharField(max_length=30) year_due = models.IntegerField() month_due = models.IntegerField() payed_amount = models.DecimalField(max_digits=8, decimal_places=2) Thank You in advance … -
When I activate the form, it gives an error in my app " 'str' object is not callable"
**I would be grateful if my friends could help me ** When I activate the form, it gives an error in my app The form inside the HTML file is not called ** view : def student_register(request, id): form = RegisterlesonForm() students = Profile.objects.get(pk=id) if request.method == "POST": form = RegisterlesonForm(request.POST) if form.is_valid(): fs = form.save(commit=False) fs.student = students fs.member_add = request.user.id register = Registerleson.objects.filter( student=id, leson=request.POST['leson']).count() if register > 0: messages.add_message(request, messages.WARNING, 'error') return redirect('register_lessone', id) else: fs.save() return redirect('member_index') context = { 'form': form, 'students': students, } return render(request, 'member/register_lesson.html', context) code forms : class RegisterlesonForm(forms.ModelForm): class Meta: model = Registerleson fields = ['leson', 'book', 'discount'] widgets = { 'leson': forms.Select(attrs={'class': 'form-control'}), 'discount': forms.NumberInput(attrs={'class': 'form-control'}), 'book': forms.Select(attrs={'class': 'form-control'}), } html code <form method="post" autocomplete="off"> {% csrf_token %} {{ form }} <div class="modal-footer"> <button type="submit" class="btn btn-primary">ثبت</button> </div> </form> -
Error 'tuple index out of range' in Django
A bit time ago I've used a regular unit tests (not django test) and now I've got some saved tests data in my project. I can open them pages in admin panel, but when trying to delete those receive error 'tuple index out of range'. How can I solve this problem? For clear case: url /admin/quest_manager/quest/15/change/ is working, url /admin/quest_manager/quest/15/delete/ raise error named above. Before and now i've never use position arguments in view, serializer and models. I use PostgreSQL for data bases, if it important. Unnecessary data in base disturb project and i want delete this elements without full clearing table in db. Thank you for help! -
why show this error on ubuntu server [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU
I build Image upscale resolution project using python Django on local using EDSR model dnn_supperres they run properly and trained the image resolution correctly but ubuntu server not support dnn_superres EDSR model didn't run properly.. it show this issue [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU (https://i.stack.imgur.com/Cm0es.png) I try these are steps in upscale resolution and used EDSR model dnn_superres on local and used EDSR model they trained on this proper way [ WARN:0@8.023] global net_impl.cpp:174 cv::dnn::dnn4_v20221220::Net::Impl::setUpNet DNN module was not built with CUDA backend; switching to CPU But, I try this steps on ubuntu server it not working proper way its show this issues [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU So please provide and solve my question soon as possible -
How to create seperate login system for user and service provider in django
I have this fully functional user auth system User model: class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) username = models.CharField(max_length=255, unique=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] User login view .I'm using JWT tokens stored in cookies. @api_view(['POST']) def LoginView(request): email = request.data['email'] password = request.data['password'] user = User.objects.filter(email=email).first() if user is None: raise AuthenticationFailed('User not found!') if not user.check_password(password): raise AuthenticationFailed('Incorrect password!') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.data = { 'jwt': token } return response In my React front-end i use react-auth-kit to check if the user if logged-in, to be able to access UserProfile.jsx component which is private as shown bellow. const PrivateRoute = ({ Component }) => { const isAuthenticated = useIsAuthenticated(); const auth = isAuthenticated(); return auth ? <Component /> : <Navigate to="/login" />; }; <Router> <NavBar /> <Routes> <Route path="/" element={<Home />} /> <Route path="/login" element={<Login />} /> <Route path="/signup" element={<Signup />} /> <Route path="/profile" element={<PrivateRoute Component={UserProfile} />} /> <Footer /> </Router> The Login.jsx component has a simple axios request to get data from backend. axios .post( "/api/login", { … -
request.query_params parsed incorrectly
Django request.query_params returns an incorrectly formatted QueryDict. For example, if the query parameters read: example_param=[{"id":"f8","example_action":"kill"}] request.query_params returns: <QueryDict: {'example_param': ['[{"id":"f8", "example_action": "kill"}]']}> Noting example_param was parsed as a list containing a string, which is not correct. How do I return request.query_params as valid json? -
Connecting checkboxes to the database (Django, python, html)?
total noob here. I'm in my third week of a bootcamp and I'm trying to go a bit beyond what we've been taught by creating a to-do list page in which, once a user is finished with a task, they can check a checkbox, hit save, and the completion status of a task with be sent to the database. I'm running into a 404 error, which is raising a number of questions for me, in addition to the code just being noob-code to begin with. I welcome any corrections and explanations because this is all very new to me and I've done a lot of reading but there are still gaps in my understanding. I apologize if I don't even know how to ask what I want to ask. Again, this is only 3 weeks of coding for me... Related question: Let's say I want the website to be just one page. But I need to create a form and a view function for the checkbox POST... does this require me to also create a new path in the apps url.py? And/or a new html template? I just want to stay on the same page forever but is it the … -
One rest endpoint works just fine, other gives CORs error
I have a react client app and django server app. React app is running on port 9997 and server API is available on port 9763. Frontend is able to access some APIs while some APIs are failing with error: As you can see first URL works, but second does not: API that works React code: import axios from "axios"; // ... async getRestEndpoint1() { let url = '/app/api/rest_endpoint1/' const axiosInstance = axios.create(); try { const response = await axiosInstance.get(url, { params: { 'format': 'json', 'propId': this.props.routeProps.match.params.propId } } ) return response.data; } catch (err) { console.error(err); } } Django REST code: def getHttpJsonResponse(obj): resp = json.dumps(obj, default=str) return HttpResponse(resp, content_type="application/json", status=status.HTTP_200_OK) @api_view(http_method_names=['GET']) def getRestEndpoint1(request): entityId = request.GET['entityId'] headers = EntityObject.objects.filter(entity_id=entityId).all() resp = [] for header in headers: resp.append({ 'id': entity.id, 'subEntityName': header.subEntity_name}) return getHttpJsonResponse(resp) API that does not work React code: import axios from "axios"; // ... async getRestEndpoint2() { let url = '/app/api/rest_endpoint2/' const axiosInstance = axios.create(); try { const response = await axiosInstance.get(url, { params: { 'format': 'json' } } ) return response.data; } catch (err) { console.error(err); } } Django code: @api_view(http_method_names=['GET']) def getRestEndpoint2(request): # business logic return getHttpJsonResponse(respStatsJson) Both APIs are in same views.py file and … -
Nested List in Django Admin
I have two models, something like this: class Category(models.Model): title = models.CharField(max_length=32) date_created = models.DateTimeField(auto_now_add=True) class Post(models.Model): title = models.CharField(max_length=64) text = models.TextField() parent = models.ForeignKey(Category, on_delete=models.CASCADE) Please tell me, is it possible to display these models in the standard Django admin panel like this: perhaps there is some extension to implement verbose output? -
Image prediction Django API predicts same result and generates errors
I tried making an API with DJANGO which I call, the api has a function called predictimage which takes the image input from the website (choose file from device on website) and sends it to the api then processes the image (with mediapipe hands to draw a mesh on the image) and then calls the pretrained model and predicts what's in the image. The problem is that when I predict the first image from the website it works but when I try to choose another file (image) from device and predict another time, it doesn't draw the hand mesh correctly and doesn't make the right prediction (it predicts the same as the first CORRECT image) making the second prediction false. This sign is supposed to be A not B and the mesh is not drawn correctly ++IM MAKING THIS API TO CALL IT FROM DART CODE :) is there a solution for this too ? thanks This is the code #DJANGO from keras.models import load_model import cv2 import numpy as np from cvzone.HandTrackingModule import HandDetector import math import time from django.core.files.base import ContentFile from django.core.files.storage import default_storage from django.shortcuts import render import base64 #imageWhite=[] detector= HandDetector(maxHands=1) offset = 20 imgSize … -
Django-debug-toolbar return error while trying to see static files
I have django-debug-toolbar and everythings works fine except i try to see static files which uses on this page Pannel shows me how many static files are using on this page but i cant get info about them I got an error 400 Bad Request and error in terminal: django.core.exceptions.SuspiciousFileOperation: The joined path (/css/style.css) is located outside of the base path component (/home/kirill_n/PycharmProjects/my_proj/venv/lib/python3.10/site-packages/django/contrib/admin/static) Bad Request: /__debug__/render_panel/ GET /__debug__/render_panel/?store_id=62e0bb7a200049efa762b6b5d59c118f&panel_id=StaticFilesPanel HTTP/1.1" 400 2 settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_ROOT_FILES = os.path.join(BASE_DIR, 'static_src') STATICFILES_DIRS = ( 'static_src', ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.FileSystemFinder', ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ALLOWED_HOSTS = ['*'] INSTALLED_APPS += [ 'debug_toolbar', ] MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INTERNAL_IPS = [ '127.0.0.1', ] urls.py if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Is it possible to restrict admin (Django Administration) not to access to Users' private information (Journal entries) in Django?
I am currently developing a journal application with Django. As the journal entries would be a private thing. Is it possible to restrict admin not to access the Journal information? I have tried to add some codes in the admin.py, put it doesn't work. from django.contrib import admin from .models import Journal class JournalAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs else: return qs.filter(user=request.user) admin.site.register(Journal, JournalAdmin) This code as well. from django.contrib import admin from .models import Journal class JournalAdmin(admin.ModelAdmin): def has_view_permission(self, request, obj=None): if obj and obj.user != request.user: return False return True admin.site.register(Journal,JournalAdmin) -
why showing this error [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU
I have try this python code in local its trained and save the image but i have use server if its using same code the did not trained the image .plz advice me. its showing [ WARN:0@11.723] global net_impl.cpp:174 setUpNet DNN module was not built with CUDA backend; switching to CPU. I install python opencv-contrib-python.but again show. I try image upscale process using djano. but its successfully run on local but ubuntu server not running its before process its windup the process .plz advice me why its not trained? -
Follow button for a profile follows the wrong profile
When I click on the Follow button for Profile 2 for example, instead of Unfollow button to show on the Profile 2, it shows on Profile 1 (which is the currently logged in profile). Then, the followers (authours) count for Profile 1 and the following (fans) profile for Profile 1 count increases instead of just the following count for Profile 1 to increase. URLS.PY path("profile/<int:user_id>", views.profile, name="profile"), path("follow/<int:user_id>", views.follow, name="follow"), MODELS.PY class User(AbstractUser): authors = models.ManyToManyField( "self", blank=True, related_name="fans", symmetrical=False ) def __str__(self): return str(self.username) PROFILE.HTML {% if user.is_authenticated %} {% if user in profile.authors.all %} <a href="{% url 'follow' user.id %}" class="btn btn-primary">Unfollow</a> {% else %} <a href="{% url 'follow' user.id %}" class="btn btn-primary"> Follow </a> {% endif %} {% else %} <button class="btn btn-outline-primary">Message</button> <p class="text-muted"> please, login to follow </p> {% endif %} <ul class="about"> {% if profile.authors.count <= 1 %} <li><span>{{ profile.authors.count }}</span>Follower</li> {% else %} <li><span>{{ profile.authors.count }}</span>Followers</li> {% endif %} <li><span>{{ profile.fans.count }} </span>Following</li> {% if post_count <= 1 %} <li><span>{{post_count}} </span>Post</li> {% elif post_count >= 2 %} <li><span>{{post_count}} </span>Posts</li> {% endif %} </ul> VIEWS.PY def profile(request, user_id): profile = User.objects.get(pk = user_id) post_count = NewTweet.objects.filter(user = user_id).count() context = { "profile": profile, "post_count": … -
NoReverseMatch at /reset-password/... in Django
I'm new to Django; I get this error when I want to reset a user's password by using a code that is set to account in db. views class ResetPassword(View): def get(self, request, active_code): user : User = User.objects.filter(email_active_code__iexact=active_code).first() if User is None: return redirect(reverse('login-page')) else: reset_password_form = ResetPasswordForm() context={ 'reset_password_form' : reset_password_form, 'title': 'Reset My Password' } return render(request, 'account_module/reset_password.html', context) urls path('reset-password/<str:active_code>', views.ResetPassword.as_view(), name='reset_password') html <form action="{% url "reset_password" %}"> {% csrf_token %} {{ reset_password_form.label_tag }} {{ reset_password_form }} {{ reset_password_form.errors }} <button type="submit" class="btn btn-default">Reset My Password</button> </form> the active code that is set Would someone please take a look and help? Thank you. -
I'm working with a tutorial and I got the error: The view main.views.home didn't return an HttpResponse object. It returned None instead
Im creating a very simple Django Website but I keep getting the same problem. my views.py file is `from django.shortcuts import render from django.http import HttpResponse from .models import ToDoList, Item Create your views here. def index(response, id): ls = ToDoList.objects.get(id=id) return render(response, "main/base.html", {}) def home(response): return render(response, "main/home.html", {})` Ive checked all necesary indentation and syntax. Im actually following an online tutorial but I think there's the problem is from my code