Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Aurora RDS transaction read inconsistency
I am using django atomic transactions to create objects. I am just writing new balances for a user (1 user, many balances) repeatedly. For example, if a user starts with a balance of 10 and we want to add 2 new balances: user.add_balance(5) -> user.balance = 15 user.add_balance(3) -> user.balance = 18 However, within the same atomic block, a subsequent balance write depends on reading the current balance, which was just affected by the previous write in the same transaction (I hope that makes sense). In other words, the second transaction above (adding 3) needs to read the balance as 15, NOT 10 which is the old balance. Here is a simplified version of the code. def add_user_balance(self, amount): WalletBalance = apps.get_model("wallet", "WalletBalance") # this is terse but it is just summing all of the user's balances to get the current balance current_balance = float( WalletBalance.objects.filter(user=self, cancelled=False).aggregate( Sum("amount") )["amount__sum"] ) # this does NOT use a cached relation from within the user model, it should go to the db and does in testing # HERE is where I need the new balance within the same transaction. if float(current_balance) + float(amount) < 0: raise ValueError("balance_low") balance = WalletBalance.objects.create( amount=amount, transaction_type=transaction_type, ) … -
How to reconnect to RDS psql DB in Django
I have recently wrote a small django app which connects to the external database (AWS RDS psql instance). Authentication is done using IAM role of EC2 instance (server). Things work OK for about 15-20min. After this time the error I'm getting is: Exception Value: FATAL: PAM authentication failed for user "quietroom_dev_beanstalk_ec2" My guess is that a token generated by boto3 expires and I loose the connection. Below shows how the token is obtained. client = boto3.client('rds', region_name=REGION) password = client.generate_db_auth_token(DBHostname=DB_HOST, Port=DB_PORT, DBUsername=DB_USER, Region=REGION) If this is the case, how can I force django to reconnect to the DB with a fresh token? The error originates in the django core. At the moment I work only with Django native admin panel. Thanks in advance for your help! -
how to update(calculate) a specific filed if the object exists django
i made a project for a store , and i want to prevent from duplicate products , if the product doesnt exists then insert it into the database , but otherwise if it doesn't then just update field(quantity) models.py class Item(models.Model): item = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.IntegerField() for example we have inserted this data: item = mouse , quantity = 20 then we add this data later item = mouse , quantity = 30 now what i try to whenever the item exists , just update the quantity like this (20 + 30 ) = 50 , add the previous quantity with new quantity to get total number of quantities ! is it possible please ? i've read some articles about get_or_create and update_or_create but still i dont have any idea how it work in my case !? thank you for your suggestion regards .. -
Properly wiring RPC service communication in Django application
I'm developing a Django app which needs to execute scheduled and/or long-running tasks. To achieve this, I've set up a service using the rpyc, paired with the apscheduler package in order to execute jobs. It seems to work well so far, but I'm wondering if more experienced developers could give me their opinion because I worry that certain aspects of my design indicate a code smell. This is the generic flow of what I am doing: Make request to a particular view Instantiate connection to service IN view Invoke an add_job method exposed by the RPC service to schedule a job Register a callback that is called with successful execution of the particular job view returns and connection is closed/dropped Currently, I instantiate a Connection instance in the View, meaning that a new connection instance is made with the appropriate request to the Django View and this is dropped after the view returns. Due to the way that apscheduler works, it requires that callables set to execute as a deferred jobs must be globally accessible, so any callable that I wish to add as a job that is not already in the namespace of the service cannot be a remote … -
How Django's "override_settings" decorator works when launching tests in parallel
I'm checking how Django's settings module is built and how the override_settings decorator deals with the settings when testing and I just can't see how the implementation of this decorator avoid problems when running the tests in parallel. I see that it in the enable method it assigns to the settings' _wrapped attribute the settings values with the changes applied and that it stores a copy of the previous values that is then restored in the disable method. This works OK with me when executing it secuentially. But when running tests in parallel I can't see how this works without affecting other tests that also use the decorator, let's say to overwrite the same value. What I see is that the value set by the latest executed test will be returned everywhere when accessing settings.OVERRIDDEN_SETTING. In fact, this settings overriding should also affect the values returned in other tests even if they are not decorated. I mean, if we have these two tests: @override_settings(SETTING=1): def test_1(self): ... ... print(settings.SETTING) @override_settings(SETTING=2): def test_2(self): ... ... print(settings.SETTING) def test_3(self): ... ... print(settings.SETTING) If they are run in parallel, and let's say test_1 is executed, starts executing it's code and in the meanwhile … -
Hi guys,Trying to get past the user registration as I assign groups to different users through giving different permisions. Kindly assist
Traceback (most recent call last): File "/home/alvin/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/alvin/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/alvin/.local/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) TypeError: 'NoneType' object is not callable [28/Apr/2021 10:17:24] "GET / HTTP/1.1" 500 70741 from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.users.groups.exists(): group = request.users.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse("You are not allowed to view this page!") return wrapper_func return decorator -
Cookies not create in browser django rest
I am trying to do authorization via access token in cookie. But i am having trouble setting cookies with react. I set cookies in login: class ApiLoginView(APIView): permission_classes = [AllowAny] def post(self, request, ): password = request.data.get("password") email = request.data.get("email") user = authenticate(username=email, password=password) if user: try: user.auth_token.delete() except Exception as e: pass Token.objects.create(user=user) response = Response() response.set_cookie(key='access_token', value=user.auth_token.key, httponly=True) response.data = {"result": True, "token": user.auth_token.key} print(request.COOKIES) auth.info("user {} login".format(user)) return response else: return JsonResponse({"error": "Wrong Credentials"}, status=status.HTTP_400_BAD_REQUEST) If I auth into postman, everything goes well and the cookies are set. print(request.COOKIES) {'csrftoken': 'JZ1OOBZ0Ilxwo8Zt7DR0SbQ8MUMyNjiPhKYOIUQqY3OeXBEheeUoIa9MSI5S0HXG', 'access_token': 'd67ab794f8752ef02bcba5418bef2c6f87cb74f2'} But if you do it through the frontend, I get only this {'_ym_uid': '1612967974591822622', '_ym_d': '1614006098'} My frontend request: const response = await fetch("httpS://blablabla/api/auth/login", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); I also have cors headers configured CORS_ALLOW_CREDENTIALS = True -
How to set exact url route in django while others are dynamic?
So I build a simple vanilla JS frontend SPA that querys recipes from my own REST API that I build with django rest framework and of course I need to access the /admin route in order to add recipes. This is my routing at the moment: from django.contrib import admin from django.urls import path, re_path, include from django.views.generic import TemplateView urlpatterns = [ re_path(r'^admin/$', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')), path('<id>', TemplateView.as_view(template_name='index.html')), path('api/', include('recipes.urls')) ] Now if someone wants to share a recipe with domain.com/<id> this should not be a problem and currently it works this way, but because I have this weird setup where anything in the pathname gets searched as an id the /admin route does not reach its desired location. I would be interested in a solution where I pass a exact keyword to the url-param for django to know when it gets a hit to return the admin page. My idea at first was a regular expression but it does not seem to work, any idea why? I also tried to match the <id> as an INT as shown in the docs. But I do not need for django to pass the <id> into a view because my JavaScript … -
drf-yasg: Change the request name appearing in redoc ui
enter image description here How do I change the name of the request that appears automatically in redoc-ui when using drf-yasg. For example: In the image, you can see that that the request is named fid_data-entities_update, it is picking this up from the url. How do I override/rename it to update data entities name -
Pass JSON object instead of array in AJAX call ->DJANGO
i have a code which should pass JSON object to another page using AJAX in django , currently when i use array it is working fine , but when i converted that to json object it is neither throwing success alert nor error alert , No idea why . Below is the code : $("[name=submit]").click(function(){ var myarray = []; $(".form-check-input:checked").each(function() { console.log($(this).val()); myarray.push($(this).val()); //push each val into the array }); var jsonObj = {}; for (var i = 0 ; i < myarray.length; i++) { jsonObj["position" + (i+1)] = myarray[i]; } var formdata = new FormData(); formdata.append('myarray', jsonObj); formdata.append('csrfmiddlewaretoken', $("[name=csrfmiddlewaretoken]").val()); formdata.append('RestartSubmit', 'RestartSubmit') $.ajax({ url: "secondtableonDashboard", //replace with you url method: 'POST', data: formdata, processData: false, contentType: false, beforeSend: function(){ // Show image container $("#loader").show(); }, success: function(data) { alert("message: " + data.message); var newDoc = document.open("text/html", "replace"); newDoc.write(data); newDoc.close(); $('#example').hide(); alert(data) }, error: function(error) { // alert('error..'+error); alert("ERROR") } }); }); so here i gave alert for both error and success but both of them is not showing up . Can anyone of you help . -
Django moving model from one app to another - ValueError: The field was declared with a lazy reference but app doesn't provide model
I am trying to move a model from one application to another. I created two migrations for this purpose. Migration 1 State operation - Creates model(Foo) in new app Migration 2 - Database operation - Alter all the models which have a foreign relation to Foo to point to new app. State operation - Deletes model(Foo) in old app When I ran the migrations on my company database, it worked fine and the model was migrated to new app. But when I am running all the migrations to create my local database, it is throwing this error. Somehow the foreign models are still pointing to the model in old app, not able to figure out where this is happening? Can someone please help. Command: python manage.py migrate main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 191, in handle pre_migrate_apps = pre_migrate_state.apps File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/ishan/.virtualenvs/campaigns-service/lib/python3.6/site-packages/django/db/migrations/state.py", line … -
Django computing variable vaue in custom middleware and passing to all view functions
I am using Django 3.2. I want to compute the value of variable and make that value available to all views in my project. I have decided to use middleware - but it is not clear (yet), how I can make the value I computed in MyCustomMiddleware available in a view. Here is my custom middleware class: class MyCustomMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. response = self.get_response(request) # Code to be executed for each request/response after # the view is called. mysecret_value = 4269 return response After making the requisite modifications to the MIDDLEWARE section in settings.py, how do I acesss mysecret_value in my views? myapp/views.py def foobar(request): the_value = mysecret_value # <- how do I access the RHS variable? -
I want to target AUTH_USER_MODEL to a custom user model in sub directory
my project structure is like below: ./apps ./apps/bizusers ./apps/bizusers/admin.py ./apps/bizusers/apps.py ./apps/bizusers/models.py ./apps/bizusers/serializers.py ./apps/bizusers/tests.py ./apps/bizusers/views.py ./apps/bizusers/__init__.py ./apps/__init__.py ./config ./config/asgi.py ./config/settings.py ./config/urls.py ./config/wsgi.py ./config/__init__.py ./manage.py ./requirements.txt My custom user model is in ./apps/bizusers/models.py I have this in settings: INSTALLED_APPS = [ 'apps', ] I added AUTH_USER_MODEL = "bizusers.User" in settings.py I have tried to edit ./apps/__init__.py and ./apps/bizusers/apps.py but I cannot get it to work. I have tried these solutions below: having models directory and AUTH_USER_MODEL Model in sub-directory via app_label? 'MyAppConfig' must supply a name attribute Thanks. -
Django Rest Framework cannot access foreign key
I am trying to create a product which contains a foreign key yet when sending some JSON it doesn't work. My models : class Category(models.Model): name=models.CharField(max_length=200) objects = CategoryManager() def __str__(self): return self.name class Product(models.Model) : name=models.CharField(max_length=200) price=models.IntegerField(default=0,blank= True, null=True) category = models.ManyToManyField(Category, blank=True, null=True) The serializers: class CategorySerializer(serializers.ModelSerializer) : class Meta : model = Category fields = ['name'] class ProductSerializer(serializers.ModelSerializer) : category = CategorySerializer(many= True) class Meta : model = Product fields = ['name','price', 'category'] The JSON I send (for ex.): { "name": "HelloThere", "price": 30, "category": { "name": "GeneralKenobi" } } the view : @api_view(['GET', 'POST']) def productcreate(request): serializer = ProductSerializer(data=request.data) if serializer.is_valid() : serializer.save() return Response(serializer.data) When posting the data as it is, I create a product which has a name and a price but category doesn't work. Thanks in advance for your help, -
django tornado project structure
I am using tornado with django. Right now, my django project structure is like this. project --apps ----accounts ----billing ----roles --settings ----defaults.py ----development.py ----production.py --__init__.py --asgi.py --wsgi.py --urls.py --celery.py manage.py README.md LICENSE requirements.txt .gitignore Where would I likely insert all of tornado related code? Ideally, I would be having a module called tornado somewhere with handlers and the application. For development, I would be running tornado via a management command. -
Djnago Models Design Database
I am new to Django project and wanted to know what is the best practice for designing models. I am working on creating a small project which will have collections of stories in a category and subcategorical manner. I am tagging it as Django because I wanted to also verify the scope of app. Apps: index, genre Design: Index Genre |-- Story |--Section |-- Chapters |--Paragraph |-- title |-- text |-- highlights genre.models.py class Story(models.Model): stry = models.CharField(max_length=256,unique=True) id =models.AutoField(primary_key=True) def __str__(self): return self.stry class Section(models.Model): stry = models.ForeignKey(Story,on_delete=models.CASCADE) name = models.CharField(max_length=256) desc=models.TextField() id =models.AutoField(primary_key=True) slug = models.CharField(max_length=240, null=True, blank=False) created_at = models.DateTimeField(auto_now_add=True, null=False) updated_at = models.DateTimeField(auto_now=True, null=False) class Chapter(models.Model): sec = models.ForeignKey(Section,on_delete=models.CASCADE) name = models.CharField(max_length=256) desc=models.TextField() id =models.AutoField(primary_key=True) slug = models.CharField(max_length=240, null=True, blank=False) created_at = models.DateTimeField(auto_now_add=True, null=False) updated_at = models.DateTimeField(auto_now=True, null=False) class Paragraph(models.Model): chap = models.ForeignKey(Chapter,on_delete=models.CASCADE) title = models.CharField(max_length=120, null=True, blank=False) subtitle = models.CharField(max_length=180, null=True, blank=False) slug = models.CharField(max_length=240, null=True, blank=False) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=False) updated_at = models.DateTimeField(auto_now=True, null=False) The genre can have many stories, and each section can have many chapters and a similar pattern Question: Is there a better design model that I can work on? Can divide these into different apps or have … -
Adding Foreign Key to Django Import Export
I am trying to import data from a csv using Django_Import Export. I saw other SO posts but they are not helping. Below are the models Models.py class TblSubject(amdl.AagamBaseModel): subject_id = models.AutoField(primary_key=True) subject_name = models.CharField(max_length=20) standard = models.ForeignKey('TblStandard', models.DO_NOTHING) remembrance_credit = models.IntegerField(default=40) applied_knowledge_credit = models.IntegerField(default=30) understanding_credit = models.IntegerField(default=30) subject_credit = models.IntegerField(default=100) class Meta: db_table = 'tblsubject' def __str__(self): return f'{self.subject_name}' class SubjectChapter(amdl.AagamBaseModel): subject_chapter_id = models.AutoField(primary_key=True) subject = models.ForeignKey('TblSubject', on_delete=models.CASCADE) chapter_id = models.IntegerField() chapter_name = models.CharField(max_length=150) remembrance_credit = models.IntegerField() applied_knowledge_credit = models.IntegerField() understanding_credit = models.IntegerField() chapter_credit = models.IntegerField() class Meta: db_table = 'subject_chapter' def __str__(self): return f'{self.chapter_id} {self.chapter_name} : {self.subject}' Here is the admin.py from django.contrib import admin from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from .models import SubjectChapter, TblSubject from import_export.admin import ImportExportModelAdmin class SubjectChapterResource(resources.ModelResource): class Meta: model = SubjectChapter import_id_fields = ('subject_chapter_id',) subject = fields.Field( column_name='subject_name', attribute='subject_name', widget=ForeignKeyWidget(TblSubject, 'subject_id')) class SubjectChapterAdmin(ImportExportModelAdmin): resource_class = SubjectChapterResource admin.site.register(SubjectChapter, SubjectChapterAdmin) And i am getting this below error I am inserting data for SUBJECTCHAPTER from csv where the SUBJECT column is a foreign key from TBLSUBJECT and it contains the name of the TBLSUBJECT. -
Not able to insert data from django to sqlite for face detection
def markAttendance(Name,inTime,InDate): #Creating a cursor object using the cursor() method cursor = connect.cursor() sql = '''INSERT INTO markAttendance(Name,inTime,InDate) VALUES(?,?,?)''' #cur = conn.cursor() val=(Name,inTime,InDate) cur.execute(sql,val) (id,Name,str(crTime),str(crDate))) conn.commit() return cur.lastrowid -
Sending text message with friend request
I am building a Simple SocialMedia AND I am stuck on a Problem. What i am trying to do :- I am trying to send message with friend request . Suppose user_1 send a friend request to user_2 with message like "How are You ?". When receiver saw a request is received then also show the message sent my sender. models.py class FriendRequest(models.Model): to_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='to_user',on_delete=models.CASCADE) from_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='from_user',on_delete=models.CASCADE) message = models.CharField(max_length=500,default='',null=True) views.py def send_friend_request(request,user_id): user = get_object_or_404(User,id=user_id) frequest,created = FriendRequest.objects.get_or_create(from_user=request.user,to_user=user) if request.method == 'POST': form = FriendRequestMessage(request.POST,request.FILES) if form.is_valid(): new_post = form.save() new_post.request.user = request.user new_post.save() return redirect('mains:settings') else: form = FriendRequestMessage() context = {'form':form} return render(request, 'send_friend_request.html',context) I have tried to search on SO BUT no one asked it before. Any help would be Appreciated. Thank You in Advacnce. -
AJAX data being passed in URL params
I have an AJAX function which is doing some AJAX stuff obviously. Can someone tell me why the data is exposed and not hidden? "GET /policies/?csrfmiddlewaretoken=8ti8IcJ0MF71GjYZghgWqv9YUQEDCzulFvkf8mnCeY2cLchmDHc6IbkTtX9epwAx&title=No+parent&parent=&groups=4&groups=6&groups=7&groups=3 HTTP/1.1" 200 53099 function addCategory(e) { e.preventDefault(); let post_url = '{% url "policies-categories-form" %}' $.ajax({ url: post_url, type:'POST', data: $('#addCategoryForm').serialize(), success: function(response){ console.log(response); // document.getElementById('editCategoriesContainer').innerHTML = data; }, error:function(){ console.log('Error'); }, }); }; Form: {% load crispy_forms_tags %} <!--Add new category form--> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.title|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.parent|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.groups|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> <button class="btn btn-warning btn-block" id="addCategoryBtn" onclick="addCategory(event)" type="button"> <span class="fas fa-plus"></span> Add Category </button> </div> </div> Thanks! -
Heroku CLI: only the RUN cmd is hanging on "connecting"
I'm facing a problem with Heroku CLI 'run' command, basically when I use the run command in any way or form is just hangs on connecting, for example, I have logged in (Heroku) from my Ubuntu machine and I am trying to launch 'bash' to any app on Heroku using "Heroku run bash -a dummy-app-12345" and all I get is "connecting" forever. Originally, I came across this problem when I was trying to push my dockerized Django app to Heroku using the Build Manifest/heroku.yml build approach and that's where I faced the issue originally GitHub Repo: https://github.com/hannody/django_bookstore_project/tree/main/books, now for any app I create on Heroku I get the same issue with the 'run' command. I also tried to follow this tutorial here https://testdriven.io/blog/deploying-django-to-heroku-with-docker/, but I was unable to complete it due to this 'run' command issue. BTW, I get no error messages or any feedback from the Heroku CLI.' I have consulted the web for this problem and found some similar issues where the developers using 'detach' mode to overcome this problem, however, this helped me only to create the database, but when I try to create a superuser it isn't, $ heroku run python manage.py migrate ( works only … -
Django Many2Many field with user
So what I'm trying to do is I'm having two table(class) in my models both of them have many2many field and it's related to user model what I'm trying to do is whatever user i select in my first table I want the users I select in my first table automatically added to the second table without me having to add it manually I tried to override the save_model method in my admin file but still having the same problem Any advice Thanks -
How to authenticate users in Nodejs with Django authentication
I'm using socket io from Nodejs to create a chat feature in my application which is mainly built using React+Django. I need to use Django's user authentication in Nodejs, so that users are authenticated before they can chat with other users. I couldn't really find much on the internet so I came up with the following method, but I don't know if it's the correct way to do this. When the user opens the chat feature, a post request is sent to the Django server containing the user's id and the user is authenticated. After successful authentication, the Django server sends a code to the Nodejs server, and the same code is sent to the user at the client-side. Now, whenever the user sends a message, the codes are compared in the Nodejs server, and if they match, the message is sent. I'm not a pro in web technologies, and I'm pretty sure there are drawbacks using this method so any help would be appreciated! -
ValueError: The view didn't return an HttpResponse object. It returned None instead. (Django/ImgKit)
ValueError: The view didn't return an HttpResponse object. It returned None instead.(Django/ImgKit) I am trying to use a fetch api to connect what the user selects in the frontend to the backend and then return a json response. For whichever html file they select, i want to convert it into an image to be displayed for them to preview Not sure why i am facing this error: def folder_view(request): if request.method == 'POST': if json.loads(request.body)['template'] == 'template': try: folder = json.loads(request.body)['folder'] templates = Template.objects.filter(user=request.user, folder=folder).values('template_name') user_templates=[] for template in templates: config = imgkit.config(wkhtmltoimage=WKHTMLTOPDF_PATH, xvfb='/usr/bin/xvfb-run') html_img = imgkit.from_url(template.html.url, False, config=config) user_templates.append(html_img) return JsonResponse({'user_templates': user_templates }) except Exception as e: print('test') Error seems to be coming from this line: html_img = imgkit.from_url(template.html.url, False, config=config) Once this line is removed, error wont be seen anymore -
Is there a way to set a default value from Microsoft Graph using Forms.Py?
Previously, I attempted to get Username and Email values from Azure AAD using Microsoft Graph. However this was done in a Html form that was done manually and not through forms.py This was the html that was done manually previously: <div> <input id="name" type="text" name="name_field" value = "{{user.name}}" readonly > </div> <div> <input id="email" type="text" name="email_field" value="{{ user.email }}" readonly> </div> Right now I have created in forms.py: class SaveClaimForm(forms.Form): name = forms.CharField(label='Name', max_length=200, disabled=True) email = forms.EmailField(label='Email', disabled=True) Is there a way to set the values of name and email in such a way that it retrieves the required information from Azure AAD