Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to display related many-to-many field in choice field?
I’m building a web app using Django for my music collection. For each album, there are multiple songs, and each song has one or more composers. Here’s the song model: class Song(models.Model): title = models.CharField(max_length=50) composer = models.ManyToManyField(Artist) class Meta: ordering = ['title'] def __str__ (self): return self.title The Artist model contains firstname and lastname fields. There are a number of occurrences of songs with the same title, and the only way to distinguish between them is by the composer. Currently, when songs are loaded into a choice field, only the title appears, using def__str. I’ve tried to include the composers, but haven’t found a way to make it work. Any suggestiions? -
python dictionary value is getting printed on a line but not getting printed on another line in django
I am new to django and using python version 3.8 In my index.html, I am trying to display the products and their info using for loop as below: {% for prod in products %} <footer class="card-footer"> <span id="atc_prod_{{ prod.product_id }}" class="atc_prod">prod_{{ prod.product_id }} <button class="button is-info is-small card-footer-item cart" id="prod_{{ prod.product_id }}">Add to Cart</button> </span> <a href="/shop/products/{{ prod.product_id }}"><button class="button is-small is-info card-footer-item cart" id="qv{{ prod.product_id }}">Quick View</button></a> </footer> {% endfor %} Structure of products list is as below: products = [ {'id':'1', 'name':'A'}, {'id':'2', 'name':'B'}, {'id':'3', 'name':'C'} ] Same prod.product_id is getting used in 3 places (span - id, button - id and a - href) but for few products (2 out of 5), id is blank. Refer screenshot below of HTML: I do not know the reason, please suggest. Also, please let me know if I missed any of the important info. Thanks in advance. -
I have problem Page not found (404) Django
import jobs.views urlpatterns = [ path('admin/', admin.site.urls), path('nick', jobs.views.nick, name='nick'), ] enter code here def nick(request): return render(request, 'jobs/nick.html') I got: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/nick/ -
Bootstrap 5 card footer not staying at the end of the page
I am still new to creating websites with Bootstrap and have come across an issue with adding a footer to my base.html template in Django. What I want is that the footer stays at the end of page and shows when I scroll to the end of that page. Here is my base.html code: {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vlereso Profesorin</title> <!-- Bootstrap --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <!-- Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <!-- Google Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap" rel="stylesheet"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'vleresoprofesorin/css/master2.css' %}"> <link rel="stylesheet" href="{% static 'css/master.css' %}"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light mynav"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav leftnav"> <li class="nav-item"> <a class="navbar-brand" href="{% url 'home' %}">Kreu</a> </li> <li class="nav-item dropdown"> <a class="navbar-brand dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Universitetet</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Universiteti i Tiranës</a></li> <li><a class="dropdown-item" href="#">Universiteti Politeknik i Tiranës</a></li> <li><a class="dropdown-item" href="#">Universiteti i Mjekësisë, Tiranë</a></li> <li><a class="dropdown-item" href="#">Universiteti i Sporteve të Tiranës</a></li> <li><a class="dropdown-item" href="#">Universiteti i Arteve Universitet</a></li> <li><a class="dropdown-item" href="#">Universiteti Bujqësor i Tiranës</a></li> … -
TypeError in heruko django
i wanna develop a Django project in Heroku but I have error. I Have Did everything that it Needs but still this Error Template error: In template /app/templates/base/Main_Layout.html, error at line 0 serve() missing 1 required positional argument: 'path' 1 : <!DOCTYPE html> 2 : <html lang="en"> 3 : {% load render_partial %} 4 : <head> 5 : {% include 'base/header_reffrences.html' %} 6 : <title> 7 : {% block title %} 8 : {% endblock %} 9 : </title> 10 : </head> Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/loader_tags.py", line … -
I am using filtering in django and it doesn't work
I am using filtering in Django and it is appearing on my website but doesn't do anything, and some of my fields I can't access to filter. def Books(request): Books = Book.objects.all() myFilter = BookFilter(request.GET, queryset=Books) Books = myFilter.qs context = {'pro':Book.objects.all(), 'myFilter':myFilter} return render(request, 'pages/Books.html', context) books.models class Book(models.Model): name = models.CharField(max_length=50) ISBN = models.IntegerField(max_length=20) image = models.ImageField(upload_to = 'photos/%y/%m/%d') stat = models.BooleanField(default=True) pubYear = models.IntegerField(max_length=4) author = models.CharField(max_length=50) categ = models.CharField(max_length=50) the fields (stat,pubYear) shows in the filter on the website but they are unwritable. -
Django -- Converting function views to class based views for TMDB API request
I'm using function views to generate render an output using the tmdb api I'm familiar with the basics on class based views. How would I write the following api request code into a TemplateView? Example output Views.py from django.shortcuts import render import requests # Create your views here. def index(request): # Query API with user input if 'movie' in request.GET: api_key = 'api' id = request.GET['movie'] url = 'https://api.themoviedb.org/3/search/movie?api_key={}&language=en-US&query={}&include_adult=false' response = requests.get(url.format(api_key,id)) # successful request if response.status_code == 200: # Parse json output for key value pairs tmdb = response.json() # backdrop image -- tmdb for each movie backdrop_path = tmdb['results'][0]['backdrop_path'] url_backdrop = 'https://image.tmdb.org/t/p/original'+backdrop_path # poster image -- tmdb for each movie poster_path = tmdb['results'][0]['poster_path'] url_poster = 'https://image.tmdb.org/t/p/original'+poster_path context = { 'title': tmdb['results'][0]['original_title'], 'overview': tmdb['results'][0]['overview'], 'release_date': tmdb['results'][0]['release_date'], 'vote_average': tmdb['results'][0]['vote_average'], 'vote_count': tmdb['results'][0]['vote_count'], 'backdrop_path' : tmdb['results'][0]['backdrop_path'], 'backdrop' : url_backdrop, 'poster' : url_poster } return render(request, 'home.html', {'context': context}) else: # returns homepage if invalid name is given in form return render(request, 'home.html') else: # Homepage without GET request return render(request, 'home.html') -
I want to use Django with Asp.net only database
I want to create a Django project where I can apply my machine learning and later want to sync it with Asp.net project which is already created, the only thing that I am interested in is the Database, and to be more specific only with a single table. Basically, I want to enter some data in my machine learning algo which on basis of that will return a specific value, and on basis of that value, I want to fetch certain records from the database. Can anyone guide me that is it possible? If yes then how. -
how do I run a function in django-admin?
I'm programming a project, and i need a way to run a function every time i access django admin. this function change some things in the DB, and if you know an easy way for it, i'll be happy. a thing like a function that run every time the database changes. thanks -
Celery/Django/Redis task getting executed multiple times
In my current project, what I need to do is to get data from 700+ endpoints and then send that data to another 700+ endpoints. My approach is to use Django Celery Redis, Put 70+ endpoints on each worker so that there are approx 10 workers which will retrieve the data and then post the data. For this, I am using Chord to do the parallel task and then calculate the time it takes. The problem is that Celery is running the same task multiple times. task_get_data is the main method that first gets the list of websites then splits it into groups of 70 each and then calls task_post_data using Chord. In the output below you can see website_A, website_B etc. multiple times, I have manually checked my data and everything and there is no repetition of websites but when the celery task is submitted, multiple entries are created. Also, Is there any way to monitor the number of workers and what are they processing? Below is the code os.environ.setdefault('DJANGO_SETTINGS_MODULE','django_backend.settings') app = Celery('django_backend', backend='redis://localhost:6379', broker='redis://localhost:6379') app.config_from_object('django.conf:settings', namespace='CELERY') # app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) def post_data(json_obj, website): for items in json_obj: md = md + items['data'] n … -
How to write a real self-contained Django app?
They say Django apps should be self-contained. I find it hard to implement. My website has 3 apps. All have their own static and templates folders. But — like many other sites — they share same front-end design. The problem is, I have a very small form at the footer of each page to sign up for my newsletter. First, I have to define the database model in one of apps, which means the other two rely on that one. Second, the view to update the database should be defined in an app — naturally, the same app that defines the model — which again means the other two have to call that view. So, app1 provides the model and view, app2 and app3 use them; so they are not self-contained. Isn't this against the philosophy? -
How to change Django Builtin dev Server inside a Docker container?
The Django builtin Development Server has the "feature" of filtering out HTTP Headers containing underscores: https://github.com/django/django/blob/7785e03ba89aafbd949191f126361fb9103cb980/django/core/servers/basehttp.py def get_environ(self): # Strip all headers with underscores in the name before constructing # the WSGI environ. This prevents header-spoofing based on ambiguity # between underscores and dashes both normalized to underscores in WSGI # env vars. Nginx and Apache 2.4+ both do this as well. for k in self.headers: if '_' in k: del self.headers[k] return super().get_environ() For development purposes, i'd like to comment out this for loop. I run Django inside a Docker container. How can I comment out these lines when building the image? -
How can I migrate changes from views.py in an app in Django?
I just started with Python/Django this week. I've been following the freeCodeCamp 4 hour course in youtube(https://www.youtube.com/watch?v=F5mRW0jo-U4&t=3885s). I didn't have any problem creating the virtual enviroment, the project and other apps that hold database models. However, at around the hour and 4 minutes mark of the video, the very same code the teacher is displaying in the video throws me an error. He creates a new app called "pages" and in the views.py script codes this function from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home_view(): return HttpResponse('<h1>Hello World</h1>') Then the pages app is included in the INSTALLED_APPS array, in the settings scripts INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', ] The problems comes when I try to migrate the changes from pages. The 'python manage.py makemigrations' followed by the 'python manage.py migrate' commands don't detect any change in the views.py script of any of the apps, so when I try to import those views in the urls.py file, it throws an error. I don't know how to make the changes in views noticeable for the manage.py, so it can migrate them. Ive been looking in the documentation and in StackOverflow, … -
For loop on form not functing properly
I have a feature that allows users to upload multiple images to their blog but it is not working correctly. When a user uploads multiple images only one of them is uploaded to the postgres db. view def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) form = CommentForm if request.method == 'POST': test = PostImagesForm(request.POST, request.FILES) files = request.FILES.getlist('images') if test.is_valid(): for f in files: instance = test.save(commit=False) instance.post = Post.objects.get(pk=pk) instance.save() else: print(instance.errors) postgallery = PostImages.objects.filter(post_id=post) #########ignore############ comments = Comment.objects.filter(post=post)#.order_by('-create') buildlogs = BuildLog.objects.filter(post_id=post) if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.author = request.user new_comment.post = post new_comment.save() context = { 'post':post, 'form':form, 'comments':comments, 'buildlogs':buildlogs, 'PostImagesForm':PostImagesForm, 'postgallery':postgallery } return render(request, 'blog/post_detail.html', context) form class PostImagesForm(ModelForm): class Meta: model = PostImages fields = ('images',) widgets = { 'images': forms.ClearableFileInput(attrs={'multiple': True}), } you can see i am getting the list of files via the files = request.FILES.getlist('images') then running a for loop on the contents. If I break the code in the stack trace I can see that the two files are in the list so i am very confused on why it is not properly iterating though the list and … -
large json data in django model slows down any query
I have a django model that looks like this: class SomeModel(Model): some_field = CharField(max_length=10) large_data = JsonField(blank=True, null=True) the "large_data" field can get really large, like 150mb. I know this is really bad practice, most of the data could decoupled into other sql database tables, but this is legacy application and the impact of the rework would be huge. It turns out that any query to this table is really slow, sometimes I just want to modify the "some_field" value, but even when I save that field individually like in the code below, the update query takes ages obj.some_field = "ice cream" obj.save(update_fields=["some_field"]) I am sure the large_data is the guilty because if I set its value to "None" then the save operation is committed right away. Are there optimization tricks that can be applied to my example without reworking the json field? Thanks in advance -
Django-rest framework "This field is required." with no empty fields
I'm tying to setup a basic API following the quickstart on https://www.django-rest-framework.org/tutorial/quickstart/ GET request are working but when I try to POST from the django-rest framework UI i get the following error. Data I want to post: { "name": "3", "description": "3", "price": 3, "speed": "3" } Answer I get from django-rest framework: (price field has default=0, anyhow it won't get the value posted) { "name": [ "This field is required." ], "description": [ "This field is required." ], "speed": [ "This field is required." ] } My serializer: class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ['name','description','price','speed'] My viewset: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } Models.py class Product(models.Model): name = models.CharField(max_length=100,null=False,unique=True) description = models.CharField(max_length=250,null=False) price = models.IntegerField(default=0) # price in cents speed = models.CharField(max_length=50,null=False) def __str__(self): return self.name def get_display_price(self): return (self.price / 100) class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' Urls.py router = routers.DefaultRouter() router.register(r'products', ProductViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('orders/', include('orders.urls')), path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Any help would be appreciated and please Let me know if I should add more code -
django and node js integrate
Hello I don't know if this is a silly question or not. I'm planning to build a chat and live streaming app, I'm a Django developer, but it would be nice to include Node in this. Django will assign and register clients, node js will take care of the data in real time, but I ended up thinking about creating a request from React to Django, then sending Django a request to Nod and then to React. This is very expensive and there is no data allocation here. All clients will have all directories, and React will filter each person's data individually Node js server let express = require('express'); let cors = require('cors'); let http = require('http'); let bodyParser = require('body-parser'); let path = require('path'); const port = 9000; app = express(); const server = http.createServer(app).listen(port, () => {}); const { Server } = require('socket.io'); const io = new Server(server, { cors: { origin: 'http://localhost:3000', methods: ['GET', 'POST'], allowedHeaders: ['my-custom-header'], credentials: true, }, }); app.use(cors()); app.use(express.static(path.join(__dirname, 'client'))); app.use(bodyParser.json()); app.post('/server', (req, res) => { io.emit('command', req.body); console.log(req.body); res.status(201).json({ status: 'reached' }); }); io.on('connection', (socket) => { socket.on('command', (data) => { io.emit('command', data); console.log(data); }); }); Django Request def handelRequest(serializer): notification = … -
django form 'str' object has no attribute 'id' when passing a list of choices
I am creating a form where the view passes a list to the form and this list is used to create choices. The choices seems to be created correctly, but I get an error 'str' object has no attribute 'id' I first learned how to pass the list using this: Django pass list to form to create Choices models.py class Grade(models.Model): """Each time a new score is added we create a grade object to track history of grades""" score = models.CharField( max_length=3, choices=PROFSCALE, blank=True, default=INCOMPLETE) assessment = models.ForeignKey( Assessment, on_delete=models.CASCADE, null=True, blank=True) objective = models.ForeignKey( Objective, on_delete=models.CASCADE, blank=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) cblock = models.ForeignKey(Classroom, on_delete=models.CASCADE, default=1) time_created = models.DateField( auto_now=False, auto_now_add=False, default=timezone.now) class Objective(models.Model): """The gradebook is graded agains learning objectives""" course = models.ForeignKey(Course, on_delete=models.CASCADE) objective_name = models.CharField(max_length=10) objective_description = models.CharField(max_length=30) def __str__(self): return self.objective_name forms.py class SingleGradeForm(forms.Form): """ form for adding in one single grade for a student. """ SCORE_CHOICES = ( ("IN", "I"), ("BE", "BEG"), ("DV", "DEV"), ("AP", "APP"), ("EX", "EXT"), ) score = forms.ChoiceField(choices=SCORE_CHOICES) objective = forms.ChoiceField(label='Learning Objectives', choices=[]) time_created = forms.DateField(widget=forms.TextInput( attrs={'type': 'date'}), label='Assessment Date') # from https://stackoverflow.com/questions/53177528/ def __init__(self, objs=None, *args, **kwargs): super(SingleGradeForm, self).__init__(*args, **kwargs) if objs: self.fields['objective'].choices = [ (o.id, o.objective_name) for o … -
How to get Django Admin Log Entries from last hour?
In standard Django, the django_admin_log table shows the date and time of changes to the database entries in the action_time column: sqlite> select * from django_admin_log; 1|2021-07-18 21:34:01.312033|6|[6] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 2|2021-07-18 21:47:02.451262|6|[6] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 3|2021-07-18 22:09:42.689067|6|[6] (1960-03-20) Pat Three|[]|8|1|2 4|2021-07-18 22:09:52.292117|6|[6] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 5|2021-07-19 12:21:57.715529|9|[9] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 6|2021-07-19 12:35:22.504624|9|[9] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 ... more entries I'd like to query the entries based on some comparison, I assumed a naive ansatz could work with filter (as is possible in SQLite itself), so I'd like the Python equivalent of the below SQL statement: sqlite> select * from django_admin_log where action_time > '2021-07-20'; 12|2021-07-20 16:34:00.114548|13|[13] (1960-01-20) Pat Changed|[{"changed": {"fields": ["Family name"]}}]|8|1|2 I thought it would be something along the lines of from django.contrib.admin.models import LogEntry last_hour_changes = LogEntry.objects.filter(last_hour > action_time) -
Remove/Strip extra space from the output of for...loop in Django template
In my template I need to print some items and add "," after each one, unless it is the last item. So here is my code: <li> <strong>Category</strong>: {% spaceless %} {% for t in project.technology.all %} {{ t.title }} {% if not forloop.last %},{% endif %} {% endfor %} {% endspaceless %} </li> While it works, it adds an extra whitespace between each item and ",", so what I see is like this: Tech1 , Tech2 , Tech3 while it should be Tech1, Tech2, Tech3 Even spaceless template tag is not working. Please assist. -
FILEFIELD Attibute has no file associated with it
This error keeps appearing when I try to update forms with image fields. I'm trying to upload or update a customer LOGO image. When I try to upload images, the field containing the image says "[field] attribute has no file associated with it" I'm using model forms and generic update views. I don't know how to make the attribute have the file associated with it. I tried a save() override in the model and it still gave me that error. models.py class Customers(models.Model): associations = models.ManyToManyField(Association) company_name = models.CharField(help_text='Company Name', max_length=200, default=None) contact1_first_name = models.CharField(help_text='Primary Contact First name', max_length=50, default=None) contact1_last_name = models.CharField(help_text='Primary Contact Last name', max_length=50, default=None) address1 = models.CharField(help_text='Address 1', max_length=50, default=None) address2 = models.CharField(help_text='Address 2', max_length=50, default=None, blank=True) city = models.CharField(help_text='City', max_length=50, default=None) state = models.CharField(help_text='State', max_length=50, default=None) zip_code = models.CharField(help_text='Postal/ZIP', max_length=20, default=None) phone = models.CharField(help_text='Phone', max_length=20, default=None) email = models.EmailField(default=None) contact2_first_name = models.CharField(max_length=50, null=True, blank=True) contact2_last_name = models.CharField(max_length=50, null=True, blank=True) contact2_phone = models.CharField(help_text='Phone', max_length=20, default=None, null=True, blank=True) contact2_email = models.EmailField(default=None, null=True, blank=True) fax = models.CharField(max_length=20, null=True, blank=True) mobile = models.CharField(max_length=50, default=None, blank=True, null=True) web_address = models.CharField(max_length=50, null=True, blank=True) date_entered = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) date_turned_off = models.DateTimeField(default=None, null=True, blank=True) num_locs = models.SmallIntegerField(default=1) notes = models.TextField(help_text='Notes', null=True, … -
How to create a Docusign envelope with a custom pdf (Python, Django)
My goal is to create a pdf using WeasyPrint and add it the the payload sent to the Docusign Api when requesting an envelope to be created. Here are my steps: generate the a pdf with WeasyPrint and return a based64 string def generate_envelope_document(document_name: str, context: dict): content = render_to_string(f"insurance_contracts/{document_name}.html", context=context) css = find(f"insurance_contracts/{document_name}.css") doc = HTML(string=content, media_type="screen").write_pdf(stylesheets=[css], zoom=0.8) return base64.b64encode(doc).decode("utf-8") create my envelope definition: def create_envelope_definition(envelope_data: dict, context: dict, custom_fields: dict = None): mandate = Document( document_base64=generate_envelope_document("name1", context), name="name1", file_extension="pdf", document_id=1, ) conditions = Document( document_base64=generate_envelope_document("name2", context), name="name2", file_extension="pdf", document_id=2, ) signer = Signer( email=envelope_data["signer_email"], name=envelope_data["signer_name"], recipient_id="1", routing_order="1", ) signer.tabs = Tabs( sign_here_tabs=[ SignHere( anchor_string="Sign", anchor_units="pixels", anchor_y_offset="50", anchor_x_offset_metadata="50", ) ] ) envelope_definition = EnvelopeDefinition( status="sent", documents=[mandate, conditions], recipients=Recipients(signers=[signer]) ) if custom_fields: envelope_definition.custom_fields = CustomFields( text_custom_fields=[ TextCustomField(name=field_name, value=field_value, required=False) for field_name, field_value in enumerate(custom_fields) ] ) return envelope_definition create a Docusign Api object: def get_envelopes_api_client(): """ Create the docusign api client object Return EnvelopesApi object """ api_client = ApiClient() api_client.host = settings.DOCUSIGN_BASE_PATH api_client.set_default_header("Authorization", "Bearer " + get_access_token()) envelope_api = EnvelopesApi(api_client) return envelope_api create and send the Docusign envelope: envelope_api = get_envelopes_api_client() try: envelope = envelope_api.create_envelope( settings.DOCUSIGN_ACCOUNT_ID, envelope_definition=envelope_definition ) except ApiException as e: logger.error(e.body.decode()) return None return envelope at the moment … -
Want to iterate through dictionary with dynamic keys in django template
I Have dictionaries within a dictionary with specific keys. Now I want to access each key in the template dynamically. I want to use main keys as subheadings within a table and show the data of that related keys under those subheadings. I have tried as like below but it seems not working. Error: TemplateSyntaxError at /daily/report Could not parse the remainder: '{{ledger}}' from 'ledgers.{{ledger}} how can I accomplish this? My View: @login_required def accounts_report(request): credit_vouchers = CreditVoucher.objects.all() debit_vouchers = DebitVoucher.objects.all() heads = AccountHead.objects.all() opening_balance = request.GET.get('balance') balance = float(opening_balance) date_from = request.GET.get('from') date_to = request.GET.get('to') credit_vouchers = credit_vouchers.filter(date__gte=date_from, date__lte=date_to) debit_vouchers = debit_vouchers.filter(date__gte=date_from, date__lte=date_to) ledgers = {} for head in heads: key = head.head_name ledgers.setdefault(key, []) for item in ledgers: key = item ledgers.setdefault(key, []) a_head = AccountHead.objects.get(head_name=key) d_vouchers = debit_vouchers.filter(account_head=a_head) c_vouchers = credit_vouchers.filter(account_head=a_head) for voucher in d_vouchers: balance -= voucher.amount ledgers[key].append({ 'date': voucher.date, 'description': voucher.description, 'voucher_no': voucher.voucher_serial, 'debit_amount': voucher.amount, 'credit_amount': 0, 'balance': balance, }) for voucher in c_vouchers: balance += voucher.amount ledgers[key].append({ 'date': voucher.date, 'description': voucher.description, 'voucher_no': voucher.voucher_serial, 'debit_amount': 0, 'credit_amount': voucher.amount, 'balance': balance, }) context = { 'heads': heads, 'opening_balance': opening_balance, 'ledgers': ledgers } return render(request, 'accounts/report.html', context=context) Template: <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> table, th, … -
Django - Get response to return image without saving file to models
I am using the tmdb api to return movie info as well as images. Steps below of Get logic Api request is made which provides movie info as well as "backdrop_path" I then use this path to make another request for the jpg related to that movie. Blocker I'm unable to then output that jpg. It currently returns a url path as below. Views.py from django.shortcuts import render from django.views.generic import TemplateView import requests import urllib # Create your views here. def index(request): # Query API with user input if 'movie' in request.GET: api_key = 'api' id = request.GET['movie'] url = 'https://api.themoviedb.org/3/search/movie?api_key={}&language=en-US&query={}&include_adult=false' response = requests.get(url.format(api_key,id)) # successful request if response.status_code == 200: # Parse json output for key value pairs tmdb = response.json() # save image jpg backdrop_path = tmdb['results'][0]['backdrop_path'] url = 'https://image.tmdb.org/t/p/original/{}' gg = urllib.request.urlretrieve(url.format(backdrop_path), 'test.jpg') context = { 'title': tmdb['results'][0]['original_title'], 'overview': tmdb['results'][0]['overview'], 'release_date': tmdb['results'][0]['release_date'], 'vote_average': tmdb['results'][0]['vote_average'], 'vote_count': tmdb['results'][0]['vote_count'], 'backdrop_path' : tmdb['results'][0]['backdrop_path'], 'jpg' : gg } return render(request, 'home.html', {'context': context}) else: # returns homepage if invalid request return render(request, 'home.html') else: # Homepage without GET request return render(request, 'home.html') -
Django/Node js/Laravell/Spring.Which of these would be best for backend beginners?
I am beginner at backend.Pls tell which of these options would be best for me and WHY?? If you have any other framework to suggest.Please speacify.