Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is it better to include token as a field in the User model for Django+SimpleJwt?
i'm looking at different ways of using django rest framework with jwt, and most cases would do it in a "normal" way (as the Getting started in the simple Jwt Documentation says), but i encoutred some ones that extends the User model and include the Token inside, something like : class User(AbstractBaseUser, PermissionsMixin): # .....(usual fields(username, password,...)) @property def token(self): return self._generate_jwt_token() def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token is this way better? or is it just a different way to handle it? what difference does it make? -
Unable to populate images in Django Rest Serializer
I'm developing a REST API using Django Rest Framework but I'm unable to populate image in Feed Serializer Django Version: 3.1.7 Python Version: 3.9.2 Models: class User(AbstractUser): age = models.PositiveIntegerField(null=True) address = models.TextField(null=True) email = models.EmailField(_('email address'), unique=True, null=False) first_name = models.CharField(_('first name'), max_length=150, blank=False, null=False) last_name = models.CharField(_('last name'), max_length=150, blank=False, null=False) image = models.ImageField(upload_to='storage', null=True) class Feed(models.Model): description = models.TextField() likes_count = models.PositiveIntegerField(default=0, null=True) comments_count = models.PositiveIntegerField(default=0, null=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') tags = models.ManyToManyField(User, related_name='tags', blank=True) class FeedImage(models.Model): path = models.ImageField(upload_to='storage', null=False) post = models.ForeignKey(Feed, on_delete=models.CASCADE, null=False, default='') Serializers: class FeedUserSerializer(ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'last_name', 'image') class FeedImageSerializer(serializers.ModelSerializer): class Meta: model = FeedImage fields = ('id', 'path', 'post') class FeedSerializer(ModelSerializer): user = FeedUserSerializer() images = FeedImageSerializer(many=True, read_only=True) class Meta: model = Feed fields = ('id', 'description', 'comments_count', 'likes_count', 'updated_at', 'created_at', 'tags', 'images', 'user') View: class FeedsListView(generics.ListAPIView): queryset = Feed.objects.all() return FeedSerializer Problem: I get this result without images [{ "id": 1, "description": "Hello world", "comments_count": 0, "likes_count": 0, "updated_at": "2021-04-26T03:01:44.219235Z", "created_at": "2021-04-26T03:01:44.219235Z", "tags": [], "user": { "id": 1, "first_name": "ZAIN", "last_name": "REHMAN", "image": "http://192.168.88.28:8000/storage/1_Facebook_1.jpg" } }] Expected Output: [{ "id": 1, "description": "Hello world", … -
how to filtering queryset in django template
I used a function in models.py to output the queryset result to the template. Now what I want to do is filter the output queryset back in views.py. Is it possible to filter with the code below? Please feedback if the logic is wrong [models.py] class Academy(models.Model): .... def student(self): return Student.objects.filter(academy_id=self.id) [views.py] @login_required() def academy_list(request): academy_list = Academy.objects.all() option_radio = request.GET.get('optionRadios') from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') count = Attribute.objects.filter( entry_date__gte=from_date, entry_date__lt=to_date) return render(request, 'academy_list.html', { 'academy_list': academy_list, 'option_radio': option_radio, 'from_date': from_date, 'to_date': to_date, 'count': count }) [academy_list.html] {% for academy in academy_list %} {% if option_radio == 'period' %} <tr> <td>{{ academy.academy_name }}</td> <td>{{ academy.student }}</td> ---- I want to filter again using the count variable in the academy_list function in views.py. </tr> {% endif %} {% endfor %} -
needs to restart supervisor everytime
i am using postgres sql and here is my queryset user_attempt_quiz_obj = UserAttemptQuiz.objects.filter(created_at__year=today.year, created_at__month=today.month, created_at__day=today.day) queryset is working fine but its response doesn't change for each days untill i restart my server. i am using nginx server with supervisor my time setting is below: TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True -
How to store in a JavaScript variable the selected rows in a table
Let's say we have a table like this: <table> <thead> <tr> <th class="active"> <input type="checkbox" class="select-all checkbox" name="select-all" /> </th> <th>A</th> <th>B</th> </tr> </thead> <tbody> {% for gene_variant in gene_variant_results %} <tr> <td class="active"> <input id="selectedGene" type="checkbox" class="select-item checkbox" name="select-item"/> </td> <td>{{ gene_variant.67 }}</td> <td> {{ gene_variant.72 }}</td> </tr> {% endfor %} </tbody> </table> <button id="select-all" class="btn btn-primary">Select all</button> <button type="submit" id="show-selected" class="btn btn-primary">Show selected</button> And let's say that gene_variant_results has for example, 4 results. Each result corresponds to a row (each row has about 100 columns, in this example I only put 11 for illustrative purposes): (1290, 'chr10', '73498294', '73498294', 'C', 'G', 'exonic', 'CDH23', 'DM', 'CM127233', 'DFNB12) (1291, 'chr11', '73498295', '73498295', 'D', 'H', 'exonic', 'CDH24', 'DM', 'CM127234', 'DFNB13) (1292, 'chr12', '73498296', '73498296', 'E', 'I', 'exonic', 'CDH25', 'DM', 'CM127235', 'DFNB14) (1293, 'chr13', '73498297', '73498297', 'F', 'J', 'exonic', 'CDH26', 'DM', 'CM127236', 'DFNB15) For example, if I click on the first two checkboxes and then click on the #show-selected button, I would like to store in a JavaScript variable the values of those selected rows. (The full gene_variant content, not just the selected <td> values) Some illustrative semi pseudo-code of what I want: $( "#show-selected" ).click(function() { var selected_checkboxes = //get the … -
why Search function is not working in django?
After I searched on a specific keyword, Django is not retrieving searched items that matches but it's showing all data. When I search for history it's showing all books though I have history books on the database. views.py def home(request): if request.method == 'POST': searchName = request.POST.get('Search') if not searchName : searchName = "" context={ 'data': Book.objects.filter(bookname__contains=searchName) } return render(request, 'library_site/home.html',context) else: context={ 'data': Book.objects.all() } return render(request, 'library_site/home.html',context) form field in html <form method="POST" action="{% url 'home' %}"> {% csrf_token %} <input class="search-input" type="text" name="searchBook" placeholder="Search Book Name here..."> <input class="btn" type="submit" name="search" value="Search"> </form> -
Django and google_streetview API
Is there a way to retrieve a street view image from google_streetview API in Python/Django and pass it to templates without having to save the image within Django? I know you can create an API call using Javascript, although I am looking to see if there is a method to do the API call in the backend to avoid showing my API Key in the frontend or is this even necessary? I am not even sure what might be best practice for this. I am currently using Javascript to allow for the Google Places Autocomplete API. Is it secure enough to simply have restrictions in place on your API key's for which API your key is good for and a Application Restriction? Currently I have this in place from the google_streetview package: import google_streetview.api def streetview(coord): params = [{ 'size': '300x200', 'location': coord, 'fov': '100', 'key': settings.STREETVIEW_KEY }] results = google_streetview.api.results(params) However, the only things I know you can do with results is .preview(), .save_links(), .download_links(), .save_metadata(). -
Saving data to database using form wizard
I am using form wizard to create a multi-page form in django, however I'm having trouble saving my data to a database using this method. Do I save the data based on the current step of each form I'm in (i.e. save it based on step 1, 2 or 3), if so how do I do this with the request? Below is my defective code, any help would be appreciated. class newWorkoutLinked(SessionWizardView): template_name = "workout_app/contact_form.html" def done(self, form_list, **kwargs): return render(self.request, 'workout_app/done.html', { 'form_data': [form.cleaned_data for form in form_list] }) if self.request.user.is_anonymous: messages.error(request, LE) return HttpResponseRedirect('/login/') if self.request.method == 'POST': form = WorkoutLinkedForm(request.POST) if form.is_valid(): ots = form.save(commit=False) ots.profile = self.request.user ots.save() return HttpResponseRedirect('/workout_linked_list') else: form = WorkoutLinkedForm() return render(self.request, 'workout_app/add_workout_linked.html', {'form': form}) -
in Django,what is the best way to store a content which consist of images and text?
I am building a website like a blog. On my website, I am going to have an article with at least 4 paragraphs and also a minimum of 4 pictures. I am planning to use RichTextField for it but I am here to get advice from you experienced people. As I said, I am totally new to Django. What is the best and fastest way to store an article with images? By the way, before I asked the question, I googled it but most questions came down to Django 2.0. There must be better ways now. Thank you all. -
Best way to handle LoginView login on all pages in Django
I am new to Django and I have spent a lot of time trying to find a solution to my problem but was not successful. I have a top navbar that is included in the base.html file and every page extends base.html. In my navbar, I have a button that shows a modal (bootstrap) and I want this modal to show the login form. My url.py is as follows: from django.urls import path, include from .views import RegisterView from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, PasswordChangeView, PasswordChangeDoneView urlpatterns = [ # Mapping django auth at the root # The URLs provided by auth are: # login/ [name='login'] # logout/ [name='logout'] # password_change/ [name='password_change'] # password_change/done/ [name='password_change_done'] # password_reset/ [name='password_reset'] # password_reset/done/ [name='password_reset_done'] # reset/<uidb64>/<token>/ [name='password_reset_confirm'] # reset/done/ [name='password_reset_complete'] #path('', include('django.contrib.auth.urls')), path('password_reset/', PasswordResetView.as_view(), name='password_reset'), path('password_reset_done/', PasswordResetDoneView.as_view(), name='password_reset_done'), path('password_reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('password_reset/complete/', PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('password_change/', PasswordChangeView.as_view(), name='password_change'), path('password_change/complete/', PasswordChangeDoneView.as_view(), name='password_change_done'), path('login/', LoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('register/', RegisterView.as_view(), name='register'), ] As you can see above, path('login/', LoginView.as_view(), name='login'), will only correctly resolve {{ form }} in localhost:8000/login but I want it to resolve in all paths to achieve what I want. Meaning, if I navigate to localhost:8000/login and open the … -
how to use request.GET['parameter'] from django models.py
I am trying to get self.request.GET['from_date'] value from django models.py. However, you cannot use the value. As a result of searching, I got feedback to use request in views.py, but I need a variable called self.id so the work has to be done in models.py. Is there a way to get parameter value from models.py? [models.py] class Academy(models.Model): def count(self): student = Student.objects.filter(academy_id=self.id) return Attribute.objects.filter( entry_date__gte=self.request.GET['from_date'], entry_date__lt=self.request.GET['to_date'], student_id__in=student ).count() -
Django user proxy
I'm using proxy model in Django to make multiple types of users (patient and doctors), I am trying to make a specific page to show all doctors signed up but I don't know how to access them in the template something like {% for doctor in Doctors.objects.all %} . this is the user model code class User(AbstractBaseUser, PermissionsMixin): class Types(models.TextChoices): DOCTOR = "DOCTOR", "Doctor" PATIENT = "PATIENT", "Patient" type = models.CharField( _("Type"), max_length=50, choices=Types.choices, default=Types.PATIENT ) class Patient(User): objects = PatientManager() class Meta: proxy = True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.PATIENT return super().save(*args, **kwargs) class Doctor(User): objects = DoctorManager() class Meta: proxy = True def save(self, *args, **kwargs): if not self.pk: self.type = User.Types.DOCTOR return super().save(*args, **kwargs) -
How to show Pagination for JSON data in DOM ( Django, JavaScript, HTML )
In my views function, I have added pagination that returns 3 posts for every page as JSON data, Right now my HTML page shows only the first 3 posts, How can I make my next and previous buttons work if I'm returning JSON data to my JavaScript and not returning as render for the HTML page? views.py def show_posts(request): all_posts = NewPost.objects.all() all_posts = all_posts.order_by("-date_added").all() all_posts_paginated = Paginator(all_posts, 3) page_number = request.GET.get('page', 1) page_obj = all_posts_paginated.get_page(page_number) return JsonResponse([website_post.serialize() for website_post in page_obj.object_list], safe=False) index.js function load_posts(){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#load-profile').style.display = 'none'; document.querySelector('#posts-view').style.display = 'block'; document.querySelector('#show-posts').style.display = 'block'; document.querySelector('#post-form').onsubmit = function() { compose_post(); } fetch('/posts/all_posts') // url with that API .then(response => response.json()) .then(all_posts => { // Loop and show all the posts. console.log(all_posts) all_posts.forEach(function(post) { // loop to loop over each object display_post(post) }); }); document.querySelector('#show-posts').innerHTML = "" } function display_post(post){ // create new div for each thing that needs to be shown const element = document.createElement('div'); const post_username = document.createElement('div'); const post_description = document.createElement('div'); const post_date_added = document.createElement('div'); const post_likes = document.createElement('div'); // add the text for each div post_username.innerHTML = 'Username: ' + post.poster post_description.innerHTML = 'Content: ' + post.description post_date_added.innerHTML = 'Date: ' + post.date_added post_likes.innerHTML … -
How do I loop through two models to get attribute differences in a django template?
I am trying to figure out how to get the attribute differences from two different django models. They have common attributes, and I want to compare the common attributes to see the differences. I have managed to define both querysets with values and I can get the primary attribute fine. The problem is when I am trying to loop through both of the models and get the attribute values and compare them. I have done something like this... {% for i in books.all %} {% if i not in author.all %} {% if i.author_name %} Author Name :{{ i.author_name }}. {% endif %} {% endif %} {% endfor %} The above works. The problem I'm having is when I try to do something like... {% for i in books.all %} {% if i not in author.all %} Author Name :{{ i.author_name }}. {% endif %} {% for j in author.all %} {% if j.publishers.name != i.author_name %} Print Don't Match {% endif %} {% endif %} {% endfor %} I tried the above example and it doesn't produce output. I've confirmed the values are identical, but I can't seem to get the template to show me the attribute differences. I … -
how to create a axios post request using react hooks with a backend framework like django
I have the following React codes using hooks and axios. I am trying to create a post request to "http://127.0.0.1:8000/api/products/create/" endpoint below. Unfortunately, I keep getting 405 (Method Not Allowed) as a response when I press the button submit ProductCreate.js function CompanyCreate() { const [fields, handleFieldChange] = FormFields({ name: "", email: "", }); function handleSubmit(e) { e.preventDefault(); console.log("submitted", fields); let axiosConfig = { headers: { 'content-type': 'application/json', } }; axios.post("http://127.0.0.1:8000/api/products/create/", fields, axiosConfig) .then(response => { console.log("Status", response.status); console.log("Data", response.data); }).catch((error => { console.log("error", error); })); } backend views @api_view(["POST"]) def product_create(request): if request.method == "POST": serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls path("products/create/", views.product_create, name="create_product"), I am not sure why the headers does not seem to work, any help would be appreciated. -
django re_path url not matching values supplied in template
I am trying to match URLs that match var1/integer of any length/var2/single integer between 1 and 5 (inclusive). I have the expression (regex101) below that I know I am trying to convert into URL pattern in Django (var1)\/\d{1,}\/(var2)\/[1-5]$ I am trying to generate URL pattern in urls.py like this: urlpatterns = [ path('admin/', admin.site.urls), re_path(r'(var1)\/<var1_id>\d{1,}\/(var2_id)\/<var2_id>[1-5]', edit, name='url_name'), ] The href value I'm trying to build with it, from template <a href="{% url 'url_name' var1_id=var1.id var2_id=1 %}"> The error I'm getting is Reverse for 'url_name' with keyword arguments '{'var1_id': 1, 'var2_id': 1}' not found. 1 pattern(s) tried: ['(var1)\/<var1_id>\d{1,}\/(var2)\/<var2_id>[1-5]'] How can I make the re work for var1/1/var2/1, for example? -
Getting error on adding class in admin.site.register function
i am getting this error when i try to add ProductoAdmin class in admin.site.register function. from django.contrib import admin from .models import Marca, Producto # Register your models here. class ProductoAdmin(admin.ModelAdmin): list_display = ('nombre', 'precio', 'nuevo', 'marca') list_editable = ["precio"] search_fields = ["nombre"] admin.site.register(Marca) admin.site.register(Producto, ProductoAdmin) Error <class 'app.admin.ProductoAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'nuevo', which is not a callable, an attribute of 'ProductoAdmin', or an attribute or method on 'app.Producto'. -
malti rows in table
hi i want to build table have about 100 empty rows and after created edit it and must 100 rows appear on template how can do it for example i have TAG BLOC in my BAPX telecom and i want to store the data in table the TAG BLOC have 100 empty lines whoever some times line one is busy and line tow is empty and line four is busy so i want to store all line busy and in future can store empty linesenter image description here i want table like this -
Why do I keep getting Class ModelSerializer missing "Meta" attribute?
whenever I try to access the view for my registration serializer I keep getting that I'm missing the Meta attribute even though it's there. I tried making some changes to the code but it doesn't seem to work so it's clearly something I'm missing. Why is this happening? This is the serializer: class UserRegistrationSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) email = serializers.ModelSerializer( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField( required=True, label="Password", style={'input_type': 'password'} ) password_2 = serializers.CharField( required=True, label="Confirm Password", style={'input_type': 'password'} ) class Meta(object): model = User fields = ['username', 'email', 'password', 'password_2',] def validate_password(self, value): if len(value) < 8: raise serializers.ValidationError( "Password should be at least 8 characters long.") return value def validate_password_2(self, value): data = self.get_initial() password = data.get('password') if password != value: raise serializers.ValidationError("Passwords doesn't match.") return value def validate_username(self, value): if User.objects.filter(username=value).exists(): raise serializers.ValidationError("Username already exists.") return value def create(self, validated_data): user_data = { 'username': validated_data.get('username'), 'email' : validated_data.get('email'), 'password': validated_data.get('password'), } user = User.objects.create_user( data=user_data, site=get_current_site(self.context['request']) ) return validated_data -
Why do I keep getting a NoReverse Error in Django 3.2
I know this question has already been asked but none of the solutions are specific to the version of Django that I am using, which is 3.2. So I am following the Django tutorial and I am getting this error. I am using the generic views in Django just like the tutorial did. Before using generic views everything was working. Do I have to hardcode my views or did I implement the generic views wrong? Internal Server Error: /polls/ Traceback (most recent call last): File "C:\Users\miche\tutorial-env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\miche\tutorial-env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\defaulttags.py", line 312, in render return nodelist.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\defaulttags.py", line 211, in render nodelist.append(node.render_annotated(context)) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 905, in render_annotated return … -
Can't execute my functions out of the fetch function - JavaScript
it's my first JavaScript snippet. I run into the following problem. I'm trying to load serialized with Django Rest Framework data and then render the list of questions and the pagination bar. I also have likeQuestion, PaginationListener and SortingListener functions. In the snippet below I execute likeQuestion, PaginationListener and SortingListener functions within fetch function. It works but since it turns out to be recursive it results in multiple http-requests doubling with every click (actually only SortingListener function behaves this way, PaginationListener - surprisingly don't). I also tried to execute all the three functions out of the fetch function. It doesn't work: when I try to get the elements the html collection is zero length. I tried it with window.addEventListener('DOMContentLoaded', (e) => {}). Still doesn't work. Outside the fetch function it works only with setTimeout. But in this case the PaginationListener works only for the first click. And timeout seems to be not a very good decision. How should I change my code to make it work smoothly? const url = document.getElementById('question-list').dataset.url getQuestionList(url) // Ask.index page loading function getQuestionList(url) { const questionList = document.getElementById('question-list') fetch(url).then(response => response.json()).then(json => { // Questions List loading questionList.innerHTML = '' for(const question of json.results){ date … -
DJANGO for loop to show product images from thumbnails
I have a product detail page with images of the product. The number of images is not fixed, and the images are uploaded using a multi-upload function. This is all working correctly. I am now having problems getting the images to show and be selectable by the user from the thumbnail in the main produce viewer. The images show, but the user can not click on an image thumbnail to show that image in the viewer. The code works if the image locations are hardcoded and for that reason I have not included the javascript that changes the images. Is there a simple pythonic way of doing this in the view or the template. Template.html <section class="shop-banner-area pt-100 pb-70"> <div class="container"> <div class="row"> <div class="col-xl-6 col-lg-6"> <div class="shop-thumb-tab"> <ul class="nav" id="myTab2" role="tablist"> {% for obj in rx %} <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-selected="false"><img src="{{obj.Rx_copy.url}}" alt=""> </a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-selected="false"><img src="{{obj.Rx_Copy.url}}" alt=""></a> </li> {% endfor %} <li class="nav-item"> <a class="nav-link" id="profile-tab2" data-toggle="tab" href="#profile1" role="tab" aria-selected="false"><img src="assets/img/products/pr-33.png" alt=""></a> </li> </ul> </div> <div class="product-details-img mb-30"> <div class="tab-content" id="myTabContent2"> {% for obj in rx %} <div class="tab-pane fade show active" id="home" role="tabpanel">[enter … -
Content of for loop not showing in email
I'm using a HTML template for sending emails. Email is delivering fine except it missed out a part containing for loop which I needed to iterate a nested data from the database. {% for item in data.cart.all %} {{ forloop.counter }} <table class="tg"> <tbody> <tr class="stdfont"> <th class="tg-0lax leftc"> {{ item.item_quantity }} x {{ item.item_name }} </th> <th class="tg-baqh rightc">£{{ item.item_price }}</th> </tr> </tbody> <tbody> <tr> <td class="tg-0lax1 stdfont3">{{ item.item_selection }}</td> <td class="tg-0lax"></td> </tr> </tbody> </table> {% endfor %} Views.py def send_email(request, subject,template,dbclass): subject = request.POST.get('subject', subject) message = request.POST.get('message', 'how are you') from_email = request.POST.get('from_email', 'email') if subject and message and from_email: data = dbclass html_message = render_to_string(template, {'data': data}) try: send_mail(subject, message, from_email, ['email'],html_message=msg_html,) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: return HttpResponse('Make sure all fields are entered and valid.') class CartView(viewsets.ModelViewSet): date_from = datetime.datetime.now() - datetime.timedelta(days=1) queryset = Cart.objects.filter( order_date_time__gte=date_from) serializer_class = CartSerializer lookup_field = 'custom_key' pagination_class = None def create(self, request, *args, **kwargs): response = super(CartView, self).create(request, *args, **kwargs) send_email(request,'Order Confirmed','email/invoice.html',Cart.objects.last()) # sending mail return response If I render the same info, for loop is showing fine there. def check_email(request): data = Cart.objects.last() context = {'data': data} return render(request, 'email/invoice.html', context) I'm not sure … -
How to create a custom template tag that passes in a dictionary of more than one object in django
I want to create a template tag that passes in a dictionary of objects models.py class Notification(models.Models): name = models.CharField() .......... template_tag.py created a template tag that gets all the objects that I want to display from django import template register = template.Library() @register.simple_tag def notifications(): context = {'notifications':Notification.objects.order_by('-date')[:4]} return context The later initiate a forloop that displays the objects {% load template_tag %} {% for obj in notifications %} <a href="">{{ obj.name }}</a> {% endfor %} Hope you get the idea..... -
Are there any updated and working Django in line editing packages?
And if not, is there an easy way to implement this? The editing would also save to the database as well. I've checked out https://djangopackages.org/ and none of them seem to be updated and working with Django 3.0+.