Monday, January 31, 2022

Django security releases issued: 4.0.2, 3.2.12, and 2.2.27

Details are available on the Django project weblog:

https://www.djangoproject.com/weblog/2022/feb/01/security-releases/

Re: how to Display images other than from static folder.

This topic solves your problem .

https://djangocentral.com/managing-media-files-in-django/

Ammar Mohammed
Tel: 0113075979
On 31 Jan 2022, 17:36 +0200, DJANGO DEVELOPER <abubakarbryar@gmail.com>, wrote:
tell me what you want to get as a result? do you want to display multiple images on HTML template?

On Mon, Jan 31, 2022 at 8:27 PM ramsha azhar <ramshaazhar12@gmail.com> wrote:
So guide me the write way ... 

On Mon, 31 Jan 2022, 7:45 pm DJANGO DEVELOPER, <abubakarbryar@gmail.com> wrote:
you are doing it the wrong way. totally the wrong way. I am not being rude.

On Mon, Jan 31, 2022 at 7:42 PM ramsha azhar <ramshaazhar12@gmail.com> wrote:
Gide me Django develpers. I just want to display my pictures that are created each time new.
My mages are created in my project folder, not in the static folder.
how I display images on the HTML page by using the path of my project folder.

views.py

def Image_display(request):
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  filename = 'Tree.jpg'
  filepath = BASE_DIR + '//' + filename
  images = Image.objects.all('filepath')
  return render(request, "xyz.html", {'images': images})

url.py
path('Image_display/', views.Image_display, name="Image_display"),

HTML page
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
 --
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8da245ea-ea90-4730-83c0-accafc93b86bn%40googlegroups.com.
 --
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKPY9p%3DE1FmUc%3Dqqy1tGYBJbimFX873XXSTDndnn4kVUjo3ZWg%40mail.gmail.com.
 --
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMyb2%3DheLgJo5dMxsCgQ8cm%3Dp0px5EHpLr2frYtDowV8mmC%2BbQ%40mail.gmail.com.
 --
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKPY9p%3DOofwq7YrTp%3DWoKyO7mgxVovK2wN3-%3Dm9Ed2zTWZ%2BdAg%40mail.gmail.com.

Re: how to Display images other than from static folder.

i think you want to use MEDIA_URL, see https://learndjango.com/tutorials/django-file-and-image-uploads-tutorial and also check https://docs.djangoproject.com/en/3.2/topics/files/ static files are things like logos, css and maybe some javascript.

On Mon, Jan 31, 2022 at 5:36 PM DJANGO DEVELOPER <abubakarbryar@gmail.com> wrote:
tell me what you want to get as a result? do you want to display multiple images on HTML template?

On Mon, Jan 31, 2022 at 8:27 PM ramsha azhar <ramshaazhar12@gmail.com> wrote:
So guide me the write way ... 

On Mon, 31 Jan 2022, 7:45 pm DJANGO DEVELOPER, <abubakarbryar@gmail.com> wrote:
you are doing it the wrong way. totally the wrong way. I am not being rude.

On Mon, Jan 31, 2022 at 7:42 PM ramsha azhar <ramshaazhar12@gmail.com> wrote:
Gide me Django develpers. I just want to display my pictures that are created each time new.
My mages are created in my project folder, not in the static folder.
how I display images on the HTML page by using the path of my project folder.

views.py

def Image_display(request):
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  filename = 'Tree.jpg'
  filepath = BASE_DIR + '//' + filename
  images = Image.objects.all('filepath')
  return render(request, "xyz.html", {'images': images})

url.py
path('Image_display/', views.Image_display, name="Image_display"),

HTML page
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8da245ea-ea90-4730-83c0-accafc93b86bn%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKPY9p%3DE1FmUc%3Dqqy1tGYBJbimFX873XXSTDndnn4kVUjo3ZWg%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMyb2%3DheLgJo5dMxsCgQ8cm%3Dp0px5EHpLr2frYtDowV8mmC%2BbQ%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKPY9p%3DOofwq7YrTp%3DWoKyO7mgxVovK2wN3-%3Dm9Ed2zTWZ%2BdAg%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CANDnEWee3Dp3B55RFDtwjmcNTz%2BNd%2BrGiufNfv%3DC7%2Bh6KeaYBQ%40mail.gmail.com.

Re: how to Display images other than from static folder.

tell me what you want to get as a result? do you want to display multiple images on HTML template?

On Mon, Jan 31, 2022 at 8:27 PM ramsha azhar <ramshaazhar12@gmail.com> wrote:
So guide me the write way ... 

On Mon, 31 Jan 2022, 7:45 pm DJANGO DEVELOPER, <abubakarbryar@gmail.com> wrote:
you are doing it the wrong way. totally the wrong way. I am not being rude.

