Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-oauth-toolkit-0.11 permission raises 401
Tech Stack:- Django1.10 + python3.6 + docker + DRF + React + Axios + Cross domain Error:- "detail": "Authentication credentials were not provided." As soon as I get my access_token I make a GET call with the same access token and every time I am getting 401 status code with the error mentioned above Integration Part for django-oauth-toolkit My settings:- INSTALLED_APPS = ( 'oauth2_provider', 'rest_framework', 'django_filters', # search engine driver ) REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', # 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'apps.common.authentication.SessionTokenAuthentication', 'oauth2_provider.ext.rest_framework.OAuth2Authentication', ], # maybe we need to add this to prod settings # 'DEFAULT_RENDERER_CLASSES': [ # 'rest_framework.renderers.JSONRenderer' # ], } OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}, 'ACCESS_TOKEN_EXPIRE_SECONDS': 36000, } views.py class SomeView(views.APIView): authentication_classes = [OAuth2Authentication] permission_classes = [TokenHasScope] http_method_names = ['get', 'head', 'options'] def get(self, request, *args, **kwargs): # dom something return However, if I remove TokenHasScope permission it runs smoothly. How can this token expire when it is getting generated seconds ago or what is the reason that this error comes -
Django - MigrationError after I add a new field into existing model and mongoDb
I have a MigrationError when a django view executes the get function of a model object user_profile = UserProfile.objects.get(user=request.user) the exeption as below : HTTP GET /media/website/bg_chat.PNG 200 [0.22, 127.0.0.1:1417] Internal Server Error: /chat/French Traceback (most recent call last): File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\djongo\sql2mongo\query.py", line 287, in _align_results ret.append(doc[selected.column]) KeyError: 'numberOfBan' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\chat\views.py", line 32, in chatroom uprofile = UserProfil.objects.get(user=user) File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\db\models\query.py", line 393, in get num = len(clone) File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\db\models\query.py", line 250, in __len__ self._fetch_all() File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\db\models\query.py", line 1186, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\db\models\query.py", line 63, in __iter__ for row in compiler.results_iter(results): File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1005, in apply_converters for row in map(list, rows): File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1466, in cursor_iter for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "C:\Users\Ahmed\Desktop\MS_ ISI\PA\Mini_Projet\ISI_Chat\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1466, in <lambda> for … -
django formwizard previous page validation
I just made multi-paged signup page. But when I click the 'prev' button it requires to fill up the current page. I want it to make it to be able to move to the previous page even when the user did not fill the forms of current page up. This is the view of the page. from django.shortcuts import render, HttpResponseRedirect from formtools.wizard.views import SessionWizardView from django.contrib.auth.forms import User from django.views.decorators.csrf import csrf_protect from .forms import HiarcUserCreationForm1, HiarcUserCreationForm2, HiarcUserCreationForm3 from .models import HiarcUser class SignupWizard(SessionWizardView): template_name = 'hiarc_registration/register.html' form_list = [HiarcUserCreationForm1, HiarcUserCreationForm2, HiarcUserCreationForm3] def done(self, form_list, **kwargs): if self.request.method == 'POST': data = {} for form in form_list: data.update(form.cleaned_data) user = HiarcUser.objects.create_user(**data) return render(self.request, 'hiarc_registration/done.html', { 'form_data' : [form.cleaned_data for form in form_list], }) -
How can I identify a user without login feature in Django?
I'm making Django app where visitors can answer to questions without login feature. The number of each answer will be counted as 'votes', but I need to restrict a user to answer a question only once. I need someone's help who has experienced in this. -
Testing with partial Django database
I am attempting to unit test a new function I wrote in what is not a very large Django project (with some legacy functionality I cannot change at this time). The database schema has become very large and very intertwined. Every test we end up writing has to go through a very long process of setting up the database with many foreign keys - all of which are not needed by most unit tests. But the Django framework will force us to set these up since one model has a foreign key to another, which will then have one to another and so on... I have tried not using the database at all to run my unit tests by mocking most of the database interactions (ie: objects.filter, objects.get, save, etc). This works, but I cannot get confirmation data about different attributes - more concrete example: @mock.patch.object(MyObject, 'save') def testing_something_that_saves(self, mock_save_function): # a bit of setup stuff mock_save_function.return_value = True call_test_function() self.assertEquals(len(mock_save_function.mock_calls), 1) But in this case, how can I - or would I validate the different MyObjects that would be saved? The save() function call doesn't take parameters - but I would like to validate that the object being saved … -
FOREIGN KEY constraint failed Django
I have a complex model with optional fields, I try to save it using my form and I get an error every time: 'FOREIGN KEY constraint failed' My all fields in the table are optional, and the form is empty, so it should allow you to save the empty model. models.py class Ordering(models.Model): massage_product = models.OneToOneField(Product, on_delete=models.CASCADE, null=True, blank=True, default = 1) masseurs = models.OneToOneField(Masseurs, on_delete=models.CASCADE, null=True, blank=True, default = 1) massage_time_interval = models.CharField(max_length=5, blank=True) price = models.CharField(max_length=5, blank=True) day_week = models.CharField(max_length=15, choices=DAY_OF_WEEK, default=date.today, blank=True) time = models.OneToOneField(Time, on_delete=models.CASCADE, null=True, blank=True, default = 1) place = models.OneToOneField(PlaceMassage, on_delete=models.CASCADE, null=True, blank=True, default = 1) payment_method = models.CharField(max_length=1, choices=PAYMENT_METHODS, default='G', blank=True) name = models.CharField(max_length=50, blank=True) surname = models.CharField(max_length=50, blank=True) e_mail = models.EmailField(blank=True) additional_requests = models.TextField(blank=True) phone_number = models.CharField(max_length=15, blank=True) reminder_visit = models.BooleanField(default=True, blank=True) website_rules = models.BooleanField(default=True, blank=True) city = models.CharField(max_length=50, blank=True) street = models.CharField(max_length=50, blank=True) street_number = models.CharField(max_length=10, blank=True) hom_number = models.CharField(max_length=10, blank=True) zip_code = models.CharField(max_length=10, blank=True) created_at_data = models.DateTimeField(auto_now_add=True) updated_at_data = models.DateTimeField(auto_now=True) forms.py if request.method == 'POST' and 'btn_massage_order' in request.POST: ordering_form = OrderingMassageForm(data=request.POST) if ordering_form.is_valid(): ordering = OrderingMassage() ordering.save() else: ordering_form = OrderingMassageForm() Django admin allows you to save an empty form why does not my allow it? any help … -
django-csrf protection on ajax post
I am working on django 1.7 and python 2.7. To prevent csrf attack on ajax post request i have added csrf token in ajax header before send. In views i have added csrf_protect decorator to check the token. Everything is working fine in this scenario. But In my project this function in views.py is being called internally in other views where i haven't implemented csrf token, this causing 403 error.So what i want to do is only when there is ajax post call have to check csrf_protect decorator. Every other calls can neglect. def check_token(func): def wrapper(request, *args, **kwargs): if request.is_ajax(): return csrf_protect(func(request,*args, **kwargs)) return func(request,*args, **kwargs ) return wrapper @check_token def myViews(request,mob,id): """function starts here""" -
NOT NULL constraint failed: name_tabel.name_field. Django - models.py
I am trying to add my field as optional, unfortunately it always ends with an error (as in Title). My model has 'null = True, blank = True' added according to the answers on the forum. I have also tried to delete all migrations and do them again, but I still have the same message. How can I solve this problem (set the field as optional) Any help will be appreciated. class OrderingMassage(models.Model): massage_product = models.OneToOneField(Product, on_delete=models.CASCADE,null=True, blank=True) -
Sendgrid email going into spam in Django Web App
I am using sendgrid for email service on my personal website. The mail is delivering successfully. But, instead of going into the inbox, it goes into spam in gmail. I am using Django framework with SendGrid-django package which is a simple django backend to send email using SendGrid's Web API. Please provide me a solution to get them into the inbox. I am using a from address like : noreply@mywebsitedomain.com -
Remove specific url from uwsgi logging
I have a service which use django+uwsgi i have in uwsgi.ini such logging settings: req-logger = stdout file:/dev/fd/1 logformat = { "message": "%(method): %(uri)", "level": "INFO" } It work allright but recently i start using healthcheck of my service which get /ping endpoint every 5 seconds. And now where are endless lines of GET /ping im my logs. I want uwsgi not to log this requests I tried: req-logger = ping file:/dev/null log-req-route = ping /ping But with no visible result Can someone suggest me how should change settings in uwsgi.ini so this requests will not be logged? -
Error while rating movies in recommender app
This error ocurred when i tried to rate movies in my movie recommender app. SyntaxError invalid syntax (, line 1) on this line:: movies,moviesindxs = zip(*literal_eval(data.get("movies"))) -
How to display the value of key in dictionary in jinja2 template?
I want to display the value of a particular key of dictionary in jinja2 template. dict1 = {'Device.Bridging.': '0', 'Device.': '0', 'Device.XMPP.SupportedServerConnectAlgorithms': '0'} For ex: I want to display the value of key "Device.XMPP.SupportedServerConnectAlgorithms" This is how I am trying to access the value. <div> <p>{{dict1.Device.XMPP.SupportedServerConnectAlgorithms}}</p> </div> But the above code is giving null value. and <div> <p>{{dict1["Device.XMPP.SupportedServerConnectAlgorithms"]}}</p> </div> Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '["Device.XMPP.SupportedServerConnectAlgorithms"]' from 'pvals["Device.XMPP.SupportedServerConnectAlgorithms"]' Above code is giving the following error Exception Type: TemplateSyntaxError Exception Value: -
How to save an object of model that have one to one field?
I want to save a comment to any posts by click on button but i receive an error: ValueError at /user_add_comment save() prohibited to prevent data loss due to unsaved related object 'profile_user'. model: class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=100, blank=True, default="Bio") profile_pic = models.ImageField(upload_to='profile_users', blank=True) def __str__(self): return self.user.username class CommentPostModel(models.Model): profile_user = models.OneToOneField(UserProfileInfo, on_delete=models.CASCADE) post = models.ForeignKey(PostModel, on_delete=models.CASCADE, related_name="comments") text = models.TextField(verbose_name="Text") comment_time = models.DateTimeField(default=datetime.now) approved = models.BooleanField(default=False) def approve(self): self.approved = True self.save() def __str__(self): return self.text view: def user_add_comment(request): post_pk = request.GET.get('post_pk', None) post = PostModel.objects.get(pk=post_pk) user_info = UserProfileInfo.objects.filter(user=request.user) user_info2 = UserProfileInfo() for temp_user_info in user_info: user_info2 = temp_user_info break comment_text = request.GET.get('post_text', None) comment = CommentPostModel(profile_user=user_info2, post=post, text=comment_text) comment.save() data = { "url": "/profile_page", } return JsonResponse(data) -
Why serializers instantiated when the Django starts?
I'm using Django rest framework and confusing why serializers instantiated when Django starts. I believe that Django is not relevant with Django-rest-framework. Any initializing prosess of rest-framework is runnning? And do you know how to stop this behavior? (I want to run some process ONLY when the making responses, not when Django starts) from rest_framework import serializers from myapi.models import SomeMyModel class MySerializer(serializers.ModelSerializer): def __init__(self): print('hello!') # <= this called when django starts!! -
How to breaking up text into individual new lines so other users can edit and have those edits highlighted (similar to github)?
I am working on a project similar to github, but instead of programming it has to do with language learning. The backend I am using is Django. How the process will work: User A submits a post -> other users can see submitted post -> user B decides he wants to correct user A's post -> user B clicks on user A's post -> user A's post is then broken up into individual sentences where each sentence is on a new line -> user B decides which sentence needs fixing -> once done, the changes are highlighted in green while deletions are striked out. It would be similar to something like this: My current model is set up as so: class Post(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() ... class Corrections(models.Model): user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.TextField(null=True) ... Sentence splitting I believe I should split these using regex to capture the "." then split()? Problem Since django cannot natively do this, I figure I would need a js library to accomplish this. I have no experience with js, so if possible can you outline the steps needed to accomplish this? How … -
Python subprocess.Popen with var/args
i want to call a subprocess.Popen cmd with a variable but for some reasone just the first word of the cmd get executed (i guess). How to properly accomplish this? users = User.objects.all() for user in users: addr = user.acc_addr check_addr = subprocess.Popen(['binary', 'binary_argument', myvar], shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip() print(check_addr) Thanks and kind regards -
Django allauth google OAuth redirect_uri_mismatch error
I am using Google OAuth for my Django App (via allauth package) I have followed all standard configuration steps. In Google Developer console here's what i have: Authorized JavaScript origins https://example.com Authorized redirect URIs https://example.com/accounts/google/login/callback/ - login fails http://example.com/accounts/google/login/callback/ - login succeeds What i observe that if i have a https redirect URL in Authorized redirect URIs, it does not allow login and it fails with redirect_uri_mismatch Error. If i have a http redirect URL then the login succeeds. What do i need to do to have a https enabled redirect URL ? -
Error "count() takes exactly 2 arguments (1 given)" in pagination function with django
Despite the fact that I have fetched successfully the data from the db and created my paginator, i find myself struggling returning the data and finally show the data in json format. I found useful this post https://simpleisbetterthancomplex.com/tutorial/2016/08/03/how-to-paginate-with-django.html (despite the fact that in my case I am using class based approach because I want as final goal to have server side processing of my datatable.) My url: url(r'^warehouse_tabledata/(?P<page>\d+)/$',views.ProductSerialNumbersListJSon.as_view(), name='warehouse_list_json'), My view: class ProductSerialNumbersListJSon(LoginRequiredMixin,BaseDatatableView): # my model model = ProductSerialNumbers columns = ['snumber' , 'order','product','registration_date'] order_columns = ['snumber','order','product','registration_date'] max_display_length = 100 def get_initial_queryset(self): #fetch the query list from db query_list=ProductSerialNumbers.objects.filter(Q(snumber__isnull=True)|Q(order_id__isnull=True)|Q (order_id__finished=0)).order_by("id") paginator = Paginator(query_list,13) #13 items per page page=int(self.kwargs['page']) try: queryset = paginator.page(page) except PageNotAnInteger: queryset = paginator.page(1) except EmptyPage: queryset = paginator.page(paginator.num_pages) return queryset My traceback: TypeError at /warehouse_tabledata/2/ count() takes exactly 2 arguments (1 given) Request Method: GET Request URL: .../warehouse_tabledata/2/ Django Version: 1.11.16 Exception Type: TypeError Exception Value: count() takes exactly 2 arguments (1 given) I tried several combinations on arguments for get_initial_queryset() function and paginator.page() function but cant solve the issue. -
How to allow an inline model with Foreign Key to be used only once?
My Goal: When I add Inlines in admin, to add that Model Object, only one Inline Item with a particular Foreign Key should be allowed. My Models: class RateCard(models.Model): name = models.CharField(max_length=100) year = models.IntegerField(choices=YEAR_CHOICES, default=timezone.now().year) class BillingCategory(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title class Meta: verbose_name_plural = "Billing Categories" class BillingCatagoryRate(models.Model): billing_category = models.ForeignKey(BillingCategory, on_delete=models.CASCADE) billing_rate = models.PositiveIntegerField() rate_card = models.ForeignKey(RateCard, on_delete=models.CASCADE, blank=True, null=True) Refer the admin screenshot. I can select the Drop Down with same value more than once and save successfully. What I need is, RateCard should have only one BillingCatagory used once . NOT multiple (like shown in the picture) My Ideas: During Save, may be we can check if there are any duplicates in Billing Categories. -
Opening Django project in Visual Studio Code -> projectname/bin/python file missing
Warning - beginner here. I've recently switched from using Sublime Text 3 to Visual Studio Code to manage my Django projects. However, i've run into git problems due to my projectname/bin/python file not opening in Visual Studio Code (I can see that it does not appear in the explorer). I've noticed that my python3.6 file also does not open. In Visual Studio Code, if i select File -> Open File and attempt to manually open projectname/bin/python i get an error stating "The file cannot be accessed by the system". Screenshot - VSC on the left, ST3 on the right -
DRF - how to implement object based permission on queryset?
I implemented DRF as per the document. At one point I figured out, once the user is authenticated, the user is allowed to fetch data of any user in the systems. I have implemented filtering as per this document. I read through the permission document and could not find a way to filter out queryset based on the owner. In my one of the views, I am checking if the owner is same as the user who requested. My question is, Do I have to do the same in all viewsets? or There is a general way where I can check this condition? -
Django update modelform with field constraints
Having the following Model: class Book(models.Model): name = models.CharField() author = models.CharField() date = models.DateField() class Meta: unique_together = ('name', 'author') class BookSerializerWrite(serializers.ModelSerializer): class Meta: model = Book class BookView(ApiView): def put(self, request, *args, **kwargs): serializer = BookSerializerWrite(data=request.data) if serializer.is_valid(): serializer.save() The view above does not work as the serializer.is_valid() is False. The message is: 'The fields name, author must make a unique set' Which is the constraint of the model. How do I update the model? I would rather not override the serializer's validation method. I also cannot access the validated_data for an update as in https://www.django-rest-framework.org/api-guide/serializers/#saving-instances as this is empty due to the fact that the form does not validate. Is there a builtin solution? -
Every page with extends reloads javascript (and re-establishes ws connection)
Good day, I'm a little stuck with one problem and somehow cannot find a solution. I have base template and two templates which are extending the base one. The base template includes websocket.js file which is establishing WebSocket connection when the user opens a page. Problem is that when he clicks on some link which leads to some child page, the browser is reloading all static files, including websocket.js what leads to disconnect/reconnect of WebSocket connection. Question how can I avoid such reloads. Should avoid using extends and move to jQuery style dynamic page updates without any reloads or can I keep javascript WebSocket object somewhere in global and do not establish a new connection if this object is not undefined (i do not know how to do that as well). websocket.js is simple: var websocketServerLocation = 'ws://' + window.location.host + '/ws/dashboard/'; function start(websocketServerLocation) { ws = new WebSocket(websocketServerLocation); ws.onmessage = function (e) { var data = JSON.parse(e.data); drawDashboard(data); }; ws.onclose = function () { // Try to reconnect in 5 seconds setTimeout(function () { start(websocketServerLocation) }, 5000); }; } start(websocketServerLocation); base.html: {% load staticfiles %} <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> .... <script type="text/javascript" src="{% static "websocket.js" %}"></script> </head> <body> … -
Disable read only fields in the response after posting the data
My model: class NewsID(models.Model): pass class News(models.Model): newsId=models.ForeignKey(NewsID,related_name = 'News', on_delete=models.CASCADE) lang_code=models.CharField(max_length=2) headline=models.CharField(max_length=100) class DefaultLanguage(models.Model): news_id = models.ForeignKey(NewsID,related_name = 'default', on_delete=models.CASCADE) defaultLanguage_id = models.IntegerField(unique=True) My serializer: class NewsSerializer(QueryFieldsMixin,serializers.ModelSerializer): class Meta: model=News fields=('lang_code','headline') class DefaultLanguageSerializer(QueryFieldsMixin,serializers.ModelSerializer): class Meta: model = DefaultLanguage fields = ('news_id ','defaultLanguage_id ') read_only_fields = ['news_id ','defaultLanguage_id '] class NewsIDSerializer(QueryFieldsMixin,serializers.ModelSerializer): News = NewsSerializer(many=True) default = DefaultLanguageSerializer(many=True,read_only=True) default_language = serializers.CharField(max_length=2,write_only=True) class Meta: model = NewsID fields = ('id','News','default','default_language') I want the response as below after posting : { "id": 10, "News": [ { "lang_code": "en", "headline": "Breaking news" } ], "default_language": "en" } Now my response is having news_id and defaultLanguage_id (read only fields) I don't want the response with read only fields after posting. How to achieve this using Django? -
Django image upload with js plugin issue
I am using js plugin to upload image, first time when i select image from the plugin the form gets submitted. The issue is that i select the image first time but then i don't want that image and i click on it again to upload another image, the form does not get validated and fails to submit. views.py class SelectObituaryView(LoginRequiredMixin, TemplateView): template_name = "website/obituary_select.html" def get_context_data(self, **kwargs): context = super(SelectObituaryView, self).get_context_data(**kwargs) church_id = self.request.session.get('church_id', None) if church_id: samples = ObituarySample.objects.filter(organization__id=church_id) context['obituary_samples'] = samples context['church_cover'] = self.request.session.get('church_cover', None) return context @transaction.atomic def post(self, request): print("Entered function") try: data = request.POST.copy() data['organization'] = request.session.get('church_id', None) data['slug'] = data['name'].replace(' ', '-') data['funeral_time'] = data['funeral_time'].replace(" ", "") data['viewing_time'] = data['viewing_time'].replace(" ", "") if len(request.FILES.getlist('gallery')) > 10: messages.error(request, "Max gallery images limit exceeded.") return HttpResponseRedirect( reverse('obituary:create', kwargs={'sample_obituary_id': request.POST.get('obituary_sample')})) obituary_form = ObituaryForm(data=data, files=request.FILES) # print("obituary form data",data) print("before is valid") if obituary_form.is_valid(): print("Inside is_valid") obituary_instance = obituary_form.save(commit=False) obituary_instance.image = obituary_instance.obituary_sample.background obituary_instance.user = request.user obituary_instance.save() obituary_instance.update_slug_with_id() #override profile_image #imageName = os.path.basename(obituary_instance.profile_image.path) imgArr = os.path.split(obituary_instance.profile_image.path) image_data = request.POST['profile_image1'] b = json.loads(image_data) head, data = b["output"]["image"].split(',') binary_data = a2b_base64(data) print(binary_data) with open(obituary_instance.profile_image.path, 'wb+') as fh: myfile = File(fh) myfile.write(binary_data) imprinted_image_path = apps.obituary.utils.imprint(obituary_instance, obituary_instance.obituary_sample) # Save imprinted image in …