Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connect django with postgres db which is in clojure platform
I have a clojure server which is a game server and need to communicate with django channels. Do anyone have any idea how to proceed with the above requirement? Clojure platform server is already up. Next need to establish a communication using python. Expecting suggestions to solve the issue Thanks in advance Details of project Django version:2, Server:Postgres in clojure environment. Need to connect django to postgres inorder to get some data values like time samples,userlogin time etc. How can I connect the django to postgres db which is in clojure platform? -
Docker connection error 'Connection broken by NewConnectionError'
I am new to docker i just installed it and did some configuration for my django project. when i am running docker build . i am getting these error whats wrong here? WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x7f1363b604f0>: Failed to establish a new connection: [Errno -3] Try again')': /simple/django/ Dockerfile FROM python:3.8-alpine MAINTAINER RAHUL VERMA ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR app COPY ./app /app RUN adduser -D user USER user requirements.txt file Django==2.2 djangorestframework==3.11.0 -
Django Reverse for 'post-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['post\\/(?P<pk>[0-9]+)\\/$']
I am working on a personal fitness blog app and am running into this error when trying to allow a user to "comment" on a post. Python 3.6.4, Django 3.0.2 models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') comment_id = models.AutoField(primary_key=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE) content = models.TextField(max_length=1000, blank=False, default="") date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['date_posted'] def __str__(self): return 'Comment {} by {}'.format(self.content, self.author.first_name) urls.py urlpatterns = [ # path('', views.home, name="main-home"), path('', PostListView.as_view(), name="main-home"), path('admin/', admin.site.urls), path('register/', views.register, name="register"), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name="main-about"), path('search/', SearchResultsView.as_view(), name="main-search"), path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'), ] post_detail.html {% extends "main/base.html" %} {% block content %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ object.author }}</a> <small class="text-muted">{{ object.date_posted }}</small> </div> <h2 class="article-title"><u>{{ object.title }}</u></h2> <p class="article-content">{{ object.content }}</p> <div class="row"> <div class="col-xs-6 col-sm-4"><b>Distance: </b>{{ object.distance }} miles</div> <div class="col-xs-6 col-sm-4"><b>Time: </b>{{ object.time }} minutes</div> <div class="clearfix visible-xs-block"></div> <div class="col-xs-6 col-sm-4"><b>Pace: </b>{{ object.pace }} mins/mile</div> </div> </div> </article> <hr> <a class="btn btn-default" href="{% url 'add_comment_to_post' pk=post.pk %}">Add comment</a> {% for comment in post.comments.all %} <div class="comment"> <div class="date">{{ comment.date_posted }}</div> <strong>{{ comment.author }}</strong> <p>{{ comment.content|linebreaks }}</p> </div> {% empty %} <p>No comments here … -
Django connect to MSSQL - django/sql_server - pyodbc
I've tried to install django_pyodbc but when I try make migrations got the error: django.core.exceptions.ImproperlyConfigured: Django 2.1 is not supported. My setttings.py: 'Test_DB': { 'ENGINE': 'django_pyodbc', 'NAME': 'TEST', 'HOST': '127.0.0.1', 'USER': 'sa', 'PASSWORD': '123456', 'OPTIONS': { 'driver': 'ODBC Driver 12 for SQL Server', }, }, When I try to install django-pyodbc-azure, I got the other error: Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' My setttings.py: 'Test_DB': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'TEST', 'HOST': '127.0.0.1', 'USER': 'sa', 'PASSWORD': '123456', 'OPTIONS': { 'driver': 'ODBC Driver 12 for SQL Server', }, }, So what should I do so that I can connect the SQL Server 2012? -
Setting username in steam OpenID authentication with Django Allauth
I'm trying to configure a new django application to use Steam's OpenID authentication. The issue i'm running into is that when a new user sign's in (no form to allow them to customize username/specify email address) the something (either allauth or django.contrib.auth) defaults their User object's username to user. That field is unique... so a 2nd user can't login. I can't figure out what/where the new user object is created so we can customize that field. We want it to pull from extra_data['personaname']) ideally. -
django pass argument from view to form only once
I have an OTP generator mechanism, whereby in GET method, a unique 4-dit OTP is generated and is sent to the OTPAuthenticationForm() as follows: views.py if request.method == 'GET': otp = 'abcd' # code to send otp via mail form = OTPAuthenticationForm(request=request, otp=otp) # this is how the OTP is passed only once. return .... elif request.method == 'POST': form = OTPAuthenticationForm(request.POST, request=request) if form.is_valid(): # the clean_field() method is not invoked/throws error. print("OTP is valid") else: print("OTP is invalid") forms.py from django.contrib.auth.forms import AuthenticationForm class OTPAuthenticationForm(AuthenticationForm): otp = forms.CharField(required=True, widget=forms.TextInput) def __init__(self, otp, *args, **kwargs): self.otp = kwargs.pop("otp") super(OTPAuthenticationForm, self).__init__(*args, **kwargs) def clean_otp(self): if self.otp!= self.cleaned_data['otp']: raise forms.ValidationError("Invalid OTP") How should the generated_otp be passed only once to the OTPAuthForm() so that it could be validated against the user input OTP (OTP received via email). -
Streaming http response does not show full contents
I am creating a website using django. I load web pages using StreamingHttpResponse, more information is here. My views code: from django.http.response import StreamingHttpResponse class SearchNews: def get(self, request): response = StreamingHttpResponse(self._load_stream(request)) return response def _load_stream(self, request): query = request.GET.get('query', '') yield loader.get_template('news_results_part1.html').render({ 'request': request, 'query': query, }) api = SearchNews() results = api.search(query) yield loader.get_template('news_results_part2.html').render({ 'request': request, 'query': query, 'results': results, }) I have two html parts, first part only includes header and the second part contains the search results. The first html part code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <title> {{ query }} </title> <style> {% include 'internal_static/css/search_results.css' %} </style> </head> <body> <div class="border-bottom clearfix"> <div class="max-width-large w-100 padding-left-lg"> {% include 'header.html' with query=query %} </div> </div> and the second html part code: <div> {% if extra_info.correct_query %} <div class="correct-query-wrapper padding-left-lg max-width-large pt-3 clear-both w-100 text-right"> <span class="float-right text-danger">did you mean?</span> <span class="p-2 font-italic"> <a href="{% url 'search' %}?query={{ correct_query }}"> {{ correct_query }} </a> </span> </div> {% endif %} <div class="padding-left-lg clearfix result-cart-wrapper max-width-large clear-both"> {% include 'result_carts.html' with query=query %} </div> </div> </body> </html> When I run the project in localhost everything is ok and browser shows the full contents of … -
HOW TO RETRIEVE DATA FROM RELATIONAL DATABASE IN DJANGO
this Child_detail model is related to clinical_test model class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) Religion = models.CharField(max_length = 50) Date_of_birth = models.DateField() Current_Address = models.CharField(max_length = 50) def __str__(self): return self.Firstname this is the clinical_test model by which i want to retrieve data from class Clinical_test(models.Model): child = models.ForeignKey(Child_detail, on_delete = models.CASCADE) Test_type = MultiSelectField(max_length=100,choices=test_type,max_choices=30) Test_date = models.DateTimeField() Next_schedule_test_date = models.DateField(blank=True) def __str__(self): return str(self.Test_type) this is my views.py def more_about_child(request,pk): child = get_object_or_404(Child_detail,pk=pk) context={ 'child':child, } return render(request,'functionality/more.html',context) Here is my template.html by which will be used to show data that retrieved <div class="container" style="margin-top:20px"> <div class="col-md-12" style="background-color:rgb(44, 44, 3);color:white"> <h4>clinical test</h4> </div> <div class="row"> <div class="col-md-3"> <p>First name: <b>{{clinical.child.Test_date}}</b> </p> </div> <div class="col-md-3"> <p>Last name: <b>{{child.Lastname}}</b> </p> </div> <div class="col-md-3"> <p>Tribe: <b>{{child.Tribe}}</b> </p> </div> <div class="col-md-3"> <p>Religion: <b>{{child.Religion}}</b> </p> </div> <div class="col-md-3"> <p>Religion: <b>{{child.Date_of_birth}}</b> </p> </div> <div class="col-md-3"> <p>Religion: <b>{{child.Current_Address}}</b> </p> </div> </div> </div> -
How to pass the file from request to do multipart upload to S3
I am trying to upload a file around 10GB to S3. I am using Django. I found this link on how to multipart the file to S3 upload https://gist.github.com/teasherm/bb73f21ed2f3b46bc1c2ca48ec2c1cf5 which really works but I have not yet integrated it in my view. So I am using multi-upload part to S3. I am uploading the file from Browser, then get the files from the Django views.py, how can I get the file from the request and pass it since it asks for the file path. Please give me some light. Below is my code. JQuery: upload.js var upload_xhr = $.ajax({ url: url, type: 'POST', cache: false, contentType: false, processData: false, data: form_data, async: true, xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = Math.floor((evt.loaded / evt.total) * 100) + '%'; let upload_size = $('div[progress-marker=' + upload_counter +']')[0]; $(upload_size).attr('style', 'width:' + percentComplete); let progress_status = $('#' + upload_counter+ '.progress-status').text(percentComplete); } }, false); return xhr; }, success: function(res) { console.log('success') }, error: function(xhr, status, thrownError){ console.log(thrownError) } }); views.py def post(self, request, *args, **kwargs): files = request.FILES.getlist('file') folder_parent_id = request.POST.get('folder_parent_pri') file_name = request.POST.get('file_name_pri') response = 'failed' print(files) with open(files[0], "rb") as f: i = 1 data … -
Content not appear in Django CMS
i follow tutorial ini here, http://support.divio.com/en/articles/49026-6-configuring-content-and-navigation Remove the paragraphs including their tags, and replace them with a pair of Django content block tags: <!-- Main Content --> <div class="container"> <div class="row"> <div class="col-lg-8 col-md-10 mx-auto"> {% block content %}{% endblock %} </div> </div> </div> Based on the tutorial , this code should show content from default.html . But it doesnt i dont know where is the mistake, im beginer of Django CMS and there is few tutorial out there -
How to preload variables in ./manage.py shell in Django 3.0.3+?
I do most of my work through the shell in django. I'd like to preload imports and variables so as to keep myself from having to type from app.models import * -
error NOT NULL constraint failed: customize form django-all-auth with 3 models (foreign key)
I'm learning django and in one of my challenges I want to add 3 foreign keys to the sign up form django-all-auth, but I have the error: NOT NULL constraint failed: advertising_profile.user_id please can you help me and explain what Im failing. I am trying to save this information for the registration form ==========views.py================== def register(request): form = CustomSignUpProfileModelForm() if request.method == "POST": form = CustomSignUpProfileModelForm(data=request.POST) if form.is_valid(): #user = form['customSignUp'].save(commit=False) profile = form.save(commit=False) profile.user = request.user profile.save() #user = form.save() if profile is not None: do_login(request, user) return redirect('welcome') #form.fields['username'].help_text = None #form.fields['password1'].help_text = None #form.fields['password2'].help_text = None return render(request,"account/signup.html",{'form':form}) ==========end views.py====================== =========forms.py====================== from django import forms from django.forms import ModelForm from betterforms.multiform import MultiModelForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from .models import Profile, Region, Commune, Nation class CustomSignUp(UserCreationForm): username = forms.EmailField(label="Correo electrónico") class Meta: model = User fields = ["username","password1","password2"] class CustomSignIn(AuthenticationForm): username = forms.EmailField(label="Correo Electrónico") class Meta: model = User fields = ["username","password"] class Profile(forms.ModelForm): class Meta: model = Profile fields = ["name","last_name","mother_last_name","phone","region","commune","nation"] class Region(forms.ModelForm): class Meta: model = Region fields = ["name"] class Commune(forms.ModelForm): class Meta: model = Commune fields = ["name"] class Nation(forms.ModelForm): class Meta: model = Nation fields = ["name"] … -
Customer user model error; ModuleNotFoundError: No module named 'account'
I am very new to using Django and I am trying to make a custom user model for my Android app. Unfortunately the custom user class is necessary. I keep encountering this error ModuleNotFoundError: No module named 'account' [26/Feb/2020 02:38:13] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 132779 I have been searching but cannot find how to fix this. My app is called capp and below are my files my models.py file from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class AccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, date_of_birth, custom_pin, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, date_of_birth=date_of_birth, custom_pin=custom_pin) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, date_of_birth, password): user = self.create_user( email=self.normalize_email(email), password=password, first_name=first_name, last_name=last_name, date_of_birth=date_of_birth) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True, blank=True) first_name = models.CharField(verbose_name="first name", max_length=60) last_name = models.CharField(verbose_name="last name", max_length=60) custom_pin = models.CharField(verbose_name="pin", max_length=4) date_of_birth = models.CharField(verbose_name="date of birth", max_length=8) # date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) # last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = AccountManager() def __str__(self): return self.email # … -
NOT NULL constraint failed, on mixin forms
thanks for your time. i've got a model(Servicos) that got a linked images model (Imagens) to his. The Servicos model is a foreign key to a model call (Parceiros) and Parceiros is linked to the user Model. my user_create and parceiros_create views works fine. although the Servicos model forms is displayed with the ImageFormSet (a form to add 4 images at once) and when i try to save the Servicos Form (at admin works fine) but on template i get this error : NOT NULL constraint failed: services_servicos.parceiro_id and point to the line : service.save() i've already tried to set the service.save(parceiros=Parceiros.id), change the foreign key to user (on a test project), and quite other things it should save the Servicos object to the Parceiros instance that is logged in. i'm not quite shure if am i calling the Parceiro object right models.py: get_user_model = User class Parceiros (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nome = models.CharField(max_length=200) endereco = models.TextField(max_length=400, blank=True) responsavel = models.CharField(max_length=100) tel = PhoneField(max_length=12) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) ativo = models.BooleanField(default=False) def get_queryset(self): queryset = super(Parceiros, self).get_queryset() return queryset def __str__(self): return '%s %s' % (self.user, self.nome) def get_absolute_url(self): return reverse('parceiro_detail2', kwargs={'pk': self.pk}) class Servicos … -
Db shell to database in Flask
I'd like to access the database in the database with a shell command in Flask. Is there any equivalent command in Flask to python manage.py dbshell in Django? -
Add "IgnoreCase" and "Contains" to Django-Filter
Is there a way that i can add Ignore-Case and Contains functionalities to Django-Filter ? -
Custom Django url for users
Hi I have been trying to create customer url for my users but it does not work. I keep getting NoReverseMatchError This is my user_login views.py def user_login(request): ''' Using different method for getting username, tried this and didnt work either ''' #if request.user.is_authenticated(): #return HttpResponseRedirect('main:home') if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request,user) messages.info(request, "Successfully signed in") return HttpResponseRedirect('home') #return HttpResponseRedirect(reverse('main:home', kwargs={'username': username})) else: message = 'Sorry, the username or password you entered is not valid please try again.' return render(request, 'login.html', {'message':message}) else: message = 'Sorry, the username or password you entered is not valid please try again.' return render(request, 'login.html', {'message':message}) This is my form for login at login.html <form method="POST" action="{%url 'main:home' user.username %}" class="form-signin"> This is my view "home" def home(request, username): username = request.user.get_username() return render(request,'home.html') This is my url path at myapp/urls.py path('home/<username>', views.home, name='home'), This is the LOGIN_REDIRECT_URL LOGIN_REDIRECT_URL = '/main/home' I am trying to get mysite.com/home/myusername, but it is giving me a NoReverseMarch error Error: NoReverseMatch at /main/ Reverse for 'home' with arguments '('',)' not found. 1 pattern(s) tried: ['main/home/(?P<username>[^/]+)$'] Am I missing … -
Elastic Beanstalk with development and production environment?
I made a Django project and have successfully deployed it to an Elastic Beanstalk environment, let's say it's called app_name. However, I realized I needed 2 environments: development and production. The purpose of this is so I can try things out in development, and when I know it's fully working, I can deploy it in production for the public to use. I tried looking around their documentations and found Managing multiple Elastic Beanstalk environments as a group with the EB CLI . It basically says you can create a group of environments in one project with the command: ~/workspace/project-name$ eb create --modules component-a component-b --env-group-suffix group-name However, I'm not sure what a group means. I mean, I just need a development and production environment. I'm fairly new at this. How do I create and manage development and production environments for this purpose? I would ever be so grateful if someone were to shed some light to my problem. -
delete and item from a list through a modal
I am trying to delete elements from a list of addresses through a modal. The issue is that I can't delete the address chosen from the list. it always deletes the first one. Template: {% extends 'base.html' %} {% block content %} <main class="login-page"> <div class="contact signin address-list" id="book-table"> <div class="titulos"> <p>Domicilios</p> <button class="btn btn-secondary" type="button"> <a href="{% url "main:address_create" %}"><i class="fas fa-plus"></i></a> </button> </div> {% for address in object_list %} <div class="crud"> <div> <p class="details">{{ address.name }}</p> <p class="details">{{ address.address1 }} ({{ address.zip_code }})</p> <p class="details">{{ address.phone }}</p> <p class="details">{{ address.city }}</p> <p class="details">{{ address.get_country_display}}</p> </div> <div> <button class="btn btn-info" type="button"> <a href="{% url "main:address_update" address.id %}"><i class="fas fa-pen"></i></a> </button> <button class="btn btn-danger" type="button"> <a href="{% url "main:address_delete" address.id %}" class="confirm-delete" data-toggle="modal" data-target="#confirmDeleteModal"><i class="fas fa-trash-alt"></i> </a> </button> <div class="modal fade" id="confirmDeleteModal" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteModal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body confirm-delete"> ¿Está seguro de eliminar la dirección {{ address.address1 }}? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal" data-target="modal">Cancelar</button> <form method="POST" action="{% url "main:address_delete" address.id %}"> {% csrf_token %} <button type="submit" class="btn btn-danger">Eliminar</a> </button> </form> </div> </div> </div> </div> </div> </div> {% if not forloop.last %}<hr style="display: block">{% endif %} {% endfor %} </div> </main> {% endblock … -
how can i overide django allauth signup success_url
I'm working on a project using allauth and i'm using customer user model and i wan the newly registered user to be redirected to a different page (say profile form page) which will be totally different from the login_redirect_url, I have tried it this way any idea how i can make this work pls? from django.shortcuts import get_object_or_404, redirect, render from allauth.account.views import LogoutView from django.urls import reverse_lazy from allauth.account.views import SignupView from django.views.generic import TemplateView from .models import CustomUser class Signup(SignupView): success_url = reverse_lazy('business:company_profile') def get_success_url(self): return self.success_url -
Django not sending Server Error (500) emails
I have a Django website hosted on a remote server. Whenever I encounter a 'Server Error (500)' I am supposed to get an email with more information about the error. I am not getting these emails. send_mail() works on this server through the shell. mail_admins() works on this server through the shell. Triggering a Server Error (500) only displays the error on the page and no email is ever sent. Here are what I believe to be the relevant settings for sending email as well as receiving error emails. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'me@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' SERVER_EMAIL = 'me@gmail.com' ADMINS = [ ('me', 'me@gmail.com'), ] -
Django signal reciever not called after connecting to pre_delete signal
Goal I'm trying to implement a voting system that tracks when a user makes a vote on a specific object in the database. I'm tracking this using an intermediate UserVotemodel with a foreign key to the object that actually contains all the votes. Whenever the UserVote gets deleted I want to remove the vote on the related object. What I've tried Since bulk deletes do not call the model.delete() method, I want to accomplish the above by listening to the pre_delete signal. When I test the below receiver function using the Django test runner, everything behaves as expected from myapp.models.users import UserVote from django.db.models.signals import pre_delete from django.dispatch import receiver @receiver(pre_delete) def user_vote_handler(sender, instance, **kwargs): if sender in UserVote.__subclasses__(): # remove the vote from the related model Problem When I call delete() on a model instance in views.py, the function is not called. If I add print statements to the receiver function as below, none of the statements are printed. from myapp.models.users import UserVote from django.db.models.signals import pre_delete from django.dispatch import receiver @receiver(pre_delete) def user_vote_handler(sender, instance, **kwargs): print('function called') if sender in UserVote.__subclasses__(): print('condition met') # remove the vote from the related model I've read through the Signal Documention and … -
How to apply CSS class to dropdown in Django forms?
I have a form that has two fields who are dropdowns that show objects from other models through a Foreign Key. class NewFlight(ModelForm): class Meta: model = Flight fields = ('date', 'flight_id', 'company', 'airport') def __init__(self, *args, **kwargs): super(NewFlight, self).__init__(*args, **kwargs) self.fields['date'].widget = forms.DateTimeInput(attrs={'class': 'form-control', 'data-target': '#datetimepicker1'}) self.fields['flight_id'].widget = TextInput(attrs={'class': 'form-control'}) Both company and airport are objects from another model. So, if in the def __init__ I use the forms.Select widget, with the class form-control, I'll get the styling correct, but all the dropdown is empty. If I just leave the default form, all the "companies" are correctly displayed. -
Django: redirect to same page after custom login
I have this code for a custom login: def login(request): if request.user.is_authenticated: return render(request, 'listings/index.html', {}) if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: if not request.POST.get('remember_me', None): request.session.set_expiry(0) auth_login(request, user) return redirect('dashboard') else: messages.error(request, "Les informations que vous venez d'entrer sont incorrects. Veuillez réessayer.") return render(request, 'dashboard/login.html', {}) return render(request, 'dashboard/login.html', {'randomtip': random.choice(RandomTip.objects.all())}) And all my views have @login_required and @user_passes_test decorators. As you can see in the login function, when the user is authenticated and logged in, s/he gets redirected to dashboard. But I have a session expiry limit (where users have their sessions expired after 6 minutes). And when they are in a specific page, they get redirected to the login after the expiry of the cookie. The problem here is that if they are in a page other than dashboard, after they login they get redirected to the dashboard. I want them to stay in the same page after they login again. How can I know the path of the current page visited and put it here: return redirect(current_page)? -
How to bulk increment a unique IntegerField?
How can I bulk increment an IntegerField that has a unique constraint? For example: class Rank(models.Model): level = models.IntegerField(unique=True) >> Rank.objects.create(level=1) >> Rank.objects.create(level=2) >> Rank.objects.create(level=3) >> Rank.objects.all().update(level=F('level')+1) django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'myapp_rank.level'") The following query works fine in mysql (assuming SQL_SAFE_UPDATES=0): UPDATE myapp_rank t SET t.rank = t.rank + 1; Is this not possible without using a raw query?