Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - The current url didn’t match any of the these
I have Django 4.0.4 I tried the following url : http://127.0.0.1:8000/cp2/sbwsec/1076/o2m/section/wseclmts/47/p/element/sbwblmnt/1077/ but it gives me error Page not found (404) The current path, cp2/sbwsec/1076/o2m/section/wseclmts/47/p/element/sbwblmnt/1077/, didn’t match any of these. Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: I have 1370 patterns - where the correct pattern is on the line 268 as you can see from the debug exception page cp2/ (?P<parent_element_name>\w+)/(?P<parent_id>\d+)/p/(?P<parent_field>\w+)/sbwblmnt/(?P<item_id>\d+)/$ [name='sbwblmnt_epec'] Thank you for the help -
genericviewset(mixins.UpdateModelMixin)
I have a problem with my code, Am Trying to write a generic view set in DRF for updating my view but I got an error. This is my portfolio model: class Portfolio(models.Model): name = models.CharField(max_length=50, blank=False, null=True, default='portfolio') user = models.ForeignKey('accounts.User', on_delete=models.DO_NOTHING, related_name='investor') assets = models.ManyToManyField(Assets, related_name='portfolio_assets') This is my serializer: class PortfolioSerializer(serializers.ModelSerializer): class Meta: model = Portfolio fields = ['id', 'name', 'user', 'assets'] and at the end my view and URL: class PortfolioUpdateDetailDestroy(viewsets.GenericViewSet, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin ): queryset = Portfolio.objects.all() serializer_class = PortfolioSerializer def get(self, request, pk): return self.retrieve(request, pk) def put(self, request, pk): return self.update(request, pk) router = DefaultRouter() router.register("Portfolio_Detail", PortfolioUpdateDetailDestroy, basename="Portfolio_Detail") urlpatterns = [ path('', include(router.urls))] when I try to update an object I have to give everything to fields again, I mean I have to update all fields together, if I want to update only the name field I got this error "user": [ "Invalid pk \"0\" - object does not exist."], "assets": [ "Invalid pk \"0\" - object does not exist."] -
xmlrpc.py not found error while using supervisor in docker
hello guys im writing a docker file and compose with ubuntu 20.04 and try to install supervisor inside it docker file : ... RUN apt-get install -y supervisor COPY backend_supervisord.conf /etc/supervisor/conf.d/ docker compose : command: bash -c "python manage.py migrate && supervisorctl reread && supervisorctl reload&&supervisorctl start daphne" daphne is my program name in my supervisor conf file i really did not realize what is happening here and this is the err msg : error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /usr/local/lib/python3.8/dist-packages/supervisor/xmlrpc.py line: 560 -
Django rest framework dictionary is full of escape characters
I have updated a column in the database postgres and it looks like this in the Database [{"author_name": "palmina petillo", "rating": " ", "text": "We really loved it! Food is sophisticated but not pretentious. Service is excellent and price is adequate for Michelin standards and quality of the ingredients. French influence + local produce. 100% recommended!!"}, {"author_name": "Ann dunphy", "rating": " ", "text": "Excellent staff\nFood beautiful"}, {"author_name": "Kieran Aherne", "rating": " ", "text": "Second time eating here and I have to say the food just keeps getting better. Couldn t fault the food or the service. Top quality restaurant and will definitely be back for a 3rd time, eventually \u263a\ufe0f"}, {"author_name": "Deirdre Watson", "rating": " ", "text": "Our party had a delicious and lovely dining experience at Campagne on Thursday evening.. the welcome, food and accompanying wines as recommended with our food by the professional staff are second to none.. I would highly like everyone to try and enjoy this experience just once"}, {"author_name": "Mary Irwin", "rating": " ", "text": "Delighted to enjoy a meal in Campagne again - if anything it was better than we remembered. Excellent staff, delicious food and great buzz. Looking forward to our next visit … -
Uncaught TypeError & memory leak error in materia-table & django
I am working a project with reactjs & material-table for the frontend and Django for the backend. Currently, I am performing CRUD operations using axios on my material-table. However, I have encountered a difficulty when doing the delete request. The table looks like this: enter image description here Everything went well when I delete the 2nd & 3rd row: enter image description here But when I delete the "last row", a bunch of error pops up in console log: DataWorker.js:68 Uncaught TypeError: Cannot read properties of undefined (reading 'id') react-dom.development.js:11102 Uncaught TypeError: Cannot read properties of undefined (reading 'id') react-dom.development.js:88 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method. This is my DataWork.js: export default function DataWorker() { const [entries, setEntries] = useState({ data: [ { id: "", position: "", defect: "", tool: "" } ] }); const [state] = React.useState({ columns: [ { title: "Position", field: "position", width: 150, // lookup: { 1: "Position 1", 2: "Position 2", 3: "Position 3"}, cellStyle: { textAlign: "center" } }, { title: "Defect Type", field: … -
Where are captcha values usually stored?
Long story short, I made a captcha that can generate from 26letters + digits using pillow that looks cool, Now I need a way to verify that captcha value without the using of database A practical and easiest way of doing this is with sessions, It does not require read or write to the DB, But since cookies are stored on the frontend, I don't think this is a very secure way of storing the value of the captcha, I want the attacker to actually decode captcha using machine learning and not session value which I assume would be easier for the attacker to do. Is there a way to hot verify them? Even with the use of APIs it changes nothing, In this case APIs would be just like sessions and the only difference would be sending value to another function vs sending value to another url. Are there any other alternatives to where these "single use only values" are stored? Or Is there truly a way to hot verify I haven't thought of? -
Payment subscription using PayPal and Django is this possible if the user does'nt have account with paypal
I develop an app using Django and i want a user to be able to pay me $5 a months. i found STRIPE but it's not working in my country. I want a user to be able to pay me with credit card or debit card. but is it possible for a user to be able to pay me without opening paypal account, or it is possible for a user to open an account with paypal before he/she can pay me. I get confused. -
How to create one to many generic relation between objects in Django
I have these two models: How do I correctly set the relationship so I can do backward queries? class Client(models.Model): city = models.CharField(max_length=16) worker = models.ForeignKey( "Worker", null=True, default="1", on_delete=models.SET_DEFAULT, related_name="assigned_workers", ) class Meta: abstract = True And: class Worker(models.Model): first_name = models.CharField(max_length=16) last_name = models.CharField(max_length=16) gender = models.CharField(max_length=1) What I want to do is set up the models in a way I can do the following queries: Query the clients assigned to a worker using the worker object. Something like this: Worker.objects.assigned_workers.all() -
Wagtail Tagging: How to keep choosen tag order?
I have a Page Model with Tags in it. class ProjectPage(AbstractContentPage): tags = ClusterTaggableManager(through=PageTag, blank=True) content_panels = AppPage.content_panels + [ FieldPanel('tags'), ... and in the template {% if page.tags.count %} <div class="width2"> {% for tag in page.tags.all %} {# Loop through all the existing tags #} &#9654; <a href="{{ self.get_parent.url }}?tag={{ tag.slug }}">{{ tag }}</a><br /> {% endfor %} </div> {% endif %} If The Editor adds 4 Tags to the Tags Field Panel these Tags should appear in same order in the template. That might work if all tags are newly created in the database but Unfortunately it seems that in the many2many table they get stored always in the order the tags where first created and not in the order they where written in the FieldPanel. -
Static file doesn't exist and html-file doesn't work properly
output: 'static' in the STATICFILES_DIRS setting does not exist. I've tried os.path.join(BASE_DIR, '/static'), but it is doesn't work. I didn't have this problem before adding new html-file and I didn't change static-folder. Setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static' ] In static-folder I have placed folder 'main' and css-file. base.html I also have a problem with the file. It doesn't work correctly. Guess I didn't wire it right. <a href="{% url 'make_vision' %}"><li><button class="btn btn-info"><i class="fas fa-plus-circle"></i>Добавить запись</button></li></a> make_vision.html {% extends 'main/base.html' %} {% block title %}Добавление записей{% endblock %} {% block content %} <div class="features"> <h1>Форма по добавлению статьи</h1> <form method="post"> <input type="text" placeholder="Название статьи" class="form-control"><br> <input type="text" placeholder="Анонс статьи" class="form-control"><br> <textarea class="form-control"><br> <input type="date" class="form-control"><br> <button class="btn btn-success" type="submit">Добавить статью</button> </form> </div> {% endblock %} urls.py urlpatterns = [ path('', views.news_home, name='news_home'), path('make_vision', views.make_vision, name="make_vision"), ] views.py def news_home(request): news = Articles.objects.order_by('-data')[:2] return render(request, 'news/news_home.html', {'news': news}) def make_vision(request): return render(request, 'news/make_vision.html') When I started the server, I got an error that this path does not exist. -
IntegrityError - Exception Value with DB relations in Django on form submission
IntegrityError - Exception Value: null value in column "username_id" of relation "post_comment" violates not-null constraint I'm building out a comments section for the post app and I'm coming across this error that I can't resolve. This is arising once I submit the comment.body with the form loaded in the views. If possible I would like the authenticated user to automatically be assigned to the username of the comment model as well as the date_added. models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) username = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return f"{self.post.title} - {self.username}" def get_absolute_url(self): return reverse("new-comment", kwargs={"slug": self.post.slug}) class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=80) slug = models.SlugField(max_length=250, null=True, blank=True) post_description = models.TextField(max_length=140, null=True, blank=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) main_image = models.ImageField(upload_to="post_pics") is_recipe = models.BooleanField() ingredients = models.TextField(blank=True, null=True) recipe_description = models.TextField(blank=True, null=True) cooking_time = models.CharField(max_length=20, blank=True, null=True) likes = models.ManyToManyField(User, related_name="post_likes") loves = models.ManyToManyField(User, related_name="post_loves") drooling_faces = models.ManyToManyField(User, related_name="post_drooling_faces") favorite_posts = models.ManyToManyField( User, related_name="favorite_posts", default=None, blank=True ) forms.py class NewCommentForm(forms.ModelForm): class Meta: model = Comment fields = [ "body" ] views.py def add_comment(request,slug): if request.method == "POST": form = NewCommentForm(request.POST, request.FILES) if form.is_valid(): form.instance.post_slug = {'slug': slug} … -
Getting indentation issue in Django while trying to pass context [duplicate]
I'm working on a project for a job interview and this is my first experience with django - I'm trying to upload an image to a dropzone and display it on a separate page. I've made the dropzone and the image upload creates a model, but when trying to pass the model into the render of the other page, I get an indentation issue. Here's what my views.py looks like: from django.http import HttpResponse, JsonResponse from django.shortcuts import render from .models import Drop def index(request): return render(request, 'dragAndDrop/index.html') def upload_file(request): if request.method == 'POST': myFile = request.FILES.get('file') Drop.objects.create(image=myFile) return HttpResponse('') return JsonResponse({'post':'false'}) def display(request): drops = Drop.objects.all() context = { 'drops': drops, } return render(request, 'dragAndDrop/display.html', context) This is the error that I'm getting: File "/mnt/c/Users/johnf/projUR/mysite/dragAndDrop/urls.py", line 2, in <module> from . import views File "/mnt/c/Users/johnf/projUR/mysite/dragAndDrop/views.py", line 20 return render(request, 'dragAndDrop/display.html', context) ^ TabError: inconsistent use of tabs and spaces in indentation If anyone can offer any assistance, that would be greatly appreciated! -
get first object from every type in Django query
I have a query like this: objs = MyModel.objects.filter(type__in=[1,2,3,4]).order_by('-created_at') is there a way to fetch only the first item of every type and not all the items with these types by adding a condition to this query? -
django name 'form' is not defined
django name 'form' is not defined. i have a problem with loginpage, i want that users will register and login. the register page work but, when i enter a username and password of the register page, i have that problem: "name 'form' is not defined". Attaches photos. Thanks for all the answers. error: error views.py-login: login -
Django URL mapping Error : Using the URLconf defined in proctor.urls(i.e project.urls), Django tried these URL patterns, in this order:
Basically, my project has three apps: 1.logreg (for login/register) 2.usersite 3.adminsite Since, I am a beginner, I am just testing the code for the admission table only which is in usersite app. Admission Table When I try to go to the next page after filling the details of admission table through the form. I am getting an error like this: Using the URLconf defined in proctor.urls, Django tried these URL patterns, in this order: [name='login'] login [name='login'] registration [name='registration'] logout [name='logout'] usersite adminsite admin The current path, submit_admission/, didn’t match any of these. This is the urls.py of my project proctor from xml.etree.ElementInclude import include from django.contrib import admin from django.urls import path,include #from usersite.views import admission,submit_admission urlpatterns = [ path('',include('logreg.urls')), path('usersite',include('usersite.urls')), path('adminsite',include('adminsite.urls')), path('admin', admin.site.urls), #path('submit_admission/', submit_admission, name='submit_admission'), ] This is the urls.py of the usersite app from django.urls import path from.import views from django.contrib.auth import views as auth_views from usersite.views import submit_admission urlpatterns = [ #path('', views.admission, name='admission'), path('', views.admission, name='admission'), path('submit_admission/', submit_admission, name='submit_admission'), path('academicdetails', views.academic, name='academic'), path('achievementdetails', views.achievements, name='achievements'), path('personalinfodetails', views.personalinfo, name='personalinfo'), path('unauth', views.unauthorised, name='unauth'), path('logout', views.logout_view, name='logout'), path('logreg/login/', auth_views.LoginView.as_view()), ] This is the views.py of the usersite app Ignore the code after def submit_admission(request): from django.http import … -
Heroku Django Get Client IP Address
I have a django application running on heroku and I can't get the client's IP address. Every time I make a request on my heroku django app, the IP address keeps showing different. Like 10.x.x.x etc. It is not client public IP. It looks as if the same user is logging in from different IP addresses. I can't get the real client IP addresses. print(self.request.META.get('REMOTE_ADDR')) it is not working.every time this code runs it gives a different IP address. How can I get the client's IP address on view of my django project? -
Django Rest Framework and React File Transfer Project
I'm creating a file transfer project using Django rest framework and React JS. I need some help. models.py class UploadFile(models.Model): file_name = models.CharField(max_length=50) file = models.FileField(upload_to='Uploads/') created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.file_name serializers.py class UploadFileSerializer(serializers.ModelSerializer): class Meta: model = UploadFile fields = '__all__' views.py class UploadFileViewSet(viewsets.ModelViewSet): queryset = UploadFile.objects.all() serializer_class = UploadFileSerializer there are two questions (1) I want to upload multiple files in that model field. And also zip them. (2) I want to generate a download link for file field. -
Bad request in django when post with flutter
I am trying to do a post request with image and text. I followed a video but the endpoint used with fakeapi is working fine with flutter. My api is working fine with postman but when done with flutter it shows bad request. Help me!! Model.py class TestImageUpload(models.Model): image = models.ImageField(upload_to = "products/",blank=True, null=True) Serializer.py class TestImage(serializers.ModelSerializer): class Meta: model = TestImageUpload fields = "__all__" Views.py class TestImageView(ListCreateAPIView): try: serializer_class = TestImage def perform_create(self, serializer): serializer.save() response_msg = {'error': False} return Response(response_msg) except: response_msg = {'error': True} urls.py path('addimage/', TestImageView.as_view(),name= 'add_image_view'), Flutter Code class UploadImageScreen extends StatefulWidget { static const routeName = '/image-upload'; const UploadImageScreen({Key? key}) : super(key: key); @override State<UploadImageScreen> createState() => _UploadImageScreenState(); } class _UploadImageScreenState extends State<UploadImageScreen> { File? image; final _picker = ImagePicker(); bool showSpinner = false; Future getImage() async { final pickedFile = await _picker.pickImage(source: ImageSource.gallery, imageQuality: 80); if (pickedFile != null) { image = File(pickedFile.path); setState(() {}); } else { print("no image selected"); } } Future<void> uploadImage() async { setState(() { showSpinner = true; }); var stream = http.ByteStream(image!.openRead()); stream.cast(); var length = await image!.length(); var uri = Uri.parse('http://10.0.2.2:8000/api/addimage/'); var request = http.MultipartRequest('POST', uri); // request.fields['title'] = "Static Tile"; var multiport = http.MultipartFile('image', stream, length); … -
The best setup for Gunicorn + Django or why workers and threads at the same time degrade performance?
On my backend I use Django + Gunicorn. I use Nginx too but that does not matter for this question. Db is Postgres. I want to improve performance of my application (i have some api points with heavy i/o operations that degrade the whole backend), so i decided to survey how gunicorn can help me with that. I have read these SOF answers, and these, and this very nice article and many more but in reality i'm getting rather strange results. I created this point to experiment with Gunicorn config (very simple one): As you can see i have created some i/o operation inside my view. I want to optimize the amount of RPS and to measure that i'm going to use WRK with basic config 2 threads with 10 connections each. Lets start gunicorn with that config (basic simplest sync without any workers): Then i'm getting these results: Ok, that correlates with reality because this api point usually response in 50-100ms. Look: Now lets increase amount of workers to 8: I'm getting: Oops: i supposed that i'll get x8 performance and 160 RPS, because as i thought, new worker works in separate parallel process. 1. So the first question … -
Traefik Django & React setup
Recently I came across server configuration using GitLab CI/CD and docker-compose, I have two separated repositories one for Django and the other for React JS on Gitlab. The Django Repo contains the following production.yml file: version: '3' volumes: production_postgres_data: {} production_postgres_data_backups: {} production_traefik: {} services: django: &django build: context: . dockerfile: ./compose/production/django/Dockerfile image: one_sell_production_django platform: linux/x86_64 expose: # new - 5000 depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start labels: # new - "traefik.enable=true" - "traefik.http.routers.django.rule=Host(`core.lwe.local`)" postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: one_sell_production_postgres expose: - 5432 volumes: - production_postgres_data:/var/lib/postgresql/data:Z - production_postgres_data_backups:/backups:z env_file: - ./.envs/.production/.postgres traefik: # new image: traefik:v2.2 ports: - 80:80 - 8081:8080 volumes: - "./compose/production/traefik/traefik.dev.toml:/etc/traefik/traefik.toml" - "/var/run/docker.sock:/var/run/docker.sock:ro" redis: image: redis:6 This is work perfectly using the Traefik, I have also the following code for React JS repo: version: '3.8' services: frontend: build: context: ./ dockerfile: Dockerfile expose: - 3000 labels: # new - "traefik.enable=true" - "traefik.http.routers.django.rule=Host(`lwe.local`)" restart: 'always' env_file: - .env Now I don't know how to connect both Django and React Js Repo using the Traefik and also how the CI/CD configuration should be, the following is the CI/CD configuration for Django Repo (I omitted unnecessary info and just include the deploy … -
get_throttling_function_name: could not find match for multiple
Traceback (most recent call last): File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube_main_.py", line 181, in fmt_streams extract.apply_signature(stream_manifest, self.vid_info, self.js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\extract.py", line 409, in apply_signature cipher = Cipher(js=js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\cipher.py", line 29, in init self.transform_plan: List[str] = get_transform_plan(js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\cipher.py", line 198, in get_transform_plan return regex_search(pattern, js, group=1).split(";") File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\helpers.py", line 129, in regex_search raise RegexMatchError(caller="regex_search", pattern=pattern) During handling of the above exception (regex_search: could not find match for $x[0]=function(\w){[a-z=.(")];(.);(?:.+)}), another exception occurred: File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Mohd Athar\Desktop\Django\New folder\youtubedownloader\downloadapp\views.py", line 13, in index stream = video.streams.get_highest_resolution() File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube_main.py", line 296, in streams return StreamQuery(self.fmt_streams) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube_main_.py", line 188, in fmt_streams extract.apply_signature(stream_manifest, self.vid_info, self.js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\extract.py", line 409, in apply_signature cipher = Cipher(js=js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\cipher.py", line 29, in init self.transform_plan: List[str] = get_transform_plan(js) File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\cipher.py", line 198, in get_transform_plan return regex_search(pattern, js, group=1).split(";") File "C:\Users\Mohd Athar\AppData\Local\Programs\Python\Python37\lib\site-packages\pytube\helpers.py", line 129, in regex_search raise RegexMatchError(caller="regex_search", pattern=pattern) Exception Type: RegexMatchError at / Exception Value: regex_search: could not find match for $x[0]=function(\w){[a-z=.(")];(.);(?:.+)} -
Preview of loaded CSV file with many columns
When the user drops the csv file in drag and drop section, He should be able to see a preview of that CSV file, but the problem is the csv file user can have many columns for example:- In the above image u can see due to the CSV file had many(23) columns it is now too long for my web page. Is it possible to contain it in a div tag or adding a scrollbar on the bottom of the table. I tried papaparse too but JS file of papaparse:- function Upload(){ var file = document.getElementById("fileUpload").value; data = Papa.parse(file, { worker: true, step: function(results) { Heiho(results.data); } }); } htmlfile of papaparse:- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="heiho.css" /> <title>Document</title> </head> <body> <input type="file" id="fileUpload" /> <input type="button" id="upload" value="Upload" onclick="Upload()" /> <hr /> <div id="dvCSV"> </div> <script src="heiho.js"></script> <script src="https://cdn.jsdelivr.net/gh/mholt/PapaParse@latest/papaparse.min.js"></script> <script src="test.js"></script> </body> </html> Note:- I am not including paparse js and css file as it is too big u can download the file from the link below. What is papaparse? -
Django remember me error didn't return an HttpResponse object
I create forms.py like this. class LoginForm(forms.Form): username = forms.CharField(max_length=100,required=True) password = forms.CharField(max_length=32,required=True,widget=forms.PasswordInput) remember = forms.BooleanField(label="Remember me") In views.py I create function loginForm like this. def loginForm(request): if request.method == 'POST': form=LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') remember = form.cleaned_data.get('remember') user=auth.authenticate(username=username,password=password) if user is not None: if remember == "on": request.session.set_expiry(1209600) auth.login(request, user) return redirect('/main') else: message = "User not found" messages.info(request, message) form = LoginForm() return render(request,'login.html',{'form':form}) else: form = LoginForm() return render(request,'login.html',{'form':form}) In login.html I create form like this. <form action="loginForm" method="post"> <h2>Login</h2> <p> <div class="mb-3"> {{form|crispy}} {% csrf_token %} </div> <button type="submit" class="btn btn-primary">OK</button> </p> </form> If I not check Remember me it show this message. It's not remember me button. Please check this box if you want to proceed when I login it show error. ValueError at /loginForm The view device.views.loginForm didn't return an HttpResponse object. It returned None instead. If I remove this line it have no error. if remember == "on": request.session.set_expiry(1209600) How to create login form with remember me? -
Django form login error didn't return an HttpResponse object
I create forms.py like this. class LoginForm(forms.Form): username = forms.CharField(max_length=100,required=True) password = forms.CharField(max_length=32,required=True,widget=forms.PasswordInput) remember = forms.BooleanField(label="Remember me") In views.py I create function loginForm like this. def loginForm(request): if request.method == 'POST': form=LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') remember = form.cleaned_data.get('remember') user=auth.authenticate(username=username,password=password) if user is not None: if remember == "on": request.session.set_expiry(1209600) auth.login(request, user) return redirect('/main') else: message = "User not found" messages.info(request, message) form = LoginForm() return render(request,'login.html',{'form':form}) else: form = LoginForm() return render(request,'login.html',{'form':form}) In login.html I create form like this. <form action="loginForm" method="post"> <h2>Login</h2> <p> <div class="mb-3"> {{form|crispy}} {% csrf_token %} </div> <button type="submit" class="btn btn-primary">OK</button> </p> </form> If I not check Remember me it show this message. It's not remember me button. Please check this box if you want to proceed when I login it show error. ValueError at /loginForm The view device.views.loginForm didn't return an HttpResponse object. It returned None instead. How to create login form ? -
I have two tables named as intermediate_transaction and merchant_table. I have to find who is inactive user among all the users
I have to find the inactive users who is not doing any transaction in a week. If a user is doing transaction in 7 days atleast one then he is active user otherwise inactive.