On Mon, Jan 31, 2022 at 7:42 PM ramsha azhar <ramshaazhar12@gmail.com> wrote:
Gide me Django develpers. I just want to display my pictures that are created each time new.
My mages are created in my project folder, not in the static folder.
how I display images on the HTML page by using the path of my project folder.

views.py

def Image_display(request):
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  filename = 'Tree.jpg'
  filepath = BASE_DIR + '//' + filename
  images = Image.objects.all('filepath')
  return render(request, "xyz.html", {'images': images})

url.py
path('Image_display/', views.Image_display, name="Image_display"),

HTML page
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8da245ea-ea90-4730-83c0-accafc93b86bn%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKPY9p%3DE1FmUc%3Dqqy1tGYBJbimFX873XXSTDndnn4kVUjo3ZWg%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMyb2%3DheLgJo5dMxsCgQ8cm%3Dp0px5EHpLr2frYtDowV8mmC%2BbQ%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKPY9p%3DOofwq7YrTp%3DWoKyO7mgxVovK2wN3-%3Dm9Ed2zTWZ%2BdAg%40mail.gmail.com.

Re: how to Display images other than from static folder.

So guide me the write way ... 

On Mon, 31 Jan 2022, 7:45 pm DJANGO DEVELOPER, <abubakarbryar@gmail.com> wrote:
you are doing it the wrong way. totally the wrong way. I am not being rude.

On Mon, Jan 31, 2022 at 7:42 PM ramsha azhar <ramshaazhar12@gmail.com> wrote:
Gide me Django develpers. I just want to display my pictures that are created each time new.
My mages are created in my project folder, not in the static folder.
how I display images on the HTML page by using the path of my project folder.

views.py

def Image_display(request):
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  filename = 'Tree.jpg'
  filepath = BASE_DIR + '//' + filename
  images = Image.objects.all('filepath')
  return render(request, "xyz.html", {'images': images})

url.py
path('Image_display/', views.Image_display, name="Image_display"),

HTML page
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8da245ea-ea90-4730-83c0-accafc93b86bn%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKPY9p%3DE1FmUc%3Dqqy1tGYBJbimFX873XXSTDndnn4kVUjo3ZWg%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMyb2%3DheLgJo5dMxsCgQ8cm%3Dp0px5EHpLr2frYtDowV8mmC%2BbQ%40mail.gmail.com.

Re: how to Display images other than from static folder.

you are doing it the wrong way. totally the wrong way. I am not being rude.

On Mon, Jan 31, 2022 at 7:42 PM ramsha azhar <ramshaazhar12@gmail.com> wrote:
Gide me Django develpers. I just want to display my pictures that are created each time new.
My mages are created in my project folder, not in the static folder.
how I display images on the HTML page by using the path of my project folder.

views.py

def Image_display(request):
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  filename = 'Tree.jpg'
  filepath = BASE_DIR + '//' + filename
  images = Image.objects.all('filepath')
  return render(request, "xyz.html", {'images': images})

url.py
path('Image_display/', views.Image_display, name="Image_display"),

HTML page
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8da245ea-ea90-4730-83c0-accafc93b86bn%40googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKPY9p%3DE1FmUc%3Dqqy1tGYBJbimFX873XXSTDndnn4kVUjo3ZWg%40mail.gmail.com.

Secure web app locally

Hello 
In our company I work with, we started developping an app for manage our company, and we affraid our database will stollen, 
I have a question, is there any way to secure our locall web app ?  
have any idea how to secure our Django project, and databases ? 
Is there any way to start running Django project on NAS manager ? 
Thank you for your service, and hope give us an advice 
thank you 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/657680df-696f-4fa2-9ffc-d2c5bd03daabn%40googlegroups.com.

TypeError: 'module' object is not iterable - django 4

Hi 
Team,
 I am getting the above error, it has persisted long enough than at this point i really need help.
I am using pickle to load an ML model, POST to get user input. Below is the error, my urls.py file and the views.py file. 
Any Help will be highly appreciated.

******* Error Message *******

(python10_env) D:\Online Drives\MDigital\CIT-Letures\python10_env\smart_health_consult>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\urls\resolvers.py", line 634, in url_patterns
    iter(patterns)
