Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stripe payment integration, error: does not exist on type 'HTMLElement'
I am integrating Stripe in my Angular 8/Django 3 app. I am so close... Following this doc page Payment Stripe I have already: 1. Set up stripe 2. Created a PaymentIntent object and received the clientSecret key from Stripe API (done on the Django server side) 3. Collected card details by mounting the Stripe Elements to the correct DOM Its the last step #4 "Submitting Payment to Stripe" that I am caught up on. I am currently trying to submit the payment on the client side using the stripe.confirmCardPayment() method. However to do this you are supposed to include the clientSecret. Problem is when I try to do this as shown below I get the error Property 'client_secret' does not exist on type 'HTMLElement'. I am not sure how to pass the clientSecret to that method. I am thinking that I could do step#4 on the backend, but I read that this should be done on the frontend. If i did this I guess i would just essentially build my own form for the card and bind it to an angular value, and then send that to the backend? Any help is appreciated. checkout.component.ts import { Component, OnInit, ChangeDetectorRef,} from … -
Django why models.py class attributes not instance attributes
I am new to Django and Python, so any help to clarify my question would be much appreciated! In models.py, why the attributes are not instance attribute but class attribute. Because I think each of these attributes will be different for each model instance created, so they should be instance attribute. For example: # articles/models.py from django.db import models from django.urls import reverse class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() In the last 2 lines, the title and body I think should be self.title and self.body because they contain information specific to each model instance created, right? If created as a class attribute, all model instances would have the same title and body, which is wrong. -
Django: use of __lte for automatic publication of a post
I'm developing a blog and I'm using this filter for put online the posts automatically: geopost_filter = GeoPost.objects.filter(draft=False, publishing_date__lte=timezone.now()) This filter run in local but doesn't run in production. For put online the post that pass from "it will be published in future" to "it is now online" I must restart the server in production. Why happen this? I can change the post's status using the draft field without problem, both in local than in production. But it seams not possible to publish automatically a post if it is marked as future post. -
How to combine to models in Django view
How do i combine this two model in 1 queryset? class ScheduleOfPayment(models.Model): GradeLevel_Category= models.ForeignKey("gradelevel_category", on_delete=models.CASCADE,blank=True, null=True) Education_Levels = models.ForeignKey(EducationLevel, on_delete=models.CASCADE, blank=True, null=True) Semester = models.ForeignKey("semestral", related_name='+', on_delete=models.CASCADE,blank=True,null=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, on_delete=models.CASCADE, blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.IntegerField(null=True, blank=True) class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True, blank=True) School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True, verbose_name="Track") strands = models.ForeignKey("N_strand", on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, on_delete=models.CASCADE, null=True ,blank=True) Discount_Type = models.ForeignKey(Discount, on_delete=models.CASCADE, null=True,blank=True) Education_Levels = models.ForeignKey(EducationLevel,on_delete=models.CASCADE,blank=True,null=True) Semester = models.ForeignKey("semestral", on_delete=models.CASCADE,blank=True,null=True) I have this code in my views.py I just want to combine the (studentenrollment query) and (scheduleofpayment query) gradelevel = request.GET.get('gradelevel') semester = request.GET.get('semester') payment = request.GET.get('payment') studentenrollment = StudentsEnrollmentRecord.objects.filter(Education_Levels=gradelevel).filter(Semester =semester).filter(Payment_Type=payment) scheduleofpayment = ScheduleOfPayment.objects.filter(Education_Levels=gradelevel).filter(Payment_Type = payment).filter(Semester=semester) and in my html {% for obj **Combination of two queryset**%} {% endfor %} -
Why do errors occur when connecting celery to sending mail with passord_reset?
I am trying to connect celery task to send mail when resetting the password. I use django views (PasswordResetView). I created a form and inherited from PasswordResetForm. Overrided the send_mail method, which sends a message to e-mail class CustomResetPasswordForm(PasswordResetForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form_control'})) def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): send_email_for_reset_password.apply_async(args=[subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name]) I put the send logic in task send_email_for_reset_password def send_email_for_reset_password(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name): """ Send a django.core.mail.EmailMultiAlternatives to `to_email`. """ subject = loader.render_to_string(subject_template_name, context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) body = loader.render_to_string(email_template_name, context) email_message = EmailMultiAlternatives(subject, body, from_email, [to_email]) if html_email_template_name is not None: html_email = loader.render_to_string(html_email_template_name, context) email_message.attach_alternative(html_email, 'text/html') email_message.send() But an error occurs EncodeError at /user/password_reset/ Object of type CustomUser is not JSON serializable Also I only tried email_message.send (), but the error is the same. What am I doing wrong? -
How to combine list and retrieve API views in Django rest framework
I am new to DRF, and was thinking of providing List and Retrieve functionality from a single view. I figured out generic views are the shortest and easiest to handle with, but there isn't any views that allow only list and retrieve functionalities. There is a ListCreateAPIView but I dont want any post data. I guess i can use a mixin, but don't know how. Maybe like this?: class PostView(generics.ListAPIView, mixins.RetrieveModelMixin): queryset = Post.objects.all() serializer_class =myserializer is that the right way? -
how to prevent user to update a post after 24 hours django
i want to prevent the user to update the post after 24 hours from the post date class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title= models.CharField(max_length=50) post = models.TextField(max_length=400) date = models.DateTimeField(auto_now_add=True) edit = models.DateTimeField(auto_now=True) class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' class PostUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView): model = Post form_class = PostForm success_message = "updated successfully" template_name = 'store/create.html' success_url = reverse_lazy('lists') def form_valid(self,form): return super().form_valid(form) i want to let the user only be able to update the post before 24 hours during the Post date thanks -
How to filter the category in Django properly?
I have categories named 'person' in my Django Blog. In my blog, Each post(article) has 1 ~ multiple categories and when I click 1 of those categories, it will show all the posts under that category. However, for some categories especially which has only English Alphabet like 'Steve', shows the same post multiple times. I think using objects.filter has some problem with filtering it but am not sure what exactly the problem is. Do you have any solution for this issue? the below are my codes. models.py class Category(models.Model): person = models.CharField(max_length=20) description = models.TextField() slug = models.SlugField() def __str__(self): return self.person views.py def blog_category(request, category): posts = Post.objects.filter(categories__person__contains=category).order_by( "-created_on" ) context = {"category": category, "posts": posts} return render(request, "blog_category.html", context) -
local variable 'context' referenced before assignment in django
from django.shortcuts import render from main import (models,forms) from django.http import HttpResponseRedirect Create your views here. def index(request): return render (request, 'index.txt') def about(request): return render (request, 'about.txt') def contact(request): contactform = forms.ContactForm() if request.method == "POST": contactform = forms.ContactForm(request.POST) if contactform.is_valid(): contact = contactform.save() return HttpResponseRedirect('/contact') context = { "contactform" : contactform } return render(request, 'contact.txt', context) def post(request): return render (request, 'post.txt') -
Can Django-apps be treated and used as Microservices?
I theoretically know the concept of microservices and know and use the Django-apps. So, Django-apps are there for SOC(separation of concerns) by modularization. And the microservice idea is to bring scalability by breaking whole system into a number of independent systems. So, my confusion and question are Can we treat and make Django-apps as microservices? Or separate projects must be created for that, so as to handle the difference in database and server-deployment?. I hope I have made my question clear. Thanks -
Django Channels Routing with Mulitiple ProtocolTypeRouter
I have 2 different django routings, where one is used along withAuthMiddlewareStack and the other would work with unauthenticated. How do I define both the conditions for auth and unauth consumer URLs: something like this : from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import OriginValidator import chat.routing import dsock.routing application = ProtocolTypeRouter({ 'websocket': OriginValidator( AuthMiddlewareStack( URLRouter( auth.routing.websocket_urlpatterns ) ), ['http://127.0.0.1:8080','localhost','127.0.0.1','dflaws.io'], #https://channels.readthedocs.io/en/latest/topics/security.html ), 'websocket-unauth': URLRouter( un_auth.routing.websocket_urlpatterns ) }) -
Django App Not Working After Deployment to heroku
The App is A Blog Post App That is Working fine Locally But After I Deployed It To Heroku, The App Cannot run. I did more Than a week trying to fix it through the views and models with no success. This Is The Error When Trying To Open The App This My Views.py This The Models.py 1/2 The Models.py 2/2 -
from.is_valid() returns false
I want to save customer entry in my database. I have created a model form and trying to save it. but its not working. Where is the problem for this ? my models.py class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name my forms.py class CustomerEntryForm(ModelForm): class Meta: model = Customer fields = ['name', 'phone', 'email'] my views.py def customer_entry(request): if request.method == 'POST': form = CustomerEntryForm(request.POST) print(form.is_valid()) context = {'form': form} return render(request, 'accounts/entry.html', context) my urls.py urlpatterns = [ path('', views.customer_entry, name="entry"), path('register/', views.registerPage, name="register"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('home/', views.home, name="home"), ] my template <form method="POST" action="{% url 'entry' %}"> {% csrf_token %} <label for="">Name</label><br> <div class="input-group mb-3"> <input type="text" name="name" class="form-control"> </div> <label for="">Phone</label><br> <div class="input-group mb-2"> <input type="text" name="phone" class="form-control" > </div> <label for="">Email</label><br> <div class="input-group mb-2"> <input type="text" name="phone" class="form-control" > </div> <input class="btn login_btn" type="submit" value="save"> </form> -
how to get the values from manytomanyfield of another model in django
There are two models:Client and Event that is used.So Is there any way like i can access and save values in client_members that take only those values that are selected in Client objects. class Client(models.Model): company_name = models.CharField(_("Company name"), max_length=255) members = models.ManyToManyField(to=User,limit_choices_to={"is_staff":True}, blank=True) class Event(models.Model): title = models.CharField(_("Title"), max_length=255) client_members = models.ManyToManyField(to=User, limit_choices_to={"is_staff":False, "is_superuser":False}, related_name='%(class)s_clientmembers') -
Python 'different_locale' bad locale conversion
conditions = [] for i in range(1, 13): with different_locale('lt_LT'): conditions.append(calendar.month_name[i]) Trying to get all months in my native "Lithuanian" language. Result of the code : ['sausis', 'vasaris', 'kovas', 'balandis', 'geguþë', 'birþelis', 'liepa', 'rugpjûtis', 'rugsëjis', 'spalis', 'lapkritis', 'gruodis'] expected result: ['sausis', 'vasaris', 'kovas', 'balandis', 'gegužė', 'birželis', 'liepa', 'rugpjūtis', 'rugsėjis', 'spalis', 'lapkritis', 'gruodis'] Also tried "lt_LT.UTF-8" but got these results : 'gegužÄ\x97', 'birželis' Any ideas why? -
Object of type timedelta is not JSON serializable while using django-celery-beat
This is my first attempt with the celery so there might be some issues. Here I want to create Task Object every 1 minutes in the database so I used django-celery-beat. I want to use custom scheduler class later so for this purpose I used the django-celery-beat package. But I am not getting the results. I used the django form to create the TaskModel object and write a task in tasks.py to run the view every 1 minutes. But it throws this error Exception Type: EncodeError Exception Value: Object of type timedelta is not JSON serializable I started celery in one console with the command $ celery -A proj beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler and started django server in another console with command py manage.py runserver settings.py CELERY_BROKER_URL = 'amqp://localhost' CELERY_BEAT_SCHEDULE = { 'task-first': { 'task': 'scheduler.tasks.create_task', 'schedule': timedelta(minutes=1) }, celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'celery_demo.settings') app = Celery('celery_demo') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # … -
'NoneType' object is not iterable - issue with context in Django
I have this models.py: class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE) event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return "%s" % (self.start_date_time) This is my context_processors.py: def events(request): return { 'next_events': dateEvent.objects.all(), } which is registered in my settings.py: 'OPTIONS': { 'context_processors': [ 'nms_app.context_processors.events' I'm getting TypeError at / 'NoneType' object is not iterable Exception Location: /home/luca/python_ve/lib/python3.8/site-packages/django/template/context.py in bind_template, line 246 /usr/local/lib/python3.8/contextlib.py in __enter__ return next(self.gen) … ▼ Local vars Variable Value self <contextlib._GeneratorContextManager object at 0x7fe90a3e7a90> when visiting any page of my website, and I can't understand why. Can someone help me finding the culprit? I can't see why dateEvent is NoneType; it is populated with valid data. -
Django Models with both same and unique fields
I am working on an inventory management system and am looking to see if I can simplify and reduce the amount of hard coding. This is completely a conceptional question. Say I have two products: Clothing Shoes They share mostly the same fields: Style-ID Brand Name Size They also have some unique fields: Clothing Clothing Category Shoes Shoe Width And some fields which they share, but would have different choices: Age ("Adult", "Children", "Infant" for clothing. "Adult", "GS", "PS", "TS" for shoes) Currently I have two models: "ShoeProduct" and "ClothingProduct", but this seems redundant as they could conceivably share the same datatable and are certainly going to be used in the same functions and manipulated in the same ways. Is there a more efficient way of going about this? (My first thought is one Product model and then field kwargs for the unique fields, but I can't figure out if this is possible in django.) And to clarify, the base case vanilla use for these models is the user would enter data into an html form and once submitted would save this model to the database. Then, as purchase and sales data are fed to the server via various api's, … -
Problem with rq background jobs in Django Heroku
I have Django app which makes lots of different analysis Here is the structure of the view: def analysis(request): making analysis 1 ... making analysis 2 ... making analysis 3 ... ........ making analysis 50 ... return render(request, 'checkapp/shots.html', var) The problem is that all these analysis takes about 1-2 minutes. While development I tested my app locally and it is working fine there. But when I deployed it on Heroku, it turned out, that heroku has 30 sec timeout limit. I was told to use background jobs. I used python RQ. Now the code is def analysis(request): task_1 = q.enqueue(function-1) time.sleep(2) task_1_res = task_fb.result task_2 = q.enqueue(function-2) time.sleep(2) task_2_res = task_3.result task_3 = q.enqueue(function-3) time.sleep(2) task_3_res = task_3.result ..... task_50 = q.enqueue(function-50) time.sleep(2) task_50_res = task_50.result return render(request, 'checkapp/shots.html', var) But I still have the same problem. I have Request timeout error... -
Django duplicates objects after reverse ordering
I'm running into a problem with requests in Django. I have a simple model with several fields include DateTimeField 'event_date'. In a view.py I make a request and return objects from this model: return Event.objects.filter(publish_date__lte=currentTime).order_by('-event_date') And sometimes (I can't see a system) response looks like this: Object5 Object1 Object3 Object2 Object1 (for the second time and where is Object4?) Interesting, if I change ordering to .order_by('event_date') - straight, not reverse, everything is ok: Object1 Object2 Object3 Object4 Object5 What is it? Could this be due to the fact that several objects have the same value of 'event_date' field? -
Show different examples for request body on Swagger with Django
I'm trying to show different examples for different content types in Swagger. I have the following method decorator for the corresponding view: from drf_yasg.utils import swagger_auto_schema from django.utils.decorators import method_decorator from drf_yasg import openapi test_decorator = method_decorator(name='post', decorator=swagger_auto_schema( tags=['Models'], responses={ "200": ModelListSerializer, "400": "Validation Error", "403": "Permission Error", "404": "Not Found Error", }, consumes={'text/plain', 'application/json'} )) I want to be able to receive both 'text/plain' and 'application/json' types and I want to show different examples for each of them. When I added the consumes field, I was able to get a dropdown list for Parameter content type. As far as I understood, it is not possible to give a list or a dictionary for the request_body field. I've seen here in Request and Response Body Examples that in content field, you can define examples. I have tried passing the following to the request_body field: request_body=Schema( type=openapi.TYPE_STRING, example='Test string', content='text/plain' ) request_body=Schema( type=openapi.TYPE_OBJECT, properties={ 'field_1': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'field_2': openapi.Schema(type=openapi.TYPE_STRING, description='string'), }, example={ 'field_1': 'field_1_value', 'field_2': 'field_2_value' }, content='application/json' ) Is there a way to combine them? I'm using: Django==3.0.2 drf_yasg==1.17.0 django-rest-swagger==2.2.0 -
Internal Server Error 500 Django, Value error:/
its leading to internal server error 500 settings.py STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ 'static' ] Internal Server Error: / ValueError at / Missing staticfiles manifest entry for 'images\favicon.ico' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.4 Python Executable: D:\Amtpl project by aman\AMTPL - Copy\env\Scripts\python.exe Python Version: 3.8.0 -
Could not joint two tables with django rest framework
I am trying to join two tables and serialize them as an API. I referred to the docs of the Django rest framework and tried a code. It didn't work. Could not resolve the problem even after may try. I am trying to get a JSON file like { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement'}, {'order': 2, 'title': 'What More Can I Say'}, {'order': 3, 'title': 'Encore'}, ... ], } But what I get is { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', } This is the model file I am using Model File from django.db import models from django.contrib.auth.models import User STATUS_CHOICE = ( ('simple', 'simple'), ('intermediate', 'intermediate'), ) class Quiz(models.Model): quiz_name = models.CharField(max_length=1000) video_id = models.ForeignKey("youtube.Youtube", on_delete=models.CASCADE) questions_count = models.IntegerField(default=0) description = models.CharField(max_length=70, null=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField() pass_mark = models.IntegerField() class Meta: ordering = ['created'] def __str__(self): return self.quiz_name class Category(models.Model): category = models.CharField(max_length=20, choices=STATUS_CHOICE, default='simple') quiz_id = models.ForeignKey(Quiz, on_delete=models.CASCADE) def __str__(self): return self.category class Questions(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.CharField(max_length=1000) mark = models.IntegerField() def __str__(self): return self.question class Choice(models.Model): question = models.ForeignKey(Questions, on_delete=models.CASCADE) choice_1 = models.CharField(max_length=1000) choice_2 = models.CharField(max_length=1000) choice_3 = models.CharField(max_length=1000) choice_4 … -
How to deactivate users using django-allauth?
I am using django cookie cutter and have implemented a way to delete users. I want a second thought on whether it is the correct way to delete users or not. Views.py class UserDeleteView(LoginRequiredMixin, TemplateView): template_name = 'users/user_delete.html' user_delete_view = UserDeleteView.as_view() user_delete.html {% extends "base.html" %} {% load crispy_forms_tags %} {% block title %}{{ user.username }}{% endblock %} {% block content %} <h1>{{ user.username }}</h1> <form class="form-horizontal" method="post" action="{% url 'users:update' %}"> {% csrf_token %} {{ form|crispy }} <div class="control-group"> <div class="controls"> <p>Press delete to delete your profile</p> <button type="submit" class="btn btn-primary">Delete</button> </div> </div> </form> {% endblock %} urls.py from django.urls import path from alife.users.views import ( user_redirect_view, user_update_view, user_detail_view, user_delete_view, ) app_name = "users" urlpatterns = [ path("~redirect/", view=user_redirect_view, name="redirect"), path("~update/", view=user_update_view, name="update"), path("<slug:pk>/", view=user_detail_view, name="detail"), path("delete/<slug:pk>/", view=user_delete_view, name="delete"), ] -
How to add a search bar functionality to all the templates of django?
I am trying to add a search bar in my django site. I added a form in my base template. I have added the functionality to my home view. It is working in the home view. But not in other views. I tried creating a new view but i.e. Is not working too. Please tell me what should I do?