Django Vanilla Views: Beautifully Simple Class-based Views.

Django Vanilla Views

Beautifully simple class-based views.

View --+------------------------- RedirectView
       |
       +-- GenericView -------+-- TemplateView
       |                      |
       |                      +-- FormView
       |
       +-- GenericModelView --+-- ListView
                              |
                              +-- DetailView
                              |
                              +-- CreateView
                              |
                              +-- UpdateView
                              |
                              +-- DeleteView

Django's generic class-based view implementation is unnecessarily complicated.

Django vanilla views gives you exactly the same functionality, in a vastly simplified, easier-to-use package, including:

  • No mixin classes.
  • No calls to super().
  • A sane class hierarchy.
  • A stripped down API.
  • Simpler method implementations, with less magical behavior.

Remember, even though the API has been greatly simplified, everything you're able to do with Django's existing implementation is also supported in django-vanilla-views. Although note that the package does not yet include the date based generic views.

If you believe you've found some behavior in Django's generic class-based views that can't also be trivially achieved in django-vanilla-views, then please open a ticket, and we'll treat it as a bug. To review the full set of API differences between the two implementations, please see the migration guide for the base views, and the model views.

For further background, the original release announcement for django-vanilla-views is available here. There are also slides to a talk 'Design by minimalism' which introduces django-vanilla-views and was presented at the Django User Group, London. You can also view the Django class hierarchy for the same set of views that django-vanilla-views provides, here.

Helping you to code smarter

Django Vanilla Views isn't just easier to use. I'd contest that because it presents fewer points of API to override, you'll also end up writing better, more maintainable code as a result. You'll be working from a smaller set of repeated patterns throughout your projects, and with a much more obvious flow control in your views.

As an example, a custom view implemented against Django's CreateView class might typically look something like this:

from django.views.generic import CreateView

class AccountCreateView(CreateView):
    model = Account

    def get_success_url(self):
        return self.object.account_activated_url()

    def get_form_class(self):
        if self.request.user.is_staff:
            return AdminAccountForm
        return AccountForm

    def get_form_kwargs(self):
        kwargs = super(AccountCreateView, self).get_form_kwargs()
        kwargs['owner'] = self.request.user
        return kwargs

    def form_valid(self, form):
        send_activation_email(self.request.user)
        return super(AccountCreateView, self).form_valid(form)

Writing the same code with django-vanilla-views, you'd instead arrive at a simpler, more concise, and more direct style:

from vanilla import CreateView
from django.http import HttpResponseRedirect

class AccountCreateView(CreateView):
    model = Account

    def get_form(self, data=None, files=None, **kwargs):
        user = self.request.user
        if user.is_staff:
            return AdminAccountForm(data, files, owner=user, **kwargs)
        return AccountForm(data, files, owner=user, **kwargs)

    def form_valid(self, form):
        send_activation_email(self.request.user)
        account = form.save()
        return HttpResponseRedirect(account.account_activated_url())

Requirements

  • Django: 2.2, 3.0, 3.1, 3.2
  • Python: 3.6, 3.7, 3.8, 3.9

Installation

Install using pip.

pip install django-vanilla-views

Usage

Import and use the views.

from vanilla import ListView, DetailView

For example:

from django.core.urlresolvers import reverse_lazy
from example.notes.models import Note
from vanilla import CreateView, DeleteView, ListView, UpdateView

class ListNotes(ListView):
    model = Note


class CreateNote(CreateView):
    model = Note
    success_url = reverse_lazy('list_notes')


class EditNote(UpdateView):
    model = Note
    success_url = reverse_lazy('list_notes')


class DeleteNote(DeleteView):
    model = Note
    success_url = reverse_lazy('list_notes')

Compare and contrast

To help give you an idea of the relative complexity of django-vanilla-views against Django's existing implementations, let's compare the two.

Inheritance hierarchy, Vanilla style.

The inheritance hierarchy of the views in django-vanilla-views is trivial, making it easy to figure out the control flow in the view.

CreateView --> GenericModelView --> View

Total number of source files: 1 (model_views.py)

Inheritance hierarchy, Django style.

Here's the corresponding inheritance hiearchy in Django's implementation of CreateView.

             +--> SingleObjectTemplateResponseMixin --> TemplateResponseMixin
             |
CreateView --+                     +--> ProcessFormView --> View
             |                     |
             +--> BaseCreateView --+
                                   |                     +--> FormMixin ----------+
                                   +--> ModelFormMixin --+                        +--> ContextMixin
                                                         +--> SingleObjectMixin --+

