Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why navbar toggle doesn't toggle?
Im working on a personal project in Django, and i have a problem. I made the navbar with bootstrap but the toggle doesn't work. I have add the javascript and css from: https://getbootstrap.com/docs/4.4/getting-started/introduction/ but still doesn't work. This is my main.html {% load static %} <!DOCTYPE html> <html> <head> <title>Webart</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> {% include 'art/navbar.html' %} {% block content %} {% endblock %} <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> This is my navbar.html: <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <a class="navbar-brand" href="#">Margjini-Art-Gallery</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo02"> <ul class="navbar-nav ml-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link" href="#">About<span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="#">Bio</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Painting </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="#">Impresionism</a> <a class="dropdown-item" href="#">Acrylic</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Something else here</a> </div> </li> <li class="nav-item active"> <a class="nav-link disabled" href="#">Contact</a> </li> </ul> </div> </nav> <br> I dont really know where the problem is. I hope you guys … -
based on the choices selected in the model...I need to select appropriate region in class view using if_else logic
class GenerateRouterConfig(View): def get(self, request, pk, *args, **kwargs): router = Router.objects.get(pk=pk) AMERICAS = ("1.2.3.4", "10.23.136.1") ASIAPAC = ("1.2.3.5", "10.23.136.4") EMEA = ("1.2.3.6", "10.23.136.3") if router.REGIONS[1] == ('AMERICAS','AMERICAS'): calculated_public_ip = AMERICAS[0] calculated_tunnel_ip = AMERICAS[1] elif router.REGIONS[2] == ('ASIA','ASIA'): calculated_public_ip = ASIAPAC[0] calculated_tunnel_ip = ASIAPAC[1] elif router.REGIONS[0] == ('EUROPE','EUROPE'): calculated_public_ip = EMEA[0] calculated_tunnel_ip = EMEA[1] print(calculated_public_ip) print(calculated_tunnel_ip) Models.. class Router(models.Model): AsiaPac = 'ASIA' Americas = 'AMERICAS' EMEA = 'EUROPE' REGIONS = [ (EMEA, 'EUROPE'), (Americas, 'AMERICAS'), (AsiaPac, 'ASIA'), ] region = models.CharField( max_length=8, choices=REGIONS, default=Americas, ) Any hints? Based on the logic I used its not working..... Based on the if else logic I need to select the appropriate region tuples with calculated tunnel and public ip address. -
Graphene: Difference between Abstract ObjectType and Interface
I am unable to tell the difference between a graphene.Interface object and a graphene.ObjectType object with abstract = True meta class options. For example: import graphene class A(graphene.Interface): field_y = graphene.Int() field_z = graphene.String() class B(graphene.ObjectType): class Meta: abstract = True field_y = graphene.Int() field_z = graphene.String() class ChildA(graphene.ObjectType): class Meta: interfaces = (A,) field_x = graphene.Float() class ChildB(B): field_x = graphene.Float() When would I use one Child over the other? When would I not use one or the other? Any help is appreciated. -
Python django query database and get all FKs in list
I am new in django and I am working in order to implement a Rest API. My issue is with a query that I can't find a working solution no matter the number of hours spent on it. More specifically I have these two models: class Subcategory(models.Model): id = models.UUIDField(primary_key=True, editable=False, null=False, blank=False, default=uuid.uuid4) name = models.CharField(max_length=50, null=False, blank=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=False, blank=False, db_column='category') class Category(models.Model): id = models.UUIDField(primary_key=True, editable=False, null=False, blank=False, default=uuid.uuid4) name = models.CharField(max_length=50, null=False) image = models.CharField(max_length=100, default=None) As you can see each category has some subcategories and in the subcategory model I have a foreign key to the category. What i want to do is to query my database, get all categories and to each category add an extra field subcategories with a list of the subcategories. My idea it was to follow the FKs using .select_related but it seems to be a wrong solution since I am taking the following error: "message": "name 'subcategory__category' is not defined" My query is: Category.objects.all().select_related(subcategory__category).values() Any ideas on how to solve this issue and find a way to implement my query? Thank you in advance -
How do I resolve a permission error with django?
I am using Django to display my code in an html format using class based views. My code reads a log file and displays stats based on what is in there. When I try to access the log file from my computer this error message is displayed: [Errno 13] Permission denied: 'C:/Users/bhattaar/Downloads/access.log' I first tried going through the properties of the folder to make sure everything was set to read only (which it already was) and then I tried running the command prompt as an administrator and it still would not work. The line the error appears on is this: log = open('C:/Users/bhattaar/Downloads/access.log', 'r') Does anyone know how I can resolve this issue? -
How to call a function every time Django restarts?
I have a Django webservice that is hosted using Gunicorn in production. I need to call the function restart_event every time the webservice is restarted. This is the pseudo code of the function def restart_event(): """This function should be called everytime Django restarts""" # read list of registered companies from the database companies = Company.objects.all() for company in companies: # perform various operations on the data business_logic1(company) business_logic2(company) change_celery_settings() How do configure Django such that the above function is called every time Django restarts? Note that since Gunicorn is being used I won't be doing a python manage.py runserver rather I will be starting and stopping the Gunicorn webserver -
Images served on aws are not displaying on my website
Kindly help me, I have tried using aws with heroku to host my images but it has not been working for days now. The main issue is that my images are not showing on my website but are sent to my bucket whenever they are uploaded. Kindly help me please, thanks. -
Is there any way to store object in django request
Hello I am new to the Django framework and while I was building a small shopping project I faced the following problem. In the shop I wanted to make the items to be chosen but reserved when actually processed the cart and some time after processing their reservation is cleared. I did this with some database call using a custom timer class and I wanted the user to stop the timer whenever they remove the item from cart since I want to remove the reservation as well at the same time. Here is some of my code # my custom timer class class MyTimerClass(threading.Thread): def __init__(self, timewait, id, quantity): threading.Thread.__init__(self) self.event = threading.Event() self.timewait = timewait self.id_= id self.item_quan = quantity def run(self): # waits for the time(seconds) specified self.event.wait(self.timewait) # main work is done if not the stop method is called if not self.event.is_set(): user = UserModel.objects.get(id=self.usr_id) # Stored JSON list of cart items with thier id and quantity in the db :) cart = json.loads(user.cart) for item in cart: if item['id'] == self.item_id: item['quantity'] -= self.item_quan user.cart = json.dumps(cart) user.save() def stop(self): self.event.set() The user first chooses the items and then process them so that they can actually … -
Twitter / Tweepy OAuth - How to save oauth_token to verify it on callback in a REST API setup
I am writing a simple Twitter authentication flow with a REST API setup. Client side is just plain javascript/Vue code - there is no server-side rendering. This consumes a backend REST API built with Django Rest Framework, using tweepy library to wrap the Twitter API. I have the authentication working, with the following steps: User clicks a 'log in to twitter' button, which fires a call to my backend API /get-url/ API calls Twitter's get_authorization_url (using my Twitter app credentials), gets the token, and returns this redirection URL to the client Client redirects user to the Twitter URL to complete authentication On callback, client passes all params thru to backend API endpoint API gets token and secret; creates a tweepy API with user auth; and calls verify_credentials If everything worked fine, we create a user account in a Django database tied to the Twitter user, storing their token and secret; logs the user in with a JWT; and returns a 200 success with token. Front end deals with doing JWT token refreshing etc; but otherwise uses this for authentication on the rest of the API. However, there is one bit I'm stumped on: The Twitter docs suggest that in my … -
Saving PDFs to disk as they are generated with django-wkhtmltopdf
What I'm trying to implement is this: User sends query parameters from React FE microservice to the Django BE microservice. URI is something like /api/reports?startingPage=12&dataView=Region These PDFs are way too big to be generated in FE, so doing it server side Request makes its way into the view.py where the data related to dataView=Region is queried from the database, each row is iterated through and a PDF report is generated for each item Each dataView=Region can consist of a few hundred items and each of those items is its own report that can be a page long or several pages long As the reports are generated, they should be saved to the server persistent volume claim and not be sent back to FE until they have all run. When they have all run, I plan to use pypdf2 to combine all of the PDFs into one large file. At that point, the file is sent back to the FE to download. I'm only working on 1. and 3. at this point and I'm unable to: Get the files to save to storage Prevent the default behavior of the PDF being sent back to the FE after it has been generated … -
Django Model serializer returning ID
i've created the models and serializers as below serializers.py class ProductCategorySerializer(ModelSerializer): class Meta: model = ProductCategory fields = ['id', 'name'] @staticmethod def get_product_category_name(obj): return obj.product_categories.name class ProductSerializer(ModelSerializer): product_categories = ProductCategorySerializer class Meta: model = Product fields = ['id', 'name', 'default_price', 'description', 'product_categories'] models.py class ProductCategory(models.Model): class Meta: db_table = 'itw_product_category' verbose_name = 'product category' verbose_name_plural = 'product categories' name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): class Meta: db_table = 'itw_product' verbose_name = 'product' verbose_name_plural = 'products' name = models.CharField(max_length=50) default_price = models.FloatField(max_length=10) description = models.TextField(max_length=50) deleted = models.BooleanField(default=False) product_categories = models.ManyToManyField(ProductCategory, verbose_name='product_categories', related_name='products') Now, when i try to create a new model, product_categories returns only the id and not the name, what should i change? Example: { "id": 25, "name": "kms", "default_price": 932.0, "description": "kms", "product_categories": [ 5 ] } -
Flutter App using App Engine backend, contained within google cloud platform
is it possible to connect flutter app(mobile front-end) to App Engine(django backend) just using google cloud? What products would require? Thank you, much appreciated :) -
Django 'no such column' after changing spelling of attribute
I have the following classes: class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='restaurant') name = models.CharField(max_length=500) phone = models.CharField(max_length=500) address = models.CharField(max_length=500) logo = models.ImageField(upload_to='restaurant_logo/', blank=False) class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant fields = ("name", "phone", "address", "logo") I realized I spelled address as "adress" so i changed it to "address". Now I get the error 'no such column'. I tried making migrations but it says no migration to make. How can I fix this? -
Filtering issue in DRF
The problem I'm having looks like: TypeError: init() got an unexpected keyword argument 'name' "GET /apartmentimages/ HTTP/1.1" 500 136691 I have such a model.py class: class Apartment(models.Model): apartment_title = models.CharField(max_length=200) apartment_description = models.TextField() apartment_location = models.CharField(max_length=200) apartment_people_quantity = models.PositiveIntegerField() apartment_price = models.CharField(max_length=200) apartment_type = models.CharField(max_length=50, null=True) def __str__(self): return self.apartment_title class ApartmentImage(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE) image = models.ImageField(upload_to='images/', null=True, blank=True) And serializers.py class: class ApartmentSerializer(serializers.ModelSerializer): class Meta: model = Apartment fields = ( 'id', 'url', 'apartment_title', 'apartment_description', 'apartment_location', 'apartment_people_quantity', 'apartment_price', 'apartment_type', ) class ApartmentImageSerializer(serializers.ModelSerializer): class Meta: model = ApartmentImage fields = ('id', 'url', 'apartment', 'image',) in views.py: apartment_id = django_filters.CharFilter(name="apartment__id", queryset=Apartment.objects.all()) class Meta: model = ApartmentImage fields = ('apartment_id',) class ApartmentImageView(viewsets.ModelViewSet): queryset = ApartmentImage.objects.all() serializer_class = ApartmentImageSerializer filter_backends = (DjangoFilterBackend,) filter_class = ApartmentImageFilter -
Sorting release versions of the format YYYY.MM.DD in a Django queryset
I have a Django model that looks like this: from django.db import models from distutils.version import LooseVersion # Create your models here. class ReleaseNotes(models.Model): version = models.CharField(max_length=64, db_index=True, help_text="Version/Release") status = models.CharField(max_length=64, blank=True, null=True, help_text="Status") release_date = models.DateField(blank=True, null=True, help_text="Release Date") description = models.TextField(blank=True, null=True, help_text="Description") def description_to_bullet_points(self): return self.description.split('\n') def release_notes_list(self): qs = ReleaseNotes.objects.order_by('-version') return sorted(qs, key=lambda qs:LooseVersion(qs.version)) def __str__(self): return self.version And I display the "release notes" with this template: {% if release_notes_list %} <ul> {% for release_note in release_notes_list %} <p><b>{{ release_note.version }}</b><br> {% for bullet_pt in release_note.description_to_bullet_points %} <br>{{ bullet_pt }} {% endfor %} </p> {% endfor %} </ul> {% else %} <p>No release notes are available.</p> {% endif %} I want to display the "release notes" with the newest release note on top. But I have versions of the format YYYY.MM.DD so the version 2020.11.1 does not show up on top. The version come out in this order: 2020.8.1 2020.7.1 2020.6.2 2020.6.1 2020.5.4 2020.5.3 2020.5.2 2020.5.1 2020.4.4 2020.4.3 2020.4.2 2020.4.1 2020.2.6 2020.2.5 2020.2.4 2020.2.3 2020.2.2 2020.2.1 2020.11.1 2020.1.4 2020.1.3 2020.1.2 2020.1.1 -
SSL context override vulnerability on Django-rest serializer
I have HCL AppScan CodeSweep installed on VScode and it picked up an SSL context vulnerability on one of my Django serializers and I was just wondering I can go about fixing it without changing my desired functionality. class CategoryDetailSerializer(CategoryListSerializer): products = serializers.SerializerMethodField() class Meta: model = Category fields = ( 'id', 'title', 'products', ) def get_products(self, obj): # The source of the SSL context override return ProductListSerializer(obj.product_set.all(), many=True, context=self.context).data -
I keep getting the error "ModuleNotFoundError: No module named 'environ' in my settings.py file". I have installed the dependency in my python shell
I keep getting an import error on environ in my settings.py file, I have it installed via poetry in my .venv file as well. Could this be an error outside the settings file possibly? ` import environ env = environ.Env( DEBUG=(bool, False), ENVIORNMENT=(str, 'PRODUCTION'), ) environ.Env.read_env() ENVIRONMENT= env.str('ENVIRONMENT') SECRET_KEY = env.str('SECRET_KEY') DEBUG = env.bool('DEBUG') ALLOWED_HOSTS = tuple(env.list('ALLOWED_HOSTS')) ` -
Pass string via POST | Python
I am trying to hit an endpoint http://localhost:8001/header in which I am sending a string(ans) to another endpoint via POST request, but at the receiving endpoint side, the data is empty. Following is my code Please suggest where I am doing wrong. def header(request): ans = '[{"id": "dag"}, {"id": "afqw"}]' requests.post("http://localhost:8001/drftoken", data=ans) return JsonResponse({'message': 'ok'}) def drftoken(request): user = dict(request.POST) print(user) # printing {} here return JsonResponse({'message': 'ok'}) -
Getting dynamic data for chart.js from Django model
I am trying to create an analytics dashboard page for users that sign into my site. So if user 'DummyCo' signs in and goes to mywebsite.com/DummyCo/dashbord, they will see analytics relating to the model records where they are listed as the user (or client as I call them on the model.) I have the data working (shown below) but that simply allows me to display the count number. What i'd like to do is start using this data in charts on chart.js which I have up and running, but it does not allow me to grab that signed-in user the way my other view does (chart view shown below also). models.py class Session(models.Model): uid = models.CharField(max_length=50, blank=True) cid = models.CharField(max_length=50, blank=True) client = models.CharField(max_length=50, blank=True) views.py class DashboardListView(LoginRequiredMixin, ListView): template_name = 'blog/dashboard.html' context_object_name = 'sessions' ordering = ['-session_date'] def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Session.objects.filter(client=user).order_by('-session_date') def get_context_data(self, **kwargs): user = get_object_or_404(User, username=self.kwargs.get('username')) context = super().get_context_data(**kwargs) session_list = list(context['sessions']) context['total_actions'] = Session.objects.filter(client=user).count() # count function context['total_users'] = Session.objects.filter(client=user).values('uid').distinct().count() context['total_modules'] = Session.objects.filter(client=user).values('cid').distinct().count() context['sessions'] = session_list return context @ login_required() def dashboard(request): return render(request, 'blog/dashboard.html', {'title': 'Dashboard'}) urls.py path('<str:username>/dashboard/', views.dashboard and DashboardListView.as_view(), name='blog-dashboard') html tags produced {{ total_users }}, {{ total_actions }}, … -
How to perform function before submitting a Django form
There are many SO questions about async functions and how to perform something before sending a POST request. My problem is specific to Django because my CSRF token is lost if I wrap the function in a $.when or do any other solutions. I want to call a function that in itself sends a GET request to and API and fills certain form fields AND THEN afterward, sends a POST request to Dajngo (because the data isn't populated until the first function completes). I want to perform these functions only after the data is validated with Jquery's ".valid". Any IE compatible methods of doing this? Heres my JS: $('#long_form').on('submit', function(e) { e.preventDefault(); if ($("#long_form").valid()) { $.when( finished()).done(function(){ $('#long_form').unbind('submit').submit(); $.ajax({ url : $(this).attr('action') || window.location.pathname, type: "POST", data: $(this).serialize(), success: function (data) { console.log("Done")}, error: function (jXHR, textStatus, errorThrown) { alert(errorThrown);}}) })}}) Finished() is a function that calls the other functions, including one that sends an GET request to an API. I am also validating the data with jquery before sending to Django which is why I'm using AJAX. I'm quite new to Django and Ajax so this may be a dumb question, but I can't figure this out on my … -
modelForm crispy formhelper and choices list datepicker not showing
I've searched through Stackoverflow for this and cannot find an answer. I am trying to render a ModelForm using crispy forms and FormHelper to help me lay it out nicely. Everything was working fine when I was using the forms.Form library. but the main problem now is that the date picker and the choices field no longer have a dropdown list with the datepicker or the So this is my forms.py file: CITIES= (("London","London"), ("Istanbul","Istanbul"), ("Cape Town","Cape Town")) class EntryForm(forms.ModelForm): class Meta: model = Items itemName = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'item name'})) ... date = forms.DateField(widget=forms.TextInput(attrs={'type': 'date'}),required=False) location =forms.ChoiceField(choices=CITIES, required=False) fields = ['itemName', 'date', 'location'] def __init__(self, *args, **kwargs): super(EntryForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( 'itemName', ... Row( Column('date', css_class='form-group col-md-6 mb-0'), Column('location', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Submit('submit','Kelepiri Paylaş') ) My template file looks like this: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>Entry Form</h1> <br> {% crispy form %} <br> {% endblock %} -
How to pass user back to front end client after authorizing and obtaining access token?
I have a Django backend and React/Redux front end and I am trying to integrate the Spotify API. I am a total django noob so please have mercy. I currently send the user to my backend via a regular ol' anchor tag on the front end. My backend then redirects the user to the Spotify Authorize page and then that page redirects them to another page which trades the authorization code for the access token which I now have. However this code and the urls just send me to my backend API. How do I get the user back to the front end with this access token? "My" code: from django.views.generic.base import RedirectView, TemplateView from rest_framework.response import Response from rest_framework import generics, viewsets, permissions from django.urls import reverse from furl import furl import requests def build_authorize_url(request): params = { "client_id": "<client-id>", "response_type": "code", "redirect_uri": request.build_absolute_uri( reverse("spotify callback") ), "scope": " ".join( [ 'user-read-currently-playing', 'user-modify-playback-state', 'user-read-playback-state', 'streaming', 'app-remote-control', 'playlist-read-collaborative', 'playlist-modify-public', 'playlist-read-private', 'playlist-modify-private', 'user-library-modify', 'user-top-read', 'user-read-playback-position', 'user-read-recently-played', ] ), } print(params) url = ( furl("https://accounts.spotify.com/authorize") .add(params) .url ) print(url) return url AUTH_HEADER = { "Authorization": "Basic " + base64.b64encode( "<my client id>:<my client secret>".encode() ).decode() } def handle_callback(request): code = request.GET["code"] response … -
Django-taggit - tags aren't saving/how to save tags?
I'm trying to integrate taggit with my app. It seems to be mostly working, and I'm able to add tags via django admin. But I want to save the input from JobForm's tags field, I have tried following the documentation adding form.save_m2m() in place of where form.save is in my example but nothing seems to get the input. In my searches I've only came accross people explaining how to do this via the shell or admin, but I need users to be able to enter their own tags. class JobForm(forms.ModelForm): ... class Meta: model = Job fields = ['company', 'title', 'description', 'application_info', 'remote', 'city', 'state', 'country', 'location', 'email', 'category', 'tags'] @login_required(login_url='/login/') def jobs_new(request): ... if request.method == 'POST': if site.siteconfig.remote: form = JobRemoteForm(request.POST) else: form = JobForm(request.POST) company_form = CompanyForm(initial={'site': site}) if form.is_valid(): job = form.save(commit=False) if site.siteconfig.remote: job.remote = True job.site_id = site.id job.user_id = request.user.id job.tags = request. job.tags.all job.save() form.save() context = {'job': job, 'protocol': site.siteconfig.protocol} send_mail_with_helper( '[%s] New job posting' % site.name.upper(), render_to_string( 'job_board/emails/new_job_notification.txt', context ), site.siteconfig.admin_email, [site.siteconfig.admin_email] ) -
Django models (ManyToManyField?) - adding same object multiple times & conserving order
I have a Battleship-like grid (with positions A1, B1, C1, ... A2, B2, C2, ...) and objects that are moving around on the grid, where a position can only be occupied by one object at any given time. I'm trying to use Django models to store the paths taken by each object and was wondering the best way to do that. For example, I would want to be able to query and see that ObjectZ has been to [A1, B1, B2, C2, C3, D3, D2, C2, C3] - then I would know that ObjectZ started at A1 and is now at C3. I tried to use the ManyToManyField, but soon realized that I could not add the same object multiple times (meaning, I could not add C2 more than once). Thanks in advance! -
Login_redirect_url not working. View always redirecting to index
This is my login redirect url in settings.py: LOGIN_REDIRECT_URL='/category/all' And this is my login view: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method == "POST": email=request.POST['email'] password=request.POST['password'] user=auth.authenticate(email=email,password=password) if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request,"Email Password didn't match") return redirect('login') else: return render(request,"login.html") Whenever the user logs in I want to redirect him to the category/all page but it is always redirecting to index("/") and this might be because I am using return redirect("/").Also even when I have login required for some view then too even when the url is like: http://localhost:8000/login/?next=/cart/ Instead of redirecting me to cart it redirects too index. Please help me to work around this so that the redirect works properly.