Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django request url changing to 'django/images' for static files after deployment
This is my settings.py. Used docker compose with nginx to deploy the backend. The images load up fine in the cpanel but the request url changes to http://django/images instead of my server url. tried changing the media url to my server url, but it still doesn't work. Hosted in bluehost vps. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = 'static/images' MEDIA_URL = '/images/' -
How to get a formset to appear within an inline form, within a form? (Python/Django)
I am trying to have an option where someone will click a button which brings up a modal box. The Modal Box will come up and display a form. I'm trying to render an inline form and within that will render my formset. ''' class BoxMovement(BoxMovementUpdateFormFormSetBase): def full_clean(self): super(BoxMovementUpdateFormFormSet, self).full_clean() class BoxMovementUpdateForm(BoxModelForm): Box = BoxChoices location = StorageLocationChoices class BoxMovementUpdateFormInlineForm(BoxModelForm): class Meta: model = models.BoxMovement fields = ('id', ) ''' -
Django notifications: ValueError at /admin/notifications/notification/ Field 'id' expected a number but got '<property object at 0x7ff00c663540>'
I am using Django - ver 3.2 and django-notification - ver 1.6 I have added the notification app to my project, as per the documentation. To generate notifications in my code, I am using statement like this: from notifications.signals import notify def my_notifier(sender, instance, created, **kwargs): notify.send(sender, actor=instance.user, verb=f"New level ({instance.level.name}) attained!", recipient=instance.user ) instance and sender are both of type Badassness: class Badassness(models.Model): score = models.PositiveIntegerField(default=0) level = models.ForeignKey(Level, on_delete=models.CASCADE, default=1) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='reputation', primary_key=True) def __str__(self): return str(self.score) When I try to view the notifications in the admin manager, I get the following error message: ValueError at /admin/notifications/notification/ Field 'id' expected a number but got '<property object at 0x7f777a446bd0>' What is causing this error (i.e. why - and where is the id field being populated as an object?) - and how do I resolve this? -
How can I create a new model entry with an incrementing field unique to a tenant in a multi-tenant database architecture in Django?
I have a model representing an Invoice. Each invoice has a non-pk identifier_number field. When a new invoice is created, this value needs to be incremented by one. Model in question: class Invoice(BaseModel): class Meta: db_table = "invoices" constraints = [ UniqueConstraint( fields=["account", "identifier_number"], name="no_duplicate_invoice_numbers"), ] ... # UUID Field PK and unrelated fields removed. account = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="account_invoices") ... identifier_number = models.PositiveIntegerField() My initial thought was to use an AutoField but this would be unsuitable as a different accounts (tentants) can have invoices with the same number. For example, the below data would be suitable. Account ID Invoice Number 1 1 1 2 2 1 2 2 My next thought was to simply find the largest invoice number currently in use for a specific account and then increment it by one like so: new_invoice_number = Invoice.objects.filter( account=account ).latest( "identifier_number" ).values( "identifier_number" ) new_invoice = Invoice.objects.create(account=account, identifier_number=new_invoice_number) However, this can lead to a race condition if two Invoices are created at the same time. The UniqueConstraint would still raise an error, but it would be better if the issue was completely removed by fetching and incrementing the invoice number in the same statement as creating the object. I've looked … -
Django urls py. Loading the index page instead of the image
I currently have two situations A) http://127.0.0.1:8000/ B) http://127.0.0.1:8000/Images/SomeImages.png This is what my urls.py looks like urlpatterns = [ path('admin/', admin.site.urls), url(r'', include("webSite.urls")), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and then my webSite.urls looks like this urlpatterns = [ url(r"", test , name="test"), ] The problem with this is it works for condition A but for condition B it routes to the main page as well instead of the image. Can anyone tell me how I can fix this? -
Send context with Django class based views
In Django ListView I send the list of items with their details, I also want to send True \ False or 0\1 whether this item is in the user bookmark list or not after checking if user id is in favorites (ManyToManyField) field of object. if query_set['posts'][i].favorites.filter(id=self.request.user.id).exists(): # send True else: # send False In template I want to do one thing if it is true and another different thing if it is false. {% if True %} ... {% else %} ... {% endif %} If it was a function view, I would send True or False with context. Like this: if post.favorites.filter(id=self.request.user.id).exists(): fav = True else: fav = False context = {..., 'fav', fav} -
Updated to Django 3.0 and now I'm seeing "Select All" and "Clear Selection" options
I updated to Django 3.2 and I'm getting this "Select All...." and "Clear Selection" options in my admin list views. It could possibly be one of the dependencies that I had to update to get her as well, but I can't figure out what is adding those there. They also don't seem to do anything. Dependency List amqp==1.4.9 anyjson==0.3.3 appdirs==1.4.3 asgiref==3.4.1 asn1crypto==0.24.0 astroid==2.1.0 attrs==19.1.0 autopep8==1.4.3 Babel==2.9.1 bcrypt==3.1.7 beautifulsoup4==4.6.3 black==19.3b0 blessed==1.15.0 boto3==1.13.2 botocore==1.16.2 braintree==3.48.0 cached-property==1.5.1 cachetools==2.1.0 cement==2.8.2 certifi==2019.9.11 cffi==1.14.0 chardet==3.0.4 Click==7.0 cloudinary==1.12.0 colorama==0.4.3 coreapi==2.3.3 coreschema==0.0.4 cryptography==2.9.2 dal-admin-filters==0.3.3 defusedxml==0.5.0 diff-match-patch==20121119 dill==0.2.8.2 Django==3.2.5 django-admin-sortable2==1.0 django-admin-tools==0.9.1 django-admin-tools-stats==0.9.0 django-appconf==1.0.4 django-autocomplete-light==3.5.0 django-autoslug==1.9.8 django-bower==5.2.0 django-colorfield==0.3.0 django-common-helpers==0.9.2 django-cors-headers==3.7.0 django-crispy-forms==1.7.2 django-cron==0.5.1 django-discover-runner==1.0 django-elasticache==1.0.3 django-extensions==2.1.4 django-filter==2.4.0 django-formtools==2.1 django-group-by==0.3.1 django-guardian==1.4.9 django-import-export==2.5.0 django-jet==1.0.7 django-jquery==3.1.0 django-jsonfield==1.0.1 django-meta==2.0.0 django-money==2.0.1 django-nested-admin==3.2.4 django-nvd3==0.9.7 django-object-actions==1.0.0 django-password-reset==2.0 django-polymorphic==2.0.3 django-qsstats-magic==1.0.0 django-redis-cache==3.0.0 django-rest-swagger==2.2.0 django-reversion==3.0.9 django-silk==3.0.2 django-sslserver==0.21 django-storages==1.9.1 django-suit==0.2.26 django-taggit==1.1.0 django-tinymce==3.0.2 django-tsvector-field==0.9.4 django-user-accounts==3.0.4 django-user-agents==0.3.2 django-widget-tweaks==1.4.3 djangorestframework==3.12.4 djangorestframework-bulk==0.2.1 djcacheutils==3.0.0 docker==4.2.0 docker-compose==1.25.5 docker-pycreds==0.3.0 dockerpty==0.4.1 docopt==0.6.2 docutils==0.14 drf-extensions==0.3.1 drf-serializer-cache==0.3.3 ebaysdk==2.1.5 entrypoints==0.3 et-xmlfile==1.0.1 flake8==3.7.7 future==0.16.0 gprof2dot==2017.9.19 grpcio==1.14.2 httplib2==0.11.3 idna==2.6 isort==4.3.4 itypes==1.1.0 jdcal==1.4 Jinja2==2.10 jmespath==0.9.3 jsonfield==2.0.2 jsonschema==2.6.0 kombu==3.0.37 lazy-object-proxy==1.3.1 libsass==0.14.5 lxml==4.2.4 Markdown==2.6.11 MarkupPy==1.14 MarkupSafe==1.1.1 mccabe==0.6.1 mock==2.0.0 mongoengine==0.15.3 numpy==1.15.1 oauthlib==2.1.0 odfpy==1.3.6 olefile==0.45.1 openapi-codec==1.3.2 openpyxl==3.0.7 packaging==20.3 paramiko==2.7.1 pathspec==0.5.9 pbr==4.2.0 pep8==1.7.1 pilkit==2.0 Pillow==5.2.0 pip-check-reqs==2.0.3 ply==3.8 protobuf==3.6.1 psycopg2==2.7.5 psycopg2-binary==2.7.5 py-moneyed==1.2 pyasn1==0.4.4 pyasn1-modules==0.2.2 pycodestyle==2.5.0 pycparser==2.20 pyflakes==2.1.1 Pygments==2.4.2 PyJWT==1.6.4 pylibmc==1.5.2 pylint==2.2.2 pymongo==3.7.1 … -
external javascript file and function not working
I am new to javascript. I was trying to make a message box popup onload. As i am beginner i copied the code from internet just to see how it works but for some reason the pop is not showing up. I know the code is not worng because it is wrking in the video. the calling method is a bit different as i am using django. console error auto.js:6 Uncaught TypeError: Cannot read property 'style' of null html code {% block content %} <script type="text/javascript" src="{% static 'auto.js' %}"></script> <div class="popup"> <div class="contentBox"> <div class="close"></div> <h3 style="color: oldlace;">TESTING POPUP</h3> </div> </div> {% endblock %} javasript code const popup = document.querySelector('.popup'); window.onload = function(){ setTimeout(function(){ popup.style.display = "block" // add some time delay o show }, 2000) } -
django object.filters.order_by() returns the same instance multiple times when the field i am ordering by is a "many to many"
Here is the problem: I have two models Contact and Title. Contact represent a person Title represent a job title A person can have more than one job title and the two models are related through a many to many relation (see models below). The issue is that for some reason when I make this query contacts = Contact.objects.filter("some filter").order_by('title') I get contacts with more than one title returned multiple times...because I am ordering by title and I guess django is confused on which title to use? I am losing my mind on how to fix it while keeping ordering by title. class Title(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title_name = models.CharField(max_length=40) class Contact(models.Model): name_surname = models.CharField(max_length=60) title = models.ManyToManyField(Title) ... -
Website refuses to open on custom domain but works on IP
I am trying to bring my Django website online with a custom domain. The website is melius.live and the IP of the webserver is 157.90.29.120. However, opening the IP works fine, opening the domain usually doesn't work, sometimes it gives me an Apache default page (I am using NGINX, not Apache), but normally just a connection refused. The site is written in Django, I am using Hetzner for hosting and Namecheap for the domain. When I do a traceroute, the correct IP shows up. Where is the problem? -
Browser prints white list in PDF instead full document
I'm using Django=3.1 pyppeteer=0.2.5 #for printing page as PDF I don't know where is the problem here, because it has worked fine before. I'm using new ability of Django for making async response. Maybe here is the problem? the code for printing PDF async def generate_pdf(request, pk=None, blueprint=''): browser = await launch( executablePath='/usr/bin/chromium-browser', headless=True, args=['--no-sandbox'], handleSIGINT=False, handleSIGTERM=False, handleSIGHUP=False ) page = await browser.newPage() url = 'https://{}/reports/{}/{}/'.format(request.get_host(), pk, blueprint) await page.goto(url, {'waitUntil': 'networkidle0', 'timeout': 60 * 1000}) pdf_file = await page.pdf({ "width": "210mm", "height": "297mm", "printBackground": True, }) await browser.close() response = HttpResponse(content_type='application/pdf') report_name = await get_report_name(pk) response['Content-Disposition'] = 'attachment; filename="{report_name}.pdf"'.format( report_name=escape_uri_path(report_name) ) response.write(pdf_file) return response uwsgi log after executing the code above unhandled exception during loop shutdown task: <Task finished coro=<WebSocketCommonProtocol.transfer_data() done, defined at /var/www/evaluation360/env/lib/python3.6/site-packages/websockets/protocol.py:818> exception=CancelledError()> Traceback (most recent call last): File "/var/www/evaluation360/env/lib/python3.6/site-packages/websockets/protocol.py", line 700, in close loop=self.loop if sys.version_info[:2] < (3, 8) else None, File "/usr/lib/python3.6/asyncio/tasks.py", line 358, in wait_for return fut.result() File "/var/www/evaluation360/env/lib/python3.6/site-packages/websockets/protocol.py", line 1169, in close_connection await self.transfer_data_task concurrent.futures._base.CancelledError [pid: 1788|app: 0|req: 7/17] 109.63.253.81 () {44 vars in 1002 bytes} [Thu Jul 29 20:00:12 2021] GET /api/v1/reports/617dd17b-217a-4489-aa5f-c7f5568a569b/pdf/test/ => generated 887 bytes in 7326 msecs (HTTP/1.1 200) 8 headers in 537 bytes (2 switches on core 0) -
how change pages without page refreshing ajax django
i'm trying to change url browsers without refreshing the pages ! i've tried several ways but still refreshes pages to go new url? <a href="{% url 'products:main' %}" id="btn-main"><button class="btn btn-primary dim btn-dim" id="btn-main" type="button"><i class="fas fa-home"> </i> main </button></a> <a href="{% url 'products:partgroup' %}" id="btn-part"><button class="btn btn-warning dim btn-dim" type="button"><i class="fas fa-grip-horizontal"> </i> part group </button></a> $('a').click(function() { window.location.hash = '{% url 'products:partgroup' %}'; return false; }); //i also tried this var stateObj = { foo: "bar" }; function change_my_url() { history.pushState(stateObj, "page 2", "{% url 'products:partgroup' %}"); } var link = document.getElementById('btn-part'); link.addEventListener('btn-part', change_my_url, false); is there a better way to achieve that ? i've used django and bootstrap 4 thank you for your helping .. -
Why am I getting an error when passing data from html to function - Django
I have the following button: <a href="{'url acceptdonation pk = donation.pk'}" >Delete</a>. In my acceptdonation function: def acceptdonation(request, pk): deleteitem = Donation.objects.filter(id = pk) deleteitem.delete() return HttpResponseRedirect('/dashboard/') As you can see, I want to delete the Donation using the pk from the previous page. My problem is that instead of deleting, I am getting this error (after the button is clicked): Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/donations/73/%7B'url%20acceptdonation%20pk%20%3D%20donation.pk'%7D This is weird, because the Request URL is not like anything I have set in my urls.py In the html, everything renders out fine, but if I want to click on the delete button to delete the data based upon the pk, I get this error. This is my url: path('donations/<pk>/', views.DonationDetail.as_view(), name='donation-detail'), -
Django Dynamic Setting : access DEBUG from admin page
I Use django 3.2 I need to change DEBUG option from admin page to do that I install Django-constance I add these in setting.py: CONSTANCE_CONFIG = { 'DEBUG':(True,'Debug mode'), } # answer_the_question() DEBUG=config.DEBUG and this signal in models.py @receiver(config_updated) def constance_updated(sender, key, old_value, new_value, **kwargs): print(sender, 'DEBUG', old_value, new_value) but its not work -
Can not save ModelForm - RadioSelect choices
I'm writing a counter for yoga practice for my friends. I have two models Practice and Session. Practice describe values about whole practice repetition. Session should save values from singe session (and also add this value to current_value which is in Practice Model. In my form I'm trying to have 5 radio choices (session_choice_value) and one more which will be an input integer from user (session_custom_value) The first problem is that I cannot save the form, I had tried many many times on different ways and could not figure. I think that maybe I'm redirecting in wrong way (maybe there is a problem with passing a context) or form is not connected with right model. The second problem is that I want this input choice to be hidden at first and appear after checking the 'CUSTOM' choice. Do You have some ideas, hints, solutions? Please help :) This is my model: from django.db import models class Practice(models.Model): practice_name = models.CharField(max_length=30) current_value = models.IntegerField(default = 0) total_value = models.IntegerField(default = 111111) def __str__(self): return self.practice_name class Session(models.Model): practice = models.ForeignKey(Practice, on_delete=models.CASCADE) session_choice_value = models.IntegerField(blank=True) session_custom_value = models.IntegerField(blank=True) session_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.practice.practice_name}: {self.session_value} repetitions, date: {self.session_date}" forms.py from django … -
Convert QuerySet into List in Dict and then regroup using regroup templatetag in Django
I want to regroup my listview based on membership on html template. Below is my model: MEMBERSHIP_CHOICES = ( ('VIP', 'VIP'), ('Premium', 'Premium'), ('New', 'New'), ) class Membership(models.Model): name = models.CharField(max_length=7, choices=MEMBERSHIP_CHOICES, default='New') def __str__(self): return self.name class Escort(models.Model): profile_pic = models.ImageField(null=True, blank=True, upload_to="images/") name = models.CharField(max_length=40) author = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE) about_me = models.TextField() phone = models.CharField(max_length=14) ethnicity = models.CharField(max_length=20) orientation = models.CharField(max_length=20) location = models.CharField(max_length=40) area = models.CharField(max_length=15) skin_color = models.CharField(max_length=40) hair_color = models.CharField(max_length=40) services = models.CharField(max_length=255) membership = models.ForeignKey(Membership, on_delete=models.CASCADE) created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['-membership'] def __str__(self): return self.name + '~' + str(self.author) I am trying to do a queryset and convert into a list dict using the code below in my views.py: def EscortGroupView(request): escort_groups = Escort.objects.values('profile_pic', 'name', 'about_me', 'phone', 'ethnicity', 'orientation', 'location', 'area', 'skin_color', 'hair_color', 'services', 'membership_id') [{'profile_pic': 'profile_pic', 'membership_id': 4}, {'profile_pic': 'profile_pic', 'membership_id': 5}, {'profile_pic': 'profile_pic', 'membership_id': 6},] return render(request, 'group.html', {'escort_groups': escort_groups}) Please note that I want to render the regrouped items on group.html. The membership_id is being used here because of the ForeignKey relationship between the Membership Model and the Escort Model. The membership_ids represent each of the three MEMBERSHIP_CHOICES. When I run the code, nothing is displayed … -
Uploading and saving multiple images in M2M field Django Rest?
I tried everything, but could not populate the validated_data dictionary with a list of images that are sent to the server. The images key is not in the dictionary, the validate_images method does not run. cover_image works fine. Tell me if it is possible to populate the validated_data dictionary with a validated list of images (InMemoryUploadedFile). I don't want to take raw files from request.FILES. class Image(models.Model): name = models.CharField(max_length=255, blank=True) image = models.ImageField(upload_to='images/', validators[validation_existing_image]) class Address(models.Model): cover_image = models.ForeignKey(Image, on_delete=models.SET_NULL, null=True) images = models.ManyToManyField(Image, related_name='+', blank=True) class UpdateAddressSerializer(serializers.ModelSerializer): cover_image = serializers.ImageField() images = serializers.ListSerializer(child=serializers.ImageField()) class Meta: model = Address fields = '__all__' def validate_images(self, value): return value -
I am unable to do crud operation in django with ajax
this is my views.py from django.shortcuts import render, redirect from .models import Member Create your views here. def index(request): members = Member.objects.all() return render(request, 'blog/index.html', {'members': members}) def insert(request): member = Member(firstname=request.POST['firstname'], lastname=request.POST['lastname'], address=request.POST['address']) member.save() return redirect('/') this is my form code <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <script src="jquery-3.5.1.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0 /css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div class="container-fluid"> <h1 class="text-light text-center bg-dark mt-5 mb-5 p-2">Let's CRUD with AJAX in Djangoooo.....!!!</h1> <div class="row"> <div class="col-sm-4"> <form method="POST"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter your email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Username</label> <input type="password" class="form-control" id="username" placeholder="Enter your username"> </div> <div class="form-group"> <label for="exampleInputPassword1">Phone</label> <input type="number" class="form-control" id="number" placeholder="Enter your Phone no."> </div> <div class="form-group"> <label for="exampleInputPassword1">Age</label> <input type="number" class="form-control" id="age" placeholder="Enter your age"> </div> <input id="btnsubmit" type="button" class="btn btn-primary w-100" value="Test AJAX Connection"/> </form> </div> <div class="table col-sm-8"> <table class="table table-bordered table-stripped" id="myTable"> <thead> <tr> <th>Email</th> <th>Username</th> <th>Phone</th> <th>Age</th> <th>Edit</th> </tr> </thead> <tbody> {% for usrs in user_list %} <tr> <td>{{ usrs.email }}</td> <td>{{ usrs.username }}</td> <td>{{ usrs.phone }}</td> <td>{{ usrs.age }}</td> <td><a class="btn btn-warning"><span></span> Edit</a> <a class="btn btn-danger … -
Weird ValueError: Missing staticfiles manifest entry for 'images/2foobar' Webflow images only
I'm having a strange issue where I have already did the collectstatic prior to deployment. This happens when my white noise is set to STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' But it works when white noise is set to STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' However, a lot of my functionality from javascript and some images are not showing up, specifically the ones that have inherited resize properties from Webflow css and js. is there something I'm missing here? -
VueJS + Django : Video data sync with table
I am trying to do a data visualisation platform in which I want to display videos based on a selection from users and while the video is playing the data that is recorded in the video should be displayed in a table (both video and table should be taken from Django and synced). If the user clicks on the table data, the video should go to that particular time interval and start playing from that point. Please help me, how this can be achieved in the frontend or backend and it is important. -
How to convert Httpresponse in xml format to convert htmlin Django
Good day! Need to convert xml that comes with HttpResponse to html ? i tried to do everything that i know but couldnt fine a solution, can someone help me, thanks. This is my request; xml_2 ="""<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <TP_WMD_UCD xmlns="https://turkpos.com.tr/"> <G> <CLIENT_CODE>10738</CLIENT_CODE> <CLIENT_USERNAME>Test</CLIENT_USERNAME> <CLIENT_PASSWORD>Test</CLIENT_PASSWORD> </G> <GUID>0c13d406-873b-403b-9c09-a5766840d98c</GUID> <KK_Sahibi>ERHAN Turan</KK_Sahibi> <KK_No>4546711234567894</KK_No> <KK_SK_Ay>12</KK_SK_Ay> <KK_SK_Yil>2026</KK_SK_Yil>a <KK_CVC>000</KK_CVC> <KK_Sahibi_GSM>5422616410</KK_Sahibi_GSM> <Hata_URL>http://localhost:62317/turkpos.api/sonuc.aspx</Hata_URL> <Basarili_URL>http://localhost:62317/turkpos.api/sonuc.aspx</Basarili_URL> <Siparis_ID>0661</Siparis_ID> <Siparis_Aciklama>a</Siparis_Aciklama> <Taksit>1</Taksit> <Islem_Tutar>100,00</Islem_Tutar> <Toplam_Tutar>100,00</Toplam_Tutar> <Islem_Hash>9pc1FYT52m/efDU+eH9Is/qfLI0=</Islem_Hash> <Islem_Guvenlik_Tip>3D</Islem_Guvenlik_Tip> <Islem_ID>123</Islem_ID> <IPAdr>127.0.0.1</IPAdr> <Ref_URL></Ref_URL> <Data1>a</Data1> <Data2>a</Data2> <Data3>a</Data3> <Data4>a</Data4> <Data5>a</Data5> </TP_WMD_UCD> </soap:Body> </soap:Envelope>""" And this is my code in views.py headers = {'Content-Type': 'text/xml'} r = requests.post(SANAL_POS['ok_url'], data=xml_2.encode('utf-8'), headers=headers) return HttpResponse(r, content_type='text/xml') This is the response <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <TP_WMD_UCDResponse xmlns="https://turkpos.com.tr/"> <TP_WMD_UCDResult> <Islem_ID>6004998478</Islem_ID> <Islem_GUID>25152b5b-7403-42c5-a14e-cfef360dd150</Islem_GUID> <UCD_HTML><!DOCTYPE html SYSTEM "about:legacy-compat"> <html class="no-js" lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta charset="utf-8"/> <title>3D Secure Processing</title> <link href="http://10.250.20.20/mdpaympi/static/mpi.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="main"> <div id="content"> <div id="order"> <h2>3D Secure Processing</h2> <img src="http://10.250.20.20/mdpaympi/static/preloader.gif" alt="Please wait.."/> <img src="http://10.250.20.20/mdpaympi/static/verifiedbyvisa.png" alt="Verified by VISA"/> <div id="formdiv"> <script type="text/javascript"> function hideAndSubmitTimed(formid) { var timer=setTimeout("hideAndSubmit('"+formid+"');",100); } function hideAndSubmit(formid) { var formx=document.getElementById(formid); if (formx!=null) { formx.style.visibility="hidden"; formx.submit(); } } </script> <div> <form id="webform0" name="red2ACSv1" method="POST" action="https://katmai2.asseco-see.com.tr/mdpayacs3/pareq" accept_charset="UTF-8"> <input type="hidden" name="_charset_" value="UTF-8"/> <input type="hidden" name="PaReq" value="eJxVUctuwjAQ/BXEB+AHSSBosZSWQzmkpSk9tJfKclZN2mLAcRD8fddJ6MMX74z2NbOwrRzi6glN61BBjk2j33FUl8vxpniUXMbzJJqOFWyyAo8KTuiaem+VmPCJBHaFVOhMpa1XoM3xZn2vojhKZpQxQNihW6+USLng4QHrCbB6h+q1dlr7t+kKWIfB7Fvr3UXNUmpxBdC6L1V5f1gwBiwAYL9zN22IGio+16XKq/zBZqcWp/OMp235+bFOztu8SO3zEljIgFJ7VKRQ8JlMR1Is4njBBbCOB70LU9W2eBnRxpOw8UDBIUzKeiB6MX8pICsdWnNRaZTS9lcEeD7sLVIGafqJocTGkJDh+1Vxexe8NJ5MknHEk3nSudkRoVVNjshE9L0CABZK2HAoNpySon8n/gYgNqGw"/> <input type="hidden" name="MD" value="454671:9CF232FAAB49AD92BF60255496CBA360E3D352878A31BB7549946FFA5EF09586:4626:##190100000"/> <input type="hidden" name="TermUrl" value="https://entegrasyon.asseco-see.com.tr/fim/est3Dgate"/> … -
django make a new model when another model gets added
class Game(models.Model): title = models.CharField(max_length=64) description = models.TextField(max_length=8192) requirements = models.CharField(max_length=128, help_text='Memory: 16GB, Gpu: RTX 3090') thumbnail = models.ImageField(upload_to='media/thumbnails/') game = models.FileField(upload_to='media/games/') upload_date = models.DateTimeField(auto_now_add=True) downloads = models.IntegerField(default=0) comments = models.IntegerField(default=0) category = models.CharField(max_length=48, null=True, default='Gaming') def create_preview(cls): # Here <------------------------ preview = GamePreview.objects.create(title=cls.title, thumbnail=cls.thumbnail) preview.save() class GamePreview(models.Model): title = models.CharField(max_length=64) thumbnail = models.ImageField(null=True) downloads = models.IntegerField(default=0) comments = models.IntegerField(default=0) Basically I want to add a new preview that has the title, thumbnail... of the game that was created, how can I achieve this? -
Django restfull api Filefield upload to S3 and return filename instead of file url
I am trying to create a restfull api using django and upload a file to aws s3 and return the filename instead of file upload url . model.py file = models.FileField(upload_to=upload_location,blank=False, null=False) serializer class FileSerializer(serializers.ModelSerializer): class Meta(): model = File fields = ('file', 'img_id','img_path' ,'timestamp', 'base_url') the file field in model.py is defined as shown above. Can you please share some info what i should be doing in order to return the filename instead of file url -
Django image compression not working in signals
I am using signals in my Blog model and trying to compress and resize image but image compressing not working in signals here is my code: class Blog(models.Model): #my this model using signals author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,max_length=100, related_name='author') blog_cover_image = models.ImageField(upload_to='blog/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True) def save(self,*args,**kwargs): super().save(*args, **kwargs) img = Image.open(self.blog_cover_image.path) if img.height > 300 or img.width > 300: out_put_size = (300,300) img.thumbnail(out_put_size) img.save(self.blog_cover_image.path) #my others model fields.. post_save.connect(Blog.blog_notify, sender=Blog) I tested this code on my another model which not using signals and it worked but why image compressing not working in my Blog model which using django post_save signals ? -
Exception handling in a Python generator function within a continuous stream from S3 to Client (Django app)
I am working on an app that encrypts/decrypts very large files in a continuous stream from S3 > Python/Django App > Client. I am trying to catch exceptions that are thrown inside a generator function and respond back to the client with an error. (ex. 'The AWS KMS key you provided is not valid for xxxx'). I can log the error out in the generator but I am unable to bubble that up so that I can throw the error back to the client. Ideally I would like to raise the exception to the @handle_exception decorator but would be happy with a solution that handles the exception in the function. Can someone point me in the right direction here? Solutions that I have found so far don't have the specific use case of a seamless stream and don't work unfortunately. Thanks!! @handle_exception @require_http_methods(["POST"]) def decrypt(request): def generate(decryptor): try: for chunk in decryptor: yield chunk except Exception as e: LOGGER.info(f"GENERATOR EXCEPTION CAN BE LOGGED HERE: {e}") raise e finally: if decryptor: decryptor.close() try: request_data = json.loads(request.body) validate(instance=request_data, schema=constant.DECRYPT_SCHEMA) s3 = boto3.client("s3", region_name=request_data["region"]) obj = s3.get_object(Bucket=request_data["bucket"], Key=request_data["key"]) set_socket_timeout(obj) if request_data.get("decrypt", True): encryptionClient = aws_encryption_sdk.EncryptionSDKClient( commitment_policy=CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT ) kms_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider( key_ids=request_data["kmsKeys"] ) return …