Total number of source files: 3 (edit.py, detail.py, base.py)


Calling hierarchy, Vanilla style.

Let's take a look at the calling hierarchy when making an HTTP GET request to CreateView.

CreateView.get()
|
+--> GenericModelView.get_form()
|    |
|    +--> GenericModelView.get_form_class()
|
+--> GenericModelView.get_context_data()
|    |
|    +--> GenericModelView.get_context_object_name()
|
+--> GenericModelView.render_to_response()
     |
     +--> GenericModelView.get_template_names()

Total number of code statements covered: ~40

Calling hierarchy, Django style.

Here's the equivalent calling hierarchy in Django's CreateView implementation.

BaseCreateView.get()
|
+--> ProcessFormView.get()
     |
     +--> ModelFormMixin.get_form_class()
     |    |
     |    +--> SingleObjectMixin.get_queryset()
     |
     +--> FormMixin.get_form()
     |    |
     |    +--> ModelFormMixin.get_form_kwargs()
     |    |    |
     |    |    +--> FormMixin.get_form_kwargs()
     |    |
     |    +--> FormMixin.get_prefix()
     |    |
     |    +--> FormMixin.get_initial()
     |
     +--> ModelFormMixin.get_context_data()
     |    |
     |    +--> SingleObjectMixin.get_context_object_name()
     |    |
     |    +--> SingleObjectMixin.get_context_data()
     |         |
     |         +--> SingleObjectMixin.get_context_object_name()
     |         |
     |         +--> ContextMixin.get_context_data()
     |
     +--> TemplateResponseMixin.render_to_response()
          |
          +--> SingleObjectTemplateResponseMixin.get_template_names()
          |
          +--> TemplateResponseMixin.get_template_names()

Total number of code statements covered: ~70

Example project

This repository includes an example project in the example directory.

You can run the example locally by following these steps:

git clone git://github.com/tomchristie/django-vanilla-views.git
cd django-vanilla-views/example

# Create a clean virtualenv environment and install Django
virtualenv env
source env/bin/activate
pip install django

# Ensure the local copy of the 'vanilla' package is on our path
export PYTHONPATH=..:.

# Run the project
python ./manage.py migrate
python ./manage.py runserver

Open a browser and navigate to http://127.0.0.1:8000.

Once you've added a few notes you should see something like the following:

image

Please see the documentation at django-vanilla-views.org.


Author: encode
Source Code: https://github.com/encode/django-vanilla-views
License: BSD-2-Clause License

#django 

What is GEEK

Buddha Community

Django Vanilla Views: Beautifully Simple Class-based Views.
Lawrence  Lesch

Lawrence Lesch

1662107520

Superdom: Better and Simpler ES6 DOM Manipulation

Superdom

You have dom. It has all the DOM virtually within it. Use that power:

// Fetch all the page links
let links = dom.a.href;

// Links open in a new tab
dom.a.target = '_blank';

Only for modern browsers

Getting started

Simply use the CDN via unpkg.com:

<script src="https://unpkg.com/superdom@1"></script>

Or use npm or bower:

npm|bower install superdom --save

Select

It always returns an array with the matched elements. Get all the elements that match the selector:

// Simple element selector into an array
let allLinks = dom.a;

// Loop straight on the selection
dom.a.forEach(link => { ... });

// Combined selector
let importantLinks = dom['a.important'];

There are also some predetermined elements, such as id, class and attr:

// Select HTML Elements by id:
let main = dom.id.main;

// by class:
let buttons = dom.class.button;

// or by attribute:
let targeted = dom.attr.target;
let targeted = dom.attr['target="_blank"'];

Generate

Use it as a function or a tagged template literal to generate DOM fragments:

// Not a typo; tagged template literals
let link = dom`<a href="https://google.com/">Google</a>`;

// It is the same as
let link = dom('<a href="https://google.com/">Google</a>');

Delete elements

Delete a piece of the DOM

// Delete all of the elements with the class .google
delete dom.class.google;   // Is this an ad-block rule?

Attributes

You can easily manipulate attributes right from the dom node. There are some aliases that share the syntax of the attributes such as html and text (aliases for innerHTML and textContent). There are others that travel through the dom such as parent (alias for parentNode) and children. Finally, class behaves differently as explained below.

Get attributes

