Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using django how can I send page-refresh without pressing enter in input field
In my app I have an input field in which the user can write a string. When he presses enter it activates a request for editing the database and the new data gets displayed. I want however that this request is being sent every time the user writes a letter into the input field. How can I achieve this? views.py def search_movie(request): # create new object and save it and redirect title = request.POST['content'] print('title') for item in movie_class.objects.all(): if item.title == title or not title: item.show_movie = True else: item.show_movie = False item.save() movieView(request) return HttpResponseRedirect('/movies/') template <form action="/search_movie/" method="post"> {% csrf_token %} <input type = "text" name = "content"/> <button type="submit">Upload text</button> </form> -
How to add element without submitting to another page
I would like to add a topping to my pizza using XMLHttpRequest without submitting to another page but I can't wrap my mind around how to implement it. So far I'm posting to add_topping route and getting a JsonResponse without any problem. But instead of going to the view, I would like to do it with JavaScript. I have already searched for similar problems but or they are all with PHP or with jquery but I would like to implement it using normal JavaScript with XMLHttpResponse. HTML <form id="add_topping" action="{% url 'orders:add_topping' %}" method="post"> {% csrf_token %} <div class="form-row align-items-center"> <div class="form-group col-auto"> <select class="form-control" name="topping_selected" id="topping_selected"> {% for topping in topping_list %} <option value="{{ topping }}">{{ topping }}</option> {% endfor %} </select> </div> <div class="form-group col-auto"> <button class="btn btn-secondary" type="submit">Add topping</button> </div> </div> </form> views.py def add_topping(request): # If request is not a POST request, return index if request.method == 'POST': # Get the data from the POST request topping_selected = request.POST.get('topping_selected') return JsonResponse({"success":True, "topping_added": topping_selected}) # Else return false return JsonResponse({"success":False}) JavaScript // Function to add topping document.querySelector('#add_topping').onsubmit = function() { // Create request object const request = new XMLHttpRequest(); // Variables to determine the size and topping … -
'NoneType' object has no attribute '__dict__' when overriding form_valid()
I'm trying to override the form_valid function of a CreateView so it sends an email to the user when the form is saved. It saves the element in the database and correctly sends the email, but afterwards it shows the 'NoneType' object has no attribute 'dict' error when trying to redirect. I tried overriding the get_success_url method but it didn't send the message I need to send to the template after it's done. I also tried changing the return redirect(self.get_success_url()) to return redirect(success_url) and the same happens, it redirects with no error but the template misses the message. ###views.py class createpetition(SuccessMessageMixin, CreateView): model = PQS form_class = CrearPeticion template_name = "peticion/createpetition.html" success_url = reverse_lazy('createpetition') success_message = "e" def form_valid(self, form): peticion = form.save() usuario = peticion.nombreUsuario usuario.enviarCorreo('Artemis - Nueva petición registrada con éxito','¡Gracias por comunicarte con nosotros!\n\nTu mensaje:\n\n' + peticion.descripcion) return redirect(self.get_success_url()) ###user models.py def enviarCorreo(self, asunto, mensaje): contenido = render_to_string('correo_base.html',{'mensaje':mensaje}) send_mail(asunto,contenido,'admin@artemis.com',[self.correo])``` -
How to apply delay for a single user in django without disturbing the whole server?
I am building a django website and for certain reasons I have to send an email to user containing a link consisting of a token, although the token is always unique and is of 100 alphanumeric characters yet I want to delay the loading time of the user if link with wrong token is used. The function related to this in my views.py is something like this- import time def my_function(request,token): if User.objects.filter(uid=token): return HttpResponse("Yes") else: time.sleep(5) return HttpResponse("No") But the problem here is that the sleep function not only affects the current user but instead the whole server. Is there any possible way to add this delay in backend or in frontend? If not then is there any other way to punish for entering url with wrong token? -
Django Rest Framework - Latest child per instance
Using Django Rest Framework, I'm building a web application that saves information on Products and its Prices. A Product can have multiple Prices over time. My models look like this: class Product(models.Model): name = models.CharField(max_length=100) class Price(models.Model): product = models.ForeignKey(Product, related_name='prices', on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2, default=0) date = models.DateField(default=datetime.date.today) I've set up the following serializers: class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ('price', 'date') class ProductSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True, read_only=True) class Meta: model = Product fields = ('name', 'prices') Now, I want to create an APIView that shows all products with their latest price. Like so: [ { "name": "Product A", "price_latest": 1.00 }, { "name": "Product B", "price_latest": 2.00 } ] Does anyone have any idea on how to achieve this? -
Sub-classing the user model from models.Model directly instead of using custom user models
Everywhere, everyone seems to be using "custom user model" derived from either AbstractUser or AbstractBaseUser class. Why nobody directly sub-classes the user model from models.Model? Won't that be much easier and simpler? What additional functionality does using these custom user models provide? -
Celery can't connect to aws RDS and instead using 127.0.0.1
I have a django app running on Elastic beanstalk with celery and redis. The celery task that is failing is to process a photo and save some results in the database (which is a postgres RDS) and it's failing because it's trying to connect to the database on localhost:5432. I have a debug task which doesn't interact with the database and I can see that it is received and executed. My settings file has the following ALLOWED_HOSTS = [ "localhost", "127.0.0.1", ".elasticbeanstalk.com", ] if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'woodpecker', 'USER': os.environ.get("DB_USER"), 'PASSWORD': os.environ.get("DB_PASS"), 'HOST': 'localhost', 'PORT': '', } } CELERY_BROKER_URL = 'redis://localhost' celery config file from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') # DON'T FORGET TO CHANGE THIS ACCORDINGLY # os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1') app = Celery('myapp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) I'm still having a problem running celery with supervisord so for now I do the following to start celery after logging to the ec2 instance source /opt/python/run/venv/bin/activate cd /opt/python/current/app/ celery worker -A myapp --loglevel=DEBUG a … -
TypeError in Diffie Hellman using Django and JQuery
I'm trying to develop Diffie Hellman using Django and JQuery, not a full-fledged website, but just to practice and demonstrate Diffie Hellman. Here is my HTML/Javascript code. function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } var BigInt1 = window.bigInt; var x = BigInt1(getRandomInt(17)); var prime = BigInt1('{{ prime_num }}'); var base = BigInt1('{{ base_num }}'); console.log("Prime:" + prime.value + "\n", "Base: " + base.value + "\n", "Private Key:+" + x + "\n") // Diffie Hellman $(function(event) { var level1KeySelf = base.modPow(x, prime); console.log("Level1 " + level1KeySelf.value); var key; $.ajax({ type: 'GET', url: "{% url 'Shenzen:diffiehellman' %}", data: { step: 'calcval', level1: level1KeySelf }, success: function(data, status, xhr) { var level1KeyOther = BigInt1(data['firstkey']); key = level1KeyOther.modPow(x, prime); $("#keyid").attr("keyval", key); }, error: function(xhr, status, e) { console.log("error"); }, async: true, datatype: 'json' }); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="keydiv" id="keyid" keyval="" hidden></div> Here is my Django View: def diffiehellman(request): bytes_y = os.urandom(32) y = int.from_bytes(bytes_y,'little') if request.method == 'GET': step = request.GET['step'] if step == 'calcval': level1KeySelf = pow(base_num,y,prime) level1KeyOther = request.GET['level1'] key = pow(level1KeyOther,y,prime) return JsonResponse({'firstkey':level1keySelf}) elif step == 'success': return JsonResponse({'success':'success'}) return HttpResponse('') else: return HttpResponse('failed! require a GET request.') I get the following TypeError in Firefox signin is a view … -
Django: TypeError Missing 1 required positional argument
So I am working on my first python project using django. It's a simple first project that shows methods of POST, GET, PUT, and DELETE. I've gotten the methods of POST and PUT down. But PUT is not working out the way I thought it would work. So I have a database of information with simple info like first name, last name, and a e-mail. I have two functions in my views with one that renders a page of the database of information and one that links to a page that "updates/edits" that one specific instance of info. So here is my model: class Information(models.Model): """Placeholder code that the viewer will be seeing.""" info_id = models.AutoField(primary_key=True,unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) e_mail = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return information.""" return f"Info ID: {self.info_id}, First Name: {self.first_name}, Last Name: {self.last_name}, E-mail: {self.e_mail}" Here is my urls: # Page(s) that shows the viewer an example of PUT. path('PUTData/', views.put_data, name='put_data'), # Page that shows all info. path('PUT/', views.put, name='put'), Here is my views with the two functions: def put_data(request): put_data = Information.objects.order_by('date_added') context = {'put_data': put_data} return render(request, 'just_projects/put_data.html', context) def put(request, info_id): info = Information.objects.get(id=info_id) if request.method != … -
What is the significance of numbers written in django server along with GET?
I am building a django website and i noticed that within my server there often occur several lines like - [28/Jul/2019 22:52:24] "GET /media/images/product_images/Q0jsuTaUwKhgOhhO.jpg HTTP/1.1" 200 2981629 In lines like these what does the number 200 and 2981629 signify? Also, does printing of these lines in my command line slow my server? -
How to get the path to a FieldField considering the upload_to() function
I am making an app with Django and I am working with an ImageField. I have this function as the upload_to argument: def group_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/group_<id>/time/<filename> return 'Groups/group_{0}/{1}/{2}'.format(instance.id, get_time(), filename) However, I want to resize the group image, so I need to access the group.photo ImageField FieldFile. My problem is that when try to get the FieldFile path with group.photo.path, I get /media/429760_490645240984035_288529563_n.JPG but I there is no file in this directory, because the file is in /media/Groups/group_2/2-3-2019-23-54/429760_490645240984035_288529563_n.JPG instead. How do I get the right file path? -
I make tags to articles, but they do not appear on the page
I have a function that processes the request by tags and sorts articles with similar tags and displays them in a template. But for some reason, they simply do not appear on the page. I fill them in the model using TaggableManager PS tags should appear on the article and when I click on them, the request should be processed and execute the post _search function and sent to the page with articles with similar tags. models.py class Articles(models.Model): title = models.CharField(max_length= 200) post = models.TextField() date = models.DateTimeField() img = models.ImageField(upload_to='', default="default_value") tags = TaggableManager() article_like = models.IntegerField(default='0') article_dislike = models.IntegerField(default='0') view = models.IntegerField(default='0') datesArticle = models.DateTimeField(auto_now=True) class Meta: ordering = ['-datesArticle'] def __str__(self): return self.title views.py def ArticleDetailView(request, pk): Articles.objects.filter(pk=pk).update(view=F('view') + 1) Articles.objects.all() article_details = Articles.objects.filter(pk=pk).first() if request.method == 'POST': comment_form = Comments(request.POST) comment_form.save() else: comment_form = Comments() commentss = CommentModel.objects.all() return render(request, 'news/post.html', {'article_details': article_details, 'comment_form': comment_form, 'comments': commentss, }) def tags_list(request, tag_slug=None): object_list = Articles.objects.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first … -
how to add two class as ForeignKey at a time in one fiield in django?
In models: team_player = models.ManyToManyField(FirstTeamPlayer and SecondTeamPlayer, blank=True, related_name="team_player_set") why don't it possible?? I only get SecondTeamPlayer this queryset data. how can i get these two class in here?? -
How correct initialize a class instance using kwargs
I try to initialize a class with ihertitance structure. I already read a lot of questions here, but still can't figure out how should I do this. My model: class BaseCrudEntity(models.Model): pass class Meta: abstract = True class Person(BaseCrudEntity): Name = models.CharField(max_length = 255) def __init__(self, *args, **kwargs): if args: self.Name = args super().__init__(self, *args) pass And here I call it: p = Person("Test2") p.save() As a result I have an error: int() argument must be a string, a bytes-like object or a number, not 'Person' Here my traceback: http://dpaste.com/2BJFF38 How should I initialize class instance? Why in shell I see None: >>> from person.models.person import * >>> p = Person('Tttt') >>> p <Person: Tttt None> What am I doing wrong? -
static Invalid block tag inside template file
I'm having the invalid block tag issue while trying to reference the styles.css file from my app file structure, even having configured everything as the django documentation (and several other answers here in stack overflow) . I'm using django 2.2.3 in a python3.6 venv along with pureCSS lib. Here's an overview of my project's files and configuration regarding the templates and the static dir/files: 1- settings.py INSTALLED_APPS and STATIC_URL definition: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pyonlinecourses.core', ] ... STATIC_URL = '/static/' 2- settings.py TEMPLATES definitions: TEMPLATES_DIR = os.path.join(BASE_DIR, "pyonlinecourses/core/templates/") TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.static', ], }, }, ] 3- Django project directory structure: - pyonlinecourses - core - migrations - static - css - templates - home **(issue located in this file)** 5- static tag definition and reference in html file <!doctype html> {& load static &} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="PyOnline Courses - Simple distance education virtual learning environment" /> <title>PyOnline MOOC</title> <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css"> <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> </head> I'm at a loss trying to identify the source of the … -
How can I nest a serializer before it is being defined?
I have these serializers class OrderItemSerializer(serializers.ModelSerializer): product = ProductSerializer(read_only=True) order = ??????????????? class Meta: model = OrderItem exclude = ['id'] class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True, read_only=True) url = serializers.HyperlinkedIdentityField( lookup_field='slug', view_name='api:order-detail') class Meta: model = Order fields = '__all__' I need to use OrderSerializer inside the OrderItemSerializer but if I do so it doesn't work because of the OrderSerializer did not get defined yet. right now I get this result when I query for the Order item. { "price": "334.00", "quantity": 1, "order": 1 } and the wanted behavior is to get the serialized order object instead of the primary key but without losing the order_items inside of the OrderSerializer -
merge/remove elements from a ManyToMany relationship (using through table) when saving model
I'm developping an app to manage commands for a restaurant. as the commands can evolve through the diner, for more clarity, I want to merge the command's lines that contain the same product. For instance, if you command 2 buckets of chicken, then later another one, I want the final Command model instance to contain only one line (bucket of chicken, 3) instead of two. I have a function (fusion_atoms) which detects similar lines and merge them. I tried to call it in the save method of Command model, and also during pre_save and post_save signals. It doesn't work. I'm quite a noob in python and django, and I think I'm not doing this the right way. models.py: class Command_Atom(models.Model): command = models.ForeignKey("Command", on_delete=models.CASCADE) produit = models.ForeignKey(Produit, on_delete=models.CASCADE) quantite = models.PositiveSmallIntegerField(default=1) @property def total(self): return self.produit.prix * self.quantite class Command (models.Model): client = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) table = models.PositiveSmallIntegerField(default=0) produits = models.ManyToManyField(Produit, through="Command_Atom") @property def atoms(self): return Command_Atom.objects.filter(command_id=self.id) def fusion_atoms(self): lines = self.atoms.all().order_by('produit','prod_options') i = 1 current_line = lines[0] to_be_deleted = [] while i < len(lines): if current_line.produit == lines[i].produit: print('merge') current_line.quantite += lines[i].quantite current_line.save() to_be_deleted.append(lines[i]) else: current_line = lines[i] i += 1 for l in to_be_deleted: l.delete() def save(self): … -
TypeError at /api/register/ argument should be a bytes-like object or ASCII string, not 'InMemoryUploadedFile'
I am trying to upload an image in my project and I am trying a solution for it. I have made some changes in the views.py but I am continuously getting the above error. What is wrong in my code? Please help as I am new to rest. class UserCreate(generics.ListCreateAPIView): serializer_class = UserProfileSerializer queryset = UserProfile.objects.all() parser_classes = (FormParser,MultiPartParser) def post(self, request): print(request.data) serializer= UserProfileSerializer(data=request.data) if serializer.is_valid(): imgstr64=serializer.validated_data['avatar'] imgdata = base64.b64decode(imgstr64) fname = '/tmp/%s.jpg'%(str(Userprofile.id)) with open(fname,'wb') as f: f.write(imgdata) imgname = '%s.jpg'%(str(Userprofile.id)) UserProfile.avatar.save(imgname,File(open(fname,'r'))) os.remove(fname) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Cannot reset migrations in Django project?
What I did: Delete db.sqlite3 file. Delete all files in migrations folder (including init file) Then command in cmd: python manage.py makemigrations No changes detected python manage.py migrate Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK But migrations folder is still empty. I have some models in models.py, also tried to add new row to some of them, but result was the same. What I'm doing wrong? -
Using regrouped variable of django template in javascript
From my view function, I have sent some data to django template. In the template, data are grouped using regroup method. {% regroup data|dictsort:"month" by month as data_month_list %} Is there any way to use the data_month_list in javascript? -
TypeErrorat /blog/21- detail() got an unexpected keyword argument 'blog_id'
I'm making a tool for my project. My final object is this:When I type a title, body in new.html page, it works through create.html and finally, gets all of information from new.html in detail.html page. I created two apps, each good(writing works) and account(sign in works). But I faced with "detail() got an unexpected keyword argument 'blog_id'" problem and can't find any solutions. I run this in Visual studio code and I'm now trying to insert def detail(request): details = get_object(Good, pk= blog_id) return redner(request, 'detail.html', {'details':details}) what I have to do after this if it's right? home.html {% extends 'base.html' %} {% block contents %} <body> </body> {% endblock %} urls.py from django.contrib import admin from django.urls import path import good.views import account.views urlpatterns = [ path('admin/', admin.site.urls), path('', good.views.home, name="home"), path('login/', account.views.login, name="login"), path('signup/', account.views.signup, name="signup"), path('new/', good.views.new, name="new"), path('create/', good.views.create, name="create"), path('blog/<int:blog_id>', good.views.detail, name="detail"), ] models.py from django.db import models class Good(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') body = models.TextField() def __str__(self): return self.title admin.py from django.contrib import admin from .models import Good admin.site.register(Good) views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Good from django.utils import timezone def home(request): return render(request,'home.html') def new(request): … -
Form doesn't save but returns 200
I want to create an object of item and save it to the database through a form i wrote. Right now I'm able to update it from my form also admin panel works i can create item from there. However, create form not saving. When i click the button, it refreshes the page, returns 200 in terminal but doesn't save it. I'm putting every part of it, i checked a lot but not seeing any error. This is my model. class Item(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='items') name = models.CharField(max_length=50) description = models.TextField(max_length=250) price = models.FloatField() picture = models.ImageField(upload_to='item_pictures') is_available = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, related_name='category') slug = models.SlugField(unique=True, null=True, blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) return super(Item, self).save(*args, **kwargs) def __str__(self): return self.name My url path('item/create/', ItemCreateView.as_view(), name='item-create'), My view class ItemCreateView(LoginRequiredMixin, CreateView): model = Item fields = ['name', 'description', 'price', 'picture', 'is_available', 'category', 'slug' ] template_name = 'item/item_update.html' success_url = '/' Success url return home page, but form only refreshes And form class ItemCreateForm(forms.ModelForm): class Meta: model = Item fields = ['name', 'description', 'price', 'picture', 'is_available', 'category', 'slug'] Lastly template just in case {% extends "base.html" %} {% … -
How to override PasswordResetConfirmView? (django.contrib.auth.views)
I tried: class CustomPasswordResetConfirmView(PasswordResetConfirmView): form_class = CustomSetPasswordForm but it raises TypeError:__init__() takes 1 positional argument but 2 were given -
How to address to app url in django URL field?
I want to make a dynamic toolbar for a website, this toolbar can have custom websites urls and also should have links to same website's apps. for example there is a search app in django project. website url is not fixed, so like how django uses urls names in HTML file (like : {% url 'name' %}), I want to use same name in model field to access to the apps. This is my toolbar menu object class main_menu_item(models.Model): name = models.CharField(max_length=10,default=None) url = models.URLField(default=None) text_color = models.CharField(max_length=7,default=None) background_color = models.CharField(max_length=7,default=None) def first_letter(self): return self.name[0].upper() -
How can I redirect to use the new context not the origin context with django?
I use a decorator to check whether the user is logged in, and redirect to the login page and remind the user. I want to use context parametric rendering template. How can I write the code? def check_login(func): def wrapper(request, *args, **kwargs): if request.session.get("unique_id"): return func(request, *args, **kwargs) else: context = {'title': 'login', 'not_login': 1} return redirect(reverse('login'), context=context) return wrapper # view.py def login(request): context = {'title': 'login', 'not_login': 0} return render(request, 'login.html', context) The code like this. If user get the login page, templates use not_login=0, if the request is from redirect, templates use not_login=1.