Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Complex Python module sorting dependency issue
I have a set of "modules" with dependencies. module B depends A module C depends on A and B module D depends on C I can represent each module as an object, and their dependencies as a property: class Module(): def __init__(self, name): self.dependencies = [] self.name = name def __repr__(self): return self.name A = Module("A") A.dependencies = [] B = Module("B") B.dependencies = [A] C = Module("C") C.dependencies = [A, B] D = Module("D") D.dependencies = [C] modules = [C, D, B, A] Suppose I have a list of modules in arbitrary order e.g. [C, D, B, A] Need to write function to take this input list and return a list of all of these modules in dependency order: e.g. [A, B, C, D] starting with A because it has no dependencies, then B because it only depends on A, then C, D for the same reasons. I am stuck in this please help with code, pseudo code """ class Module(): def __init__(self, name): self.dependencies = [] self.name = name def __repr__(self): return self.name # normal modules A = Module("A") B = Module("B") C = Module("C") D = Module("D") E = Module("E") F = Module("F") A.dependencies = [] B.dependencies … -
Django Redis-Queue pass result from background job into html
My small Django project only has one view. The user can enter some options and press submit, hence commiting the job that takes >3 minutes. I use redis-queue to carry out the jobs via a background process - the web process simply returns (and renders the .html). All this works. Question is, how can I pass the background's result (filename of file do be downloaded) after completion back into the html so I can display a download button? I guess I would have to put a small Java / jQuery script into the .html that keeps polling if the job has completed or not (perhaps making use of RQ's on_success / on_failure functions?), however, I'm unsure about the approach. Searching the matter has brought no success (see simular issue). Could anyone tell me if this is the way to go or if I have to fundamentally change my code? I do not intend to use Celery. Ideal solution would be the one providing some code. Here's a stripped example: view.py from django.shortcuts import render from django.contrib import messages from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .forms import ScriptParamForm from .queue_job import my_job @csrf_exempt def home(request): context = {} … -
Using the TempFile Python Module to print multiple .pdf's at once
I am currently trying to print financial documents for companies based on the settings they have added to my app. These documents are checked by a Bool value (checkbox) to see if the user has this document selected. If it is selected , the document must print. However the program cannot currently print multiple documents at once for some reason. I don't know if it is because it cannot re-direct to multiple .HTML files at once? Please see the following code: import tempfile def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) complexName = pkForm.Complex if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"x_AlltrbYTD":x_AlltrbYTD , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal , 'complexName':complexName , 'openingBalances': openingBalances ,'printZero':printZero , 'printDesc':printDesc , 'printAcc':printAcc} html_string=render_to_string('main/reports/trialBalanceYear.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) return response if pkForm.Trial_balance_Monthly == True: ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalanceMonthly' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' content = {"xtrbMonth":xtrbMonth , 'xCreditTotalM':xCreditTotalM , 'xDebitTotalM':xDebitTotalM , 'complexName':complexName , 'printZeroM':printZeroM} html_string=render_to_string('main/reports/trialBalanceMonthly.html' , content) html=HTML(string=html_string) result=html.write_pdf() with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output.seek(0) response.write(output.read()) else: … -
need some explanation about pillow in django
i have a caroussel and i want all my images to have the same height for that is used this to compress the image. def compressImage(uploaded_image): image_temp = Image.open(uploaded_image) outputIoStream = BytesIO() image_temp.thumbnail((500,500)) image_temp.save(outputIoStream , format='JPEG', quality=99) outputIoStream.seek(0) uploaded_image = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % uploaded_image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None) return uploaded_image class RecognizePost(models.Model): name = models.ForeignKey(Post,on_delete=models.CASCADE) image = models.ImageField(upload_to='files', null=True, blank=True) def __str__(self): return self.pk def save(self, *args, **kwargs): if not self.pk: self.image = compressImage(self.image) super(RecognizePost, self).save(*args, **kwargs) my question why if have two images then the compress works like this: original image1 (735x739) after compress (498x500) original image2 (880x612) after compress (500x347) why i am not getting all 2 images with this (500x500).I really need the height to be 500.why the second image has 347.am i missing something ? -
dj restauth reset password customizing template not working
I am using dj rest auth package to register and login and for resseting password i have customized the template settings to use my own email html template: class CustomPasswordResetSerializer(PasswordResetSerializer): def save(self): request = self.context.get('request') # Set some values to trigger the send_email method. opts = { 'use_https': request.is_secure(), #'from_email': 'noreply@mizbans.com', 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': request, # here I have set my desired template to be used # don't forget to add your templates directory in settings to be found 'email_template_name': 'password_reset_email.html', 'html_email_template_name': 'password_reset_email.html' } opts.update(self.get_email_options()) self.reset_form.save(**opts) and in a file named email.py : class MyPasswordResetSerializer(PasswordResetSerializer): context={'domain':settings.WEBSITE_DOMAIN,'site_name':'mizban'} def get_email_options(self) : return { 'email_template_name': 'password_reset_email.html', 'context':'context' } the problem is this code works on my local pc and sends emails with customized html template but when i deploy it ,it still uses the default package's html template what am i missing? -
DataTable slow rendering large amount of data
I'm using serverSide process, and I have more than 10,000 but the rendering time is to long almost a minute. also tried using deferRender and deferLoading but still too slow. Apps uploaded in heroku and using paid add-ons. Anyone can suggest how to speed up rendering time and also if able to load by page.Like:(100/1000 data load every secs)? heroku logs: dyno=web.1 connect=0ms service=2557ms status=200 bytes=9409840 protocol=https $(document).ready(function() { var table = $('#vtable').DataTable({ "serverSide": true, "scrollX": true, "scrollY": "500px", "deferRender": true, "autoWidth":true, "columns": [] .......................... <table id="vtable" class="table table-striped table-bordered" style="width:100%" data-server-side="false" data-ajax="/api/Url/?format=datatables"> -
How to pass context to a different view function?(Django)
My models.py: class fields(models.Model): name = models.CharField(max_length=18) link = models.TextField() The link contains the hyperlink of the related name. My views.py: def index(request): listing = fields.objects.all() context ={'listing':'listing'} return render(request,'index.html',context) Now, I want to pass the context of this function which only includes the link to the other view function so that another view function will be: def bypass_link(request): # get the link from above function # execute some selenium scripts in the link The simple template to illustrate this will be: {% for i in listing %} <tr> <td data-label="name">{{ i.name }}</td> <td data-label="Quote"><button><a href ="{ % url 'bypass_link' %} " target="_blank">{{ i.link }}</a></button></td> <tr> {% endfor %} -
how to override django auth password reset email method?
I am using Django's authentication password_reset system in order to reset a forgotten password. Instead of django emailing the reset password link, I would like to perform another custom action with this email message (or link), for example send the message to a random API. How do I do it? -
uwsgi_master_fifo()/mkfifo(): Permission denied
Well I am trying to get django aplication on a prodaction server using uwsgi and docker. On production server nginx is started but it does not configured for uwsgi. I install uwsgi using pip without virtual environment into docker. However when I try up service with django app I get uwsgi_master_fifo()/mkfifo(): Permission denied [core/fifo.c line 112]. My uwsgi.ini: [uwsgi] socket = :8000 chmod-socket = 777 chdir = /api/ module = MenStore.wsgi:application static-map = /staticfiles=static master = true processes = 4 offload-threads = 4 vacuum = true harakiri = 30 max-requests = 10000 stats = :9191 memory-report = true enable-threads = true logger = internalservererror file:/tmp/uwsgi-errors.log post-buffering = 1 buffer-size = 16383 uid = 1000 gid = 1000 touch-reload = uwsgi-reload master-fifo = uwsgi-fifo My django app service into docker-compose file: api: &api build: context: Backend dockerfile: Dockerfile ports: - "8000:8000" volumes: - "/root/MenStore/media/:/api/media/:rw" command: uwsgi --ini /api/uwsgi.ini depends_on: postgres: condition: service_healthy redis: condition: service_started -
How to deploy Django project with React inside as an app to Heroku
Can someone help me to deploy my Django app, first I startproject with django and then startapp for front-end and api, npm react is installed inside front-end, I follow this project from https://www.youtube.com/watch?v=JD-age0BPVo&list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j , and I follow the deployment steps from https://dev.to/mdrhmn/deploying-react-django-app-using-heroku-2gfa, here is my github for the project https://github.com/khuongduy354/django-rest-react, beside the working project in development mode, i made changes mostly in settings.py file and package.json for the deployment When i first ran git push heroku master, it said package.json must be in root, so I moved it from frontend to root, then it said cant find matching node version, i ran node --version and made sure it's the same as the one in package.json file Most of the tutorial separate backend and frontend files, so i don't really know how to deploy my app in my situation, can someone help me, thank you very much. -
how to pass argouments from django to built js files (webpack)
I am approaching nodejs and django for the creation of a project that involves the rendering of 3D objects. I installed threejs via node in my django project using webpack as a boundler. Now my need is to receive data from the back end which, passed to a given function, will create a dynamic threejs scene. The problem I encountered is "how do I pass arguments to the functions contained in the built js files?". I hope that the use of scripting in html files and template tags are not the only way. Thanks for any help -
virtual environment activation error in python [closed]
when I was trying to activate virtual environment, I faced this error. how can I fix this? I search on the link that error returned, but I didn't find out how to fix it! enter image description here -
How to capture picture or generate thumbnail from video in python django restframework?
Actually, I am trying to capture to make a thumbnail from an uploaded video in python Django. And then I have to save this thumbnail in a separate model field for later use. class Post(models.Model): user= models.ForeignKey(Profile, on_delete=models.CASCADE) video = models.FileField(upload_to='post_videos/%Y/%m', null=True) thumbnail = models.ImageField(upload_to='post_images/%Y/%m', null=True) I just want to upload a video, capture a thumbnail at any timestamp and then save it to the thumbnail field. Please, Let me know if anyone can help me out. I tried using FFmpeg and moviepy but unable to resolve the issue. waiting for help. Thanks -
Why we need to have the full Django project folder in the celery worker container?
I am new to Celery and Django. When I tried to build Django, Celery in different containers, the Examples always have the whole Django project folder in both Celery and Django Containers as a share volume. And these two containers share the same Dockerfile. Consider we only need the task module in the Celery worker. And I don't really want to install the same amount of "requirements" in the celery image. Is there a way we can build the celery image without putting the whole django project folder in the celery container? Thanks. -
Is there a way to tag and display the reception number and MCO number in 1 cell
I have created a website where user will enter the reception number(Verify if the reception number is same as the database, if different, they cannot be redirected to the success page) and MCO number as shown below: When it is redirected to my table page which is my success page, it created a new column show below, the 234 reception number should be tag to 13873827 the mco number and not a new column, how do I do that?: When I enter the 234 and a different MCO number it will show an error message: UNIQUE constraint failed: account_photo.reception when i enter 234 and 13873827, it will show this error message: UNIQUE constraint failed: account_photo.mcoNum, so I assume that it is tag? views.py @login_required() def verifydetails(request): if request.method == 'POST': form = verifyForm(request.POST) if form.is_valid(): Datetime = datetime.now() mcoNum = form.cleaned_data['mcoNum'] if Photo.objects.filter(reception=form.cleaned_data['reception']): form = Photo(Datetime=Datetime, mcoNum=mcoNum) form.save() return redirect('gallery') else: messages.success(request, 'The reception number you have enter is incorrect') return redirect('verifydetails') else: form = verifyForm() return render(request, 'verifydetails.html', {'form': form, }) forms.py class verifyForm(forms.Form): reception = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter Reception number'})) mcoNum = forms.CharField(label='', widget=forms.TextInput(attrs={"class": 'form-control', 'Placeholder': 'Enter MCO NUMBER'})) class Meta: model = Photo fields … -
Can't solve django templatedoesnotexist error
I know this question has been asked many times before yet I either can't find an answer that isn't outdated or that generally works. I keep getting this error even though my server is running correctly Environment: Request Method: GET Request URL: http://localhost:8000/subscribe/ Django Version: 3.1.4 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'subscribe'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.8/dist-packages/django/contrib/admin/templates/subscribe/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /usr/local/lib/python3.8/dist-packages/django/contrib/auth/templates/subscribe/index.html (Source does not exist) * django.template.loaders.app_directories.Loader: /root/project/subscribe/templates/subscribe/index.html (Source does not exist) Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/root/project/subscribe/views.py", line 16, in subscribe return render(request, 'subscribe/index.html', {'form':sub}) File "/usr/local/lib/python3.8/dist-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/usr/local/lib/python3.8/dist-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/usr/local/lib/python3.8/dist-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /subscribe/ Exception Value: subscribe/index.html these are my template settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
Django (uwsgi) + nginx throws 504 Gateway timeout after 120 seconds
Is there is any default setting that would return this timeout after 2 minutes when waiting response from a Django view (even if view contains just a simple time.sleep(200)) no matter my nginx configuration. I set all timeouts that I could think of to 300s. Excerpt from nginx config: http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; proxy_send_timeout 300s; proxy_read_timeout 300s; proxy_connect_timeout 75s; ## # Virtual Host Configs ## upstream uwsgi_upstream { server localhost:8000; } server { listen 80; server_name {{ 'SERVER_NAME' | env }}; location / { include uwsgi_params; uwsgi_pass uwsgi_upstream; uwsgi_read_timeout 300s; uwsgi_send_timeout 300s; # Match the upstream header buffer size to http setting uwsgi_buffer_size 64k; uwsgi_buffers 8 64k; uwsgi_param HTTP_Host $http_host; uwsgi_param HTTP_X_Real_IP $remote_addr; uwsgi_param HTTP_X_Forwarded_For $proxy_add_x_forwarded_for; uwsgi_param HTTP_X_Forwarded_Proto $scheme; client_max_body_size 200M; } } } -
Minimize Number of Queries in Django Model Admin
Suppose I have two models ModelA, ModelB, class Model1(models.Model): # multple model fields, also contains foreign key class Model2(models.Model): model1_id = models.ForeignKey(Model1, models.DO_NOTHING) # other model fields field1 = models.IntegerField() field2 = models.ForeignKey() field3 = models.CharField(max_length=50) field4 = models.DateTimeField(blank=True, null=True) admin file for Model1 like, @admin.register(Model1) class Model1Admin(admin.ModelAdmin): list_per_page = 10 list_display = ['some_model1_fields', 'get_field1','get_field2', 'get_field3', 'get_field4'] def get_field1(self, obj): return obj.model2_set.last().field1 def get_field2(self, obj): return obj.model2_set.last().field2 def get_field3(self, obj): return obj.model2_set.last().field3 def get_field4(self, obj): return obj.model2_set.last().field4 when I get related model fields using method in list_display, it repeats same query multiple time (list_per_page * no_of_fields_by_method which is 40 in current case). I don't want to join model1 with model2 because model1 already join with other models and we know Count() query will takes time if we have large tables. My question is , Is any other way to get releted model objects without repeat the same query? (means only 10 times query instead of 40 times same query in current case.) -
How to get list of tags related to any Blogpost in model - Django
So I have two models: class Tag(models.Model): name = models.CharField(max_length=15) def __str__(self): return str(self.name) and class BlogPost(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True, blank=True, null=True) author = models.CharField(max_length=255) tags = models.ManyToManyField(Tag) body = models.TextField(blank=True, null=True) snippet = models.TextField(max_length=255) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created_on',) def __str__(self): return str(self.title) I am trying to get a list of tags that have been used in any BlogPost model object i.e. if there are tags stored in database are ['movie','entertainment','games','documentary'] and BlogPost A has tags with m2m relation: ['movie','documentary'] and BlogPost B has tags with m2m relation:['games'] then I want to get a list of tags that has been used in any object BlogPost model as ['movie','documentary','games']. I couldn't find the answer to this.Is there a way to query for this? -
How to loop multiple urls in javascript
The chkArray list contains numbers. If the condition is satisfied, I want the function to work by adding the values of the list to the url parameter one by one through the for statement. This is because the function defined in views.py is returned only when the url below is returned. However, window.location.href seems to only work once. Is there any way to make the url work multiple times? Please help. [student_list.html] <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Register date</th> <th>Select</th> </tr> </thead> <tbody> {% for student in student %} <tr> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td><input type="checkbox" class="Checked" id="{{ student.id }}"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Update Teacher</button> [student_list.js] $('button.addteacher').on('click',function () { $checkbox = $('.Checked'); var chkArray = []; var updateTeacher = confirm("Will you update?"); chkArray = $.map($checkbox, function(el){ if(el.checked) { return el.id }; }); console.log(chkArray); for (let x = 0; x < chkArray.length; x++) { if (updateTeacher && chkArray.length > 0) { window.location.href = '/student/add_teacher/' + chkArray[x] + '/'; } else { alert('At least one checkbox must be checked.'); } } }); [urls.py] path('student/add_teacher/<int:id>/', views.add_teacher, name='add_teacher'), [views.py] def add_teacher(request, id): student= Student.objects.get(pk=id) student.teachcer = request.user.name student.save() return HttpResponseRedirect(f'/student_list/') -
Effect of periodic page refresh on server in a django web application
i'm refreshing a web page at interval of every 10 sec using meta refresh tag in a django application.I want to know that how much it effects the server. Is it best practice to refresh a web page. -
saving image URL using django shell
I want to save the url of images in my database using django shell here is my model class Album(models.Model): reference = models.IntegerField(null = True) created_at = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) title = models.CharField(max_length=200) picture = models.URLField() artists = models.ManyToManyField(Artist, related_name='albums', blank=True) here is what i did in the shell album = Album.objects.create(title="Funambule", picture="/home/MyUbuntu/Images/moi.png") the url is correctly save in the database but it's impossible to load it in the view here is the view <div class="col-sm-4 text-center"> <a href="/"> <img class="img-responsive" src="{{ album.picture }}" alt="{{ album.title }}"> </a> <h3><a href="/">{{ album.title }}</a></h3> {% for artist in album.artists.all %} <p>{{ artist.name }}</p> {% endfor %} </div> thank you -
Set initial (default) instances in django admin
I am building a Blog App and I am trying to add inbuilt initial instances in django admin so when user clone the repo , then user will see several initial blogs every time even after reset the database. I didn't find anywhere to set the initial data. I also tried How to set initial data for Django admin model add instance form? But it was not what i am trying to do. models.py class BlogPost(models.Model): title = models.CharField(max_length=1000) body = models.CharField(max_length=1000) I tried to use Providing data with fixtures But I have no idea , How can I store in. Any help would be much Appreciated. Thank You. -
GDAL configuration for Django in mac GDAL_LIBRARY_PATH exception
I tried to install GDAL in macos by the command for django brew install django and it successfully installed and I have also used pip install GDAL command and it also installed successfully. But, When I tried to run the django server it throw a error set a path for GDAL library. django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. -
Django app working locally but throws 'NotSupportedError at /accounts/login/' on Elastic Beanstalk
I don't understand why my django app works locally but throws a NotSupportedError error upon elastic beanstalk deploy using the awsebcli. I follow the normal password flow for logging in and redirecting to a certain app, however when I'm doing this via the deployment it throws the following error: NotSupportedError at /accounts/login/ deterministic=True requires SQLite 3.8.3 or higher Additional info Django Version: 3.2.7 Exception Type: NotSupportedError Exception Value: deterministic=True requires SQLite 3.8.3 or higher Exception Location: /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py, line 217, in get_new_connection Python Executable: /var/app/venv/staging-LQM1lest/bin/python Python Version: 3.8.5 Python Path: ['/var/app/current', '/var/app/venv/staging-LQM1lest/bin', '/var/app/venv/staging-LQM1lest/bin', '/usr/lib64/python38.zip', '/usr/lib64/python3.8', '/usr/lib64/python3.8/lib-dynload', '/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages', '/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages'] Server time: Thu, 30 Sep 2021 06:32:23 +0000 I've roughly followed this tutorial for deploying a Django app via eb, albeit with python 3.8 changes login/logout setup followed this tutorial this post has a similar issue with a different deployment method Thanks for reading! Any help is appreciated.