Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to add pydantic field validation for django model?
So, I have a django model, let's say, it's field division is as follows: class ModelA(models.Model): f1 = models.CharField(max_length=127) f2 = models.CharField(max_length=127) I want to create a pydantic class, with a field type containing list of these models. Consider the following example: class TestPydanticClass(BaseModel): model_a_values: List[ModelA] f4: int When I am trying to create the TestPydanticClass object, but it throws the following error: RuntimeError: no validator found see `arbitrary_types_allowed` in Config Based upon this, I added arbitrary_types_allowed as True, under the Config class for the model, and it still throws an error. Can someone pls suggest a better method of achieving this? -
How should I design the Django Database Schema for below scenario?
I have been learning Django for a time being. I hope to get some help with Database Schema design. Which type of relationship should I use for the below use cases. I tried to search for similar use cases but non of those meet my specific need (please point out some online resources where I can learn these types of topics with practical use cases). Here is the most simplified concept of the whole problem (models.py) from django.db import models from django.contrib.auth.models import User class Companys(models.Model): # like Google, Amazon name = models.CharField(max_length=30) def __str__(self): return self.name class Persons(models.Model): # like Jon, Toney person = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class WorkHistory(models.Model): # like # Jon: as Developer at Google # Jon: as Manager at Amazon # Toney: as Sr. Team Leader at Amazon # Toney: as Manager at Google position = models.CharField(max_length=30) person = models.ForeignKey(Persons, on_delete=models.CASCADE) # may be ManyToManyField company = models.ForeignKey(Companys, on_delete=models.CASCADE) # may be ManyToManyField def __str__(self): return self.position Here is how I want to query the data afterward: List of people who have worked on google. List of people who have worked on amazon. (written this line also to make the … -
Why is the field value stored as a set?
When the input field value is saved to the db and I retrieve the same value for updating the field, I get the updated field as a set Data when i retrieve from db, <QuerySet [{'id': 21,'book_title': 'pokolo', 'book_category': '0', 'book_type': 'F'}]> Data after updating the retrieved field value, <QuerySet [{'id': 21,'book_title': "('pokolo',)", 'book_category': '0', 'book_type': 'F'}]> The book title is a CharField and is cleaned before sending to the db -
Django Admin Show Row Results As a Group by ForeignKey Object
I am working on a quiz app. So I have Quiz, Question and Answer tables. Also I have TakingQuiz and TakingQuizAnswer tables. For example, I want to show rows as a group by quiz. If I select a quiz, I just want the list of answers for that quiz to appear or same thing for question-answer. Nested inline isn't a solution for me. It works well for edit page, but I want to make this in list pages. Is there any way to do this? Because there are too many results in these pages, and filters and search also working to some extent. For example, when I select question 1 and click it, a new page or accordion menu may open. From this page or menu, I can see the results related to that parent, and I can edit the one I want. This subject isn't clear for me. Because I am a newbie in Django. I found some solutions, but they came too complicated. And also I found so many unanswered questions about this. I didn't add any code because it's a general question, it can be thought of as an article-comment relationship. I am looking for source and … -
How to setup Django and Python telegram bot to deploy to Heroku?
When I deploy my Django app with my bot.py to Heroku there is a conflict because Django does not let the bot receive the calls. Procfile web: python bot.py web: gunicorn tlgrmbot.wsgi the logs show that it keeps looking for the https://herokuappname.com/token not found, because I don´t have urls, and if I only leave the python bot.py in the procfile the bot responds but it does not finds the Database. Does someone knows how to resolve this? -
Django: aggregate or annotate function, flatten JSON and filter data
The solution would be simple and easy, but I am not able to fetch what I want. I am trying to get the summary a summary table that has a foreign key primary key relationship and provides an array of nested JSON data, which is difficult to display in table format in the frontend. So I am trying to flatten it in the backend, add filters and fetch accordingly. The way I am approaching would be wrong, if someone can please help, I am thankful. model.py class Place(models.Model): id = models.IntegerField(primary_key=True) location = models.CharField(max_length=100) class Meta: db_table = 'place' managed=False class Session(models.Model): id = models.IntegerField(primary_key=True) place = models.ForeignKey(Place,related_name='session',on_delete=models.CASCADE, null=True) start = models.DateField(auto_now=True) count = models.IntegerField() num_not_placed = models.IntegerField() class Meta: db_table = 'session' managed=False class Animal(models.Model): id = models.IntegerField(primary_key=True) sess = models.ForeignKey(Session,related_name='details',on_delete=models.CASCADE, null=True) type = models.CharField(max_length=100) is_active = models.BooleanField() length = models.DecimalField(max_digits=6, decimal_places=2) class Meta: db_table = 'animal' managed=False serializers.py class PlaceSerializer(FlexFieldsModelSerializer): length_max = serializers.DecimalField(max_digits=10, decimal_places=2) length_min = serializers.DecimalField(max_digits=10, decimal_places=2) length_avg = serializers.DecimalField(max_digits=10, decimal_places=2) length_std = serializers.DecimalField(max_digits=10, decimal_places=2) is_active_percent = serializers.IntegerField() counts = serializers.IntegerField() Num_of_not_placed = serializers.IntegerField() Date = serializers.DateField() type = serializers.CharField() class Meta: model = Tank fields = ["Date","location","type","is_active_percent","length_max","length_min","length_avg","length_std","Num_of_not_placed","counts"] expandable_fields = { 'session': (SessionSerializer, {'many': True}) } I … -
How to pass data from html to django view
I have the following button: <a href="{% url 'acceptdonation' %}" >Delete</a> I also have this acceptdonation function (in views.py): def acceptdonation(request, pk): #add pk after request deleteitem = Donation.objects.filter(id = pk) deleteitem.delete() return redirect('/dashboard/') I want to pass {{donation.pk}} to the view after the delete button is clicked. The code should delete the data assosiated with the pk given and redirect the user -
Django 'UNIQUE constraint failed' when post same massages
I am building a socialsite. In this site user create group and post messages. I get this error when user put same message in same group or even in other group. **IntegrityError at /posts/new/ UNIQUE constraint failed: posts_post.user_id, posts_post.message Request Method: POST Request URL: http://127.0.0.1:8000/posts/new/ Django Version: 3.2.4 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: posts_post.user_id, posts_post.message Exception Location: F:\Program Files\envs\MyDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: F:\Program Files\envs\MyDjangoEnv\python.exe** Here is models.py: class Post(models.Model): user = models.ForeignKey(User, related_name="posts",on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name="posts",null=True, blank=True,on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = misaka.html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "posts:single", kwargs={ "username": self.user.username, "pk": self.pk } ) class Meta: ordering = ["-created_at"] unique_together = ["user", "message"] views.py: class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = super().get_queryset() return queryset.filter( user__username__iexact=self.kwargs.get("username") ) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): # form_class = forms.PostForm fields …