The fetching will always return an array with the element for each of the matched nodes (or undefined if not there):

// Retrieve all the urls from the page
let urls = dom.a.href;     // #attr-list
  // ['https://google.com', 'https://facebook.com/', ...]

// Get an array of the h2 contents (alias of innerHTML)
let h2s = dom.h2.html;     // #attr-alias
  // ['Level 2 header', 'Another level 2 header', ...]

// Get whether any of the attributes has the value "_blank"
let hasBlank = dom.class.cta.target._blank;    // #attr-value
  // true/false

You also use these:

  • html (alias of innerHTML): retrieve a list of the htmls
  • text (alias of textContent): retrieve a list of the htmls
  • parent (alias of parentNode): travel up one level
  • children: travel down one level

Set attributes

// Set target="_blank" to all links
dom.a.target = '_blank';     // #attr-set
dom.class.tableofcontents.html = `
  <ul class="tableofcontents">
    ${dom.h2.map(h2 => `
      <li>
        <a href="#${h2.id}">
          ${h2.innerHTML}
        </a>
      </li>
    `).join('')}
  </ul>
`;

Remove an attribute

To delete an attribute use the delete keyword:

// Remove all urls from the page
delete dom.a.href;

// Remove all ids
delete dom.a.id;

Classes

It provides an easy way to manipulate the classes.

Get classes

To retrieve whether a particular class is present or not:

// Get an array with true/false for a single class
let isTest = dom.a.class.test;     // #class-one

For a general method to retrieve all classes you can do:

// Get a list of the classes of each matched element
let arrays = dom.a.class;     // #class-arrays
  // [['important'], ['button', 'cta'], ...]

// If you want a plain list with all of the classes:
let flatten = dom.a.class._flat;     // #class-flat
  // ['important', 'button', 'cta', ...]

// And if you just want an string with space-separated classes:
let text = dom.a.class._text;     // #class-text
  // 'important button cta ...'

Add a class

// Add the class 'test' (different ways)
dom.a.class.test = true;    // #class-make-true
dom.a.class = 'test';       // #class-push

Remove a class

// Remove the class 'test'
dom.a.class.test = false;    // #class-make-false

Manipulate

Did we say it returns a simple array?

dom.a.forEach(link => link.innerHTML = 'I am a link');

But what an interesting array it is; indeed we are also proxy'ing it so you can manipulate its sub-elements straight from the selector:

// Replace all of the link's html with 'I am a link'
dom.a.html = 'I am a link';

Of course we might want to manipulate them dynamically depending on the current value. Just pass it a function:

// Append ' ^_^' to all of the links in the page
dom.a.html = html => html + ' ^_^';

// Same as this:
dom.a.forEach(link => link.innerHTML = link.innerHTML + ' ^_^');

Note: this won't work dom.a.html += ' ^_^'; for more than 1 match (for reasons)

Or get into genetics to manipulate the attributes:

dom.a.attr.target = '_blank';

// Only to external sites:
let isOwnPage = el => /^https?\:\/\/mypage\.com/.test(el.getAttribute('href'));
dom.a.attr.target = (prev, i, element) => isOwnPage(element) ? '' : '_blank';

Events

You can also handle and trigger events:

// Handle click events for all <a>
dom.a.on.click = e => ...;

// Trigger click event for all <a>
dom.a.trigger.click;

Testing

We are using Jest as a Grunt task for testing. Install Jest and run in the terminal:

grunt watch

Download Details:

Author: franciscop
Source Code: https://github.com/franciscop/superdom 
License: MIT license

#javascript #es6 #dom 

Ahebwe  Oscar

Ahebwe Oscar

1620177818

Django admin full Customization step by step

Welcome to my blog , hey everyone in this article you learn how to customize the Django app and view in the article you will know how to register  and unregister  models from the admin view how to add filtering how to add a custom input field, and a button that triggers an action on all objects and even how to change the look of your app and page using the Django suit package let’s get started.

Database

Custom Titles of Django Admin

Exclude in Django Admin

Fields in Django Admin

#django #create super user django #customize django admin dashboard #django admin #django admin custom field display #django admin customization #django admin full customization #django admin interface #django admin register all models #django customization

Ahebwe  Oscar

Ahebwe Oscar

1620185280

How model queries work in Django

How model queries work in Django

