Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React and Django Cannot post Image using react hooks and formData()
I am trying to upload image to my Django model, Can use same API from postman and upload image as expected, but when posting through react I get error and in colsole formdata is not able to create a object to send to API. Also, everything works fine if I remove picture append, imagefield can be null in my model. import React, { useState, useEffect } from "react"; import { FaExclamationCircle } from "react-icons/fa"; import { Button } from "../../globalStyles"; import { useForm } from "react-hook-form"; import { ErrorsSignUp, FormField, FormName } from "../Login/Login.element"; import { PopContainer, ModalWrapper, FromContainer, FormFieldImage, } from "./AddItem.element"; import axios from "axios"; const AddItem = ( callback, { showModal, seteShowModal }, requestType, articleID ) => { const [values, setValues] = useState({ title: "", price: "", category: "", quantity: "", }); const data = [ { title: "new comer", description: "This is coming from form ", completed: true, }, ]; const handleChange = (e) => { const { name, value } = e.target; setValues({ ...values, [name]: value, }); }; const handleSubmit = (e) => { const formData = new FormData(); formData.append("title", values.title); formData.append("category", values.category); formData.append("quantity", values.quantity); formData.append("price", values.price); formData.append("picture", values.picture); # It works if I comment … -
How can I add 'dynamic' (?) data to the Django admin panel
Full disclosure, I'm working on this project that I did not start. My knowledge of Django is fairly limited, so I apologize if I make a mistake in my wording or otherwise. In our DB our objects have a UUID that we generate upon creation. In our backend, we have code that converts the UUID into a base64 token and subsequent verification hash. We use these two pieces of data to generate unique URLs for our users. Obviously we don't want these pieces of data to be stored, as that would defeat the entire security purpose. However, we want to be able to see this data in the admin panel when looking at the specific object. So my question is, how can I load this data into the form without storing it permanently in the object? We want to add a generated URL at the bottom of the form, picture included for reference: image -
Django: How to return a field from a ForeignKey model through filter queryset. As it throws not JSON Serializable
I want to return a field from the Contet model which is a ForeignKey field of Saved model. I'm using filter queryset since it returns multiple values. But, the problem is I can't return the slug field from Content model by using content.slug after Saved.objects.filter(user=self.request.user)! Content model: class Content(models.Model): title = models.CharField(max_length=200, blank=False) slug = models.CharField(max_length=200, blank=False) ... My Saved model: class Saved(models.Model): content = models.ForeignKey('Content', on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ... My view: class SavedList(viewsets.ModelViewset): serializer_class = SavedSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): return Saved.objects.filter(user=self.request.user) def list(self, request): savedList = [] for i in self.get_queryset(): dict = { 'slug': i.content.slug, # i want this 'content': i.content, 'user': i.user } savedList.append(dict) return Response(savedList) When I'm running this, it's returning Object of type 'Content' is not JSON Serializable! How do I get the slug from Content model? -
I want to use fields in an object to filter product
Here is my model: class PromotedProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) start_date = models.DateField( verbose_name="When do you want your advert to start", null=True, blank=True) stop_date = models.DateField( verbose_name="When do you want your advert to end", null=True, blank=True) is_promotion_paid = models.BooleanField(default=False) is_active = models.BooleanField(default=False) created_at = models.DateTimeField( auto_now_add=True, editable=False, null=True) updated_at = models.DateTimeField(auto_now=True, editable=False, null=True) class Product(models.Model): merchant = models.ForeignKey( MerchantProfile, on_delete=models.SET_NULL, null=True) name = models.CharField(verbose_name="Product Title", max_length=255, null=True, blank=True) is_digital = models.BooleanField(default=False, null=True, blank=False) category = models.ForeignKey( ProductCategory, on_delete=models.RESTRICT, null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to='products') product_video_provider = models.CharField( max_length=60, null=True, blank=True) product_video = models.CharField(max_length=60, null=True, blank=True) brand = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) class ProductCategory(models.Model): name = models.CharField(max_length=200, null=True) image = models.ImageField(null=True, blank=True, default="category/blank.jpg", upload_to='category') icon = models.ImageField(null=True, blank=True, default="category/icon.jpg", upload_to='category') added_by = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True, null=True, blank=True) slug = models.SlugField(null=True, unique=True, default=None) I want to filter our promoted products under a category, say we have the category "computers" and a promoted product "Laptop" which has the category "computers". i want to filter my PromotedProduct table with products under the category 'computers', i tried this but got an error, any help will be appreciated: def promoted_products(request) cat = ProductCategory.objects.get(slug='computers') promoted = PromotedProduct.objects.filter(product.category=cat … -
I am getting an error in when i am trying to execute django models migrate command - python manage.py migrate . How to solve this error?
from django.db import models from django.contrib.auth.models import User class Student(models.Model): rollno = models.CharField(max_length=13) name = models.OneToOneField(User, on_delete=models.CASCADE) dept = models.CharField(max_length=30) def __str__(self): return str(self.name) class Subject(models.Model): subname = models.CharField(max_length=50) deptname = models.CharField(max_length=50) def __str__(self): return str(self.subname) PS C:\Users\Akhil\Desktop\django\studentportal> python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, studentapp Running migrations: Applying studentapp.0003_auto_20210602_0944...Traceback (most recent call last): File "C:\Users\Akhil\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\fields_init_.py", line 1823, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'CSE' I tried to delete a model which I have created. After deleting whenever I try to migrate the model, I am getting this error. So I added the same model Subject again -
Errors When I try to migrate in django python
I was following This Tutorial https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=19075s I am not able to migrate models to intial.py this is the Intial enter image description here apps enter image description here models enter image description here settings enter image description here Squlite enter image description here When I run make migrations enter image description here when I run migrate enter image description here I can't migrate all of the models to the intial.py I'm a begginer . I'm trying to figure out in th last few days , But I can't .Anyone please help -
Django form - how to use django on HTML with radio button options with image tag
I have a following HTML script that does what I want to achieve, obviously with CSS and JS. <form id="wrapped" method="POST"> <div class="container"> <div class="row"> <div class="col"> <div class="item"> <input id="id_1" name="group1" type="radio" class="required"> <label for="id_1"><img src="{% static 'website/images/Car.svg' %}" alt=""><strong>Motor vehicle</strong></label> </div> </div> <div class="col"> <div class="item"> <input id="id_2" name="group1" type="radio" class="required"> <label for="id_2"><img src="{% static 'website/images/Motorcycle.svg' %}" alt=""><strong>Motorcycle</strong></label> </div> </div> This is what I want to achieve (radio select with an image inside a box):outcome - Target and I am tring to use Django to achieve the same result and here is what I have so far: Model.py class Asset_Category(models.Model): ASSET_TYPE = ( ('Car','Car'), ('Van','Van'), ('Plane','Plane') ) asset = models.CharField(max_length=20,choices=ASSET_TYPE,null=True) forms.py from django import forms from .models import Asset_Category from django.utils.safestring import mark_safe from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit class Asset_Form(forms.ModelForm): class Meta: model = Asset_Category fields = ['asset'] class Asset_Form_Form(forms.Form): asset = forms.ChoiceField(choices=ASSET_TYPE, initial=0, widget=forms.RadioSelect(attrs={'class':'form-check-inline'})) HTML - with django code <div class="container"> <div class="row"> <div class="col"> <div class="item"> {{ form.asset.0 }} <label for="{{ form.asset.id_for_label }}"><img src="{% static 'website/images/Car.svg' %}" alt=""></label> <strong>Car</strong> </div> </div> <div class="col"> <div class="item"> {{ form.asset.1 }} <label for="{{ form.asset.id_for_label }}"><img src="{% static 'website/images/Van.svg' %}" alt=""><strong>Van</strong></label> </div> </div> </div> … -
How to change default numpy error handling
The default numpy error handling is: import numpy as np np.geterr() # {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'} I know that I can change the error handling with: np.seterr(divide='raise', over='raise', under='ignore', invalid='raise') In my Django project, I have a lot of files that are importing numpy. Is there a way to change the default numpy error handling somehow, or do I really have to call np.seterr in each and every file? -
DoesNotExist at /admin/
DoesNotExist at /admin/ URL matching query does not exist. I copy code form old study-project and i haven't similar problem in old project. settings.py INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cutter', ] admin.py: from .models import URL from django.contrib import admin admin.site.register(URL) urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('cutter.urls')), path('admin/', admin.site.urls), ] All another functions work. -
Loading data in django project to new postgres database taking very long
In my django project I am trying to migrate my database from sqlite to postgres. I've made a dump file of the database, changed my settings file to reflect the new database and now I want to upload this data to postgres. So initially I was running the following in the terminal: python manage.py loaddata data.json But this took very long - it was still running for more than a day, with no errors, and I eventually I stopped it. So then I found this answer on SO, and therefore I created a load_data.py file, like so: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import django django.setup() from django.core.management import call_command from django.db import transaction DJANGO_SETTINGS_MODULE='mysite.settings' with transaction.atomic(): call_command('loaddata', 'data.json') And then run it via python load_data.py. But it still takes incredibly long and the data has not loaded. My data file is 20.8MB. Is there anything that I can do to speed things up? For reference, the model that has the most data looks like this: class WordManager(models.Manager): def search(self, query=None): qs = self.get_queryset() if query is not None: or_lookup = (Q(target_word__icontains=query) | Q(source_word__icontains=query)| Q(example_sentence__icontains=query) ) qs = qs.filter(or_lookup).distinct() # distinct() is often necessary with Q lookups return qs class Word(models.Model): objects … -
How to create a .exe file of the Django project?
Can someone tell me how to How to create a .exe file of the Django project? I build my project using Django, AJAX and Jquery now I want to make a windows desktop app. Can someone help me? I tried pyinstaller, exe file was generated but it was just opening a cmd prompt and closing it automatically. -
Django class based View with 2 post forms returns valid unknown
I've got a view in django where post method has 2 different types of form: def post(self, request): tweet_form = TweetForm(request.POST, request.FILES) comment_form = TweetCommentForm(request.POST) print(request.POST['form-button']) if request.POST['form-button'] == 'add_tweet': print(tweet_form.is_valid) if tweet_form.is_valid(): content = tweet_form.cleaned_data['content'] image = tweet_form.cleaned_data['image'] tweet = Tweet.objects.create( user=request.user, content=content, ) if image != None: tweet.image = image tweet.save() return redirect("/home") if request.POST['form-button'] == 'add_comment': print(comment_form.is_valid) if comment_form.is_valid(): content = comment_form.cleaned_data['body'] return redirect("/home") ctx = {"tweet_form": tweet_form, "comment_form": comment_form} return render(request, "home.html", ctx) The both forms have different name, value, and id. When i print (tweet_form.is_valid()) or (comment_form.is_valid()) i receive sth like: <bound method BaseForm.is_valid of <TweetForm bound=True, valid=Unknown, fields=(content;image)>> Respectively for both forms. Can i somehow reorganize view to deal with both of forms or i have to have another View? Regards -
django join filtered realted model
I have three related model and want Aggregated filtered result models: class Symbol(models.Model): name = models.CharField(max_length=50) status = models.SmallIntegerField(choices=Status.types, default=Status.enable) class SymbolDailyInfo(models.Model): symbol = models.ForeignKey('Symbol', null=True, on_delete=models.PROTECT) monthly_vol_avg = models.BigIntegerField() ct = jmodels.jDateTimeField(auto_now_add=True) class MarketSnapshot(models.Model): symbol = models.ForeignKey('Symbol', null=True, on_delete=models.PROTECT) ct = jmodels.jDateTimeField(auto_now_add=True) tvol = models.BigIntegerField(null=True, blank=True) I would like to get symbols which its last tvol is 3 more time its last monthly_vol_avg I write this filter the problem is how to filter latest SymbolDailyInfo and MarketSnapshot objects? qs = Symbol.objects.prefetch_related('marketsnapshot_set', 'symboldailyinfo_set')\ .filter(status=Status.enable, marketsnapshot__tvol__gte= 3 *F('symboldailyinfo__monthly_vol_avg'))\ .values_list('i18', 'marketsnapshot__tvol', 'symboldailyinfo__monthly_vol_avg') qs = qs.extra(select={'trade_vol_grth_rate': "marketsnapshot__tvol / symboldailyinfo__monthly_vol_avg"}) qs = qs.extra(order_by=['trade_vol_grth_rate']) -
django how to use Choices for a Model DecimalField
i need to have a field to store values in range of (-20 to 20 with step 0.25) and the values should be displayed like (1.50, 3.00, 5.25), so i thought i should use decimal instead of float an after some searching i have used this function to generate the required range : def decimal_range(A, B, X): """ function to generate decimal floating numbers from start(A), to end(B), by step(X) """ getcontext().prec = 5 while A < B: yield float(A) A += Decimal(X) and generated the filed choices like so. S_CHOICES = tuple(tuple([i, f"{i:.2f}"]) for i in decimal_range(-20, 20.25, 0.25)) the result tuple is ((-20.0, '-20.00'), (-19.75, '-19.75'), (-19.5, '-19.50'), (-19.25, '-19.25'), (-19.0, '-19.00'), ...) the model field is arrs = models.DecimalField(max_digits=4, decimal_places=2, choices=S_CHOICES, null=True, blank=True, default=None) and when looking inside the db.sqlite3 file i see some different values like (-20 instead of -20.0). also when checking from python shell for field value it is like Decimal('15.00'), Decimal('4.50') in the end if i submitted a form with this field to value like 7.50 or 7.00 it is saved and retrieved correctly, but when trying to update this form the field value is going to be empty but if the value … -
Build a Third Party API Using Django
I am interested in building a third party software to provide service through API. But the problem is I don't have any in depth knowledge related to this (i.e how am I suppose to count the api calls, where I will store the data from both side like this) Can someone suggest me some resources that will help me to go through this. Thank you! -
allauth urls are not accessible - 404 error
Can someone please help to solve my issue. Thanks in advance when i try to access 'accounts/' in django,then causing 404 error. I'm using allauth. URL Trying to access : http://127.0.0.1:8000/accounts/ URL's below are showing errors: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/ Using the URLconf defined in videoservice.urls, Django tried these URL patterns, in this order: admin/ accounts/ ^ ^signup/$ [name='account_signup'] accounts/ ^ ^login/$ [name='account_login'] accounts/ ^ ^logout/$ [name='account_logout'] accounts/ ^ ^password/change/$ [name='account_change_password'] accounts/ ^ ^password/set/$ [name='account_set_password'] accounts/ ^ ^inactive/$ [name='account_inactive'] accounts/ ^ ^email/$ [name='account_email'] accounts/ ^ ^confirm-email/$ [name='account_email_verification_sent'] accounts/ ^ ^confirm-email/(?P<key>[-:\w]+)/$ [name='account_confirm_email'] accounts/ ^ ^password/reset/$ [name='account_reset_password'] accounts/ ^ ^password/reset/done/$ [name='account_reset_password_done'] accounts/ ^ ^password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(? P<key>.+)/$ [name='account_reset_password_from_key'] accounts/ ^ ^password/reset/key/done/$ [name='account_reset_password_from_key_done'] accounts/ ^social/ ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, accounts/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Problem to run a check in my database in django
I have created a model called Certs, the models is registered and it is showing in the admin page, however I am trying to call it to run a check and try to make a task, but I am getting the error: No module named 'ships', This is the structure of my project (note I am writing the code in reminders.py): And here my code: from django.core.mail import send_mail from ships.models import Certs from datetime import datetime, timedelta b = Certs.objects.count() def notifications(): for dates in range(b): if Certs.exp_date[b] <= datetime.datetime.now() - timedelta(days=30): send_mail(subject='Test',message='This is a reminder where you will be reminded about expiring certifications', recipient_list=['info@intermaritime.org']) Thank you very much -
How can I upload file using DRF in my own custom html template?
class Contents(models.Model): name = models.CharField(max_length=100) formula = models.CharField(max_length=20) description = models.TextField(null=True, max_length=100) wiki = models.CharField(null=True, max_length=100) youtube = models.CharField(null=True, max_length=100) file = models.FileField() def __str__(self): return self.name this is my models.py class ContentsListCreateAPIView(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'admin3.html' style = {'template_pack': 'rest_framework/vertical/'} def get(self, request): queryset = Contents.objects.all() serializer = ContentsSerializer return Response({'serializer': serializer, 'contents': queryset, 'style': self.style}) def post(self, request): queryset = Contents.objects.all() serializer = ContentsSerializer(data=request.data) print(serializer.is_valid()) print(serializer.data) if serializer.is_valid(): serializer.save() return redirect('contents_list') return redirect('contents_list') views.py from rest_framework import serializers from .models import Contents class ContentsSerializer(serializers.ModelSerializer): class Meta: model = Contents fields = '__all__' serializers.py <form action="{% url 'contents_list' %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> admin.html It seems that the filefield does not get the proper input. I don't get what the problem is. The CreateAPIView works well when I use the default DRF template. -
Modelform: Missing Manytomany field in cleaned_data
I've got all the fields needed in the form.cleaned_data dict except one field is missing, the manytomany field. It's in form.data though. models.py class Tags(models.Model): tagtext = models.CharField(max_length=20) class Taggeditems(models.Model): name = models.CharField(max_length=20) tags = models.ManyToManyField(Tags, related_name='item_with_this_tag') forms.py class TaggeditemsForm(forms.ModelForm): name = forms.CharField(max_length=200,required=True) tags = tag_fields.TagsInputField(queryset=Tags.objects.all(), create_missing=True, required=False) class Meta: model = Taggeditems fields = '__all__' widget= { 'tags': tag_widgets.TagsInputWidget, } views.py if request.method == 'POST': f = TaggeditemsForm(request.POST) if f.is_valid(): if 'new' in request.GET.keys(): saved_taggeditem = f.save(commit=False) saved_taggeditem.save() saved_taggeditem.tags.set(f.cleaned_data["texttags"]) f.save_m2m() ... else: f = TaggeditemsForm(request.user, request.POST) ... I'm using an app django-tag-input for the display of the tag by the way. So I've got, when posting, the field tags in f.data but it's missing in f.cleaned_data (whereas the field name is present in both f.data and in f.cleaned_data). -
Creating a AP quiz using Django involving HTML
I currently use Django 3.1.2 and Python 3.7. I have a problem with creating the quiz below. Here's my code: views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import Question from .models import Answer #from .models import Answer # Create your views here. def index(request): return render(request, 'apquiz/index.html') #print(request.POST) def question(request): template = loader.get_template('apquiz/hi.html') questions = ["1. What is Dosie's position in PURPLE KISS?", "2. Yuki's position in PURPLE KISS, based on this excerpt is:","3. PURPLE KISS has how many members:","4. PURPLE KISS debuted on","5. Which of the following is PURPLE KISS's main vocalist?"] answers = [{'a. main rapper, main dancer, vocalist':0,'b. lead dancer, lead rapper':0, 'c. main dancer, vocalist':1,'d. main dancer, lead rapper':0},{'a. lead dancer, vocalist, rapper, visual':0,'b. lead rapper, lead dancer, vocalist, visual':0, 'main rapper, lead dancer, vocalist, visual':1, 'd. main vocalist, lead dancer, rapper, visual':0},{'a. 7':1,'b. 2':0,'c.9':0,'d.2':0}, {'a. August 3, 2020':0,'b. March 15, 2021':1, 'c. February 3, 2021':0,'d. November 26, 2020':0},{'a. Yuki':0,'b. Dosie':0,'c. Jieun':0,'d. Swan':1}] #questions = Question.objects.get() #answers = Answer.objects.get() print(questions) print(answers) context = {} numberofquestions = len(questions) numberofcorrectanswers = 0 for i in questions: … -
how to File upload in graphene django
hello i wanted to upload images and files in graphene , i am bit confused here in what i want to do... here is my code below seems like its not working i installed package graphene file upload schema.py class Users_Type(DjangoObjectType): class Meta: model = Users fields = '__all__' class Users_mutation(graphene.Mutation): class Arguments: name = graphene.String() password = graphene.String() image = Upload() users = graphene.Field(Users_Type) def mutate(cls,info,name,image,password): user = Users(username=name,password=password,user_profile=image) user.save() return Users_mutation(users=user) Under main mutation class create_user = Users_mutation.Field() my main goal is to upload files and images , pls tell me how to do it and neccassary string that need to be put in mutation... Help would be appreciated -
Customise JWT auth-token generation using user_id and otp as input
I have a system that uses 'mobile_number' and 'otp' for login. For the purpose I have create the first api that accept the mobile number and returns the user details. Otp generation and sending is done in the sane api. I want to create the togen-generation api, and the api accepts 'user_id' and 'otp'. Models: class User(AbstractUser): password = models.CharField(max_length=128, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) dial_code_id = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100, blank=True, null=True) username = models.CharField(max_length=150, unique=True, blank=True, null=True) is_resource = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) skills = models.ManyToManyField(Skills) class Meta: db_table = "my_user" def __str__(self): return self.mobile_number class Otp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) otp = models.IntegerField() created_on = models.DateTimeField(default=timezone.now()) class Meta: db_table = "otp" I have done the Token generation using https://django-rest-framework-simplejwt.readthedocs.io/en/latest/ but the below endpoint, path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), it accepts username and password for token generation. I am a beginner to django-rest and I want your help for the customisation. -
How to get square box to dropdown list in javascript
A square box of color corresponding to each condition is output, not a value in the column. And I am using Datatable jquery, in the dropdown list of the column I want a square box of three colors to be printed. (So the goal is to only see the green square box when you select the green square box.) $(this).val() -> Should I change this part? <td> <div> {% if alpha == 'A' %} <div class="square-box green"></div> {% elif alpha == 'B' %} <div class="square-box gray"></div> {% elif alpha == 'C' %} <div class="square-box yellow"></div> {% endif %} </div> </td> $(document).ready(function() { $('#table').DataTable( { initComplete: function () { this.api().columns().every( function () { var column = this; var colTitle = this.header().innerHTML; var select = $('<select><option class="" selected>' + colTitle + '</option></select>') .appendTo( $(column.header()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option>'+d+'</option>' ) } ); } ); } } ); } ); -
Django saml2 login missing session variables
For my Django application, I am trying to enable SSO using Djangosaml2 and following are the versions I am using djangosaml2==1.2.0 pysaml2==7.0.0 djangorestframework==3.12.2 Django==3.1.7 python==3.8 My saml2_settings is as follows from os import path import saml2 import saml2.saml from app.local_settings import SERVER_URL AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'djangosaml2.backends.Saml2Backend', ) SAML_SESSION_COOKIE_NAME = 'saml_session' SAML_ATTRIBUTE_MAPPING = { 'username': ('username', ), 'email': ('email', ), 'first_name': ('first_name', ), 'last_name': ('last_name', ), } BASEDIR = path.dirname(path.abspath(__file__)) SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' LOGIN_URL = '/saml2/login/' LOGOUT_URL = '/saml2/logout/' SESSION_EXPIRE_AT_BROWSER_CLOSE = True SAML_CREATE_UNKNOWN_USER = True SAML_SERVER_URL = '10.23.1.114' SAML_ENABLED = True # MIDDLEWARE.append('djangosaml2.middleware.SamlSessionMiddleware') SAML_CONFIG = { # full path to the xmlsec1 binary programm 'xmlsec_binary': '/usr/bin/xmlsec1', # your entity id, usually your subdomain plus the url to the metadata view 'entityid': path.join(SAML_SERVER_URL, 'saml2/metadata'), # directory with attribute mapping 'attribute_map_dir': path.join(BASEDIR, 'attribute_maps'), # this block states what services we provide 'service': { # we are just a lonely SP 'sp' : { 'name': 'Dummy app', 'allow_unsolicited': True, 'authn_requests_signed': True, 'force_authn': True, 'want_response_signed': True, 'want_assertions_signed': True, 'logout_requests_signed': True, 'name_id_format_allow_create': False, 'endpoints': { # url and binding to the assetion consumer service view # do not change the binding or service name 'assertion_consumer_service': [ (path.join(SAML_SERVER_URL, 'saml2/acs/'), saml2.BINDING_HTTP_POST), ], # url and binding to … -
what is difference b/w django-admin startapp vs python manage.py startapp?
both does the same job creating the app in projects what the different between these two in Django?