Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ValueError Cannot query "customer1@gmail.com": Must be "Customer" instance
I am trying to save the customer to the Order Model, but the customer is not being saved, it shows customer1@gmail.com must be Customer instance. And also I want to save the seller to the Order model. Because, A product is related to a seller. When I order something, and after the order is saved, I should be able to see from which seller I bought that product from. But here I am not able to save the seller. cart views.py def checkout(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect('cart:cart') login_form = CustomerLoginForm() signin_form = CreateCustomerForm() address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) address_qs = None if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter(billing_profile=billing_profile) order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj, request) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get(id=billing_address_id) del request.session["billing_address_id"] if billing_address_id or shipping_address_id: order_obj.save() if request.method == "POST": is_done = order_obj.check_done() if is_done: order_obj.mark_paid() request.session['cart_items'] = "" del request.session['cart_id'] return redirect("cart:success") context = { 'object':order_obj, 'billing_profile':billing_profile, 'login_form':login_form, 'signin_form': signin_form, 'address_form':address_form, 'address_qs': address_qs, } return render(request, 'cart/checkout.html', context) order models.py class OrderManager(models.Manager): def new_or_get(self, billing_profile, cart_obj, request): created … -
Searching class based views in Django
I'm trying to make a search option for my ecommerce app in Django. I'm using a ListView for showing my posts and paginate them: def search(request): qs = '' title_query = request.GET.get('q') if title_query != '' and title_query is not None: qs = qs.publicaciones.objects.filter(title__icontains=title_query) context = { 'queryset': qs, } class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 4 This is the relevant HTML: {% for q in queryset %} <div class="container"> <h1>{{ q.Título }}</h1> </div> <div class="container"> {{ q.Descripción }} </div> <div class="container"> <img class="item-img" src="{{ q.Fotos.url }}" width="250"> </div> {% endfor %} However, this codes just shows all the items, my goal is to filter them by the search obviously. It's also really strange that when I set the value for queryset to anything like 'foo', it will still display all the items. I'm compleatly lost. Any help would be appreciated. I already tried these, but didn't get any results: Django: Search form in Class Based ListView How to create a filter form for a (class based) generic object list in Django? -
html css file note displaying image using jinga format for django
my index.html: {% load static %} {% static "images" as baseurl %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Travello template project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css'%}"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css'%}" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.carousel.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.theme.default.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/main_styles.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/responsive.css' %}"> <link rel="stylesheet" href={% static 'index.css"' %}> </head> <body> <div class="super_container"> <!-- Header --> <header class="header"> <div class="container"> <div class="row"> <div class="col"> <div class="header_content d-flex flex-row align-items-center justify-content-start"> <div class="header_content_inner d-flex flex-row align-items-end justify-content-start"> <div class="logo"><a href="{% static 'index.html' %}">Travello</a></div> <nav class="main_nav"> <ul class="d-flex flex-row align-items-start justify-content-start"> <li class="active"><a href="{% static 'index.html' %}">Home</a></li> <li><a href="{% static 'about.html' %}">About us</a></li> <li><a href="accounts/register">Register</a></li> <li><a href="{% static 'news.html' %}">News</a></li> <li><a href="{% static 'contact.html' %}">Contact</a></li> </ul> </nav> <div class="header_phone ml-auto">Call us: 00-56 445 678 33</div> <!-- Hamburger --> <div class="hamburger ml-auto"> <i class="fa fa-bars" aria-hidden="true"></i> </div> </div> </div> </div> </div> </div> <div class="header_social d-flex flex-row align-items-center justify-content-start"> <ul class="d-flex flex-row align-items-start justify-content-start"> <li><a href="#"><i class="fa fa-pinterest" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-twitter" … -
How to change order_by dynamically using django-tables2?
My table class looks pretty typical except that maybe it includes a before_render() function. What's great about before_render is that I can access self. This gives me access to dynamic information about the model I'm using. How can I access dynamic information (like from before_render) to change the order_by variable in the Meta class? def control_columns(table_self): # Changes yesno for all Boolean fields to ('Yes','No') instead of the default check-mark or 'X'. for column in table_self.data.table.columns.columns: current_column = table_self.data.table.columns.columns[column].column if isinstance(current_column,tables.columns.booleancolumn.BooleanColumn): current_column.yesno = ('Yes','No') class DynamicTable(tables.Table): def before_render(self, request): control_columns(self) class Meta: template_name = 'django_tables2/bootstrap4.html' attrs = {'class': 'custom_table', 'tr': {'valign':"top"}} order_by = 'index' -
Chart JS Issue while rendering the data from database
From last couple of days I was trying hard to integrate chartjs-plugin-streaming on my page, data is properly coming from ajax call, even the graph is responding properly but some time the y-axis gets changed but x remains the same which makes the graph curve bad, it is basically getting overlapped, let me share you the graph and api data with codes, {% load static %} {% block header %} <link rel="stylesheet" href="{% static 'charts/cpu.css' %}"> <script src="{% static 'charts/moment.min.js' %}"></script> <script src="{% static 'charts/chart.js@2.8.0' %}"></script> <script src="{% static 'charts/chartjs-plugin-streaming@1.8.0' %}"></script> {% endblock header %} {% block scripts %} <script> var chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', grey: 'rgb(201, 203, 207)' }; function onRefresh(chart){ chart.config.data.datasets.forEach(function(dataset) { data.forEach((ele) => { dataset.data.push({ x: Date.now(), y: ele.load_1m }); }); }); }; var color = Chart.helpers.color; var config = { type: 'line', data: { datasets: [{ label: 'Dataset 2 (cubic interpolation)', backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(), borderColor: chartColors.blue, fill: false, cubicInterpolationMode: 'monotone', data: [] }] }, options: { title: { display: true, text: 'Line chart (hotizontal scroll) sample' }, scales: { xAxes: [{ type: 'realtime', realtime: … -
How can I make different photos take modal image from an array of photos, from database?
So I'm working on a Django project, a Portfolio website. And I started making some cards for showcasing: I'm pulling all data from Django Database and using bootstrap for frontend: {% for project in projects %} <div class="cardies"> <div class="card" style="width: 18rem;"> <img src="{{ project.image.url }}" class="card-img-top img-fluid" id="myImg" alt="{{ project.description }}"> <div class="card-body"> <h6 class="card-subtitle mb-2 text-muted">{{ project.date }}</h5> <h5 class="card-title">{{ project.title}}</h6> <!-- <p class="card-text">{{ project.description}}</p>--> </div> </div> </div> {% endfor %} And I have some local css styling just to display those cards inline. Now I wanted to create a image modal, where when I click on any of those images, they zoom in like shown: And as you can see, it works, but only for the first picture. I used some javascript to to it, here's the code: HTML: <div id="myModal" class="modal"> <span class="close">&times;</span> <img class="modal-content" id="img01"> <div id="caption"></div> </div> CSS: #myImg { border-radius: 5px; cursor: pointer; transition: 0.3s; } #myImg:hover {opacity: 0.7;} /* The Modal (background) */ .modal { display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 1; /* Sit on top */ padding-top: 100px; /* Location of the box */ left: 0; top: 0; width: 100%; /* Full … -
Shopping cart in Python for a beginner as a learning project
I am learning Python and would like to create a simple e-commerce site, very basic - just for the sake of example to give myself a goal to create something. Is there something I should know ahead of the time, does Python have classes for this functionality or should I just look for a ready made plug-in for Django? Thank you! -
How to open a link in another tab in Django using reversed URL mapping?
I know that target="_blank" normally works, however, I'm having trouble implementing that code using reversed URL mapping. It does not work for this link as formatted. It opens the link, but in the same tab. Any ideas? Here is the code for the link: <a href="{{ meter.url }}" target="_blank"> <img src="{{ meter.image.url }}" class="img-fluid mb-2" width="100%" height="auto"> </a> -
React useState hook not consistently updating
I started integrating websockets into an existing React/Django app following along with this example (accompanying repo here). In that repo, the websocket interface is in websockets.js, and is implemented in containers/Chat.js. I can get that code working correctly as-is. I then started re-writing my implementation to use Hooks, and hit a little wall. The data flows through the socket correctly, arrives in the handler of each client correctly, and within the handler can read the correct state. Within that handler, I'm calling my useState function to update state with the incoming data. Originally I had a problem of my single useState function within addMessage() inconsistently firing (1 in 10 times?). I split my one useState hook into two (one for current message, one for all messages). Now in addMessage() upon receiving data from the server, my setAllMessages hook will only update the client where I type the message in - no other clients. All clients receive/can log the data correctly, they just don't run the setAllMessages function. If I push to an empty array outside the function, it works as expected. So it seems like a problem in the function update cycle, but I haven't been able to track it … -
"Unicode-objects must be encoded before hashing" when i try send .m3u8 file to S3 using boto3 - Django
I was able to send the video normally to my local machine, but when I changed the storage settings, I just started getting this error. The error points to the line where the code is instance.file.save(file_name_m3u8, file_m3u8) And then immediately points to # .../python3.8/site-packages/storages/backends/s3boto3.py # ... obj.upload_fileobj(content, ExtraArgs=params) # ... My file object file_m3u8 is: file_object <_io.TextIOWrapper name='/tmp/media/lectures/first_video_2/2020-04-04_16-11-20.m3u8' mode='r' encoding='UTF-8'> Simple example: from django.db.models.signals import post_save from django.dispatch import receiver from django.core.files import File from .models import Lecture @receiver(post_save, sender=Lecture) def handle_video_upload (sender, instance, created, ** kwargs): with open ( "/tmp/media/lectures/first_video_2/2020-04-04_16-11-20.m3u8", "r") as file_object: file_m3u8 = File ( name = "media/lectures/first_video_2/2020-04-04_16-11-20.m3u8", file = file_object) instance.file.save ("2020-04-04_16-11-20.m3u8", file_m3u8) The complede code: https://pastebin.com/xVc3gbCK Again: when i remove all s3 and boto storage settings and use local storage, all works fine PS: the vars in settings.py: # STATIC AWS+CLOUDFRONT STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = config("AWS_STORAGE_BUCKET_NAME") CLOUDFRONT_ID = config("CLOUDFRONT_ID") CLOUDFRONT_DOMAIN = f"{CLOUDFRONT_ID}.cloudfront.net" AWS_S3_CUSTOM_DOMAIN = f"{CLOUDFRONT_ID}.cloudfront.net" PS2: i also can upload other files to the s3, but this not works when i try send the .m3u8. -
Django BinaryTreeLike choices
I have this main choice input CATEGORY_CHOICES = ( (0, 'Default'), (1, "Development"), (2, "Business-Finance"), (3, "Entrepreneurship"), (4, "Communications"), (5, "Management"), (6, "Finance&Accounting"), (7, "IT&Software"), (8, "Office&Productivity"), (9, "Personal Development"), (10, "Personal Development"), (11, "Design"), (12, "Marketing"), (13, "Lifestyle"), (14, "Photography"), (15, "Health&Fitness"), (15, "Music"), (16, "Teaching&Academics")) Each of them has a sub-choice menu DEVELOPMENT_CATEGORY_CHOICES = ( (1, 'Web Development'), (2, 'Data Science'), (3, 'Mobile Apps'), (4, 'Programming Languages'), (5, 'Game Development'), (6, 'Databases'), (7, 'Software Testing'), (8, 'Software Engineering'), (9, 'Development Tools'), (10, 'E-commerce')) BUSINESS_FINANCE_CATEGORY_CHOICES = ( (1, 'Analytics'), (2, 'Investing'), (3, 'Stock Trading'), (4, 'Forex'), (5, 'Finance Education'), (6, 'Financial Modeling'), (7, 'Excel'), (8, 'Accounting'), (9, 'Python') ) ENTREPRENEURSHIP_CATEGORY_CHOICES = ( (1, 'Business Fundamentals'), (2, 'Dropshipping'), (3, 'Amazon FBA'), (4, 'Entrepreneurship Fundamentals'), (5, 'Business Strategy'), (6, 'Business Plan'), (7, 'Startup'), (8, 'Blogging'), (9, 'Shopify') ) COMMUNICATIONS_CATEGORY_CHOICES = ( (1, 'Writing'), (2, 'Public Speaking'), (3, 'Communication Skill'), (4, 'Presentation Skill'), (5, 'Fiction Writing'), (6, 'Story Telling'), (7, 'Novel Writing'), (8, 'Marketing Strategy') ) MANAGEMENT_CATEGORY_CHOICES = ( (1, 'Product Management'), (2, 'Leadership'), (3, 'Management Skills'), (4, 'Business Process Management'), (5, 'Agile') ) SALES_CATEGORY_CHOICES = ( (1, 'Strategy'), (2, 'Operations'), (3, 'Project Management'), (4, 'Business Law'), (5, 'Data and analytics'), (6, … -
How to fix ModuleNotFounError in Django?
I'm following a tutorial to deploy Django on Heroku and I've run into an error where after I have uploaded project to github, I can't run manage.py runserver. It sends an error message trace and one of the messages is module not found. Venv is activated, debug is set to false. Below is the stack trace errors. This is the guide I'm following for anyone curious. I am on Re-test and save changes to Github section. -
Filter form for Manytomanyfield
I'm writing an inventory app. The idea is this: there's a parts list class and a vendor class, which are related to each other. class Part(models.Model): vendr = models.ManyToManyField('Vendor', blank=True) class Vendor(models.Model): parts = models.ManyToManyField(Part, blank=True) On the template to create new vendor i want to put a "Add parts" button. Now it will render as SelectMultiple widget. But when there are hundreds of parts it doesn't really work. So what i want is to be able to add parts one by one through a charfield which also works as a filter. But i can't figure out how to do it (i'm new to python/django). What would be the best approach for this. -
Django how to do admin.site.register
i have app written in django 1.8, doing admin.site.register(A, Admin) or admin.site.register(B) Also using admin.site.unregister(User). But none of these are working in Django 2.2, whenever I type admin.site. In help I don't get neither register or unregister functions.When I try to run in apache in crashes. Any help in django 2.2.7 and python 3.6.9 from django.contrib import admin -
How should I organise my code in project?
Good morning. I've been learning spring for some time and I knew two approaches to organise code in projects. First is to divide project into layers(repository, service etc.). Second one is to separate by modules(for instance products, customers, orders etc.). My question is how does it look like in Django? My second question is whether I should place model classes into separate files or everything in default model.py file? -
Make a resource to retrieve API Keys from the API using username and password
I am building an API with tastypie to use a mobile application on my website (built with django). From what I've seen, instead of storing the credentials on the phone, I should use an API key. I wanted to do as follow : whenever a new account is created, generate an api key (done with create_api_key) have a resource for the phone to grab the API key using username and password. I am stuck on the second step. How can I make such a resource ? I though about using custom filters to retrieve the credentials, though it seems really convoluted... I also tried to adapt code from this answer (https://www.semicolonworld.com/question/55071/how-can-i-login-to-django-using-tastypie), though I am not really comfortable with the whole tweaking of urls to include the login entry point. How can I achieve this in the most idiomatic way ? Also, is this a good way of implementing communication between the app and django ? -
Graphql: How to implement condition in my mutation in my project?
So I have been assigned with a project where already a developer worked and he left so I have no one to ask it to. It is with Django and Graphql and I am very new to Graphql. The business logic is, if there is a boolean field "ban" set to true, user will not be able to upvote the news and raise a validation error. What I have done so far: I have tried adding @property def ban(self): return self.user.generaluser.last().ban in my UserVoteNews model. In the mutation I tried to acces the value with user.ban but couldn't. Here is the model: class GeneralUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE) image = models.CharField(max_length=2000) ban = models.BooleanField(default=False) class UserVoteNews(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) news = models.ForeignKey(News, on_delete=models.CASCADE) vote = models.IntegerField(default=0) created_date = models.DateTimeField(auto_now=True, help_text="When user voted") class Meta: verbose_name = "User Vote News" verbose_name_plural = "User Vote News" And the mutation where I need to get the value of ban and raise the error: class UpdateUpvote(graphene.Mutation): class Arguments: id = graphene.ID() user_id = graphene.Int() news = graphene.Field(NewsType) def mutate(self, info, id, user_id): user = info.context.user if UserVoteNews.objects.filter(user_id=user.id, news_id=id).exists(): UserVoteNews.objects.filter( user_id=user.id, news_id=id).update(vote=1) news = News.objects.get(pk=id) news.upvote = news.upvote+1 news.downvote = … -
How to handle JavaScript event inside a inlineformset_factory with formset_media_js
I have an inlineformset_factory implemented with formset_media_js, these two by itself are working ok. What I need to implement is to be able to handle the enable and disable state of some checkboxes and input fields that are inside the inlineformset_factory. I have a javascript that works on the first group of formset created on page load, but when a new formset is added by the user the javascript is not working. How can I handle the new formsets input fields added by the user with javascript? If "is chapter" is checked then "is subchapter" and "quantity" are disabled, by default the inlineformset_fatory creates 1 formset on page load, on this formset the javascript works. But when the user adds another formset with button "Add another Budget Item" the javascript is no longer working. If for example, I configure the inlineformser_factory to create 3 formset on page load the javascript works on those 3 formset but not on the formsets added by the user. forms.py : at this forms.py i have the inlineformset_factory that is created every time the user adds a formset. from django import forms from django.forms import inlineformset_factory from djangoformsetjs.utils import formset_media_js from accounts.models import ProjectManager from … -
Calculate field based in two ajax requests
i am trying to develop a web app in django, and i have two ajax request in an html template that are working well, but when i try to calulate a field and put it on another field(#minherente), this calculate the field with the previously value, but not with the values got in two ajax. I'll apreciate your help. <script type="text/javascript"> $("#id_Falla").change(function () { var url = $("#MatrizForm").attr("data-fi-url"); var FallaId = $("#id_Falla").val(); var url1 = $("#MatrizForm").attr("data-ii-url"); $.ajax({ url: url, data: { 'Falla': FallaId }, success: function (data) { $("#finherente").val(data); } }); $.ajax({ url: url1, data: { 'Falla': FallaId }, success: function (data1) { $("#iinherente").val(data1); } }); var frecuencia = $('#finherente').val(); var impacto = $('#iinherente').val(); $('#minherente').val(frecuencia*impacto); }); Any help would be most appreciated thanks -
How to implement view and url patterns for Post and Category models in Django 3
I'm trying to learn Django by building a simple blog. I have three models: Post, Category, and Tag. class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True, null=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') updated_on = models.DateTimeField(auto_now=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=POST_STATUS, default=0) visibility = models.IntegerField(choices=POST_VISIBILITY, default=0) content = models.TextField() excerpt = models.TextField() category = models.ForeignKey('blog.Category', on_delete=models.CASCADE) tags = models.ManyToManyField('blog.Tag') image = models.ImageField(upload_to="images/", default=0) class Meta: ordering = ['-created_on', 'title'] verbose_name = 'Post' verbose_name_plural = 'Posts' unique_together = ('title', 'slug') def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True, null=False) description = models.TextField() class Meta: ordering = ['title'] verbose_name = 'Category' verbose_name_plural = 'Categories' unique_together = ('title', 'slug') def __str__(self): return self.title class Tag(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True, null=False) description = models.TextField() class Meta: ordering = ['title'] verbose_name = 'Tag' verbose_name_plural = 'Tags' def __str__(self): return self.title I have two views - posts_index shows all the posts, and single should show a single post. from django.shortcuts import render from .models import Post, Category, Tag def posts_index(request): all_posts = Post.objects.all() return render(request, 'index.html', {'posts': all_posts}) def single(request, slug, category): single_post = Post.objects.get(slug=slug) return render(request, 'single.html', {'single': single_post, 'category_slug': single_post.slug}) In mu … -
Python is inserting newline characters into requests header
Some background. This code takes a data from a data collection script and then posts it to a secured REST API in Django. I have an api key generated and it is the only line in the file api.key. I also have the url to post to in the file post.url (it looks like http://example.com/api/ and then I concatenate the proper api node name on the end). The code is below for my solar data api node (posts data collected from solar panels) import gather_solar as gs import requests import json import os def post_solar(): print("DEBUG: start solar") data = gs.gather_solar() api_key = None url = None try: here = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(here, 'api.key') file = open(filename, "r") api_key = file.readline() api_key.replace('\n', '') except Exception as e: print("ERROR: " + str(e)) try: here = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(here, 'post.url') #server will use different url file = open(filename, "r") url = file.readline() url.replace('\n', '') except Exception as e: print("ERROR: " + str(e)) if api_key is not None and url is not None: authorization = "Token " + api_key authorization.replace('\n', '') headers = { 'Content-Type': 'application/json; charset=UTF-8', 'Authorization': authorization } json_data = json.dumps(data) url += "solar/" url.replace('\n', '') print(url) req = … -
How to dynamically add sequence numbers to labels in django forms
I'm using Modelformset to dynamically add/remove rows in my form. I wonder if there is a way to dynamically add sequence numbers to labels in django forms? Currently my code is as below. I want dynamically add sequence numbers to Building type # everytime the user adds new field. BuildingFormset = modelformset_factory( Building, fields=('building_type', 'building_length', 'building_width', ), labels={'building_type':'Building type #'}, extra=1, ) I tried to use <label for="{{ form.field.id_for_label }}"></label> and auto_id but it didn't work for some reason (could it be because I'm using bootstrap?). -
Populate list in Django using view
I have the following function to read news headlines into a Python list: import requests def us_news_articles(): url = 'https://newsapi.org/v2/top-headlines?country=us&apiKey=### source = requests.get(url) data = source.json() us_news_articles_list = [] for article in data['articles']: us_news_articles_list.append(article) return us_news_articles_list This function works, and I've verified it. Now I want to be able to use this to populate HTML li items I have the following views built: def viz(request): return render(request, 'resume/viz.html') class USNewsArticles(TemplateView): template_name = 'viz' def get_context_data(self, *args, **kwargs): context = { 'articles': us_news_articles(), } return context My URL looks like this path('viz/', views.viz, name='viz') And in my HTML file, I have the following: <ul> {% for article in articles %} <li>{{ article.title }}</li> <ul> <li>{{ article.description }}</li> </ul> {% endfor %} </ul> However, when I deploy the website, I get no list. I believe it's an issue with the view, but I am not well-versed enough in understand views and functions to understand why it will not populate the li items -
serve multiple base64 images to download
My django application has a model with base64 encoded images. I would like to add the option to my ListView to download all the displayed images to the location of the user's choice. Should I create an AJAX view, or can jQuery take care of it? I googled around and I saw some examples of serving a single file to download. But how do I serve all the images at the same time? -
Why does django-dynamic-formset 'add another' button duplicate foreign key field?
I went through the instructions to set up django-dynamic-formset to my project and my specific inline formsets. All of the formsets seem to work except one that includes a foreign key. When I 'add another' it duplicates that field right under it. Before pressing 'add another': After pressing 'add another': The formset: <h3>Services</h3> <div class="row"> {{ services_formset.management_form }} {% for formserve in services_formset %} {{ formserve.non_field_errors }} <div class="container" id="services_formset"> <div class="row" name="service_form"> {% for hidden in formserve.hidden_fields %} {{ hidden }} {% endfor %} {% for field in formserve %} {% if field.name != 'index' and field.name != 'invoice'%} <div class="col-sm"> {{ field.errors }} {{ field|as_crispy_field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endif %} {% endfor %} </div> </div> The javascript: <script type="text/javascript"> $(function() { $('#services_formset').formset({ prefix: '{{ formserve.prefix }}' }); }) </script>