Welcome to my blog, hey everyone in this article we are going to be working with queries in Django so for any web app that you build your going to want to write a query so you can retrieve information from your database so in this article I’ll be showing you all the different ways that you can write queries and it should cover about 90% of the cases that you’ll have when you’re writing your code the other 10% depend on your specific use case you may have to get more complicated but for the most part what I cover in this article should be able to help you so let’s start with the model that I have I’ve already created it.

**Read More : **How to make Chatbot in Python.

Read More : Django Admin Full Customization step by step

let’s just get into this diagram that I made so in here:

django queries aboutDescribe each parameter in Django querset

we’re making a simple query for the myModel table so we want to pull out all the information in the database so we have this variable which is gonna hold a return value and we have our myModel models so this is simply the myModel model name so whatever you named your model just make sure you specify that and we’re gonna access the objects attribute once we get that object’s attribute we can simply use the all method and this will return all the information in the database so we’re gonna start with all and then we will go into getting single items filtering that data and go to our command prompt.

Here and we’ll actually start making our queries from here to do this let’s just go ahead and run** Python manage.py shell** and I am in my project file so make sure you’re in there when you start and what this does is it gives us an interactive shell to actually start working with our data so this is a lot like the Python shell but because we did manage.py it allows us to do things a Django way and actually query our database now open up the command prompt and let’s go ahead and start making our first queries.

#django #django model queries #django orm #django queries #django query #model django query #model query #query with django

Django Vanilla Views: Beautifully Simple Class-based Views.

Django Vanilla Views

Beautifully simple class-based views.

View --+------------------------- RedirectView
       |
       +-- GenericView -------+-- TemplateView
       |                      |
       |                      +-- FormView
       |
       +-- GenericModelView --+-- ListView
                              |
                              +-- DetailView
                              |
                              +-- CreateView
                              |
                              +-- UpdateView
                              |
                              +-- DeleteView

Django's generic class-based view implementation is unnecessarily complicated.

Django vanilla views gives you exactly the same functionality, in a vastly simplified, easier-to-use package, including:

  • No mixin classes.
  • No calls to super().
  • A sane class hierarchy.
  • A stripped down API.
  • Simpler method implementations, with less magical behavior.

Remember, even though the API has been greatly simplified, everything you're able to do with Django's existing implementation is also supported in django-vanilla-views. Although note that the package does not yet include the date based generic views.

If you believe you've found some behavior in Django's generic class-based views that can't also be trivially achieved in django-vanilla-views, then please open a ticket, and we'll treat it as a bug. To review the full set of API differences between the two implementations, please see the migration guide for the base views, and the model views.

For further background, the original release announcement for django-vanilla-views is available here. There are also slides to a talk 'Design by minimalism' which introduces django-vanilla-views and was presented at the Django User Group, London. You can also view the Django class hierarchy for the same set of views that django-vanilla-views provides, here.

Helping you to code smarter

Django Vanilla Views isn't just easier to use. I'd contest that because it presents fewer points of API to override, you'll also end up writing better, more maintainable code as a result. You'll be working from a smaller set of repeated patterns throughout your projects, and with a much more obvious flow control in your views.

As an example, a custom view implemented against Django's CreateView class might typically look something like this:

from django.views.generic import CreateView

class AccountCreateView(CreateView):
    model = Account

    def get_success_url(self):
        return self.object.account_activated_url()

    def get_form_class(self):
        if self.request.user.is_staff:
            return AdminAccountForm
        return AccountForm

    def get_form_kwargs(self):
        kwargs = super(AccountCreateView, self).get_form_kwargs()
        kwargs['owner'] = self.request.user
        return kwargs

    def form_valid(self, form):
        send_activation_email(self.request.user)
        return super(AccountCreateView, self).form_valid(form)

Writing the same code with django-vanilla-views, you'd instead arrive at a simpler, more concise, and more direct style:

from vanilla import CreateView
from django.http import HttpResponseRedirect

class AccountCreateView(CreateView):
    model = Account

    def get_form(self, data=None, files=None, **kwargs):
        user = self.request.user
        if user.is_staff:
            return AdminAccountForm(data, files, owner=user, **kwargs)
        return AccountForm(data, files, owner=user, **kwargs)

    def form_valid(self, form):
        send_activation_email(self.request.user)
        account = form.save()
        return HttpResponseRedirect(account.account_activated_url())

Requirements

  • Django: 2.2, 3.0, 3.1, 3.2
  • Python: 3.6, 3.7, 3.8, 3.9

Installation

Install using pip.

pip install django-vanilla-views

Usage

Import and use the views.

