Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django uWSGI unresponsive after period of inactivity
I have deployed a Python Django REST API using uWSGI (new to it) in a container. The API responds to requests as expected when tested. But if there is no activity for a couple of days and then later I send a request, I receive no response despite running service. Attaching Dockerfile, uwsgi.ini and entrypoint.sh for your reference. uwsgi.ini [uwsgi] strict = True http = :XXXX master = True enable-threads = True wsgi-file = OCR_django/wsgi.py http-timeout = 1200 die-on-term = True auto-procname = True procname-prefix = "rf_invoice " memory-report = True cheaper-algo = spare cheaper = 2 cheaper-initial = 2 workers = 32 cheaper-step = 2 cheaper-overload = 10 dockerfile -
How to create multiple selection checkbox using model field values?
I am trying to create multiple selection checkbox from model field values and pass the selections to view. Is there any appropriate method to do this? -
Saving Django ModelForms
I am using the modelForms to have a user/ a staff apply for leave but am unable to save the form into the db using the code below. Views.py: @login_required def ApplyLeave(request): if request.method == 'POST': form = ApplyLeaveForm(request.POST, instance=request.user) if form.is_valid(): leave = form.save(commit=False) messages.success(request, f'Submitted successfully') leave.staff = request.user.username leave.save() return redirect('/') else: form = ApplyLeaveForm(instance=request.user) context = {'form': form, } return render(request, 'apply-leave.html', context) -
python: i am trying to solve below question
class Order_ListAPIView(APIView): def get(self,request,format=None): totalData=[] if request.method == 'GET': cur,conn = connection() order_query = ''' SELECT * FROM orders''' order_detail_query = ''' SELECT * FROM order_details''' with conn.cursor(MySQLdb.cursors.DictCursor) as cursor: cursor.execute(order_detail_query) order_detail_result = cursor.fetchall() order_detail_data = list(order_detail_result) # print(order_detail_data) cursor.execute(order_query) order_result = cursor.fetchall() order_data = list(order_result) dic = {} for d in order_detail_data: if d['order_id'] not in dic: dic[d['order_id']] = [] dic[d['order_id']].append(d) order_data.append(dic) totalData.append({"order_data":order_data, }) return Response({"totalData":totalData,},status=status.HTTP_200_OK) else: return Response(status=status.HTTP_400_BAD_REQUEST) output: { "totalData": [ { "order_data": [ { "order_id": 1, "user_id": 4, "billing_shipping_id": 5, "payment_method_id": 1, "delivery_id": 2, "txnid": "584ffb7fd622eca10a6d", "order_no": "1-1583152683-0005", "delivery_amount": 0.0, "discount_amount": 0.0, "order_total": 1.0, "payment_status": "Paid", "created_datetime": "2020-03-02T18:09:27", "updated_datetime": "2020-03-02T12:39:27", "status": "Active", "mihpayid": "9956109007", "payuMoneyId": "306043618" }, { "order_id": 2, "user_id": 11, "billing_shipping_id": 19, "payment_method_id": 2, "delivery_id": 2, "txnid": "", "order_no": "1-1583152785-0010", "delivery_amount": 0.0, "discount_amount": 0.0, "order_total": 1.0, "payment_status": "Unpaid", "created_datetime": "2020-03-02T18:09:45", "updated_datetime": "2020-03-02T12:39:45", "status": "Active", "mihpayid": "", "payuMoneyId": "" }, { "order_id": 3, "user_id": 12, "billing_shipping_id": 20, "payment_method_id": 1, "delivery_id": 2, "txnid": "83e066ca75437f3d05b0", "order_no": "2-1583152964-0019", "delivery_amount": 0.0, "discount_amount": 0.0, "order_total": 2.0, "payment_status": "Paid", "created_datetime": "2020-03-02T18:13:43", "updated_datetime": "2020-03-02T12:43:43", "status": "Active", "mihpayid": "9956136979", "payuMoneyId": "306044826" }, { "1": [ { "order_detail_id": 1, "order_id": 1, "user_id": 4, "product_id": 229, "product_size_id": 982, "size_id": 2, "qty": 1, "product_price": 1.0, "order_item_status": … -
How Make a feature join course in Django 3
I have a "courses" model, and I want to make a join course feature, if the join will already be saved in my course, can anyone help? from django.db import models from django.urls import reverse class Course(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) description = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('courses:detail', kwargs={'slug': self.slug}) @property def lessons(self): return self.lesson_set.all().order_by('position') class Lesson(models.Model): slug = models.SlugField() title = models.CharField(max_length=120) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) position = models.IntegerField() video_url = models.CharField(max_length=200) thumbnail = models.ImageField() def __str__(self): return self.title def get_absolute_url(self): return reverse('courses:lesson-detail', kwargs={ 'course_slug': self.course.slug, 'lesson_slug': self.slug }) from django.shortcuts import render from django.views.generic import ListView, DetailView,View from .models import Course, Lesson # Create your views here. class CourseListView(ListView): model = Course class CourseDetailView(DetailView): model = Course class LessonDetailView(View): def get(self,request,course_slug,lesson_slug, *args,**kwargs): course_qs = Course.objects.filter(slug=course_slug) if course_qs.exists(): course = course_qs.first() lesson_qs = course.lessons.filter(slug=lesson_slug) if lesson_qs.exists(): lesson = lesson_qs.first() context = { 'object' : None } context = {'object': lesson} return render(request, "courses/lesson_detail.html",context) from django.urls import path from .views import CourseListView, CourseDetailView,LessonDetailView app_name = 'courses' urlpatterns = [ path('',CourseListView.as_view(),name='list'), path('<slug>',CourseDetailView.as_view(),name='detail'), path('<course_slug>/<lesson_slug>',LessonDetailView.as_view(),name='lesson-detail') ] I have made courses along with lessons, I want users to be able to save their courses and save them … -
Django, keeps redirecting to the wrong page
So I'm trying to make a payment page which I did but I'm having an issue when you click on the button "Submit Payment" It's supposed to send you back to the home page while also displaying a message. I have tried multiple solutions but I can't figure out where the part is that tells it to redirect to the page called /payment Here's my code; class PaymentView(View): def get(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) context = { 'order': order } return render(self.request, "payment.html", context) def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.get_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="eur", source=token ) # create the payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.get_total() payment.save() # assign the payment to the order order.ordered = True order.payment = payment order.save() messages.success(self.request, "Your order was successful!") return redirect("/") except stripe.error.CardError as e: body = e.json_body err = body.get('error', {}) messages.error(self.request, f"{err.get('message')}") return redirect("/") except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly messages.error(self.request, "Rate limit error") return redirect("/") except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API messages.error(self.request, "Invalid parameters") … -
Django - Image isn't getting saved into the upload_to folder when done through view, but image is uploaded when uploaded through the admin page
I created an edit profile page along with its view to add a profile picture and other details, the image is somehow not getting saved in the folder mentioned in the model. But when I try the same through Django admin it works, and the image gets stored in the mentioned location. Note: I do have the enctype="multipart/form-data" in the form. **views.py** image = request.FILES.get('fileupload') user = request.user user_exists = Users.objects.filter(phone=user) if user_exists: data = UserProfile.objects.filter(user_id=user) if data: data.update( image=image, ) return redirect('/users/edit') else: data_create = UserProfile.objects.create( image=image,user_id=user ) data_create.save() return redirect('/users/edit') else: return redirect('/users/edit') **models.py** image = models.ImageField(upload_to='user/%Y/%m/%d') **settings.py** MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '/media') **urls.py** ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = format_suffix_patterns(urlpatterns) -
Checking a particular group in suit config django
I am trying to check if the user has the group called patients in the suit config. So what i understood is basically when we give permissions for a label it act as an OR condition. So in my case, either the user should be part of any of the below listed access upload.access_patients_data superuser patients So i have tried with the above two, but when i added patients group for a user the link is not visible. {'label': 'Upload Patients Details', 'url': '/admin/patients/upload_patients_data/', 'permissions': ('upload.access_patients_data', 'user.superuser', 'user.group.name == patients')}, i have a basic knowledge that user.group is a collection, so is there any method that i can check like array.includes in js . So if the user has either of any of three the user can see the link. How can i achieve this any help is appreciated -
Django-q Scheduled task
Im trying to run scheduled task using Django-q I followed the docs but its not running heres my config CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'db_cache_table', } } Q_CLUSTER = { 'name': 'DjangORM', 'workers': 4, 'timeout': 90, 'retry': 120, 'queue_limit': 50, 'bulk': 10, 'orm': 'default' } heres my scheduled task Nothin is executing, please help -
How to use DurationField in django
This is models.py class Exams(models.Model): timeDuration = models.DurationField(null=True, blank=True) but when I go to admin I get this error this is the picture of the error Can someone please help me, I am a beginner in django. Thankyou! -
How to use django queryset through javaScript?
I have a queryset queryset = Model.objects.all() initially i used {% for data in queryset %} {% endfor %} How to write javascript code for the same? -
Retrieve items from Many-to-Many relationship in Django query
Models.py class SalesOrderItems(models.Model): item = models.ForeignKey(MasterItems, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=0) class SalesOrder(models.Model): delivery_method_choice = (('Full-Truck Load', 'Full-Truck Load'), ('Part-Truck Load', 'Part-Truck Load')) status_choices = (('On Hold', 'On Hold'),('Ready to Dispatch', 'Ready to Dispatch'),('Dispatched', 'Dispatched')) owner = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='so_owner') client = models.ForeignKey(MasterClient, on_delete=models.CASCADE, related_name='so_client') reference_no = models.CharField(max_length=500, blank=True, null=True) date = models.DateField(default=datetime.date.today) shipment_date = models.DateField(default=datetime.date.today) delivery_method = models.CharField(max_length=500, default='Full-Truck Load', choices=delivery_method_choice) items = models.ManyToManyField(SalesOrderItems, related_name='items_so', blank=True, null=True) status = models.CharField(max_length=500, default='On Hold', choices=status_choices) origin = models.CharField(max_length=255) destination = models.CharField(max_length=255) I want to retrieve the items of a particular sales order by django query My attempt to get the items: items = [] for i in sales_orders: so = SalesOrder.objects.filter(pk=i)[0] print("items",so.items) Output: items classroom.SalesOrderItems.None How can I get the list of items in a particular SalesOrder ?? -
Django : Register or load { % block content % } tag in HTML
I am trying to extend my templates . base_layout.html: {% load static from staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Articles</title> <link rel = "stylesheet" href = "{% static 'styles.css' %}"> </head> <body> <div class="wrapper"> {% block content %} {% endblock %} </div> </body> </html> article_list.html: {% extends 'base_layout.html' %} {% block content %} <h1>Article List</h1> <div class = "articles"> {% for article in articles %} <div class = "article"> <h2><a href = "#">{{ article.title}}</a></h2> <p>{{ article.body }}</p> <p>{{ article.date }}</p> </div> {% endfor %} </div> {% endblock %} When i run this i am getting the error like this: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 11: 'blockcontent'. Did you forget to register or load this tag? What mistake am i doing? -
How to display in html the student name not the foreignkey
Good day everyone, I hope the title is enough for you guys to understand what my problem is, i have this code in my views.py def corevalues(request): coregradelevel = request.GET.get('coregradelevel') teacher = request.GET.get('teacher') corevalues = CoreValues.objects.all().order_by('Display_Sequence') corevaluesdescription = CoreValuesDescription.objects.values('Description').distinct('Description').order_by('Description') corevaluesperiod = CoreValuesDescription.objects.all().order_by('Display_Sequence') print(corevaluesperiod) gradelevel = EducationLevel.objects.filter(id__in = coregradelevel).distinct().order_by('id') studentcorevalues = StudentsCoreValuesDescription.objects.filter(Teacher = teacher).filter(GradeLevel__in = gradelevel.values_list('id'))\ .values('Students_Enrollment_Records').distinct('Students_Enrollment_Records').order_by('Students_Enrollment_Records') student = StudentSubjectGrade.objects.filter(Teacher = teacher).filter(GradeLevel__in = gradelevel.values_list('id'))\ .values('Students_Enrollment_Records').distinct('Students_Enrollment_Records').order_by('Students_Enrollment_Records') return render(request, 'Homepage/behavior.html',{"studentcorevalues":studentcorevalues,"corevalues":corevalues,"corevaluesdescription":corevaluesdescription,\ "corevaluesperiod":corevaluesperiod,"student":student}) from this line student = StudentSubjectGrade.objects.filter(Teacher = teacher).filter(GradeLevel__in = gradelevel.values_list('id'))\ .values('Students_Enrollment_Records').distinct('Students_Enrollment_Records').order_by('Students_Enrollment_Records') i filter and distinct the name of the student to remove the duplicate data, but when i display it to my html , the result is bad result it display the foriegnkey not the name of the student even my html is {% for student in student %} <tr> <td>{{student.Students_Enrollment_Records}}</td> <td></td> <td></td> <td></td> <td></td> </tr> {% endfor %} -
Which video format is best for all type of browser?
Iam working in a django application with video uploading in server. I need to stream a video in browser on a button click. Iam using the below code, <video style="background-color: #efefef;" controls> <source src="{{ url }}" type='video/mp4'> Your browser does not support the video tag. </video> where the {{url}} comes from views.py, The code is , def get(self, request): video_name = 'demo.mp4' video_url = settings.MEDIA_URL + video_name if video_url: return render(request, "videostream.html", {"url": video_url}) Can anyone please suggest the video format which supports for all the browsers such as safari, firefox, chrome, internet explorer etc.? Thanks in advance.. -
Django - dbbackup - What does this mean?
(venv) don@ip$ python manage.py shell Traceback (most recent call last): File "manage.py", line 26, in <module> main() File "manage.py", line 22, in main execute_from_command_line(sys.argv) File "/home/don/VA-boutique/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/don/VA-boutique/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/don/VA-boutique/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/don/VA-boutique/venv/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/don/VA-boutique/venv/lib/python3.6/site-packages/dbbackup/apps.py", line 15, in ready from dbbackup import checks File "/home/don/VA-boutique/venv/lib/python3.6/site-packages/dbbackup/checks.py", line 3, in <module> from django.utils.six import string_types ModuleNotFoundError: No module named 'django.utils.six' (venv) don@ip$ django-admin version 3.0.3 (venv) don@ip$ python -V Python 3.6.9 Hi, I'm new to django. I've just deployed my first django app. Everything worked well until I installed django-dbbackup. Don't understand what's happening... Try to access website page: 502 Bad Gateway nginx/1.14.0 (Ubuntu) is the warning on the page... -
Problem with login Forbidden (403) CSRF verification failed. Request aborted
I have a problem that so far I have not been able to solve. I have a login in django but when I try to login the first time it takes a long time and the Forbidden (403) CSRF verification failed. Request aborted. If I go back he will be logged in. My users are never able to log into my system at first. Is there any way to resolve this? Ps.: Django 2.2 I am using <form> {% csrf_token %} </form> -
Pass data from multiple forms into 1 form for review in Django?
I want to create a Django "review" form that takes user input from several other forms, prints those inputs out for the user to review, then submit the "review" form with the collated data to a server. How could I get started doing this? -
Select latest entry of ForeignKey and return as nested object with Django ORM
I'm trying to return a query via the Django ORM that results in this object: [ ..., { "id": 1, "product_id": 1, "created_at": "2020-03-03T03:34:59.275941Z", "updated_at": "2020-03-03T03:34:59.291653Z", "latest_comment": { "comment": "Leaving a comment", "author": { "id": 1, "name": "John Lennon", "profile": { "avatar": null } }, "updated_at": "2020-03-03T03:34:59.329229Z" } } ] I have the following models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to="avatar", blank=True) created_at = models.DateTimeField(default=timezone.now) updated_at = AutoDateTimeField(default=timezone.now) class Product(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(default=timezone.now) updated_at = AutoDateTimeField(default=timezone.now) class Note(models.Model): product = models.ForeignKey(Product, related_name="notes", on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) updated_at = AutoDateTimeField(default=timezone.now) class Comment(models.Model): note = models.ForeignKey(Note, related_name="comments", on_delete=models.CASCADE) comment = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) updated_at = AutoDateTimeField(default=timezone.now) class Meta: get_latest_by = "updated_at" I've been able to achieve the structure above with the following code, but it introduces the N + 1 problem. product = Product.objects.get(id=1) notes = [] for note in product.notes.all(): try: note.latest_comment = note.comments.latest() except ObjectDoesNotExist: note.latest_comment = None notes.append(note) I've been playing around with prefetch_related as well as annotations with the Max function without much success. I've also been able to write a raw query that can reproduce this using some Postgres and the json_build_object function. The reason I'm … -
How to customize django admin login form class with full compatibility with default django admin
How are you doing? So, I've been working on some Django admin customizations and I'm currently working on the customization for the login page. To enable this I've followed this guide from docs and my admin is currently working with my custom AuthenticationForm! The problem is that the internal Django apps, like authentication and authorization that use Django admin to display data disappeared from my CustomAdminSite. Is there a way to override the Django default AuthenticationForm without the need to override the whole admin site system? Or is there a way to register the internal Django apps, like the one for authentication and authorization, on my custom admin site? -
Debugging Dockerized Django Application Using PyCharm
I'm running a dockerized Django application using the Mac terminal and then trying to debug it using PyCharm. Is it possible to do this or do I have to run the application from within PyCharm for it to be available for debugging? Any help would be greatly appreciated. Thanks. -
How to create relationships between django models
I have the two models, One is the User model and the other is a Contact model. The Contact model is as follows: class Contact(models.Model): pass user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.CASCADE, verbose_name=_('User'), related_name="user") contact = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.CASCADE, verbose_name=_('Contact'), related_name="contact") created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) is_contact = models.BooleanField(default=False) Basically, what is does is create a contact for a user. Kind of a friend request and accept simple model. So the loggedIn user(request.user) could be either the contact.user or contact.contact. And the settings.AUTH_USER_MODEL is a CustomUser model: class CustomUser(AbstractUser): pass email = models.EmailField(unique=True) first_name = models.CharField(max_length=20, default="", blank=True) last_name = models.CharField(max_length=20, default="", blank=True) How can I create a relationship, where I can get a users contact by doing something like this: // get user contacts user=CustomUser.objects.get(pk=1) user.contacts.objects.all() -
Read data from cache in Django Admin Changelist View
I want to read data from cache in Django admin changelist view. But I notice that ChangeList is using QuerySet and read data from database. I was wondering if there is a way to custom Changlist view to make it read from cache? -
Django code not working for following scripts
following queries not working : data = replypost.objects.annotate( appreciate=Count(Case( When( review__userlikes='1', then='1' ), output_field=IntegerField() )), varygood=Count(Case( When( review__userlikes='2', then='1' ), output_field=IntegerField() )), good=Count(Case( When( review__userlikes='3', then='1' ), output_field=IntegerField() )) ) -
How to update two models using one serializer
I am facing one issue for updating models using django serializer. Here is my models: class User(models.Model): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class UserProfile(AuditFields): user = models.ForeignKey(User, on_delete=models.CASCADE) designation = models.CharField(max_length=200, blank=True) contact_number = models.CharField(max_length=20, blank=True) team = models.CharField(max_length=200, blank=True) manager = models.CharField(max_length=200, blank=True) joining_date = models.DateField(default=datetime.now) I need to create a serializer for editing profile details of the current user This is my serializer. But it is a modelserializer so only getting the detauls from the User Profile table only class ProfileSerializer(ModelSerializer): class Meta: model = UserProfile fields = '__all__' extra_kwargs = {'user': {'required': False}} How can I edit first_name , last_name from User table and using same serializer and save it. I am using UpdateAPIView for updating the details Here is my view for reference . class ProfileUpdateView(UpdateAPIView): def get_queryset(self, *args, **kwargs): queryset_list = UserProfile.objects.filter( user=self.request.user) return queryset_list serializer_class = ProfileSerializer