Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I use a models current id to query another model
I have two classes, JobFinancialInfo(models.Model) and another model class with a field called financial_info = models.OneToOneField(JobFinancialInfo, on_delete=models.PROTECT). I'm trying to create an @property on JobFinancialInfo that will return all of the objects from the second model that has the id of self.id(?) of JobFinancialInfo. I want to do this specifically so I can run an aggregation on another field in the second models as a property on the first. Is there a way to do this, or is there a better, more efficient way? -
How to access an authenticated django webapp from a link within an email?
I have a Django webapp on Ubuntu that displays report information. I need to send emails to users that include links to view filtered data in the report depending on the user. I understand that I should generate a unique key for each customer and insert it into the query string of the included URL in the email. I am not sure how to do that. Should I use JWT? Or Oath2? If Oath2, don't I need an account? Could someone please point me to a good reference or an example? I am not sure of the best way to do this. -
Accessing API Key from django settings.py for script tag src in template
I am trying to add my api key from my settings.py to to the src for my script tag. I have been unsuccessful, so I'm hoping someone has an idea I haven't thought of or found online. <script> let GOOGLE_API_KEY='{{GOOGLE_API_KEY}}' console.log(GOOGLE_API_KEY) </script> <script src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY&callback=initMap&libraries=&v=weekly" async defer> </script> GOOGLE_API_KEY successfully logs the correct api key from my views.py -
Run batch file by clicking button in django
I have some problem with running the file (which run program from my disc) using a button in django. So this is my batch file which i would like to run: set dir=C:\Users\ciach\Desktop\openpose\bin cd %dir% openposedemo.exe --net_resolution 272x272 --model_folder C:\Users\ciach\Desktop\openpose\models --video C:\Users\ciach\X\Squat\P0.mp4 --write_json C:\Users\ciach\X\JSON This is my run.py file which i run script by python: import subprocess def squat(): subprocess.call(['C:/Users/ciach/Desktop/praca/django/mysite/main/file.bat']) #squat() Django files: views.py: def squat(request): if request.method == 'POST' and 'run_script' in request.POST: from .run import squat squat() return redirect("/home") home.html: {% block content %} <form method="post"> {% csrf_token %} <button type="submit" name="run_script">Run script</button> </form> {% endblock %} After clicking nothing happens. I have tried with only .bat file (without run.py) but doesn't work either. All I want is for the .bath file to start after pressing the button which will run the command as above. Is there any way to run something like that at all? This is based on: How to execute file.py on HTML button press using Django? Python version: 3.5.0 Django version: 2.0.7 -
How to send an email or write a function/logic after Django Rest Framework Throttles a view
I'm building an Authentication system using Django and Django Rest Framework as my backend. I've finally done the throttling to disable Annoymous Users from logging in to the site if it makes 3 Annoymous requests which will help prevent some Brute Force attacks if the user is a hacker or something similiar.. Now my problem is , how will I know if the whole throttling process is completed so that I can send an email to the user checking to see if indeed they really are the one logging in or someone else with their username/email. Summary Anonymous user tries logging in with some email/username Gets blocked for 5mins after 3 Annoymous Request An email gets sent to the respective user warning that user. -
How to make post request with CSRF token from flutter to django. Post Request from Flutter App to Django backend gives CSRF error. How to fix this
I have a flutter app for the frontend and Django for the backend. I wanna make a post request from the flutter app to the Django server. I checked the documentation and found CSRF exempt which is not something I want to do can someone tell me how I can make a post request from a Flutter app? -
How to split a string inside of django template
I am passing a strings consists of characters separated with comma like A, B, C, .. to django template, using javascript. This is my code: <div> {% for tag in wizard.form.tags %} <a href="" ><span class="btn btn-outline-primary btn-xs mb-3"> <span class="h6 text-uppercase"> <div class="badge badge-rounded-circle badge-danger-soft mt-1 mr-0"> <i class="fe fe-check"></i> </div> {{ tag }} </span></span></a> {% endfor %} </div> where {{wizard.form.tags}} returns a long string, however I need to separate it inside of the template to style it. Is there solution for that? P.S. Just note that I can't probably add method to the model as the value inside the {{wizard.form.tags}} are passed by js and not reading from database. -
add built-in filter method in template returns empty string
I am having trouble in Djagno template built-in method of add. When I do <img class="card_image" src="{% static '/image/products/'|add:product.image %}" alt="design"> it returns empty string. and after doing a research, it seems like add method can be only used if a variable is surrounded with strings. ex. does not work {% static '/image/products/'|add:product.image %} does work ? {% static '/image/products/'|add:product.image|add:"closing_string" %} I dont understand why it works this way. and my work around is {% static '' %}image/products/{{product.image}} it works, but personally I just want to know why i cannot concatenate variable at the end using add. let me know if someone can help me understand better. Thank you in advance -
Sums in django gives wrong results
My models: class Leider(models.Model): naam = models.CharField(max_length=100, unique=True) volgorde = models.IntegerField(default=0, blank=True) def __str__(self): return self.naam class Meta: ordering = ['volgorde'] class PrijsKlasse(models.Model): naam = models.CharField(max_length=50, unique=True) normaal = models.DecimalField(max_digits=6, decimal_places=2) zwaar = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.naam + " - €" + str(self.normaal) + " - €" + str(self.zwaar) class Telling(models.Model): leider = models.ForeignKey(Leider, on_delete=models.CASCADE) aantalNormaal = models.IntegerField(default=0, null=True) aantalZwaar = models.IntegerField(default=0, null=True) prijsKlasse = models.ForeignKey(PrijsKlasse, on_delete=models.PROTECT) datum = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return str(self.leider) + ' normaal:' + str(self.aantalNormaal) + ' zwaar:' + str(self.aantalZwaar) class Betaling(models.Model): leider = models.ForeignKey(Leider, on_delete=models.CASCADE) hoeveelheid = models.DecimalField(max_digits=8, decimal_places=2) datum = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self) -> str: return str(self.leider) + " - " + str(self.hoeveelheid) my view code: teBetalen = Leider.objects.values('naam').order_by('volgorde').\ annotate(prijsNormaal=Coalesce(Sum(F('telling__aantalNormaal') * F('telling__prijsKlasse__normaal'), output_field=FloatField()), Value(0))).\ annotate(prijsZwaar=Coalesce(Sum(F('telling__aantalZwaar') * F('telling__prijsKlasse__zwaar'), output_field=FloatField()), Value(0))).\ annotate(totaal=Coalesce(F('prijsNormaal') + F('prijsZwaar'), Value(0))).\ annotate(betaald=Coalesce(Sum('betaling__hoeveelheid'), Value(0))) I am pretty new to django so i may be doing something stupid or to complicated I have tried using distinct in the sums but this didn't solve it. I have rewritten the query used the raw sql and i think it has something to do with the LEFT OUTER JOIN and it multiplying the sum. Just can't figure out how to fix it. I … -
How to use django inlines with a composite key?
and thank you for your help. I'm using inlines in django to display a model in another admin model, it seems like it demmands a primary key, i get this error: OperationalError at /admin/accounts/estadosm/18/change/ (1054, "Unknown column 'flora2estado.id' in 'field list'") But!, the model actually have a composite key, like so: class Flora2Estado(models.Model): estado = models.ForeignKey(EstadosM, models.DO_NOTHING) especie = models.ForeignKey('Listaflor', models.DO_NOTHING) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie'),) How can i fix this, to tell django admin fields to use the composite key?! django.admin: class flora2EstadosInline(admin.TabularInline): model = Flora2Estado fields = ['estado','especie'] extra = 1 def get_extra (self, request, obj=None, **kwargs): """Dynamically sets the number of extra forms. 0 if the related object already exists or the extra configuration otherwise.""" if obj: # Don't add any extra forms if the related object already exists. return 0 return self.extra class EstadosAdmin(admin.ModelAdmin): inlines = [flora2EstadosInline] -
How can I force django.allauth to require an email
In my django project I am using django.allauth to manage my users. I want the user to provide both a user name and an email address. If I use the allauth SignupView it the email field must be filled, however if I override it with my own view, it does not make it mandatory. What am I missing? settings.py # User model AUTH_USER_MODEL = 'accounts.CustomUser' # django-allauth settings AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) LOGIN_REDIRECT_URL = '/home' LOGOUT_REDIRECT_URL = '/home' SITE_ID = 1 ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = True models.py import json import datetime from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): logged_in = models.BooleanField(default=False) last_active_time = models.DateTimeField(null=True) login_datetime = models.DateTimeField(null=True, blank=True) email_confirmed = models.BooleanField(default=False) date_of_birth = models.DateField(null=True) forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('username', 'email') urls.py from .views import MySignupView urlpatterns = [ path('signup/', MySignupView.as_view(), name='signup'), ] views.py from .forms import CustomUserCreationForm SIGNUP_SUCCESS = 'You have successfully signed up!' class MySignupView(SignupView): form_class = CustomUserCreationForm success_url = reverse_lazy('home') template_name = 'account/signup.html' def form_valid(self, form): messages.success(self.request, SIGNUP_SUCCESS) return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["button_text"] = 'Sign Up' return … -
How to real-time update React app with data from Django REST API
I have a project that uses React for frontend and Django REST Framework for backend.Simply, when a new comment post for an article, I want to notify other users that are currently reading comments for that specific article. How can I do that? -
How to handle empty values if there is no file in request.FILES[''] in django without using django forms
I want user can fill all information and there is no required field when i try to submit my form without uploading image it gives me error MultiValueDictKeyError at /update-home-content/1/ 'bg_image' this is my models.py from django.db import models # Create your models here. class ImageUpload(models.Model): get_image = models.FileField(upload_to='gallery/new/',null=True) and this is my views.py from upload.models import ImageUpload # Create your views here. def add_image(request): if request.method == "POST": image = request.FILES['bg_image'] -
Gmail sending with currently generated pdf in Django
I am trying to send a pdf as a Gmail attachment in Django, which is just generated by the same view. For generating the pdf, I use to try this tutorial link. my views.py: def submit_report(request, pk): template = get_template('app/pdf_rprt.html') Industry_obj = Industry.objects.get(id=pk) Industry_Report_obj = Industry_obj.industry_report_set.all() report_tableA_obj = report_tableA.objects.filter(industry_report__industry=Industry_obj) context = { 'industry' : Industry_obj, 'Industry_Report' : Industry_Report_obj, 'report_tableA' : report_tableA_obj, } html = template.render(context) pdf = render_to_pdf('app/pdf_rprt.html', context) if pdf: to = "kanchon2199@gmail.com" email = EmailMultiAlternatives( #subject = "final report sending (beta)", #content = 'hello, this is test report sending mail', #from email settings.EMAIL_HOST_USER, #list of recipent [to] ) email.attach_file(pdf) email.send() return redirect('app:index') here the render_to_pdf comes from a custom build function in utils.py: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None But it says error like (for the line email.attach_file(pdf)): TypeError at /submit_report/1/ expected str, bytes or os.PathLike object, not HttpResponse How can I fix it? -
How to find Min(Sum(annotated column)) in Django
I have four tables A, B, C and D. each table is associated in a way A -> B -> C -> D by id column. eg. A.id = B.a_id, B.id = C.b_id and C.id = D.c_id I am trying to achieve something like this SELECT x.id, min(x.total) as mintotal FROM (SELECT “A”.”id", SUM((“D”.”amount” * “D”.”quantity")) AS "total", “C”.”id" AS "qid" FROM “A” LEFT OUTER JOIN “B” ON (“A”.”id" = “B”.”a_id") LEFT OUTER JOIN “C” ON (“B”.”id" = “C”.”c_id") LEFT OUTER JOIN “D” ON (“C”.”id" = “D”.”c_id") GROUP BY “A”.”id", “C”.”id") as x group by x.id ORDER BY mintotal ASC My equivalent django code query1 = A.objects.all().annotate(qid = models.F(‘b__c__id'),total=Sum(models.ExpressionWrapper( models.F(‘b__c__d__amount') *models.F('b__c__d__quantity'), output_field=models.DecimalField()))).order_by('total') it gives me the inner query output, however when I try to select id and Min(total) again it throws error - FieldError: Cannot compute Min('total'): 'total' is an aggregate I am new to Django and I am not sure how I can use subquery or exists to get this result. Any help will be appreciated -
My HTML form is not showing block content in Django
I have a base template where I have a Navbar. In my contact_form HTML file I am extending base template. And in block content, I am giving an HTML form, that supposed to be shown in the browser. But In the browser, it shows only the navbar. The form is not showing. Here is my base template: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Home</title> </head> <body> <!--NAVEBAR --> <nav class="navbar navbar-expand-lg navbar-light bg-dark sticky-top" > <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo03" aria-controls="navbarTogglerDemo03" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand text-white" href="#">Imtinan</a> <div class="collapse navbar-collapse" id="navbarTogglerDemo03"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link text-white" href="home.html">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link text-white" href="{% url 'blog' %}">Blog</a> </li> <li class="nav-item"> <a class="nav-link text-white" href="{% url 'contact' %}">Contact</a> </li> <li class="nav-item"> <a class="nav-link text-white" href="about.html">About</a> </li> <li class="nav-item"> <a class="nav-link text-white" href="project.html">Project</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <!--NAVEBAR END --> {% block content %} {% endblock %} <!-- Optional JavaScript; choose one of … -
Not appear bootstrap validation message in django
In Django I add a bootstrap template with form fields I replace paths by static validation of fields but if I submit form with blan fields there is not any validation messages. In the terminal I see that it is loading all files. Outside of Django template it works. I used template https://getbootstrap.com/docs/4.5/examples/checkout/?fbclid=IwAR3u58tn3MZS8b2a8sRKZYt12Jk_qnC1PW3FSMl1OkHHZC2HyV8dAV2s9zQ [my in DJanko looks:][1] [1]: https://pastebin.com/D5ZDXW2D -
AWS CONFIG FILES FOR ELASICBEANSTALK DON'T WORK
I have an old django project setup with elastic beanstalk using a .ebextensions folder. This old project contains many files, some of which update Apache by putting configuration files into the following location: /etc/httpd/conf.d/ For example, it would add an enable_mod_deflate.conf by having the following command in one of the .ebextensions configuration files: container_commands: 01_setup_apache: # Setup gzip compression on apache server by copying enable_deflate.conf into appropriate directory. command: "cp .ebextensions/enable_mod_deflate.conf /etc/httpd/conf.d/enable_mod_deflate.conf" Similarly there is a file for cache configuration that looks something like this: files: "/etc/httpd/conf.d/enable_cache.conf": mode: "000444" owner: root group: root content: | <IfModule mod_expires.c> ExpiresActive on ExpiresDefault "access plus 1 day" ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType text/css "access plus 1 month" ExpiresByType text/javascript "access plus 1 month” ExpiresByType application/javascript "access plus 1 month” ExpiresByType image/ico "access plus 1 month" ExpiresByType text/html "access plus 600 seconds" </IfModule> The problem that I have is that I have just tried to create another Django project. When I ssh into the old ec2 instance (I am using a single instance elastic beanstalk environment), I can see all of the files in … -
'HttpResponse' object has no attribute '_committed'
I am working with a Django project, where I am trying to render a pdf and save it in my database. my models.py: class Final_report(models.Model): industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) inspector = models.ForeignKey(Inspector, null=True, blank=True, on_delete=models.CASCADE) created_date = models.DateTimeField(default=datetime.now, blank=True) pdf = models.FileField(upload_to='documents') my views.py: def submit_report(request, pk): template = get_template('app/pdf_rprt.html') Industry_obj = Industry.objects.get(id=pk) Industry_Report_obj = Industry_obj.industry_report_set.all() report_tableA_obj = report_tableA.objects.filter(industry_report__industry=Industry_obj) context = { 'industry' : Industry_obj, 'Industry_Report' : Industry_Report_obj, 'report_tableA' : report_tableA_obj, } html = template.render(context) pdf = render_to_pdf('app/pdf_rprt.html', context) if pdf: this_industry = Industry_obj this_inspector = request.user.inspector_releted_user this_pdf = pdf this_created_date = timezone.now() Final_report_obj = Final_report.objects.create(industry=this_industry, inspector=this_inspector, pdf=this_pdf, created_date=this_created_date) Final_report_obj.save() return redirect('app:index') here the render_to_pdf comes from a custom build function in utils.py: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None Now it says the following error: Internal Server Error: /submit_report/1/ Traceback (most recent call last): File "G:\Python\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\Python\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Project\django\hackathon practice\ProjectSurokkhaBeta_1.7\app\views.py", line 526, in submit_report Final_report_obj = Final_report.objects.create(industry=this_industry, inspector=this_inspector, pdf=this_pdf, created_date=this_created_date) File "G:\Python\lib\site-packages\django\db\models\manager.py", line … -
django not receiving signals from celery
I have a model called class Vcf(models.Model): ... And I have a post_save signal receiver for this model @receiver(post_save, sender=Vcf) def vcf_post_save(sender, instance, created, **kwargs): group = Group.objects.get(name='name') if created: assign_perm('view_vcf', instance.user, instance) assign_perm('view_vcf', group, instance) I have a view function where users can fill out a form and this will start a celery task. Which calls a function get_results which in turn calls another function create_vcf_model @shared_task def do_stuff(user_id, run_id, config): ...other stuff... get_results(run_id) get results(run_id): ...other stuff... create_vcf_model(run_id, vcf_path) create_vcf_model(run_id, vcf_path): vcf, created = Vcf.objects.get_or_create() Problem is here. I am guessing because create function is called from a celery task django is not receiving the signal? -
AttributeError at /accounts/login/ 'str' object has no attribute 'field'
i'm having this error after trying to use the auth system with using crispy form login html page {% extends 'base.html'%} {% block content %} {% load crispy_forms_tags %} <form method="POST"> {% csrf_token %} {{ form.as_p|crispy }} <button type="submit">Log In</button> </form> </div> {% endblock %} -
Django serve various file types using IIS / Virtual Directory
I am trying to serve various file types using Django on a IIS windows server. And for the life of me, I can't seem to figure it out. I am working with a legacy DB that stores file paths in a column. The files are held on a network share so have created a Virtual Folder (tired pass-though and connect as) I get the URLS created in HTML using the file path from the DB / model <td><a href ="/{{doc.location}}" download>{{doc.location}}</a></td> which results in http://panel/docs/07/xxxxxx.doc File downloads but get a Fail - No file in Chrome. The files are mix of doc / pdf/ txt and a few other file types. Any help would be greatly appreciated, racking my brain with this. -
Django: How to link a client-side component with a server-side information
I know the title is maybe confusing, but let me clarify my problem. I have an Animal model with simply a name field in it. In my HTML template, I list each instance of Animal in an a element (display order may vary). view.py: def index(request): animals = Animal.objects.all() return render(request, 'index.html', {'animals': animals}) index.html: {% for animal in animals %} <a>animal.name</a> {% endfor %} Output is something like this: Cow Duck Horse Cat Bee My question is, when the user clicks on an animal, I have to perform certain actions in the database. But how can I know which animal did he click ? I don't want to get the client-side text with javascript, because this is not secure and the user can change it by inspecting the element. I simplified my problem with animals, but in reality it is more complicated than this and I really need to find a secure way to get the correct clicked animal, even if the user changed the text or the HTML class or ID or something like this. -
Handling long file uploads with Django on GKE
I need to be able to upload large files on a Django app hosted on GKE which can take a long time if the connection is slow. I'm relying on gunicorn to serve the application. The problem I have is: once I start the file upload, the gunicorn worker is stuck processing the upload request and cannot process anything else. As a result, kubernetes cannot access the liveness probe and restart the container, which kills the upload. It also means my site is very unresponsive. I could add more gunicorn worker but it's not a proper solution since users can upload many files in parallel. It would just increase the threshold of what I can manage. Scaling up would solve the responsiveness but not the fact the user needs time to upload the file. Since this issue is usually (by usually I mean when not running on kubernetes) solved by putting a nginx sever in front of gunicorn, I was wandering how I could to this with kubernetes. I think I have two solutions: Add an nginx sidecar in the pod. This looks simple enough and would avoids installing something cluster wide. I can also let the GKE ingress handle … -
Django backend in Rest-framework resource for eCommerce
I want to create an eCommerce store's entire backend in django (using Restful framework APIs), I am looking for resource available online especially on github. Ofcourse I have done extensive research but I am unable to find anything that is recently updated and yet simple enough for me to understand, as I am not expert in django yet. All I want is a resource from where I can see overall flow and model it by using their models, views, serializers and permissions as a reference