from vanilla import ListView, DetailView

For example:

from django.core.urlresolvers import reverse_lazy
from example.notes.models import Note
from vanilla import CreateView, DeleteView, ListView, UpdateView

class ListNotes(ListView):
    model = Note


class CreateNote(CreateView):
    model = Note
    success_url = reverse_lazy('list_notes')


class EditNote(UpdateView):
    model = Note
    success_url = reverse_lazy('list_notes')


class DeleteNote(DeleteView):
    model = Note
    success_url = reverse_lazy('list_notes')

Compare and contrast

To help give you an idea of the relative complexity of django-vanilla-views against Django's existing implementations, let's compare the two.

Inheritance hierarchy, Vanilla style.

The inheritance hierarchy of the views in django-vanilla-views is trivial, making it easy to figure out the control flow in the view.

CreateView --> GenericModelView --> View

Total number of source files: 1 (model_views.py)

Inheritance hierarchy, Django style.

Here's the corresponding inheritance hiearchy in Django's implementation of CreateView.

             +--> SingleObjectTemplateResponseMixin --> TemplateResponseMixin
             |
CreateView --+                     +--> ProcessFormView --> View
             |                     |
             +--> BaseCreateView --+
                                   |                     +--> FormMixin ----------+
                                   +--> ModelFormMixin --+                        +--> ContextMixin
                                                         +--> SingleObjectMixin --+

Total number of source files: 3 (edit.py, detail.py, base.py)


Calling hierarchy, Vanilla style.

Let's take a look at the calling hierarchy when making an HTTP GET request to CreateView.

CreateView.get()
|
+--> GenericModelView.get_form()
|    |
|    +--> GenericModelView.get_form_class()
|
+--> GenericModelView.get_context_data()
|    |
|    +--> GenericModelView.get_context_object_name()
|
+--> GenericModelView.render_to_response()
     |
     +--> GenericModelView.get_template_names()

Total number of code statements covered: ~40

Calling hierarchy, Django style.

Here's the equivalent calling hierarchy in Django's CreateView implementation.

BaseCreateView.get()
|
+--> ProcessFormView.get()
     |
     +--> ModelFormMixin.get_form_class()
     |    |
     |    +--> SingleObjectMixin.get_queryset()
     |
     +--> FormMixin.get_form()
     |    |
     |    +--> ModelFormMixin.get_form_kwargs()
     |    |    |
     |    |    +--> FormMixin.get_form_kwargs()
     |    |
     |    +--> FormMixin.get_prefix()
     |    |
     |    +--> FormMixin.get_initial()
     |
     +--> ModelFormMixin.get_context_data()
     |    |
     |    +--> SingleObjectMixin.get_context_object_name()
     |    |
     |    +--> SingleObjectMixin.get_context_data()
     |         |
     |         +--> SingleObjectMixin.get_context_object_name()
     |         |
     |         +--> ContextMixin.get_context_data()
     |
     +--> TemplateResponseMixin.render_to_response()
          |
          +--> SingleObjectTemplateResponseMixin.get_template_names()
          |
          +--> TemplateResponseMixin.get_template_names()

Total number of code statements covered: ~70

Example project

This repository includes an example project in the example directory.

You can run the example locally by following these steps:

git clone git://github.com/tomchristie/django-vanilla-views.git
cd django-vanilla-views/example

# Create a clean virtualenv environment and install Django
virtualenv env
source env/bin/activate
pip install django

# Ensure the local copy of the 'vanilla' package is on our path
export PYTHONPATH=..:.

# Run the project
python ./manage.py migrate
python ./manage.py runserver

Open a browser and navigate to http://127.0.0.1:8000.

Once you've added a few notes you should see something like the following:

image

Please see the documentation at django-vanilla-views.org.


Author: encode
Source Code: https://github.com/encode/django-vanilla-views
License: BSD-2-Clause License

#django 

Yashi Tyagi

1617449307

CA Classes - Best CA Classes Online

Chartered Accountancy course requires mental focus & discipline, coaching for CA Foundation, CA Inter and CA Finals are omnipresent, and some of the best faculty’s classes have moved online, in this blog, we are going to give the best way to find online videos lectures, various online websites provide the CA lectures, Smartnstudy one of the best site to CA preparation, here all faculty’s video lecture available.

check here : ca classes

#ca classes online #ca classes in delhi #ca classes app #ca pendrive classes #ca google drive classes #best ca classes online