Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add prices to total with checkbox select Django
i am building a feature to add different services to the checkout in my django template, but i don't know how to add the total price when selecting checkboxes. I put a change event on each checkbox and to this and when i check one it is supposed to add the service and its price in the card. The card : <div class="col-4"> <h4 class="d-flex justify-content-between align-items-center mb-3"> <span class="text-muted">Votre commande</span> </h4> <ul class="list-group mb-3" id="panier"> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div> <h6 class="my-0">{{annonce.titre_logement}}</h6> <small class="text-muted">{{annonce.categorie_logement}}</small> </div> <span class="text-muted">{{annonce.loyer_tc}} €</span> </li> </ul> <li class="list-group-item d-flex justify-content-between"> <span>Total (€)</span> <strong><span id="total"></span> €</strong> </li> </div> The checkboxes and the script : {% for categorie in categorie_service %} {% for service in services %} {% if service.categorie.value == categorie_service.nom %} <div class="form-check"> <input class="form-check-input" type="checkbox" name="service" value="{{ service.nom }}" id="service{{ service.id }}"> <label class="form-check-label" for="service{{ service.id }}"> {{ service.nom }} </label> </div> <script> $(document).ready(function() { $('#service{{ service.id }}').change(function() { if(this.checked) { var returnVal = "<li class='list-group-item d-flex justify-content-between lh-condensed'>\ <div>\ <h6 class='my-0'>{{service.nom}}</h6>\ </div>\ <span class='text-muted'>{{service.price}}€</span>\ </li>" $('#panier').append(returnVal); var total total = {{annonce.loyer_tc}} total = total + parseInt({{service.price}} || 0,10); totalDiv = document.getElementById("total"); totalDiv.innerHTML = total; } }); }); </script> {% endif %} {% … -
Django request.user not showing correct user in frontend
When user updates profile with username which is already in use ,message appear of "A user with that username already exists." but username on profile is changed to which user requested. for example: if user with username test001 update profile with already taken username "test0012" this will happen: Notice:username is updated with "test0012" Code in frontend for username: <h2 id="user-name" class="account-heading user__name">@{{ user.username }}</h2> also going on "my posts" will redirect to posts of user "test0012". code for profile and update: @login_required def profile(request): if request.method=="POST": u_form=UserUpdateForm(request.POST,instance=request.user)#,op_email=request.user.email) p_form=ProfileUpdateForm(request.POST,request.FILES,instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request,f'Your Account has been updated!') #changing email on profile tusername=u_form.cleaned_data.get('username') temail=u_form.cleaned_data.get('email') registeruser=User.objects.get(username=tusername) registeruser.email=temail registeruser.save() return redirect('profile') else: u_form=UserUpdateForm(instance=request.user) p_form=ProfileUpdateForm(instance=request.user.profile) userupdateform code: class UserUpdateForm(forms.ModelForm): email=forms.EmailField() username=forms.CharField(required=True,validators=[username_check,]) class Meta: model =User fields =['username','email'] ProfileUpdateForm: class ProfileUpdateForm(forms.ModelForm): class Meta: model=Profile fields=['image'] -
CSS is not rendering with HTML file in Django
I've been trying to link up my css with the HTML code, but CSS is not working in DJANGO! I'm sharing all the screenshots of my code! Hope anyone can help me out with this. Thanks in advance! h2{ color: blue; } .heading { color: blue; } <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]> <html class="no-js"> <!--<![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>MY PROFILE</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> {% load static %} <link rel="stylesheet" href="{% static 'css/index.css' %}"> </head> <body> WELCOME HERE! <h2 class="heading">This is CSS</h2> <script src="" async defer></script> </body> </html> -
GraphQL works on Postman, but not on React - using Django API
When I try to query my API on React, I am getting a 400 Bad Request, however I am able to make the same queries fine on Postman (browser and interface version). I don't get any error message so it seems impossible to troubleshoot. Does anyone know how I can at least troubleshoot this? index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { Route, BrowserRouter as Router, Switch } from 'react-router-dom'; import { ApolloClient, InMemoryCache, ApolloProvider, HttpLink, from } from "@apollo/client"; import { onError } from '@apollo/client/link/error'; const errorLink = onError(({ graphqlErrors, networkError }) => { if (graphqlErrors) { graphqlErrors.map(({ message, location, path }) => { alert(`Graphql error ${message}`); }); } }); const link = from([ errorLink, new HttpLink({ credentials: 'same-origin', uri: "http://localhost:8000/graphql/", fetchOptions: { mode: 'no-cors', }, }), ]); const client = new ApolloClient({ cache: new InMemoryCache(), link: link, connectToDevTools: true, }); ReactDOM.render( <ApolloProvider client={client}> <Router> <React.StrictMode> <Switch> <Route exact path="/" component={App} /> </Switch> </React.StrictMode> </Router> </ApolloProvider>, document.getElementById('root')); Queries.js import { gql } from '@apollo/client' export const LOAD_USERS = gql` query { users { edges { node { email } } } } `; GetUsers.js import React, { useEffect } from 'react'; import … -
Displaying HTML carrots without it being treated as HTML with DJango
I am working with a Django project and right now I am building my HTML table inside of my view and this displaying it on my html template. Some of the data that is in my table looks like <word>. The issue is when it gets displayed it is treating those carrots as HTML code and this the word is not being displayed. I am displaying my table like: {% autoescape off %} {{table}} {% endautoescape %} Any way to make sure the carrots get displayed correctly? -
Django-React deployed app how to go to admin app
i have a web app running on django api on the backend and React on the frontend, after deploying it to heroku everything is working great except i don't know how to go to the admin page since i used to access localy (before deployment) it via 127.0.0.1:8000/admin/ while the main page was running on localhost:3000/ -
ModuleNotFoundError: No module named 'allauth.accounts'
I need to to render two login and signup form on the same page and i use allauth package to do the process,i have already installed djano-allauth and added it to INSTALLED_APS ,this is my code: from allauth.accounts.views import SignupView from allauth.accounts.forms import LoginForm class CustomSignupView(SignupView): # here we add some context to the already existing context def get_context_data(self, **kwargs): # we get context data from original view context = super(CustomSignupView, self).get_context_data(**kwargs) context['login_form'] = LoginForm() # add form to context return context but i get this error : ModuleNotFoundError: No module named 'allauth.accounts' i don't know why i get this error while i have installed the django-allauth package! -
Why js doesn't save in html some information
I am working with django and I am using js and Maps JavaScript API in my web. So, in JS I am saving two values: document.getElementById(id_latitude).value = latitude; document.getElementById(id_longitude).value=longitude; However, the previus lines doesn't save values in the first POST, but yes in the second. I don't know why. Thank you -
Call my Search results view with valid parameters from search
I have a function which puts up a search template and when the search template is completed and valid, calls my search results view which generates the result based on the completed parameters in the response. My problem is I used render to put up the search results page, and the URL does not change (ie. the URL still says get_search, instead of search_results..). It means that the pagination won't work because it doesn't have the correct URL. What should I use to pass the response to the search results view and change the URL. Attempted reverse_lazy but as I expected it gave me an attribute error - 'proxy' object has no attribute 'get'. My function is below: def get_search(request): if request.method == 'POST': form = SearchForm(request.POST) request.method = "GET" request.GET = request.POST if form.is_valid(): return SearchResultsView.as_view()(request) else: form = SearchForm() if form.is_valid(): return SearchResultsView.as_view()(request) else: form = SearchForm(request.GET) return render(request, 'get_search.html', {'form':form}) The search Results view is pretty lengthy but the beginning of the search_results view looks like this: class SearchResultsView(ListView): model = Program template_name = 'search_results.html' paginate_by = 5 def get_context_data(self, **kwargs): context = super(SearchResultsView, self).get_context_data(**kwargs) # segment_results = None program_results = None segment_program_list = None query = … -
Base 64 encoded in python2.7 and decoding in python3.6
Facing issue when base64 decoding in python3.6 whatever encoded in python2.7. Python 2.7: Below is the code, using for encoding. encoded_session = base64.b64encode('{}:{}'.format(_hash,session_str).encode('ascii')).decode('ascii') Let's assume I have some value for _hash and session_str. Python 3.6: I have the encoded_session already and below is what I am trying to decode. _hash, session_str = base64.b64decode(encoded_session).split(b':', 1) when I am executing this, getting the below error. binascii.Error: Incorrect padding I have tried multiple things adding b'==' in encoded_session and other stuff but nothing helps. Please help. -
Only return users that are not already part of a Patient relationship
In my current implementation I can query for users by name. I would like however that the search results only contain users that do not appear as part of a Patient relationship for a certain therapist. Should I try to populate my user objects with their therapist? Or is there a way to filter users out that appear in Patient table with a certain therapist? class User(AbstractUser): is_therapist = models.BooleanField(default=False) is_patient = models.BooleanField(default=True) def __str__(self): return self.email class Patient(models.Model): therapist = models.ForeignKey(User, related_name="patients", on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) complaints = models.TextField(blank=True, default="") class Meta: constraints = [ models.UniqueConstraint(name='unique_patient', fields=['therapist', 'user']) ] class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): queryset = User.objects.all() full_name = self.request.query_params.get('full_name', None) therapist_id = self.request.query_params.get('therapist_id', None) if full_name is not None: queryset = User.objects.annotate(full_name=Concat('first_name', V(' '), 'last_name')).filter(full_name__icontains=full_name) return queryset -
django.db.utils.IntegrityError: null value in column "extra" of relation "units_unit" violates not-null constraint
I'm getting a strange error that I can't find information for. The error occurs for app 'units' on my site deployed on Heroku; it doesn't happen locally. It is as if Django has created a table column that I'm not allowed to access? models.py: class Unit(models.Model): div_number = models.CharField(max_length=200, null=True) div_type = models.CharField(max_length=200, default=None, blank=True, null=True) unit_hierarchy = models.CharField(max_length=200, null=True) nationality = models.CharField(max_length=200, null=True) To demonstrate the error, I'll try to create an instance: >>> from units.models import Unit >>> x=Unit(div_number='1st',div_type='Infantry',unit_hierarchy='Division',nationality='Canada') >>> x <Unit: Canada 1st Infantry Division> But then x.save() gives the following error traceback. >>> x.save() Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.NotNullViolation: null value in column "extra" of relation "units_unit" violates not-null constraint DETAIL: Failing row contains (118, 1st, Infantry, Division, Canada, null). The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 763, in save_base updated = self._save_table( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 868, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 906, in _do_insert return manager._insert( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method … -
Django read passwords without bcrypt$
I am using a legacy database that stores passwords for a different application, I have integrated django with it and I found that django reads the password if it has this prefix bcrypt$ django validates this one bcrypt$$2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK the app is storing this way $2a$10$Pdg3h8AVZ6Vl3X1mMKgQDuMriv8iysnValEa5YZO3j9pEboLrOBUK settings.py PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.BCryptPasswordHasher', ] -
Why does ExtractIsoYear annotation not filter correctly?
In Django 2.2.18, if I create an annotation that extracts the IsoYear, I can't filter on it correctly. Why? import datetime from django.db import models from django.db.models.functions import ExtractIsoYear class Meal(models.Model): time = models.DateTimeField(db_index=True) Meal(time=datetime.datetime(2019, 12, 31)).save() Meal(time=datetime.datetime(2020, 1, 1)).save() Meal(time=datetime.datetime(2020, 1, 2)).save() query = Meal.objects.all().annotate( isoyear=ExtractYear('time') ) print(query[0].isoyear) # 2020 print(query[1].isoyear) # 2020 print(query[2].isoyear) # 2020 print(query.filter(isoyear=2020).count()) # 2 My expectations is that, if the annotation for isoyear is 2020, and I filter for the isoyear=2020, all three results should be returned. Was this a bug in Django 2? -
Best approach to create a global search field for a postgres table in Django based GraphQL API?
I am working with an Angular UI with a Django-graphene GraphQL API and a postgres db. Currently I have implemented a functionality to arrive at a global search field by adding a "searchField" for each table and updating it with each create and update of an item in that table. And using the graphql filter, every time a user would do a global search, I would just filter hte searchField for the query. I am very new to Django so I'm not sure if this is an efficient way to go about this, but this is what I have:- Create mutation class CreateUser(graphene.Mutation): class Arguments: input = UserInput(required=True) ok = graphene.Boolean() user = graphene.Field(UserType) @staticmethod def mutate(root, info, input=None): ok = True searchField = input.username if input.username is not None else "" + \ input.title if input.title is not None else "" + \ input.bio if input.bio is not None else "" user_instance = User(user_id=input.user_id, title=input.title, bio=input.bio, institution_id=input.institution_id, searchField=searchField) user_instance.save() return CreateUser(ok=ok, user=user_instance) Update mutation class UpdateUser(graphene.Mutation): class Arguments: id = graphene.Int(required=True) input = UserInput(required=True) ok = graphene.Boolean() user = graphene.Field(UserType) @staticmethod def mutate(root, info, id, input=None): ok = False user = User.objects.get(pk=id) user_instance = user if user_instance: ok = … -
Django. Should I use ForeignKey or Addtional Cross Table for one to many relation?
I'm aware of this question was asked before, but that question doesn't have concise answer for my problem. I'm bit confused after seeing two examples in order to impelement OneToManyRelation. In my example: class Product(BaseModel): name = models.CharField(max_length=255) class Advantages(BaseModel): title = models.CharField(max_length=255) product = models.ForeignKey(Product, PROTECT) Different products can have many advantages linked to it, so I'm using ForeignKey for this, but here I saw that it is also possible to use cross table relation in order to implement OneToManyRelation categories & sub categories with many to many relationship class ProductAdvantage(BaseModel): title = models.CharField(max_length=255) product = models.ForeignKey(Product, CASCADE) Which one best practice for the OneToManyRelation? One product can have many advantages Thank you for the answer -
Forever loop in Django?
Is it possible to have an infinite loop in Django which listens to a queue? For example: class tester(): def __init__(self): pass def test(self): while (True): print("Does this block?2") def tester(self): while(True): print("Does this block?") class Test(AppConfig): def ready(self): test = tester() t1 = threading.Thread(target=test.test) t1.start() t2 = threading.Thread(target=test.tester) t2.start() It seems to block at the first loop. Any pointers on how to start two forever loops on Django? -
How to Create a Business Owner Page on my django blog
I have created a blog successfully and am looking to add a Business Owner Page to my blog but dont seem to get any reuasble module package that comes along on github or any other site. I am just looking to plug the code into my blog that has a decent look and feel. -
How to integrate Reinforcement Learning Algorithms with Firebase?
I'm working on an ITS(Intelligent Tutoring System) which will recommend suggested materials and questions on the basis of the level of student. My data is stored in Firebase(NoSQL). I have to create an RL environment and integrate it with firebase. Can someone guide me on how to do that? In django, I'm able to find a method where we can train the existing data and save the model and then connect with django to predict based on the data on which the model was trained.. but nothing like realtime connection where instantly data is taken as input and then trained on spot and predict accordingly. I also came across https://www.tensorflow.org/agents/overview but unsure if it will work in my case. -
Get the count of the same options from multiple dropdowns in a table
in this table I need to get the total count of options having green value selected or red or yellow from the dropdown bar and show it on the green yellow re input boxes. Html Code: <td> <select class="form-control col-md-6 " type="text" id="Zone" name="Zone"> {% for z in Zone %} <option value="{{z.ZoneName}}">{{z.ZoneName}}</option> {% endfor %} </select> Database Table -
Django Rest Framework Nested Relationships Displays ID
Basically I have a receipt that has a Vendor, and Location associated with it. I would like the HTTP get requests to return the associations as nested models. Following the documentation here to create the serializers does not get the expected result. python: 3.9.1 django: 3.2.3 djangorestframework: 3.12.4 models.py from django.db import models class Vendor(models.Model): description = models.CharField(max_length=1000, blank=True, null=True) def __str__(self) -> str: return self.description class VendorLocation(models.Model): description = models.CharField(max_length=5000, blank=True, null=True) vendor = models.ForeignKey( Vendor, blank=True, null=True, on_delete=models.CASCADE, related_name='locations', ) def __str__(self) -> str: return self.description class Receipt(models.Model): datetime = models.DateTimeField(null=True, blank=True) vendor = models.ForeignKey( Vendor, blank=True, null=True, on_delete=models.SET_NULL, related_name='receipts', ) location = models.ForeignKey( VendorLocation, blank=True, null=True, on_delete=models.SET_NULL, related_name='receipts', ) subtotal = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) tax = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) serializers.py from rest_framework import serializers from .models import Vendor, VendorLocation, Receipt class VendorSerializer(serializers.ModelSerializer): class Meta: model = Vendor fields = '__all__' class VendorLocationSerializer(serializers.ModelSerializer): class Meta: model = VendorLocation fields = '__all__' class ReceiptSerializer(serializers.ModelSerializer): vendor: VendorSerializer(many=False) location: VendorLocationSerializer(many=False) class Meta: model = Receipt fields = [ 'datetime', 'subtotal', 'tax', 'amount', 'vendor', 'location', ] views.py from rest_framework import viewsets from .models import Receipt from .serializers import ReceiptSerializer class ReceiptViewSet(viewsets.ModelViewSet): queryset = Receipt.objects.all() … -
Django testing with psql schemas
I've got a couple of models like this (nothing fancy really) class Building(SchemaModel): name = models.CharField(max_length=50, null=False) site = models.ForeignKey(Site, null=False, on_delete=models.CASCADE) def __str__(self): return self.name They are saved in a PSQL Database with implemented schemas as asked in a previous post here basically my models all extend a the base class SchemaModel class SchemaModel(models.Model): """Base Model for dynamically implementing schema information""" class Meta: abstract = True managed = True and at the end of models.py make sure the db_table property has the correct schema in it for model in SchemaModel.__subclasses__(): db_table = '{}s'.format(model._meta.label_lower.replace('.', '\".\"')) model._meta.original_attrs['db_table'] = db_table model._meta.db_table = db_table i also added options to the database profile in settings.py (jdb is the schema used) 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=jdb,public' }, This has worked perfectly fine until i implemented unit tests. Django's unit test engine creates its own database but doesn't create the schema it needs. Nonetheless it tries to access the same schema as on the real db on the test db which isn't there. After creating the test database the test engine tries to create the table "jdb"."buildings" and obviously fails. stacktrace: (venv) C:\code\py\thommen>py manage.py test jdb schema: jdb table: companys new db_table=jdb_companys schema: jdb … -
ValueError: Cannot assign "'26 Balkanskaya Street'": "paidparking.adress" must be a "Parking" instance
I have a model paidparking class paidparking(models.Model): adress = models.ForeignKey(Parking, on_delete=models.SET_NULL, null=True) carnumber = models.CharField(max_length=150) amountoftime = models.IntegerField() price = models.FloatField() telephone = models.CharField(max_length=20) email = models.EmailField(,null=True,blank=True ) datetimepaidparking = models.DateTimeField(auto_now_add=True) expirationdate = models.DateField(null=True) expirationtime = models.TimeField(null=True) enddateandtime = models.DateTimeField(null=True,blank=True) Model Parking: class Parking(models.Model): adress = models.CharField(max_length=150) starttime = models.TimeField(auto_now=False, auto_now_add=False,null=True) endtime = models.TimeField(auto_now=False, auto_now_add=False,null=True) minimaltimeforpayment = models.CharField(max_length=50) price = models.IntegerField() numberofavailableseats = models.IntegerField(default=0) tickets = models.ManyToManyField('tickets', blank=True) I have a page on the site where there is a form. Through this form I save the data to the model class paidparkingForm(forms.ModelForm): class Meta: model = paidparking fields = ['adress','carnumber','amountoftime', 'price', 'email','telephone','expirationdate','expirationtime','enddateandtime'] widgets = { 'adress': forms.Select(attrs={"class": "form-control form", "id": "exampleFormControlSelect1"}), 'carnumber': forms.TextInput(attrs={"class": "form-control form-control-lg form"}), 'amountoftime': forms.NumberInput(attrs={"class": "number form-control form-control-lg form", "disabled": 1}), 'price': forms.NumberInput(attrs={"class": "form-control form-control-lg form", "readonly": 0}), 'email': forms.EmailInput(attrs={"class": "form-control form-control-lg form"}), 'telephone': forms.TextInput(attrs={"class": "form-control form-control-lg form"}), 'expirationdate': forms.DateInput(attrs={"type": "date","class": "form form-control form-control-lg", "disabled": 1}), 'expirationtime': forms.TimeInput(attrs={"type": "time", "class": "form form-control form-control-lg", "disabled": 1}), 'enddateandtime': forms.TextInput(attrs={"class": "form form-control form-control-lg", "readonly": 0}), } How do I save data to the model directly from the function? I do this def save_payment_parking(request): adress = request.GET["adress"] carnumber = request.GET["car_number"] amountoftime = request.GET["amount_of_time"] price = request.GET["price"] telephone = request.GET["telephone"] expirationdate = … -
django- clicking on href link redirects me to the index page rather than web page pointed
İmplemented pinax django-user-accounts to my project and followed the instructions for quick use.After the package implementation the migrations works perfectly but when i arranged the href links towards sign-up and login page it redirects me to the homepage. i suppose im missing something very basic, and i need help.. below you can see my url-mappings and the href links.. main.urls from django.contrib import admin from django.urls import path from django.conf.urls import url,include from zetamedweb import views from django.conf.urls.static import static app_name = 'Index' urlpatterns = [ url(r"^$", views.IndexView.as_view(),name='ındex'), url('admin/', admin.site.urls), url(r"^ Treatments/", include('Treatments.urls')), url(r"^ AboutUs /", include('About_Us.urls')), url(r"^ Contact /", include('Contact.urls')), url(r"^ Travel_Tips /", include('Travel_Tips.urls')), url(r"^ Destinations/", include('Destinations.urls')), url(r"^ FAQ/", include('FAQ.urls')), url(r"^ TailorMade/", include('TailorMade.urls')), url(r"^ APP/",include('APP.urls')), url(r"^account/", include("account.urls")), ] app.urls(i included only app_name for url purposes) from django.urls import path from django.conf.urls import url from account.views import ( ChangePasswordView, ConfirmEmailView, DeleteView, LoginView, LogoutView, PasswordResetTokenView, PasswordResetView, SettingsView, SignupView, ) app_name = 'Lol' urlpatterns = [ url("signup/$", SignupView.as_view(), name="account_signup"), url("login/$", LoginView.as_view(), name="account_login"), url("logout/$", LogoutView.as_view(), name="account_logout"), url("confirm_email/<str:key>/$", ConfirmEmailView.as_view(), name="account_confirm_email"), url("password/$", ChangePasswordView.as_view(), name="account_password"), url("password/reset/$", PasswordResetView.as_view(), name="account_password_reset"), url("password/reset/<str:uidb36>/<str:token>/$", PasswordResetTokenView.as_view(), name="account_password_reset_token"), url("settings/$", SettingsView.as_view(), name="account_settings"), url("delete/$", DeleteView.as_view(), name="account_delete"), ] and href links at html page that supposed to redirect me login and signup page instead of homepage.. … -
Filter nested list by map key
I have a list like given in bellow. I want to filter this data using "map" key. [ { "model": "map.mapreferencepoints", "pk": 3, "fields": {"map": 2, "referenceName": "RF1", "corX": 906, "corY": 377}}, { "model": "map.mapreferencepoints", "pk": 4, "fields": {"map": 1, "referenceName": "RF2", "corX": 1017, "corY": 377}}, { "model": "map.mapreferencepoints", "pk": 5, "fields": {"map": 2, "referenceName": "RF3", "corX": 1171, "corY": 377}} ] I want to get data has only map = 1 like; [ { "model": "map.mapreferencepoints", "pk": 4, "fields": {"map": 1, "referenceName": "RF2", "corX": 1017, "corY": 377} } ] How can I filter data by map key in this way?