TypeError: 'module' object is not iterable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner
    self.run()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run
    self._target(*self._args, **self._kwargs)
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run
    self.check(display_num_errors=True)
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\management\base.py", line 438, in check
    all_issues = checks.run_checks(
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 67, in _load_all_namespaces
    namespaces.extend(_load_all_namespaces(pattern, current))
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\Online Drives\MDigital\CIT-Letures\python10_env\lib\site-packages\django\urls\resolvers.py", line 642, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'ml_dp_model.urls' from 'D:\\Online Drives\\MDigital\\CIT-Letures\\python10_env\\smart_health_consult\\ml_dp_model\\urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import.

******************************

****  urls.py  *****
from django.urls import path
from . import views

#from .views import index
#from .views import predict

urlpartterns = [
    path('', views.index, name='index'),    
    path('result.html', views.predict, name='predict')
   
]
******************

********* views.py *********
from django.shortcuts import render
# Testing if context can solve circular refference issue.
from django.template import context
# Model related imports
import pandas as pd #install pandas
import pickle
import numpy as np #  helps to manipulate the data

# Create your views here.
def index(request):
    return render(request, 'index.html')

# importing the models using pickle.
    #Loading Naive Bayes Pickle  Model load method 1
nb_pickle = open('./models_store/final_nb_model.pickel','rb+')
nb_model = pickle.load(nb_pickle)
    #Loading RandomForest Pickle Modal load method 1
rf_pickle = open('./models_store/final_rf_model.pickel', 'rb+')
rf_model = pickle.load(rf_pickle)
    #Loading Scala Vector Machine  Pickle  Model load method 2
svm_model = pickle.load(open('./models_store/final_svm_model.pickel', 'rb+'))

# Disease prediction Function:
def predict(request):
    if request.method=='POST':
        symptom_index = {}
        symptom_index['symptom1'] =float(request.POST.get('symptom1')) # Add data in string format to the dictionary
        symptom_index['symptom2'] =float(request.POST.get('symptom2'))
        symptom_index['symptom3'] =float(request.POST.get('symptom3'))
        user_symptoms = pd.DataFrame({'X':symptom_index}).transpose() #think about changing dictionary to list at this line.
        # Using pickle model() to predict
        nb_prediction = nb_model.predict(user_symptoms)[0]
        rf_prediction = rf_model.predict(user_symptoms)[0]
        svm_prediction = svm_model.predict(user_symptoms)[0]
               
        '''
        Making final prediction by taking mode of all predicitions
        '''
        final_prediction = np.mode([rf_prediction, nb_prediction, svm_prediction])
       
        predicted  =  final_prediction

    return render(request,'result.html',{'results':predicted} )

****************************
 Am running python 3.10  and Django 4.0


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/38397119-dd1a-4824-985e-84ad0311a46dn%40googlegroups.com.

Sunday, January 30, 2022

how to Display images other than from static folder.

Gide me Django develpers. I just want to display my pictures that are created each time new.
My mages are created in my project folder, not in the static folder.
how I display images on the HTML page by using the path of my project folder.

views.py

def Image_display(request):
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  filename = 'Tree.jpg'
  filepath = BASE_DIR + '//' + filename
  images = Image.objects.all('filepath')
  return render(request, "xyz.html", {'images': images})

url.py
path('Image_display/', views.Image_display, name="Image_display"),

HTML page
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">
<img src="/Image_display/" alt="" class="img">

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8da245ea-ea90-4730-83c0-accafc93b86bn%40googlegroups.com.

Re: Perform a join in 5 tables or more than that USIN ORM

from django.db import models
from django.conf import settings
from django.db.models.signals import pre_save
from django.utils.text import slugify
from django.dispatch import receiver
# Create your models here.


class course_categories(models.Model):
deleted_flag = [('y', 'yes'), ('n', 'no')]
category_name = models.CharField(max_length=50, unique=True)
category_slug = models.SlugField(max_length=100, unique=True)
course_categories_code = models.CharField(max_length=7, unique=True)
created_by = models.CharField(max_length=50, null=True, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=50, blank=True, null=True)
modified_date = models.DateTimeField(
auto_now_add=False, blank=True, null=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')

def __str__(self):
return self.category_name


def create_course_category_slug(instance, new_slug=None):

slug = slugify(instance.category_name)
if new_slug is not None:
slug = new_slug
slug = "%s-%s" % (slug, instance.course_categories_code)
qs = course_categories.objects.filter(category_slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" % (slug, qs.first().id)
return create_course_category_slug(instance, new_slug=new_slug)
print("slug", slug)
return slug


@receiver(pre_save, sender=course_categories)
def pre_save_course_categories_receiver(sender, instance, *args, **kwargs):
# if not instance.category_slug:
instance.category_slug = create_course_category_slug(instance)


class courses(models.Model):
deleted_flag = [('y', 'yes'), ('n', 'no')]
course_name = models.CharField(max_length=70)
course_categories = models.ForeignKey(
'course_categories', related_name='courses', on_delete=models.CASCADE)
course_slug = models.SlugField(unique=True)
course_code = models.CharField(max_length=7, unique=True)
created_by = models.CharField(max_length=50, null=True, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=50, blank=True, null=True)
modified_date = models.DateTimeField(
auto_now_add=False, blank=True, null=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')

def __str__(self):
return self.course_name


def create_course_slug(instance, new_slug=None):

slug = slugify(instance.course_name)
if new_slug is not None:
slug = new_slug
slug = "%s-%s" % (slug, instance.course_code)
qs = courses.objects.filter(course_slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" % (slug, qs.first().id)
return create_course_slug(instance, new_slug=new_slug)
print("slug", slug)
return slug


@receiver(pre_save, sender=courses)
def pre_save_course_receiver(sender, instance, *args, **kwargs):
# if not instance.category_slug:
print("course")
instance.course_slug = create_course_slug(instance)


class subcourse(models.Model):
deleted_flag = [('y', 'yes'), ('n', 'no')]
subcourse_name = models.CharField(max_length=50, unique=True)
courses = models.ForeignKey(
'courses', related_name="subcourse", on_delete=models.CASCADE)
subcourse_slug = models.SlugField(unique=True)
subcourse_code = models.CharField(max_length=7, unique=True)
subcourse_short_description = models.CharField(max_length=150, blank=True)
created_by = models.CharField(max_length=50)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=50, blank=True, null=True)
modified_date = models.DateTimeField(
auto_now_add=False, blank=True, null=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')

def __str__(self):
return self.subcourse_name


def create_subcourse_slug(instance, new_slug=None):

slug = slugify(instance.subcourse_name)
if new_slug is not None:
slug = new_slug
slug = "%s-%s" % (slug, instance.subcourse_code)
qs = subcourse.objects.filter(subcourse_slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" % (slug, qs.first().id)
return create_subcourse_slug(instance, new_slug=new_slug)
print("slug", slug)
return slug


@receiver(pre_save, sender=subcourse)
def pre_save_subcourse_receiver(sender, instance, *args, **kwargs):
# if not instance.category_slug:
print("course")
instance.subcourse_slug = create_subcourse_slug(instance)



class course_description(models.Model):
pass
from rest_framework import serializers
from .models import course_categories, courses, subcourse
from course_setup.serializers import MainTopicSerializer

class CourseCategorySerializerRedesign(serializers.ModelSerializer):
value = serializers.IntegerField(source="id")
label = serializers.CharField(source="category_name")

class Meta:
model = course_categories
fields = ('value', 'label')


class SubCourseSerializers(serializers.ModelSerializer):
course_name = serializers.SerializerMethodField(read_only=True)
subcourse_main_topic = MainTopicSerializer(many=True)
class Meta:
model = subcourse
fields = ('id', 'subcourse_name', 'courses', 'subcourse_slug', 'subcourse_code',
'subcourse_short_description', 'courses', 'course_name','subcourse_main_topic')

def get_course_name(self, instance):
return instance.courses.course_name


class CourseSerializerView(serializers.ModelSerializer):
# subcourse = SubcourseSerializerView()

class Meta:
model = courses
fields = ('id', 'course_name', 'course_code', 'course_categories')


class SubcourseSerializerView(serializers.ModelSerializer):
# courses = CourseSerializerView()

class Meta:
model = subcourse
fields = ('id', 'subcourse_name',
'subcourse_code', 'courses')
# depth = 2


class CourseSerializers(serializers.ModelSerializer):
subcourse = SubCourseSerializers(many=True, read_only=True)

class Meta:
model = courses
fields = ('__all__')


class CourseCategorySerializers(serializers.ModelSerializer):
# courses = CourseSerializers(many=True)

class Meta:
model = course_categories
fields = ('id', 'category_name', 'course_categories_code')


class GetCourseCategorySerializer(serializers.ModelSerializer):

class Meta:
model = course_categories
fields = ('id', 'category_name', 'course_categories_code',
'category_slug')


class CourseCategoryTreeSerializer(serializers.ModelSerializer):
courses = serializers.SerializerMethodField('get_children')

def get_children(self, course_categories):
serialized_data = CourseSerializers(course_categories.courses.all(
), many=True, read_only=True, context=self.context)
return serialized_data.data

class Meta:
model = course_categories
fields = ('id', 'category_name', 'course_categories_code',
'category_slug', 'courses')
from dataclasses import fields
from pyexpat import model
from rest_framework import serializers
from .models import subcourse_main_topic,sub_topic,subcourse


class MainTopicSerializer(serializers.ModelSerializer):
class Meta:
model = subcourse_main_topic
fields='_all_'

class SubTopicSerializer(serializers.ModelSerializer):
class Meta:
model = sub_topic
fields='_all_'from django.db import models
from course_category.models import subcourse
from instructors.models import instructor
# Create your models here.
deleted_flag = [('y', 'yes'), ('n', 'no')]
class subcourse_main_topic(models.Model):
subcourse = models.ForeignKey('course_category.subcourse',related_name="subcourse",on_delete=models.CASCADE)
topic_title = models.CharField(max_length=255)
created_by = models.CharField(max_length=100)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=100)
modified_date = models.DateTimeField(auto_now_add=True)
modified_remarks = models.CharField(max_length=255,blank=True,null=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')

class sub_topic(models.Model):
subcourse_main_topic_id = models.ForeignKey('subcourse_main_topic',related_name="subtopic",on_delete=models.CASCADE)
topic_title = models.CharField(max_length=255)
video_url = models.URLField()
preview_status = models.BooleanField(default=False)
resource_url = models.URLField(null=True,blank=True)
instructors = models.ForeignKey('instructors.instructor',related_name="instructors",on_delete=models.CASCADE)
created_by=models.CharField(max_length=70)
created_date = models.DateTimeField(auto_now_add=True)
modified_by = models.CharField(max_length=70,null=True,blank=True)
modified_date = models.DateTimeField(null=True,blank=True)
modified_remarks = models.CharField(max_length=150,null=True,blank=True)
is_deleted_flag = models.CharField(
max_length=1, choices=deleted_flag, default='n')from django.shortcuts import render
import base64
from .serializers import (
CourseCategorySerializers,
GetCourseCategorySerializer,
CourseSerializers,
CourseCategorySerializerRedesign,
CourseCategoryTreeSerializer,
SubCourseSerializers,
CourseSerializerView,
SubcourseSerializerView
)
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.parsers import JSONParser
from .models import course_categories, courses, subcourse
from rest_framework.generics import ListAPIView
from django.db.models import Prefetch
# Create your views here.


@api_view(['GET'],)
def get_all_course_category(request):
result = {
'data': '',
'response': False,
'msg': 'Operation Failed !!'
}
queryset = course_categories.objects.all()
serializer = GetCourseCategorySerializer(queryset, many=True)
print(serializer.data)
# serializer.data['enc_id'] = base64.standard_b64encode(serializer.data.id)
result = {
'data': serializer.data,
'response': True,
'msg': ''
}
# return Response({'course_category': serializer.data})
return Response(result)


@api_view(['POST'])
def create_course_category_serializer(request):
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
if request.method == 'POST':
serializer = CourseCategorySerializers(
data=request.data)
if serializer.is_valid():
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Course category added successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': 'Operation Failed !!',
'type': 'form-error'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'],)
def get_course_category_by_id(request, slug):
# print("slug", slug)
result = {
'data': '',
'response': False,
'msg': 'Operation Failed !!'
}
try:
queryset = course_categories.objects.get(category_slug=slug)
# print("queryset", queryset)
serializer = GetCourseCategorySerializer(queryset, many=False)
result = {
'data': serializer.data,
'response': True,
'msg': ''
}
return Response(result)
except course_categories.DoesNotExist:
result = {
'data': serializer.errors,
'response': False,
'msg': 'Data Doesnot exist !!'
}
return Response(result)


@api_view(['PATCH'])
def update_course_category_serializer(request):
if request.method == "PATCH":
result = {
'data': '',
'response': False,
'msg': 'Operation Failed !!'
}
category_id = request.data['category_id']
try:
category_data = course_categories.objects.get(pk=category_id)
serializer = CourseCategorySerializers(category_data, request.data)
if(serializer.is_valid()):
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Updated Successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': 'Operation Failed !!',
'type': 'form-error'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
except course_categories.DoesNotExist:
result = {
'data': request.data,
'response': False,
'msg': 'Data Doesnot exist !!'
}
return Response(result)


@api_view(['GET', ])
def get_course_category_select(request):
queryset = course_categories.objects.all()
serializer = CourseCategorySerializerRedesign(queryset, many=True)
return Response({'course_category': serializer.data})


@api_view(['GET', ])
def get_all_course(request):
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
queryset = courses.objects.all()
serializer = CourseSerializers(queryset, many=True)
result = {
'data': serializer.data,
'response': True,
'msg': ''
}
return Response(result)


@api_view(['POST', ])
def create_course(request):
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
if request.method == "POST":
serializer = CourseSerializerView(data=request.data)
if (serializer.is_valid()):
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Course Added Successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': ''
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', ])
def get_course_by_id(request, slug):
if request.method == 'GET':
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
try:
print("slug", slug)
getData = courses.objects.get(course_slug=slug)
serializer = CourseSerializers(getData, many=False)

result = {
'data': serializer.data,
'response': True,
'msg': ''
}
return Response(result, status=status.HTTP_200_OK)
except courses.DoesNotExist:
result = {
'data': '',
'response': False,
'msg': 'Data Doesnot exist'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)


@api_view(['PATCH', ])
def edit_course(request):
if request.method == "PATCH":
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
try:
course_id = request.data['course_id']
checkData = courses.objects.get(pk=course_id)
serializer = CourseSerializerView(checkData, request.data)
data = {}
if serializer.is_valid():
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'updated successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': ''
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
except courses.DoesNotExist:
result = {
'data': '',
'response': False,
'msg': 'Data doesnot exist'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', ])
def get_all_sub_course(request):
result = {
'data': '',
'response': False,
'msg': 'Opertaion Failed !!'
}
queryset = subcourse.objects.select_related(
'courses')
serializers = SubCourseSerializers(queryset, many=True)
result = {
'data': serializers.data,
'response': True,
'msg': ''
}
return Response(result, status=status.HTTP_200_OK)


@api_view(['POST', ])
def create_sub_course(request):
result = {
'data': '',
'response': False,
'msg': 'Operation Failed'
}
if request.method == "POST":
serializer = SubcourseSerializerView(data=request.data)
if serializer.is_valid():
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Subcourse created successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': ''
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', ])
def get_sub_course_by_slug(request, slug):
result = {
'data': '',
'response': False,
'msg': 'Operation Failed!!'
}
if request.method == "GET":
try:
data = subcourse.objects.get(subcourse_slug=slug)
serializer = SubCourseSerializers(data, many=False)
result = {
'data': serializer.data,
'response': True,
'msg': ''
}
return Response(result, status=status.HTTP_200_OK)
except subcourse.DoesNotExist:
result = {
'data': '',
'response': False,
'msg': 'Data Doesnot Exist '
}
return Response(result)


@api_view(['PATCH', ])
def edit_subcourse(request):
result = {
'data': '',
'response': False,
'msg': 'Operation Failed !!'
}
if request.method == "PATCH":
try:
subcourse_id = request.data['subcourse_id']
checkData = subcourse.objects.get(pk=subcourse_id)
serializer = SubcourseSerializerView(checkData, data=request.data)
if serializer.is_valid():
serializer.save()
result = {
'data': serializer.data,
'response': True,
'msg': 'Updated Successfully !!'
}
return Response(result, status=status.HTTP_200_OK)
result = {
'data': serializer.errors,
'response': False,
'msg': ''
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)
except subcourse.DoesNotExist:
result = {
'data': request.data,
'response': False,
'msg': 'Data Doesnot exist !!'
}
return Response(result, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', ])
def get_course_tree_view(request):
# queryset = course_categories.objects.prefetch_related('courses')

children = Prefetch(
'courses__subcourse', queryset=subcourse.objects.select_related('courses'))
queryset = course_categories.objects.prefetch_related(children)
serializer = CourseCategoryTreeSerializer(queryset, many=True)

return Response(serializer.data)

here are my models serializers and views and i need a data in tree structure. the function in view file is get_course_tree_view
and rest are the models and serializers I need to join all these tables together to fetch data i was able to do only three joins

On Sun, Jan 30, 2022 at 8:37 PM Sam Chaffy <joezeppe.code@gmail.com> wrote:
Yes you can 

What's your model look like ?

On Sun, Jan 30, 2022 at 7:26 AM narendra...@gmail.com <narendrathapa222@gmail.com> wrote:
hello folks,
 any django ex[ert here, I want to know if anybody can do multiple join more than 5 tables at once using ORM Prefetch,prefetch_related,select_related using any of these or in a different way please ping, or just write over here how can we solve that. i didn't get any clue
help will be appreciated

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a2097a78-1446-4456-83a1-c96059a12a1dn%40googlegroups.com.
--
Oussama Chafiqui

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAPvcp%2BVtMGtBmC5RZNn8k_-6WRhY9UCbMg%3DqjFZDH7dc81%2B%3DCw%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAEtntjVFE24MnzyE27jccambxLm63%3D4C1FH4%3D5Ls3h8mspOcyw%40mail.gmail.com.

Reusable form templates not working in Django 4.0?!

Please find the respective post in the Django Forum

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d1082262-7028-484b-968b-487ea128e59cn%40googlegroups.com.

Perform a join in 5 tables or more than that USIN ORM

hello folks,
 any django ex[ert here, I want to know if anybody can do multiple join more than 5 tables at once using ORM Prefetch,prefetch_related,select_related using any of these or in a different way please ping, or just write over here how can we solve that. i didn't get any clue
help will be appreciated

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a2097a78-1446-4456-83a1-c96059a12a1dn%40googlegroups.com.

Re: Syntax to Generate salary for next month

Or get method if you want to retrieve a single value

On Sun, 30 Jan 2022, 1:45 pm AliHassanRaza Khan, <alihsnrazakhan@gmail.com> wrote:
use filter method 

On Sun, 30 Jan 2022, 4:50 am Feroz Ahmed, <feroz.resh@gmail.com> wrote:

Hi,

I came across the problem, how to generate salary for upcoming month ( records are of month January in db)

 

 

I have records in django db.

Insert of new record

update / delete / hide    of record functions are ok

 

Request your support, to generate the salary for month February (by clicking on generate salary button) see pic2 below.

 

syntax to code in views??

 

model.py

Fields are :    month , cmonth, name, salary

 

* month field is in list format , (values from January to December)

                                                                                          pic1

                                                                                         

 

                                                                                          pic2

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/61f5d2a5.1c69fb81.f300.5a1c%40mx.google.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAD54KQaYkvbm-oki3ijjom13ZSviqyMFs%2ByfznuP3%3DvdNQPMFA%40mail.gmail.com.

Re: Syntax to Generate salary for next month

use filter method 

On Sun, 30 Jan 2022, 4:50 am Feroz Ahmed, <feroz.resh@gmail.com> wrote:

Hi,

I came across the problem, how to generate salary for upcoming month ( records are of month January in db)

 

 

I have records in django db.

Insert of new record

update / delete / hide    of record functions are ok

 

Request your support, to generate the salary for month February (by clicking on generate salary button) see pic2 below.

 

syntax to code in views??

 

model.py

Fields are :    month , cmonth, name, salary

 

* month field is in list format , (values from January to December)

                                                                                          pic1

                                                                                         

 

                                                                                          pic2

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/61f5d2a5.1c69fb81.f300.5a1c%40mx.google.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAD54KQYLH8ROS13ksObkLRd7V8Z3yfK0%3DZ4G0jbuSfe%3D46qoSw%40mail.gmail.com.

Saturday, January 29, 2022

Syntax to Generate salary for next month

Hi,

I came across the problem, how to generate salary for upcoming month ( records are of month January in db)

 

 

I have records in django db.

Insert of new record

update / delete / hide    of record functions are ok

 

Request your support, to generate the salary for month February (by clicking on generate salary button) see pic2 below.

 

syntax to code in views??

 

model.py

Fields are :    month , cmonth, name, salary

 

* month field is in list format , (values from January to December)

                                                                                          pic1

                                                                                         

 

                                                                                          pic2

Re: Download html pages as pdf using headless Chrome


from request.get("https://---") i am getting instance of requests.models.Response, how can i convert it to pdf

On Sat, Jan 29, 2022 at 9:31 PM Vishesh Mangla <manglavishesh64@gmail.com> wrote:
Get the link and cookies from the webdriver and put that in requests.get using request library to download the html on the page.

On Sat, 29 Jan 2022, 21:29 Vishesh Mangla, <manglavishesh64@gmail.com> wrote:
Use requests for that .

On Sat, 29 Jan 2022, 21:28 Aadil Rashid, <aadil10121998@gmail.com> wrote:
Hello Django Family, I came across the problem of downloading HTML pages as pdf using headless chrome, Can anybody here who could please let me know how can I do it or any good resource to follow, it would be appreciable. I am using Django python,
Thank you very much.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAYXZx-Ar-PeKeOLA27TgTwQoct3e9Y1E%2BAPtWyPQMq78EaTNg%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACaE8x5C2dihUH4iapMvu8aqMZFWFfpF6VRPHA%2BEkF5PhDQDJA%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAYXZx-1w-U-LrNM2fG3WzMohXY-PayNCdw53rR2osKM7BNyhw%40mail.gmail.com.

Re: Download html pages as pdf using headless Chrome

Get the link and cookies from the webdriver and put that in requests.get using request library to download the html on the page.

On Sat, 29 Jan 2022, 21:29 Vishesh Mangla, <manglavishesh64@gmail.com> wrote:
Use requests for that .

On Sat, 29 Jan 2022, 21:28 Aadil Rashid, <aadil10121998@gmail.com> wrote:
Hello Django Family, I came across the problem of downloading HTML pages as pdf using headless chrome, Can anybody here who could please let me know how can I do it or any good resource to follow, it would be appreciable. I am using Django python,
Thank you very much.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAYXZx-Ar-PeKeOLA27TgTwQoct3e9Y1E%2BAPtWyPQMq78EaTNg%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACaE8x5C2dihUH4iapMvu8aqMZFWFfpF6VRPHA%2BEkF5PhDQDJA%40mail.gmail.com.

Re: Download html pages as pdf using headless Chrome

Use requests for that .

On Sat, 29 Jan 2022, 21:28 Aadil Rashid, <aadil10121998@gmail.com> wrote:
Hello Django Family, I came across the problem of downloading HTML pages as pdf using headless chrome, Can anybody here who could please let me know how can I do it or any good resource to follow, it would be appreciable. I am using Django python,
Thank you very much.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAYXZx-Ar-PeKeOLA27TgTwQoct3e9Y1E%2BAPtWyPQMq78EaTNg%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACaE8x4R2oyqJGjDPM7t_%2Be4mF52bO%3DZB82AiQd11iYDzDTDQg%40mail.gmail.com.

Download html pages as pdf using headless Chrome

Hello Django Family, I came across the problem of downloading HTML pages as pdf using headless chrome, Can anybody here who could please let me know how can I do it or any good resource to follow, it would be appreciable. I am using Django python,
Thank you very much.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAAYXZx-Ar-PeKeOLA27TgTwQoct3e9Y1E%2BAPtWyPQMq78EaTNg%40mail.gmail.com.

Friday, January 28, 2022

Re: Queryset in settings.py?

The solution I think of for this is to overwrite get_template_names

https://ccbv.co.uk/projects/Django/4.0/django.views.generic.base/TemplateView/#get_template_names

I quickly made a draft implementation (which I couldn't test)


from django.core.exceptions import ImproperlyConfigured
from django.views.generic import TemplateView
from app.models import UserTemplate

class PrependTemplatePathMixin:

    def get_template_names(self):
        """
        Return a list of template names to be used for the request. Must return
        a list. May not be called if render_to_response() is overridden.
        """
        if self.template_name is None:
            raise ImproperlyConfigured(
                "PrependTemplatePathMixin requires either a definition of "
                "'template_name' or an implementation of 'get_template_names()'")
        else:
            user_template = UserTemplate.object.get(
                user_id=self.request.user.pk
            )
            template_namespace = user_template.template_namespace.strip().replace('..', '').lstrip('/')
            template_name = f'{template_namespace}/{self.template_name}'
            return [template_name]


class MyTemplateView(PrependTemplatePathMixin, TemplateView):
    template_name = 'my-template.html'



another option is to use or implement something similar to https://github.com/jazzband/django-dbtemplates/


Em sex., 28 de jan. de 2022 às 20:20, Sebastian Jung <sebastian.jung2@gmail.com> escreveu:
Hello Fabio,

i want that admin can make in database a entry to a field in my own settings model in field standardtemplatepath for example /newtemplate/ in my views.py there are exists a normal CBV Templateview with template_name = 'Testtemplate.html' and in settings.py i have a entry TEMPLATES = [
    {
       
        'DIRS': [
            location('templates'),
        ]}

Now when a endcustomer open this view then this view get template from /templates/newtemplate/Testtemplate.html. How can archive this?

Thank you very much

Am Sa., 29. Jan. 2022 um 00:14 Uhr schrieb Fabio C. Barrionuevo da Luz <bnafta@gmail.com>:
Hi Sebastian, I guess this is not possible.

But the real question is: why do you need a queryset to perform in the settings?

Perhaps if you explain what problem you want to solve, we can give you some options for other possible solutions.



Em sex., 28 de jan. de 2022 às 20:00, sebasti...@gmail.com <sebastian.jung2@gmail.com> escreveu:
Hello,

i want to import from a app models.py like this:

from app1.models import classname

then i get:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I want to get a queryset from app1.models.classname in settings.py. How is this possible?

Regards

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/18ef496c-c9a1-40df-b251-7ce2cc2dad82n%40googlegroups.com.


--
Fábio C. Barrionuevo da Luz
Palmas - Tocantins - Brasil - América do Sul


Blog colaborativo sobre Python e tecnologias Relacionadas, mantido totalmente no https://github.com/pythonclub/pythonclub.github.io .

Todos são livres para publicar. É só fazer fork, escrever sua postagem e mandar o pull-request. Leia mais sobre como publicar em README.md e contributing.md.
Regra básica de postagem:
"Você" acha interessante? É útil para "você"? Pode ser utilizado com Python ou é útil para quem usa Python? Está esperando o que? Publica logo, que estou louco para ler...

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAPVjvMaWUcpwzWePO3XF%2BtqRP3e-YFH4iE9om8ig2hhTeazN%3DQ%40mail.gmail.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKGT9myirfhUNdMhThSMFwCVStWgpYyFfJUZb6uieD%3Dt%3DMipkA%40mail.gmail.com.


--
Fábio C. Barrionuevo da Luz
Palmas - Tocantins - Brasil - América do Sul


Blog colaborativo sobre Python e tecnologias Relacionadas, mantido totalmente no https://github.com/pythonclub/pythonclub.github.io .

Todos são livres para publicar. É só fazer fork, escrever sua postagem e mandar o pull-request. Leia mais sobre como publicar em README.md e contributing.md.
Regra básica de postagem:
"Você" acha interessante? É útil para "você"? Pode ser utilizado com Python ou é útil para quem usa Python? Está esperando o que? Publica logo, que estou louco para ler...

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAPVjvMa-5LXwnHU8UCTdqQYXwvkvFpGc27tYZk8%2BTLDUZfJ1Rw%40mail.gmail.com.