Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
saving image in a create/update view in django
In the model i have ImageField: image = models.ImageField(null=True, blank=True, upload_to='post_images') The problem is when i am trying to add a picture in create/update view. It does not work. It looks like it is working, there is no erros, but the image is not being saved. The only way I can do this is by django admin panel. create view: class PostCreateView(generic.CreateView): model = Post template_name = 'posts/create.html' form_class = PostModelForm def form_valid(self, form): post = form.save(commit=False) post.author = self.request.user post.save() return super(PostCreateView, self).form_valid(form) def get_success_url(self): return reverse('posts:home') urls: if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) form: class PostModelForm(forms.ModelForm): class Meta: model = Post fields = ( 'title', 'text', 'image', ) settings: MEDIA_URL = '/media/' MEDIA_ROOT = 'media_root' What can be the problem? -
How to make a sampling to get rid of duplicates in the GeneriсForeignKey model?
I'm already broken. I want to get rid of the duplicates that seem to come from files and articles. I am displaying comments, specifically the comment block in the sidebar. @register.simple_tag() def get_last_comments(): article_comments = Comment.objects.filter(content_type=ContentType.objects.get_for_model(Article)).select_related('author') files_comments = Comment.objects.filter(content_type=ContentType.objects.get_for_model(File)).select_related('author') result_list = sorted(chain(article_comments, files_comments), key=attrgetter('time_create'), reverse=True)[:5] return result_list I want to add a prefetch_related in order to get rid of duplicates from materials. In models class File(models.Model): ...some fields... author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) category = models.ForeignKey('Category', on_delete=models.PROTECT) comments = GenericRelation(Comment, related_query_name='file', related_name='file_comments_related') class Article(models.Model): ...some fields... category = models.ForeignKey('Category', on_delete=models.PROTECT) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) type = models.ManyToManyField('Type', blank=True) comments = GenericRelation(Comment, related_query_name='article', related_name='article_comments_related') How can I enter prefetch_related correctly? I looked through other topics, but it does not work for me as it should. It is necessary that the type, categories, author do not make duplicates. -
How to create front end for a chat bot made with python, json, react?
I've learnt basic HTML, CSS but have no idea how I'd link a pre-existing backend created by someone else as a web app. I've heard Django and Flask, but no idea how to get started. Trying to learn fast for now - just to connect the dots. Later I can look more into theory/practice (it's for my first hackathon and we're all beginners and I don't know what I'm doing - but if anyone can save you it's stackoverflow!) -
Write UniqueConstraint (migrations fail)
Django 3.1.7 Model class BranchSemanticsTemplate(ArchivedMixin, FlagMixin, clients.model_mixins.BranchMixin, semantics.model_mixins.SemanticsLevelTwoMixin, models.Model): """ As a general rule of thumb samantics level 2 has its own template. If a branch needs a special template for that semantics, stipulate it in this model. """ semantics_tmplt = models.ForeignKey("tmplts.SemanticsLevel2Tmplt", on_delete=models.PROTECT, verbose_name=gettext("Semantics template")), branch_tmplt = models.ForeignKey("tmplts.BranchTmplt", on_delete=models.PROTECT, verbose_name=gettext("Branch template")), def __str__(self): return "{} - {} - {} - {}".format(str(self.branch_tmplt), str(self.branch), str(self.semantics_level_two), str(self.semantics_tmplt), ) class Meta: verbose_name = gettext("Branch template - branch- semantics - semantics template") verbose_name_plural = verbose_name constraints = [UniqueConstraint(fields=['branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt', ], name='semantics_branch_template')] Migration class Migration(migrations.Migration): initial = True dependencies = [ ('clients', '0001_initial'), ('semantics', '0001_initial'), ] operations = [ migrations.CreateModel( name='BranchSemanticsTemplate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('archived', models.BooleanField(db_index=True, default=False, verbose_name='Archived')), ('flag', models.BooleanField(default=False, verbose_name='Flag')), ('branch', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='clients.branch', verbose_name='Branch')), ('semantics_level_two', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='semantics.semanticsleveltwo', verbose_name='Level 2')), ], options={ 'verbose_name': 'Branch template - branch- semantics - semantics template', 'verbose_name_plural': 'Branch template - branch- semantics - semantics template', }, ), migrations.AddConstraint( model_name='branchsemanticstemplate', constraint=models.UniqueConstraint(fields=('branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt'), name='semantics_branch_template'), ), ] migrate (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, clients, commerce, contenttypes, dashboard, generals, images, semantics, sessions, staticassets, tmplts, toponyms Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK … -
How to get selected value in clean form?
I want to validate a field based on a seleted field. However when I put the prints on the form the select field appears as None (but in the view I can get the value without problems). models.py class NyModel1(models.Model): field1 = models.CharField(max_length=50) description = models.TextField(blank=True) def __str__(self): return self.field1 class MyModel2(models.Model): f_field = models.ForeignKey(NyModel1, on_delete=models.PROTECT) my template <select id ="id_fild" class="select" name="f_fild" required=True> {% for value, field in Form.fields.f_field.choices %} <option value="{{value}}"> {{field}} </option> {% endfor %} </select> forms.py class Form(forms.ModelForm): document = forms.CharField() class Meta: model = MyModel2 fields = ['f_field', 'document'] def clean_document(self): doc = self.cleaned_data.get('document') f= self.cleaned_data.get('f_field') print("Document: ",doc) print("f Field : ",f) if f == "something one": #validate document else: #other action return doc In the print appear: Document: 12345 f Field : None How can I get the value of select on the form? -
How to display images from api in nextjs
I am building an ecommerce store with django rest framework and nextjs as the frontend. Thee api has the product data and i want to show product data in nextjs. SO far i can only show the string characters but cannot show the images. Here's my index.js file.What am i doing wrong?: import react from 'react'; import axios from 'axios'; import 'bootstrap/dist/css/bootstrap.min.css'; import Button from 'react-bootstrap/Button'; import Container from 'react-bootstrap/Container'; import Col from 'react-bootstrap/Col'; import Card from 'react-bootstrap/Card'; import Image from 'next/image'; //images from the api in variables const image1 = 'http://localhost:8000/media/media/3_Tiny-glass-cup-of-espresso-coffee.jpg' const image2 = 'http://localhost:8000/media/media/americano.jpeg' const image3 = 'http://localhost:8000/media/media/banana.jpeg' const image4 = 'http://localhost:8000/media/media/bigbfast.jpeg' const image5 = 'http://localhost:8000/media/media/caffe_latte.jpeg' const image6 = 'http://localhost:8000/media/media/cappuccino.jpg' const image7 = 'http://localhost:8000/media/media/caramel-latte-image-square.jpg' const image8 = 'http://localhost:8000/media/media/choco_lava.jpeg' const image9 = 'http://localhost:8000/media/media/hot_tea.jpeg' function Page({stars}) { return ( <div> {stars.map((post) => ( <Card style={{ width: '18rem',float:'right' }} key={post.id}> <img src={post.image} width='70' height='70'/> <Card.Body> <Card.Title>{post.title}</Card.Title> <Card.Text> {post.description} </Card.Text> <Button variant="primary">Add to cart</Button> </Card.Body> </Card> ))} </div> ) } Page.getInitialProps = async (ctx) => { const res = await fetch('http://localhost:8000/api/products') const json = await res.json() return { stars: json } } export default Page -
django filter and pagination
Actually I have two inquiries. I looked a lot for answers, but I could not find. 1 _ How to add multiple pagination to same view ? 2 _ How to add options to the filter, such as dropdown ? this is my view.py: def Multimedia_Software(requset): category = Categorie.objects.all() Multimedia_Software = Apps.objects.filter(category=category[6]).order_by('App_title') myFilter = AppsFilter (requset.GET,queryset = Multimedia_Software) Multimedia_Software = myFilter.qs paginator = Paginator(Multimedia_Software,15) page = requset.GET.get('page') try: Multimedia_Software=paginator.page(page) except PageNotAnInteger: Multimedia_Software=paginator.page(1) except EmptyPage: Multimedia_Software=paginator.page(paginator.num_pages) context = { 'page':page, 'Multimedia_Software':Multimedia_Software, 'myFilter':myFilter, } return render( requset , 'windows/Multimedia_Software.html' , context ) this my filter.py: import django_filters from .models import Apps class AppsFilter (django_filters.FilterSet): App_license = django_filters.CharFilter(label='Filter the license' ) class Meta: model = Apps fields = ['App_license'] this is my model.py: App_license = models.CharField(max_length=100 , null=True) I used pagination with first queryset and I want to use it too with filter.How is this done? and How can I add options to the filter like freeware , trail , demo ? -
Django 2.1: Template structure
I am having trouble with Django routing to find templates located at the app-level. That is, templates at the app-level directory are not rendered unless I put them in the root project-level directory. But the problem with this architecture for me is that, if I have two or more apps all having a file named index.html how do I resolve that from the templates folder at the project-level so that they won't be confliction -
No module named 'django' when trying to import Django into Scrapy
This is my folder structure: root: |--Django_project |--|-- db_app |--|-- Django_project |--|-- manage.py |--Scrapy_project |--|--Scrapy_project |--|--|--spiders |--|--|--settings.py |--|--|--pipelines.py |--|--|--items.py |--|--|--middlewares.py |--|--scrapy.cfg In settings.py I have this: import sys import os sys.path.append(os.path.dirname(os.path.abspath('.'))) os.environ['DJANGO_SETTINGS_MODULE'] = 'Django_project.settings' import django django.setup() I've tried every possible path, including an absolute path to the project root, to the Django project, to the Django app - nothing works and I get this: ModuleNotFoundError: No module named 'django' Thanks for the help! -
server is running but page not accessing?
while working in a Django latest version, I got a error like Page not found (404) Request Method:GETRequest URL:http://127.0.0.1:8000/ Using the URLconf defined in now.urls , Django tried these URL patterns, in this order: admin/ home [name='home'] The empty path didn't match any of these. for creating a simple webpage with more than 3 HTML pages.why..? -
Where do I place the password validators? (django)
I'am working on a website for a school project where members are supposed to log in. I know of the built-in password validators in Django and I have added them to my settings.py. This is what I have so far in the serializers.py: def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance I have imported the validators like this: import django.contrib.auth.password_validation as validators Can I add the validators to this code and do something like this: def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) try: validators(password, self.instance) except forms.ValidationError as error: self.add_error('password', error) return password instance.save() return instance -
Django app data deployed to Heroku reverts back to normal after a certain period of time
I've deployed an app I made with Django to Heroku, but after a certain period of time after saving new data, it reverts to the state it was in when I deployed it. I am using the initial sqlite3 for the database, is this the cause? I would appreciate it if you could tell me more about it. -
BranchSemanticsTemplate has no field named 'semantics_tmplt'
Django 3.1.7 Model class BranchSemanticsTemplate(ArchivedMixin, FlagMixin, clients.model_mixins.BranchMixin, semantics.model_mixins.SemanticsLevelTwoMixin, models.Model): """ As a general rule of thumb samantics level 2 has its own template. If a branch needs a special template for that semantics, stipulate it in this model. """ semantics_tmplt = models.ForeignKey("tmplts.SemanticsLevel2Tmplt", on_delete=models.PROTECT, verbose_name=gettext("Semantics template")), branch_tmplt = models.ForeignKey("tmplts.BranchTmplt", on_delete=models.PROTECT, verbose_name=gettext("Branch template")), def __str__(self): return "{} - {} - {} - {}".format(str(self.branch_tmplt), str(self.branch), str(self.semantics_level_two), str(self.semantics_tmplt), ) class Meta: verbose_name = gettext("Branch template - branch- semantics - semantics template") verbose_name_plural = verbose_name constraints = [UniqueConstraint(fields=['branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt', ], name='semantics_branch_template')] Migration # Generated by Django 3.1.7 on 2021-03-20 10:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('clients', '0001_initial'), ('semantics', '0001_initial'), ] operations = [ migrations.CreateModel( name='BranchSemanticsTemplate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('archived', models.BooleanField(db_index=True, default=False, verbose_name='Archived')), ('flag', models.BooleanField(default=False, verbose_name='Flag')), ('branch', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='clients.branch', verbose_name='Branch')), ('semantics_level_two', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='dashboard_branchsemanticstemplate_related', related_query_name='dashboard_branchsemanticstemplates', to='semantics.semanticsleveltwo', verbose_name='Level 2')), ], options={ 'verbose_name': 'Branch template - branch- semantics - semantics template', 'verbose_name_plural': 'Branch template - branch- semantics - semantics template', }, ), migrations.AddConstraint( model_name='branchsemanticstemplate', constraint=models.UniqueConstraint(fields=('branch', 'semantics_level_two', 'semantics_tmplt', 'branch_tmplt'), name='semantics_branch_template'), ), ] Traceback (venv) michael@michael:~/PycharmProjects/ads6/ads6$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, clients, commerce, contenttypes, dashboard, generals, images, semantics, … -
How to add placeholder for search field in admin.py
How can I add placeholder in django for a search field I am using in admin.py with Django3.1 as: class MyAdmin(admin.ModelAdmin): list_display = ['community'] search_fields = ['community'] Is there any way to do something like this? class MyAdmin(admin.ModelAdmin): search_fields = ['community'] search_input_placeholder = 'Please input community id' -
Finding correlation in Django
I am working on a practice Django prooject. I have a small data frame with three columns Price, Sale, Reviews. I need to calculate correlation between all columns. User will see a Bootstrap form with select menu with three options Price, Sale, Reviews. If user selects Price it will calculate correlation with other two variables. here is my code Templates: <form action="/home/corelation/" method=post> {% csrf_token %} <div class="form-group"> <label for="variable">Voucher</label> <select name="variable" id="variable" class="form-control"> <option>Price</option> <option>Sale</option> <option>Reviews</option> </select> </div> <button type="submit" class="btn btn-success">Submit</button> </form> Views.py def corelation(request): if request.method == "POST": data = {'Price':[40, 50], 'Sale':[33, 27], 'Reviews':[25, 11]} df = pd.DataFrame(data) var_input = request.POST.get('variable') corr = df.corr() var_corr = corr['var_input'].sort_values(ascending = False) print(var_corr) Error Exception Type: KeyError Exception Value: 'var_input' -
django-cte leading zeros in query
How can I add leading zeros to an integer field in a Django query? I want to add an extra field in the Django query below with leading zeros add to the id. something like idwithzeros = str(id).zfill(6), but this is not working Example: Here I use django-cte (https://github.com/dimagi/django-cte): def ProjectTree(ProjectID): def get_tree(childs): return Project.objects.filter( # start with root nodes id = ProjectID ).values( "id", "parent", path=F("id"), depth=Value(0, output_field=IntegerField()), ).union( # recursive union: get descendants childs.join(Project, parent=childs.col.id).values( "id", "parent", path=Concat( childs.col.path, Value(";",output_field=TextField()) ,F("id"), output_field=TextField(), ), depth=childs.col.depth - Value(1, output_field=IntegerField()), ), all=True, ) childs = With.recursive(get_tree) return (childs.join(Project, id=childs.col.id) .with_cte(childs) .annotate( path=childs.col.path, depth=childs.col.depth, ) .order_by("path") ) -
'choices' must be an iterable containing (actual value, human readable name) tuples django 3.1
whene i want to makemigration it show me this error user.User.allowd_to_take_appointement: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. user.User.type_of_user: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. this is my models.py class TypeOfUser(models.TextChoices): PATIENT = 'patient', 'Patient' DOCTOR = 'doctor', 'Doctor' RECEPTION = 'reception', 'Reception' TEMPORARY = 'temporary', 'Temporary' class AllowdToTakeAppointement(models.TextChoices): YES = ('yes', 'Yes') NO = ('no', 'No') class User(AbstractUser): type_of_user = models.CharField(max_length=200, choices=TypeOfUser, default=TypeOfUser.PATIENT) allowd_to_take_appointement = models.CharField(max_length=20, choices=AllowdToTakeAppointement, default=AllowdToTakeAppointement.YES) def is_doctor(self): return self.type_of_user == TypeOfUser.DOCTOR def can_add_appointment(self): return self.type_of_user == AllowdToTakeAppointement.YES i'm using django 3.1 -
Submit Button in django bootstrap form doesn't work
I'm begginer in making django projects. I'm creating easy app which plots earthquakes positions on map with data from api. One of features of my app is the possibility to paste range of dates to my api query. I made the form which includes the datepicker and the code in views that i suppose should handle it. I have problem because my submit button that should grab data from datepicker doesn't work. Or may be i did something wrong in my views and it cannot take data from post method to variable datebeg and dateend Any idea? views.py def graph(request): #=========data========================================================================= datebeg='2021-03-19' dateend='2021-03-20' if request.method == 'post': datebeg=request.POST['datebeg'] dateend = request.POST.get("dateend") if datebeg=='': datebeg='2021-03-21' if dateend=='': dateend='2021-03-21' graph.html <body> <div class="container my-container"> <form action="{% url 'graph' %}" method="post"> {% csrf_token %} <div class= "row my-row"> <div class="col-4 my-col"> Trzęsienia ziemi z zakresu dat: </div> <div class="col-4 my-col"> od: <input type="date" placeholder="0" name="datebeg" size="1" /> </div> <div class="col-4 my-col"> do: <input type="date" placeholder="0" name="dateend" size="1" /> </div> <a class="btn btn-primary" type="submit" href="{% url 'graph'%}" >Pokaż na mapie</a> </div> </form> </div> graph/urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('', views.graph,name='graph'), ] -
How to create a firefox health check
I have written some functional tests for a django app which I test with selenium in a docker container. I use circleci for ci/cd. I have also written a health test for selenium hub to ensure it is up and running before the testing can begin. It looks like below: #!/usr/bin/env python3 import logging import time import urllib.request logger = logging.getLogger("selenium-hub-health-check") status = 0 while status != 200: try: f = urllib.request.urlopen('http://selenium-hub:4444/wd/hub/status') status = f.status logger.info("The Selenium hub is ready!") f.close() logger.info("Closing this session") time.sleep(1) except Exception as e: logger.error(e) time.sleep(1) pass This one runs fine. However, recently, I have started noticing the error below in one in four tests which I believe comes from the firefox service that I'm also using as the browser not being ready. ERROR: test_visitor_can_access_the_about_page (functional_tests.navigation.ftest_endpoints.EndpointsVisitorTest) When a user goes to the browser and types the domain with the ---------------------------------------------------------------------- Traceback (most recent call last): File "/teke/common/tests/base_function_tests.py", line 8, in setUp self.browser = webdriver.Remote( File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__ self.start_session(capabilities, browser_profile) File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Error forwarding the new … -
What is the best way to implement "liking" a post with Django?
I am making a blog as my first project with the Django REST framework and I want to add the ability to like a post. I have seen two different ways that liking a post can be implemented using Django. Firstly, there is the option of creating a different model for likes, as in the following example: class Like(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) post = models.ForeignKey(Post) Secondly, I've also seen likes created in the following way: likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="app_posts") Which version is best? Is the difference not especially important? Is one method more standard and widely practiced? -
How do you fix a memory leak within Django tests?
Recently I started having some problems with Django (3.1) tests, which I finally tracked down to some kind of memory leak. I normally run my suite (roughly 4000 tests at the moment) with --parallel=4 which results in a high memory watermark of roughly 3GB (starting from 500MB or so). For auditing purposes, though, I occasionally run it with --parallel=1 - when I do this, the memory usage keeps increasing, ending up over the VM's allocated 6GB. I spent some time looking at the data and it became clear that the culprit is, somehow, Webtest - more specifically, its response.html and response.forms: each call during the test case might allocate a few MBs (two or three, generally) which don't get released at the end of the test method and, more importantly, not even at the end of the TestCase. I've tried everything I could think of - gc.collect() with gc.DEBUG_LEAK shows me a whole lot of collectable items, but it frees no memory at all; using delattr() on various TestCase and TestResponse attributes and so on resulted in no change at all, etc. I'm quite literally at my wits' end, so any pointer to solve this (beside editing the thousand or … -
How can i get all the product categories a suppliers product belongs
I am working a Supplier Management System. I need to make a particular type of query which I am having issue implementing. I have the user models, and then the user_type which is of two types the suppliers and the admin. Of Course, the filter I need to implement is based of the supplier because only the supplier is able to create product in which they have to specify what categories as well. My Problem: How can I get all categories a supplier products belongs to. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) def get_email(self): return self.email class user_type(models.Model): is_admin = models.BooleanField(default=False) is_supplier = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): if self.is_supplier == True: return User.get_email(self.user) + " - is_supplier" else: return User.get_email(self.user) + " - is_admin" class Category(models.Model): name = models.CharField(max_length=256) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=36) price = models.PositiveIntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name -
How to validate accessToken in Azure AD
I just wanted to know how can we validate the azure ad access token in a backend API in my case i.e. Django rest framework. Consider that I have a single page app or a native app and a backend API (django rest framework) completely independen of each other. In my case if my single page app/native app wants to access certain data from the backend API, and inorder to access the API, user should be logged in the backend API. So what my approch is to make use of MSAL library to get the access token from the SPA/native app and then once token is acquired, pass that token to backend API, validate it, get the user info from graph api. If user exists in the DB then login the user and pass the required info. If user info doesn't exist then create the user, login and pass the info from the API. So my question is when I pass the access token to my backend api, how can I validate that the token that a user/SPA/native app has passed to backend API is valid token or not? Is it just we need to make an API call to … -
Django-OIDC with keycloak - OIDC callback state not found in session oidc_states
I am trying to implement Keycloak SSO with Django API using OIDC. Getting below error message after requesting the call to Keyclock as a response SuspiciousOperation at /^oidc/callback/ OIDC callback state not found in session oidc_states! The same thing I did in the Flask framework and it's working as expected. Please find the below details. Django Log: [20/Mar/2021 15:30:57] "GET / HTTP/1.1" 404 2229 [20/Mar/2021 15:31:03] "GET /hi HTTP/1.1" 302 0 [20/Mar/2021 15:31:03] "GET /oidcauthenticate/?next=/hi HTTP/1.1" 302 0 failed to get or create user: Claims verification failed [20/Mar/2021 15:31:11] "GET /oidccallback/?state=UziLDF2ZcE9p2WrUIihUahgUsWdQ8zYQ&code=22d5a22b-16a6-42e3-81ba-9b569a3f1c81.2cd52631-8c4c-4f2e-a718-c908611336a3.81db1495-24af-402d-8244-a82f32bf4355 HTTP/1.1" 302 0 Not Found: / [20/Mar/2021 15:31:11] "GET / HTTP/1.1" 404 2229 Settings: Django settings for keycloakexample project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '_vg@)t*rri()^^wm7yl*i&$%gk2h1h%!xk$xms19ceb3*2z&g^' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition … -
Public Key not found Django
I'm trying to place this secret key in my env DJPADDLE_PUBLIC_KEY=-----BEGIN PUBLIC KEY----- abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijk== -----END PUBLIC KEY----- my settings.py from decouple import config DJPADDLE_PUBLIC_KEY = config('DJPADDLE_PUBLIC_KEY') but i get this error DJPADDLE_PUBLIC_KEY not found. Declare it as envvar or define a default value. This is how it looked like previously in my settings file DJPADDLE_PUBLIC_KEY = '''-----BEGIN PUBLIC KEY----- abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijklmnoopasdasdhjahsdjahsdjkahsjdhasdsadasdasdasdasdasdasdaasda abcdefghijk== -----END PUBLIC KEY-----'''