Codenerix https://codenerix.com/en/ Framework libre Open Source Mon, 10 Feb 2025 05:16:37 +0000 en-US hourly 1 https://wordpress.org/?v=7.1.5 Make a Form field Conditionally Required from another field (also DynamicSelect) https://codenerix.com/en/make-a-form-field-conditionally-required-from-another-field-also-dynamicselect/?utm_source=rss&utm_medium=rss&utm_campaign=make-a-form-field-conditionally-required-from-another-field-also-dynamicselect https://codenerix.com/en/make-a-form-field-conditionally-required-from-another-field-also-dynamicselect/#respond Mon, 12 Aug 2024 20:14:00 +0000 https://codenerix.com/?p=986/ What we are going to explain below is how to link the behaviour of one field to others in a GenModelForm. To set conditional behaviour in your fields, the trade-off is that you must tune the fields using AngularJS code. Since form rendering is not a CPU-bound process, there is no problem with spending a […]

The post Make a Form field Conditionally Required from another field (also DynamicSelect) appeared first on Codenerix.

]]>
What we are going to explain below is how to link the behaviour of one field to others in a GenModelForm.

To set conditional behaviour in your fields, the trade-off is that you must tune the fields using AngularJS code. Since form rendering is not a CPU-bound process, there is no problem with spending a little time rewriting the fields. To do it, we will use a Custom Widget inherited from your desired Form Widget.

Create a custom Widget

In your app, create a file named widgets.py that contains your custom widget OptionaTextArea that inherits from TextArea. So OptionalTextArea will do the same job as TextArea right now:

from django import forms

class OptionalTextArea(forms.widgets.Textarea):
    pass

Override a Widget in your form

Now, let’s replace the default widget with our custom OptionalTextArea. When you need to change the default HTML element used for a form field in a Django ModelForm, you can override the widgets in the form’s Meta class.

  • To define the widgets dictionary, inside the inner Meta class of your GenModelForm, create a widgets dictionary.
  • Map field names to widgets: in this dictionary, map the names of the fields you want to customize to either:
    • An instance of the desired widget class (e.g., OptionalTextarea(attrs={‘cols’: 80, ‘rows’: 20}))
    • The widget class itself (e.g., OptionalTextarea)

Let’s say you have an Author model and want the bio field to be an OptionalTextArea instead of the default TextArea input.

from codenerix.forms import GenModelForm
from myapp.models import Author
from myapp.widgets import OptionalTextArea

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date', 'bio')
        widgets = {
            'bio': OptionalTextArea(attrs={'cols': 80, 'rows': 20}),
        }

In this example, the name bio in the form will now be rendered as an OptionalTextArea with 80 columns and 20 rows.  

Relax the constraints from the GenModelForm

Before writing the solution, we must ensure that your TextField is not mandatory. This can be done inside your model (it will become optional in your form). The main reason is that you are allowing this field not to be filled, so the model should not force us to fill it. In this way, the GenModelForm won’t fail when this field is empty.

Customize the OptionalTextArea widget

Now it is time to work on our OptionalTextArea widget, which is done in 2 steps:

  1. Inherit from TextArea to get the typical behaviour from it.
  2. Override the render() method to request the HTML to the TextArea widget through the super() call and then rewrite the HTML as needed. Take into account that the default front end is written with AngularJS, so any code added must conform to that framework.

The source code will look like:

from django import forms

class OptionalTextArea(forms.widgets.Textarea):

    def render(self, *args, **kwargs):

        # Get html
        html = super().render(*args, **kwargs)

        # Transform html
        html = html.replace(
            " id=",
            "ng-required='(selector_field!=undefined)&&(selector_field==\"ABC")||(isNaN(any_other_field))' "
            "ng-invalid='(this.value==undefined)||(this.value.length<=10) '"
            " id=",
        )

        print(html)  # For debugging

        return html

The code explained

Here, the render method is overridden to customize how the text area is rendered in HTML. This method is responsible for generating the widget’s HTML output.

The html.replace() function modifies the generated HTML. Specifically, it looks for the string ” id=” within the HTML and replaces it with additional AngularJS attributes (ng-required and ng-invalid) followed by ” id=”.
AngularJS Directives:

  • ng-required: this directive dynamically sets the required attribute on the text area based on a condition. The condition here checks if the selector_field is defined and equal to “ABC” or if another field (any_other_field) is not a number (isNaN).
  • ng-invalid: this directive dynamically sets the invalid attribute based on whether the text area’s value is undefined or has a length less than or equal to 10 characters.
  • The ” id=” part of the original HTML is kept intact, so the only change is the insertion of the AngularJS directives before it.

You should also override the clean_field() process on your form to check whether the selector has a specific value. This will ensure that you produce a ValidationError when the OptionalTextArea is empty or doesn’t meet the conditions in the front end.

Debugging the HTML generated

Since AngularJS already render the HTML source code, what you see in the browser may not be what you have returned from the render function. To keep track of your changes and what the browser is getting, you can print out the HTML variable to see its content on the Django console. Comment out this print() when you are done editing.

DynamicSelect

It happens that CODENERIX is coming with StaticSelect, DynamicSelect, MultiStaticSelect and MultiDynamicSelect, which help to produce selectors.

  • StaticSelect and MultiStaticSelect are the usual selectors for which content is sent by the server when the form is rendered. MultiStaticSelect allows several items to be selected; those are rendered using “Chips“.
  • DynamicSelect and MultiDynamicSelect are new selectors that render content in real-time; once you write in the search box, the server items are requested from the server using the introduced text in the search box. Those are very convenient when talking about a massive list of items inside the selectors because they drastically reduce the overload of the server, rendering many items that may not be used. Instead, you can define how they work using GenForeignKey. This particular kind of selector can send the values from other fields to the server when requesting items so the served items are aware of the context of the form (e.g., a select which Cities depend on a Country selector when a Country is selected to one specific Country, the items returned by the Cities DynamicSelect is reduced to those from that Country). This kind of selector can also overwrite the value from other fields in the same form when the item is selected. We can say they work bi-directionally. If you are willing to know how this kind of selector works, please visit: GenForm with Autofill

The post Make a Form field Conditionally Required from another field (also DynamicSelect) appeared first on Codenerix.

]]>
https://codenerix.com/en/make-a-form-field-conditionally-required-from-another-field-also-dynamicselect/feed/ 0
Customizing GenList with custom partials, controllers, filters and so on https://codenerix.com/en/customizing-genlist-with-custom-partials-controllers-filters-and-so-on/?utm_source=rss&utm_medium=rss&utm_campaign=customizing-genlist-with-custom-partials-controllers-filters-and-so-on https://codenerix.com/en/customizing-genlist-with-custom-partials-controllers-filters-and-so-on/#respond Thu, 06 Jun 2024 15:15:52 +0000 https://codenerix.com/?p=952/ You can customize many details of CODENERIX by telling the software to behave one way or the other. In this tutorial, you will learn how to customize GenList results to get improved listing. This is quite common when you want to do new things, like adding buttons to your lists or showing elements in one […]

The post Customizing GenList with custom partials, controllers, filters and so on appeared first on Codenerix.

]]>
You can customize many details of CODENERIX by telling the software to behave one way or the other. In this tutorial, you will learn how to customize GenList results to get improved listing. This is quite common when you want to do new things, like adding buttons to your lists or showing elements in one way or the other. With a lot of tunning, your website can look like this example:

Let’s explain the parts

  • Partials
    • What are they? Partials are essentially snippets of HTML code. They represent reusable chunks of your user interface (UI). Think of them as building blocks for your views.
    • Why use them? Partials promote modularity and maintainability. They help avoid repeating HTML code and make your codebase more organized.
    • How they work: You typically load partials into your main view using AngularJS directives like ng-include or through routing mechanisms.
  • Controllers
    • What are they? Controllers are JavaScript functions that govern the behaviour and data of a specific portion of your AngularJS application (often associated with a particular partial).
    • Why use them? Controllers provide the logic for interacting with your data, handling user input, and updating the view accordingly.
    • How they work: Controllers are linked to parts of your view using the ng-controller d-rective. They have access to a special $scope object, which bridges the controller’s data and the view.
  • The AngularJS App (Module)
    • What is it? The AngularJS app, often called a module, is the container that holds all the pieces of your application together. It defines the dependencies (other modules your app needs) and sets up the overall structure.
    • Why use it? The app module is essential for organizing and bootstrapping your AngularJS application. It provides a way to declare components like controllers, directives, filters, and services.
    • How it works: You create an AngularJS app using the angular.module function. You then use this module to register various components of your application.
  • Filters
    • What are they? Filters are functions that transform or format data before it’s displayed in the view.
    • Why use them? Filters provide a convenient way to make data more readable or visually appealing. For example, you can use filters to format dates, currency, or uppercase text.
    • How they work: You can use filters directly in your templates with the pipe (|) symbol or apply them within controllers or services.
  • Illustrative Example: let’s imagine a simple product listing application.
    • Partial: A product.html partial would contain the HTML for displaying a single product’s details (name, image, price).
    • Controller: A ProductController would fetch product data from a service and make it available to the product.html partial. It might also handle actions like adding a product to a shopping cart.
    • App: The myApp module would bring the partial, controller, and any necessary services together.
    • Filter: A currency filter might format the product’s price into a user-friendly format (e.g., “19.99€”).

Quick HOWTO

Adding a custom partials, controllers and filters to a GenList is quite straight forward since CODENERIX already manage custom files for you. Let’s watch a quick guide and then we will talk in detail:

  1. Let’s imagine that you are working on a “shop” Django project with a “book” app/module which has a model named “page” which contains four fields: “title”, “subtitle”, “isbn” and “qrcode”.
  2. Inside your “book” module folder create a “static/book/” folder that will hold all statics for this module in place. The full path would be “shop/book/static/book/“.
  3. Inside the newly created folder edit a new file named “pages_rows.html“.
  4. Inside “pages_rows.html” write your AngularJS Partial’s code thinking that your $scope contains a “row” element that has all the elements you wrote down in your __fields__() method in your GenList or GenModel, so the file would look like:
    <td>{{row.title|codenerix}}</td>
    <td>{{row.subtitle|codenerix}}</td>
    <td>{{row.isbn|codenerix}}</td>
    <td>{{row.qrcode|qr}}</td>
  5. And you are all set. Everytime that you visit this PageListView(GenList) CODENERIX will render it using your custom “pages_rows.html” so every row will have 4 columns.
  6. Watch out your __fields__() methods, because if you add or reduce the number of fields then you will have to update also your partials files, “pages_rows.html” in this example.

Filters in partials

In the example before we used “codenerix” and “qr” predefined filters to produce a result like this:

CODENERIX already bring some ready to use filters that make life easier, they can be used in __fields__() methods, example:

def __fields__(self, info):
    fields = []
    fields.append(("title", _("Title"))
    fields.append(("subtitle", _("Subtitle"))
    fields.append(("isbn", _("ISBN"))
    fields.append(("qrcode", _("QR"), 100, None, "qr:100"))
    return fields

This will render inside the partial as: “<td>{{row.qrcode|codenerix:qr:100}}</td>” showing an image with a QR in your GenList. Keep an eye on the just inserted “|codenerix” filter to your elements specified in your __fields__() method; this is done automatically; for your custom partials, you will have to add “|codenerix” yourself if desired or any other filter at your will.

Some of the most common filters that you can use inside __fields__() (remember to remove the “codenerix:” prefix) method or inside your custom partials are:

  • codenerix: this is the most important one since it will try to do the most basic job for you, like:
    • Render a ‘–‘ if the content of the field is equal to “null“, “undefined“, or empty string.
    • Render as a ✔ or ❌ for fields that are equal to the string “True” / “False” or “true” / “false“.
    • It also has arguments like:
      • codenerix:bool: will render all results as booleans, ✔ or ❌ if the object evaluates to false or is equal to “null“, “undefined“, or empty string.
      • codenerix:skype: it will render a “tel:” link so the user can click on it to make a call.
      • codenerix:qr: it will render the string as an image of a QR code that it may render disabled if the object is “null”, “undefined”, or empty string. This filter also accepts the following parameters:
        • codenerix:qr:100: being 100, the size of the QR code generated in pixels. At the moment of writing this guide, the filter renders by default using 200px.
      • codenerix:link: it will render as a <a> link; by default, it will render the text wrapped by <a> tags linking to the provided text in the object. For example, for “hello/world” it will render as: <a href=”hello/world”>hello/world</a>
        • codenerix:link:blank: it will add a target=”_blank” to the render result.
        • codenerix:link:icon: it will add a link icon before the text (deprecated).
        • codenerix:link:link: it will add a link icon before the text.
        • codenerix:link:download: it will add a download icon before the text.
        • codenerix:link:onlyicon: it will render only the icon without the text.
        • codenerix:link:download:blank:onlyicon: it will render as a download only without text and with target=”_blank”.
      • codenerix:copytoclipboard: it will copy the text to the clipboard when clicked, it support arguments:
        • codenerix:copytoclipboard:text: it will show a modal window with the provided text.
        • codenerix:copytoclipboard:title:text: itit will show a modal window with the title as a title and the provided text as a body.
        • When using the modal window, it will close after 2 seconds automatically.
      • codenerix:image: it will render as a <img> tag using the input as the path for the image.
        • codenerix:link:styletext: it will render as a <img> tag and add a “style=styletext” with the provided text.
      • codenerix:round: it will round numbers using Math.round()
        • codenerix:round:decimals: it will round to a number of provided decimals.
      • codenerix:money:currency: it will add a suffix or prefix to your number; by default, it will add a “?” at the end if no currency is provided. Available currencies are: “euro“, “dollar“, “pound“, “yuan” and “bitcoin“
  • abs: executes Math.abs() before returning the value.
  • base64_encode: encodes the provided text as a Base 64
  • base64_decode: decodes the provided Base64 string
  • choice_match:needle: visits all the elements from a list of tuples/lists, checking the first element from each element (tuple/list) and checking if it matches the provided needle. It will return the second element from the selected tuple/list, or if not found, it will return the original input with an added character ‘*‘ at the end.
  • cut:wordwise:max:tail: it cuts the string and adds “…” at the end. It cuts at max (returning a sublist of string[0:max]). The argument wordwise may be null or empty and won’t have any effect, but if it is evaluable to true it will cut the string at the last space found so the final string may be shorter than string[0:max]. If tail is defined, tail will be used instead of “…“.
  • default:value: returns the value when the input evaluates to “undefined“, “null” or empty string.
  • highlightRow:search: it highlights the searched string using <mark> tags around the found text.
  • highlightSelect:search:query: it highlights the searched string using <span class=”ui-select-highlight”> tags around the found text if query evaluates to true.
  • htmlToPlaintext: convert any string to a text (usually used to display HTML code)
  • length: returns the number of elements that have a dictionary (Strings and Lists already implement lengths)
  • nicenull: it will return “—” if the object evaluates to false otherwise it will return the object.
  • round:decimals: it execute Math.round() on the given number with a precision of decimals.
  • split:splitchar:splitindex: split the string using the splitchar and select from the splitted result the element splitindex.
  • strReplace:search:final: find and replace search in the string with final.
  • weekday: given a day of the week it converts to the day of the week word in English (Example: 1 is converted to Monday and 7 to Sunday)

⚠ Remember to remove the “codenerix:” prefix on __fields__() methods. ⚠

Autodiscover for statics

CODENERIX comes with an Autodiscover system for static files that support languages and user profiles. For the example before, CODENERIX will try to find (in this order) the static files it needs to render the website (and it will choose over the existing one before falling to the default ones inside CODENERIX). The best way is to learn how this work by example:

  • Partials:
    1. book/pages_rows.username.es.html
    2. book/pages_rows.username.html
    3. book/pages_rows.admin.es.html
    4. book/pages_rows.admin.html
    5. book/pages_rows.administrator.es.html
    6. book/pages_rows.administrator.html
    7. book/pages_rows.es.html
    8. book/pages_rows.html
    9. < CODENERIX default >
  • Partials (headers):
    1. book/pages_header.username.es.html
    2. book/pages_header.username.html
    3. book/pages_header.admin.es.html
    4. book/pages_header.admin.html
    5. book/pages_header.administrator.es.html
    6. book/pages_header.administrator.html
    7. book/pages_header.es.html
    8. book/pages_header.html
    9. < CODENERIX default >
  • Summary (footer):
    1. book/pages_summary.username.es.html
    2. book/pages_summary.username.html
    3. book/pages_summary.admin.es.html
    4. book/pages_summary.admin.html
    5. book/pages_summary.administrator.es.html
    6. book/pages_summary.administrator.html
    7. book/pages_summary.es.html
    8. book/pages_summary.html
    9. < CODENERIX default >
  • Angular APP definition:
    1. book/pages_app.username.es.js
    2. book/pages_app.username.js
    3. book/pages_app.admin.es.js
    4. book/pages_app.admin.js
    5. book/pages_app.administrator.es.js
    6. book/pages_app.administrator.js
    7. book/pages_app.es.js
    8. book/pages_app.js
    9. < CODENERIX default >
  • Angular Controllers definition:
    1. book/pages_controllers.username.es.js
    2. book/pages_controllers.username.js
    3. book/pages_controllers.admin.es.js
    4. book/pages_controllers.admin.js
    5. book/pages_controllers.administrator.es.js
    6. book/pages_controllers.administrator.js
    7. book/pages_controllers.es.js
    8. book/pages_controllers.js
    9. < CODENERIX default >
  • Angular Filters definitions:
    1. book/pages_filters.username.es.js
    2. book/pages_filters.username.js
    3. book/pages_filters.admin.es.js
    4. book/pages_filters.admin.js
    5. book/pages_filters.administrator.es.js
    6. book/pages_filters.administrator.js
    7. book/pages_filters.es.js
    8. book/pages_filters.js
    9. < CODENERIX default >

🐰Easter egg: The same thing also works on CODENERIX Django templates. 😉

The post Customizing GenList with custom partials, controllers, filters and so on appeared first on Codenerix.

]]>
https://codenerix.com/en/customizing-genlist-with-custom-partials-controllers-filters-and-so-on/feed/ 0
Unlocking Advanced Data Transformation in Django CODENERIX: A Complete Guide https://codenerix.com/en/unlocking-advanced-data-transformation-in-django-codenerix-a-complete-guide/?utm_source=rss&utm_medium=rss&utm_campaign=unlocking-advanced-data-transformation-in-django-codenerix-a-complete-guide https://codenerix.com/en/unlocking-advanced-data-transformation-in-django-codenerix-a-complete-guide/#respond Mon, 25 Mar 2024 13:44:17 +0000 https://codenerix.com/?p=929/ In this guide, we will cover how to transform data or produce new data by calculating existing data, and we will go through the process of building our widgets using AngularJS for a ModelForm. Some of the ways explained here will follow the standard Django way of doing things, while others will follow the CODENERIX way. […]

The post Unlocking Advanced Data Transformation in Django CODENERIX: A Complete Guide appeared first on Codenerix.

]]>
In this guide, we will cover how to transform data or produce new data by calculating existing data, and we will go through the process of building our widgets using AngularJS for a ModelForm. Some of the ways explained here will follow the standard Django way of doing things, while others will follow the CODENERIX way.

When the software grows and matures, we usually need to customize some things better and add newer features over the existing ones. One of the most basic needs is data generation from other fields or data transformation while saving the information in the database.

Producing new data over existing ones is usually a straightforward step. Let’s explore it travelling from the server (backed) to the user (frontend):

1. Overloading the save() method in your model

This is a pretty straightforward backend solution solution. In your model, you create a new save() method that calls to super().save(). This can be done in two ways:

The first one is by modifying data before it gets written to the database:

self save(self):
  # Use existing data to setup the custom field
  self.custom_field = modifier(self.existing_fields)
  # Save and return returned data to keep consistency
  return super().save()

The second one is by modifying data and saving it again; in this way, you can pick up the PK from the object after calling super().save() and use it to recalculate it. (NOTE: if you have to save twice in your save() method, it usually means what you are doing is not a good idea)

self save(self):
  # Save existing data
  super().save()
  # Calculate seed based on the regiter's PK
  self.seed = create_seed_based_on_register_pk(self.pk)
  # Save it again and return returned data to keep consistency
  return super().save()

The third method extends the second one by modifying other models’ data after this one is written to the database. This way, we can pick up the PK from the object after calling super().save() and use it with the other model. A common example of this could be to add the just created object into an existing ManyToMany relationship:

self save(self):
  # Save existing data
  answer = super().save()
  # Lookup for the other object
  other = OtherModel.objects.filter(...).first()
  # Add our selves into the relationship
  other.custom_related_field.add(self)
  # Answer back keeping consistency between calls
  return answer

2. Using Django signals

This is a backend solution based on something that Django implements called signals. They are a great tool in complex scenarios, but keep in mind that they make the code harder to maintain, and those should be used only in situations where the other methods wouldn’t work. Read directly from Django’s documentation how to use signals. https://docs.djangoproject.com/en/5.0/ref/signals/

Signals can be incredibly useful in complex scenarios where different components need to react to events or actions in a decoupled manner. For example, you might want to trigger specific actions whenever a new user registers, a post is created, or an order is placed.

Signals introduce an element of indirection in your code, making it harder to follow the control flow. Since signals allow disparate parts of your application to interact, tracing the logic executed when a signal is triggered can sometimes be challenging. This can lead to difficulties in debugging and maintaining the codebase, especially as the application grows in complexity.

Example of pre_save signal:

from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.template.defaultfilters import slugify

@receiver(pre_save)
def my_callback(sender, instance, *args, **kwargs):
    instance.slug = slugify(instance.title)

Example of post_save signal:

from django.dispatch import receiver
from django.db.models.signals import post_save
from django.contrib.auth.models import User

@receiver(post_save, sender=User)
def create_profile(sender, **kwargs):
    # write you functionality
    pass

3. The clean_<field>() methods at Forms classes

This is a backend solution based on Django clean_() methods.

Django clean_<field>() methods are special methods used within Django form classes to clean and validate individual form fields. They are automatically called during form validation after the respective field’s default validation has been performed.

Here’s how clean_<field>() methods work:

  1. Validation and Cleaning: When you define a form class in Django, each form field gets its method for validation and cleaning. These methods are named clean_<field_name>(), in which <field_name> is replaced by the name of the field.
  2. Execution Order: These methods are executed after the default field validation. Django first checks the field’s built-in validators, and then if there are any clean_<field>() methods, it calls them one by one.
  3. Customized Cleaning Logic: In your form class, you can define these methods to implement custom validation and cleaning logic for individual fields. This is particularly useful when you need to perform complex validation or when the validation depends on the values of multiple fields.
  4. Error Handling: Inside these methods, you can raise a ValidationError if the field’s value doesn’t pass your custom validation criteria. This error can contain a message explaining the reason for the validation failure, which will be displayed to the user.

Here’s a simple example demonstrating the usage of clean_<field>() methods in a Django form:

from django import forms

class MyForm(forms.Form):
    age = forms.IntegerField()

    def clean_age(self):
        age = self.cleaned_data.get('age')
        if age is not None and age < 18:
            raise forms.ValidationError("You must be 18 or older to use this service.")
        return age

In this example, the clean_age() method checks if the provided age is under 18. If it is, it raises a ValidationError with a corresponding error message. Otherwise, it returns the cleaned (validated) value.

Now let’s see how we can use the clean_<field>() methods to rewrite data in another field:

from django import forms

class MyForm(forms.Form):
    start_date = forms.DateField()
    end_date = forms.DateField()

    def clean_start_date(self):
        start_date = self.cleaned_data.get('start_date')
        end_date = self.cleaned_data.get('end_date')

        # Check if start_date is after end_date
        if start_date and end_date and start_date > end_date:
            # If start_date is after end_date, swap the values
            self.cleaned_data['start_date'] = end_date
            self.cleaned_data['end_date'] = start_date

        return start_date

4. Create a custom widget

This is one of the most beautiful approaches because it lets you work with the form from the Angular JS point of view without messing with custom controllers (which is the last point of this manual). This is a frontend solution designed from the backend.

This is usually the best approach when you post-process data in the form (straight inside the browser). You need to know Angular JS programming to go with this solution if you want to make big things, but for simple changes, it is perfectly fine.

Process:

  • Create a widget.py file in your app folder with your CustomWidget:
  • Example of a new Custom field in the frontend (you can inherit from any other Django Field at your convenience) and overload the render() method to replace the HTML created by the original Widget, then you just replace the HTML returned by the original widget. Just print it out while designing to understand what the server is rendering and rewrite it at your convencience.
  • In your forms.py, import your CustomWidget and inside your form class, add a “widgets” attribute which should be a dictionary with the field name as a key and your custom widget as the value. Example: widgets = { “myfield”: MyCustomWidget() }

Example 1: in this example the field will be disabled if some other field is not filled or its value evaluates to False.

class MyCustomWidget(forms.widgets.TextInput):

    def render(self, name, value, attrs=None, renderer=None):
        # Get html
        html = super().render(name, value, attrs, renderer)

        # Transform html to make sure this field is disabled if some other field is not filled
        html = html.replace(
            'type="text"',
            'type="text" min="1" ng-disabled="!some_other_field"',
        )

Example 2: Here is another example that brings a new field (visible only) that will show the maximum points that the program will give when a max number of minutes is defined together with a cost of points_per_minutes:

class MaxMinutes(forms.widgets.NumberInput):

    def render(self, name, value, attrs=None, renderer=None):
        # Get html
        html = super().render(name, value, attrs, renderer)

        # Transform html to configure the field to a fixed minimum value
        html = html.replace(
            'ng-readonly="readonly_max_minutes" ',
            'ng-readonly="readonly_max_minutes" min="0"',
        )

        # Put all together with an extra piece of HTML code that will summarize
        # the maximum points the program will give with those "max_minutes"
        # using "points_per_minute" field configured somewhere else
        html = (
            html
            + """
            <label for="points">Max Points</label>
                <input
                    type="number"
                    class="form-control"
                    ng-readonly="true"
                    min="0"
                    ng-value="max_minutes * points_per_minute">
            """
        )

        # Return result
        return html

If you field is a SelectField there are some specific structure to help you inspect data in it.

5. Overwrite the $scope.submit()

This is a frontend solution and it is actually one of the most difficult approaches because it requires incorporing a custom controller to your form to allow you overwrite methods. This solution happily will give you full control of the system from the AngularJS point of view but you will pay back in complexity.

DISCLAIMER: you need advance knowledge about Angular JS programming to go with this solution.

Basically this solutions is based on overwritting the method submit() in side the $scope of your controller with your one. Please check submit() method inside the desired controller at codenerix.js for more information.

To override the default CODENERIX controllers you have to make use of the following attributed inside your GenList class to override the default ones:

  • ws_entry_point: set ws_entry_point variable to a fixed value
  • static_partial_row: set static_partial_row to a fixed value
  • static_partial_header: set static_partial_header to a fixed value
  • static_partial_summary: set static_partial_summary to a fixed value
  • static_app_row: set static_app_row to a fixed value
  • static_controllers_row: set static_controllers_row to a fixed value
  • static_filters_row: set static_filters_row to a fixed value

Conclusions

In conclusion, this guide comprehensively explores techniques for transforming and generating data within Django applications, encompassing both backend and frontend solutions. It outlines methods such as overloading the save() method, utilizing Django signals, and leveraging clean_<field>() methods for backend data manipulation. Additionally, it highlights frontend approaches, emphasizing the creation of custom widgets and AngularJS integration. While each method offers unique advantages, developers must carefully consider factors like complexity, maintainability, and project requirements when choosing the most suitable approach. Overall, this guide equips developers with the knowledge and tools necessary to enhance data management and customization in CODENERIX Django applications.

The post Unlocking Advanced Data Transformation in Django CODENERIX: A Complete Guide appeared first on Codenerix.

]]>
https://codenerix.com/en/unlocking-advanced-data-transformation-in-django-codenerix-a-complete-guide/feed/ 0
GenForm with Autofill https://codenerix.com/en/genform-with-autofill/?utm_source=rss&utm_medium=rss&utm_campaign=genform-with-autofill https://codenerix.com/en/genform-with-autofill/#respond Sat, 08 Apr 2023 15:59:13 +0000 https://codenerix.com/?p=882/ In this post, we will share with you how to use the autofill feature from CODENERIX GenForm and GenModelForm. If you want to visit the general documentation, please follow this link. What does the autofill feature? This feature helps the developer to interconnect several fields into a dynamic field, giving the user a better experience while using […]

The post GenForm with Autofill appeared first on Codenerix.

]]>
In this post, we will share with you how to use the autofill feature from CODENERIX GenForm and GenModelForm. If you want to visit the general documentation, please follow this link.

What does the autofill feature?

This feature helps the developer to interconnect several fields into a dynamic field, giving the user a better experience while using the ERP.

Imagine that you have “Country“, “Region“, and “City” selectors, and you need to filter one field with the other so the user can choose data from the filtered results of the previous field. It is easier to see it with an example:

  • Let’s say the user selects “Spain” as a “Country“.
  • In the “Region” selector, the user should be able to choose only Spanish Regions and not any region from any other country.
  • The user chooses “Andalusia” from all the Spanish Regions.
  • In the “City” selector again, the user should see only Andalusian cities and not Madrid or Valencia.

The same example can be shown with “Family“, “Category“, and “Subcategory“:

Let’s see what we should expect from the browser:

“Family” (Familia) is a static selector. We choose “Ordenadores (23)“


We click on the dynamic select for “Category” (Categoría), and an XHR request happens


The XHR request included the selected ID from “Family” (Familia), so “Categories” are filtered with this “Family“


In the answer, the information for this selector is coming (including “id” and “label“)


We choose “Portátiles (LAPTOPS)” from the Dynamic Select, and another XHR request happens to refresh data in the selector.


We click on the dynamic select for “Subcategory” (Subcategoría), and an XHR request happens.


The XHR request included the selected ID from “Category” (Category); again, several elements came from the server.


We click on the dynamic select for “Subcategory” (Subcategoría), and an XHR request happens.

We can see in the public ERP example that the autofill feature is cool and can lead to smaller selectors. We actually encourage the usage of Dynamic Selectors over Static Selectors because they can be tuned in a very granular way and lead to smaller answers from the server, reducing the overhead also on the database.

Let’s see how this was configured in CODENERIX

To use the autofill feature, you have to add a “Meta” class to your GenForm or GenModelForm class and declare inside the Meta class a new attribute named “autofill”, and it should look similar to:

autofill = {
    # Search of attr3 based in attr2
    "attr3": ["select", 3, "related_name_foreignkey_url", "attr2"],
    # Search based in its own pk
    "attr5": ["select", 3, "related_name_foreignkey_url", "__pk__"],
    # Search based in his own pk and attr2.
    "attr4": ["select", 3, "related_name_foreignkey_url", "__pk__", "attr2"],
}

Autofill is an attribute designed to fill foreign key attributes with data based on a textbox, any other information from the form or an AngularJS function. The structure is a dictionary with the attribute name as a key and a list as a value which will contain elements using the next format:

  • position[0]: Type of the selector that you need to create:
    • select: shows a box that takes a single choice.
    • multiselect: shows a box which lets you select multiple choices.
  • position[1]: minimum number of letters required in the textbox to start the execution of a search. When this number of chars is reached, the field will start an XHR request to the server querying for data to fill the field. To request all records to choose from, you should write ‘*’.
  • position[2]: Related name of the URL for the GenForeignKey class that will attend the request to fetch the field’s data.
  • position[3-n]: (Optional fields) The rest of the fields are filters used to send the pk (primary key) of a selected attribute. Usually is used to take the value of an attribute and perform the search using it. There are two options for using these filters:
    • attrName: sends the current value, if it exists, from a selected attribute.
    • pk: send the pk (primary key) of the own object.

In our previous examples, the request looked like this:

Request: https://erp.codenerix.com/products/categorys/foreign/*?def=1&filter={“FeatureForm_family”:”1″}

and the autofill field was filled as follows:

class Meta:
	autofill = {
		"FeatureForm_category": [
			"select",
			3,
			"CDNX_products_categorys_foreign",
			"FeatureForm_family"
		]
	}

In action:

  • The software built the URL using the related URL name “CDNX_products_categorys_foreign“.
  • It searched on the click for every register “*“.
  • If we wrote in the search box, the string would be sent if it had 3 characters or more.
  • Example URL for the search “hola” would be: /products/categorys/foreign/hola?def=1&filter={“FeatureForm_family”:”1″}
  • It sent the ID from the selected element in the “Family” selector, which would actually be the pk “1“.

Let’s see how does it look the GenForeignKey class

Following the example before, here is the resulting GenForeignKey class that would answer any request to this field. This is actually one of the most complex GenForeignKey you may build. Under this one, there is a simpler example:

class CategoryForeign(GenCategoryUrl, GenForeignKey):
    model = Category
    label = "{<LANGUAGE_CODE>__name} ({code})"

    def get_foreign(self, queryset, search, filters):
        # Filter with search string
        query = [Q(code__icontains=search), ]
        for lang in settings.LANGUAGES_DATABASES:
            query.append(Q(**{"{}__name__icontains".format(lang.lower()): search}))

        qs = queryset.filter(
            reduce(operator.or_, query)
        )
        family = filters.get('FeatureForm_family', None)
        if family is None:
            family = filters.get('AttributeForm_family', None)
        if family is None:
            family = filters.get('FeatureSpecialForm_family', None)
        if family is None:
            family = filters.get('ProductForm_family', None)
        if family is None:
            family = filters.get('ProductFormCreate_family', None)
        if family is None:
            family = filters.get('ProductFormCreateCustom_family', None)

        if family:
            qs = qs.filter(family__pk=family)

        return qs[:settings.LIMIT_FOREIGNKEY]

This is actually one of the most complex GenForeignKey you may build.

class ProductForeign(GenForeignKey):
    model = Product
    label = "{name}"
    public = True

    def get_foreign(self, queryset, search, filters):
        qsobject = Q(name__icontains=search)
        qs = queryset.filter(qsobject).order_by("name")
        return qs[: settings.LIMIT_FOREIGNKEY]

References

The examples shown in this post were taken from “django-codenerix-products” package reading from forms.py and views.py

Remember to visit:

The post GenForm with Autofill appeared first on Codenerix.

]]>
https://codenerix.com/en/genform-with-autofill/feed/ 0
Elasticsearch, Solr, Whoosh or Xapian in CODENERIX https://codenerix.com/en/elasticsearch-solr-whoosh-or-xapian-in-codenerix/?utm_source=rss&utm_medium=rss&utm_campaign=elasticsearch-solr-whoosh-or-xapian-in-codenerix Sat, 18 Jun 2022 19:30:31 +0000 https://codenerix.com/?p=734/ In this article, you will learn how to enable Elasticsearch, Solr, Whoosh, or Xapian on your CODENERIX website. CODENERIX is ready to work with Search Indexes. For this purpose, it will require you to configure Haystack. Haystack can connect Solr, Elasticsearch, Whoosh, and Xapian to a Django website, and CODENERIX will use those Indexes to improve search speed. For […]

The post Elasticsearch, Solr, Whoosh or Xapian in CODENERIX appeared first on Codenerix.

]]>
In this article, you will learn how to enable Elasticsearch, Solr, Whoosh, or Xapian on your CODENERIX website.

CODENERIX is ready to work with Search Indexes. For this purpose, it will require you to configure Haystack.

Haystack can connect Solr, Elasticsearch, Whoosh, and Xapian to a Django website, and CODENERIX will use those Indexes to improve search speed.

For this tutorial, we will configure Haystack to work together with Elasticsearch:

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'codenerix.contrib.haystack_engines.AsciifoldingElasticSearchEngine',
        'URL': 'http://127.0.0.1:9200/',
        'INDEX_NAME': 'haystack',
    },
}

As you can see, the search engine we are configuring is one of the predefined ones we included in CODENERIX: codenerix.contrib.haystack_engines.AsciifoldingElasticSearchEngine

Remember to add “haystack” to your INSTALLED_APPS as a second step.

And this is all you need to do. Your CODENERIX website is ready to work with Haystack.

Indexes

Now that we have ready our CODENERIX website for Haystack, we will define the desired Indexes.

Inside the folder of any desired app from your CODENERIX project, create a new file named “search_indexes.py” for access to lists. Add inside this file the desired Indexes you want Haystack to manage, for example, from an OCR Document Management Software:

from haystack import indexes
from .models import Document

class Document(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, use_template=True)
    year = indexes.IntegerField(model_attr='year')
    number = indexes.IntegerField(model_attr='number')
    subject = indexes.EdgeNgramField(model_attr='subject')
    date_doc = indexes.DateField(model_attr='date_doc')
    date_input = indexes.DateTimeField(model_attr='date_input')
    sender = indexes.EdgeNgramField(model_attr='sender')
    doc_type = indexes.IntegerField(model_attr='doc_type__pk')
    doc_type__name = indexes.EdgeNgramField(model_attr='doc_type__name')
    total_files = indexes.IntegerField(model_attr='total_files')
    total_documents = indexes.IntegerField(model_attr='total_documents')
    seeker = indexes.EdgeNgramField(model_attr='seeker')

    def get_model(self):
        return Document
    
    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

To let a view work with Haystack, add the following:

haystack = True

to your GenList and voilá, the lists are sped up.

What about the maintenance of Indexes?

Haystack is aware of Indexes and search engines and will keep your Indexes updated so you don’t have to do anything else.

The post Elasticsearch, Solr, Whoosh or Xapian in CODENERIX appeared first on Codenerix.

]]>
CODENERIX API https://codenerix.com/en/codenerix-api/?utm_source=rss&utm_medium=rss&utm_campaign=codenerix-api Sat, 18 Jun 2022 17:43:03 +0000 https://codenerix.com/?p=766/ In this article, you will learn how does work CODENERIX API. Since all the operations between the front and back end are happening through JSON communication, it is easy to think there is a protocol behind all of that. In fact, there is a RESTful API based on JSON to manage everything that is happening […]

The post CODENERIX API appeared first on Codenerix.

]]>
In this article, you will learn how does work CODENERIX API.

Since all the operations between the front and back end are happening through JSON communication, it is easy to think there is a protocol behind all of that. In fact, there is a RESTful API based on JSON to manage everything that is happening inside CODENERIX.

Actually, not everything happens on JSON. Forms are rendered on the server side and verified on the user side, but you can also enable the RESTful API for those.

The explanations below are for public view. If you would like to use those with protected views (the ones requiring a logged-in user), read “CODENERIX Authentication System“.

There are several ways to make CODENERIX work fully as a REST service:

  • Any view can work as a REST service just by enabling the “json” attribute on that view:
    json = True

    GenCreate, GenUpdate, GenDetail, and GenDelete also support “json_details“, which will return extra information about field types, mandatory fields, and restrictions:
    json_details = True
  • Any GET request that specifies that it wants a JSON answer using “force_rest_api=1” as a GET parameter in the URL
  • Any POST request that includes a “json” parameter
  • In GenList, if method json_builder() exists.
  • Any request that includes an HTTP “X-HTTP-REST” header (this is the most comfortable way to use REST)
  • There are basic actions like GET operation on lists that will return JSON naturally

NOTES:

  • POST operations on forms will accept JSON but will answer with a rendered form, except that any of the above is in action.
  • Any request with an ‘x-requested-with‘ parameter set to ‘XMLHttpRequest‘ will be threaded as an XHR request and processed as it is, not as a REST request.

The basic actions you can perform on any URL are mostly based on the nature of that URL. We recommend exploring the XHR panel from your browser to understand what information provides what service.

Valid methods:

  • GenList:
    • GET: get the list of data
    • POST: works as “add“, “create“, or “new“
  • GenDetail:
    • GET: get details from a register
    • PUT: works as an “edit” or “update” operation
    • DELETE: works as a “delete” operation
  • GenDelete:
    • POST: works as a “delete“

Examples

For a table that looks like this:

GenList – GET

An empty GET over a GenList will return exactly that information: [ /geodata/continents ]

{
	"meta": {
		"getval": {},
		"username": "xxxxxxxx",
		"context": {},
		"url_media": "/media/",
		"url_static": "/static/",
		"page": 1,
		"pages": [1],
		"pages_to_bring": 1,
		"linkadd": true,
		"vtable": false,
		"export_excel": true,
		"export_name": "list",
		"ngincludes": {
			"table": "/static/codenerix/partials/table.html"
		},
		"linkedit": true,
		"show_details": true,
		"show_modal": false,
		"search_filter_button": false,
		"request": {
			"path_info": "/geodata/continents",
			"query_string": "authtoken=test&authuser=xxxxxxxx&string=test&force_rest_api=1"
		},
		"version": "0.1",
		"version_api": null,
		"gentranslate": {
			"Add": "A\u00f1adir",
			"Cancel": "Cancelar",
			"Change": "Cambiar",
			"CleanFilters": "Limpiar filtros",
			"Date": "Fecha",
			"Day": "D\u00eda",
			"Delete": "Borrar",
			"Done": "Hecho",
			"Download": "Descargar",
			"Edit": "Editar",
			"Error": "Error",
			"Filters": "Filtros",
			"Go_back": "Volver",
			"Hour": "Hora",
			"Month": "Mes",
			"Minute": "Minuto",
			"PageNumber": "N\u00famero de p\u00e1gina",
			"PleaseWait": "Por favor espere",
			"PrintExcel": "Imprimir en Excel",
			"Save": "Guardar",
			"Save_here": "Guardar aqu\u00ed",
			"Save_and_new": "Guardar y nuevo",
			"Reload": "Recargar",
			"RowsPerPage": "Filas por p\u00e1gina",
			"Search": "Buscar",
			"Second": "Segundo",
			"Time": "Hora",
			"View": "Ver",
			"Warning": "Atenci\u00f3n",
			"Year": "A\u00f1o",
			"registers": "registros"
		},
		"rowsperpage": 50,
		"rowsperpageallowed": {
			"All": "Todos"
		},
		"row_total": 8,
		"row_first": 1,
		"row_last": 8,
		"content_type": null
	},
	"filter": {
		"search": "",
		"date": null,
		"subfilters": [],
		"subfiltersC": [{
			"key": "code",
			"name": "C\u00f3digo",
			"kind": "input",
			"value": null
		}, {
			"key": "es__name",
			"name": "Nombre",
			"kind": "input",
			"value": null
		}]
	},
	"table": {
		"head": {
			"columns": [{
				"id": "code",
				"name": "C\u00f3digo",
				"align": null,
				"type": "CharField"
			}, {
				"id": "es__name",
				"name": "Nombre",
				"align": null,
				"type": "CharField"
			}],
			"ordering": {},
			"datetimeQ": null,
			"extra_fields": {
				"field_check": null,
				"field_delete": false
			}
		},
		"body": [{
			"pk": "1",
			"code": "Eu",
			"es__name": "Europa"
		}, {
			"pk": "2",
			"code": "As",
			"es__name": "Asia"
		}, {
			"pk": "3",
			"code": "Tc",
			"es__name": "Todos los continentes"
		}, {
			"pk": "5",
			"code": "AF",
			"es__name": "\u00c1frica"
		}, {
			"pk": "6",
			"code": "AN",
			"es__name": "Ant\u00e1rtida"
		}, {
			"pk": "7",
			"code": "OC",
			"es__name": "Ocean\u00eda"
		}, {
			"pk": "8",
			"code": "NA",
			"es__name": "Norteam\u00e9rica"
		}, {
			"pk": "9",
			"code": "SA",
			"es__name": "Sudam\u00e9rica"
		}],
		"header": null,
		"summary": null
	}
}

But you may decide to filter the result, and then you would send a request including a “json” parameter in the URL:

The “json” parameter in the URL will look like this: [ /geodata/continents?json=… ]
{
	"listid": 0,
	"search": "",
	"page": 1,
	"pages_to_bring": 1,
	"rowsperpage": 50,
	"filters": {
		"code": null,
		"en__name": "ame"
	},
	"ordering": {
		"en__name": 1
	},
	"year": null,
	"month": null,
	"day": null,
	"hour": null,
	"minute": null,
	"second": null,
	"context": {},
	"search_filter_button": true
}

And the answer would look like this:

{
	"meta": {
		"getval": true,
		"username": "xxxxxxxx",
		"context": {},
		"url_media": "/media/",
		"url_static": "/static/",
		"page": 1,
		"pages": [1],
		"pages_to_bring": 1,
		"linkadd": true,
		"vtable": false,
		"export_excel": true,
		"export_name": "list",
		"ngincludes": {
			"table": "/static/codenerix/partials/table.html"
		},
		"linkedit": true,
		"show_details": true,
		"show_modal": false,
		"search_filter_button": true,
		"request": {
			"path_info": "/geodata/continents",
			"query_string": "json=%7B%22listid%22:0,%22search%22:%22%22,%22page%22:1,%22pages_to_bring%22:1,%22rowsperpage%22:50,%22filters%22:%7B%22code%22:null,%22en__name%22:%22ame%22%7D,%22ordering%22:%7B%22en__name%22:1%7D,%22year%22:null,%22month%22:null,%22day%22:null,%22hour%22:null,%22minute%22:null,%22second%22:null,%22context%22:%7B%7D,%22search_filter_button%22:true%7D"
		},
		"gentranslate": {
			"Add": "A\u00f1adir",
			"Cancel": "Cancelar",
			"Change": "Cambiar",
			"CleanFilters": "Limpiar filtros",
			"Date": "Fecha",
			"Day": "D\u00eda",
			"Delete": "Borrar",
			"Done": "Hecho",
			"Download": "Descargar",
			"Edit": "Editar",
			"Error": "Error",
			"Filters": "Filtros",
			"Go_back": "Volver",
			"Hour": "Hora",
			"Month": "Mes",
			"Minute": "Minuto",
			"PageNumber": "N\u00famero de p\u00e1gina",
			"PleaseWait": "Por favor espere",
			"PrintExcel": "Imprimir en Excel",
			"Save": "Guardar",
			"Save_here": "Guardar aqu\u00ed",
			"Save_and_new": "Guardar y nuevo",
			"Reload": "Recargar",
			"RowsPerPage": "Filas por p\u00e1gina",
			"Search": "Buscar",
			"Second": "Segundo",
			"Time": "Hora",
			"View": "Ver",
			"Warning": "Atenci\u00f3n",
			"Year": "A\u00f1o",
			"registers": "registros"
		},
		"rowsperpage": 50,
		"rowsperpageallowed": {
			"All": "All"
		},
		"row_total": 2,
		"row_first": 1,
		"row_last": 2,
		"content_type": null
	},
	"filter": {
		"search": "",
		"date": null,
		"subfilters": [],
		"subfiltersC": [{
			"key": "code",
			"name": "Code",
			"kind": "input",
			"value": null
		}, {
			"key": "en__name",
			"name": "Name",
			"kind": "input",
			"value": "ame"
		}]
	},
	"table": {
		"head": {
			"columns": [{
				"id": "code",
				"name": "Code",
				"align": null,
				"type": "CharField"
			}, {
				"id": "en__name",
				"name": "Name",
				"align": null,
				"type": "CharField"
			}],
			"ordering": {
				"en__name": 1
			},
			"datetimeQ": null,
			"extra_fields": {
				"field_check": null,
				"field_delete": false
			}
		},
		"body": [{
			"pk": "8",
			"code": "NA",
			"en__name": "North America"
		}, {
			"pk": "9",
			"code": "SA",
			"en__name": "South America"
		}],
		"header": null,
		"summary": null
	}
}

GenDetail – GET

A basic GET over a register with no parameters in the URL: [ /geodata/continents/5 ]

{
	"meta": {
		"gentranslate": {
			"Add": "Añadir",
			"Cancel": "Cancelar",
			"Change": "Cambiar",
			"CleanFilters": "Limpiar filtros",
			"Date": "Fecha",
			"Day": "Día",
			"Delete": "Borrar",
			"Done": "Hecho",
			"Download": "Descargar",
			"Edit": "Editar",
			"Error": "Error",
			"Filters": "Filtros",
			"Go_back": "Volver",
			"Hour": "Hora",
			"Month": "Mes",
			"Minute": "Minuto",
			"PageNumber": "Número de página",
			"PleaseWait": "Por favor espere",
			"PrintExcel": "Imprimir en Excel",
			"Save": "Guardar",
			"Save_here": "Guardar aquí",
			"Save_and_new": "Guardar y nuevo",
			"Reload": "Recargar",
			"RowsPerPage": "Filas por página",
			"Search": "Buscar",
			"Second": "Segundo",
			"Time": "Hora",
			"View": "Ver",
			"Warning": "Atención",
			"Year": "Año",
			"registers": "registros"
		},
		"linkedit": true,
		"linkdelete": true,
		"linkback": true,
		"cannot_delete": null,
		"cannot_update": null,
		"extra_context": {
			"no_render_as_foreign": [],
			"user": "xxxxxxxx",
			"ws_entry_point": "geodata/continents",
			"static_partial_row": "/static/codenerix/partials/rows.html",
			"static_partial_header": null,
			"static_partial_summary": "/static/codenerix/partials/summary.html",
			"static_app_row": "/static/codenerix/js/app.js",
			"static_controllers_row": null,
			"static_filters_row": "/static/codenerix/js/rows.js",
			"field_delete": false,
			"field_check": null,
			"extends_base": "base/base.html",
			"tabs_js": "[]",
			"is_modal_window": false,
			"tabs_autorender": []
		}
	},
	"body": {
		"code": "AF",
		"es__name": "África"
	}
}

GenAdd – GET

A basic GET to add a new element with authjson_details enabled:
[ /geodata/continents/add?authtoken=…&authuser=….&json={}&force_rest_api=1&authjson_details=1 ]

{
	"head": {
		"bound": false,
		"groups": [
			[
				"Details",
				12,
				[
					"code",
					6
				]
			]
		],
		"form_name": "AF8Q903HFSO8RZB"
	},
	"meta": {
		"version": "0.1",
		"version_api": null
	},
	"body": {
		"code": {
			"for": "id_GeoContinentForm_code",
			"type": "char",
			"html_name": "GeoContinentForm_code",
			"value": "",
			"label": "Code",
			"notes": [
				"This field is required.",
				"Ensure this value has at most 2 characters"
			],
			"limits": {
				"max_length": 2,
				"required": true
			}
		},
		"name": {
			"for": "id_ContinentTextFormEN_name",
			"type": "char",
			"html_name": "ContinentTextFormEN_name",
			"value": "",
			"label": "Name",
			"notes": [
				"This field is required.",
				"Ensure this value has at most 100 characters"
			],
			"limits": {
				"max_length": 100,
				"required": true
			}
		}
	}
}

Final

For any questions you may have about the RESTful API, check your browser for extra information and check out how CODENERIX is doing under the hood.

The post CODENERIX API appeared first on Codenerix.

]]>
Authentication system https://codenerix.com/en/authentication-system/?utm_source=rss&utm_medium=rss&utm_campaign=authentication-system Sat, 18 Jun 2022 17:36:51 +0000 https://codenerix.com/?p=738/ In this article, you will learn everything about CODENERIX‘s authentication system. Every request that is getting to CODENERIX is passing through several middlewares, and some of them may be authentication backends. Those authentication backends are used to grant users into the system since some parts of its maybe have limited access. Authentication Before communicating with […]

The post Authentication system appeared first on Codenerix.

]]>
In this article, you will learn everything about CODENERIX‘s authentication system.

Every request that is getting to CODENERIX is passing through several middlewares, and some of them may be authentication backends. Those authentication backends are used to grant users into the system since some parts of its maybe have limited access.

Authentication

Before communicating with the server, you must ensure you have enough rights to resolve the request as expected. Usually, when you work with a front-end, you will use views without permission to process data, so your Anonymous users won’t have problems using the website.

Therefore, if you have an external app that would like to communicate using the API against views that require some permission levels, then you must know that CODENERIX will require a user to be granted into the system. If you do not wish to log in as a user, you must define some Public Views that will do the authentication job on your way (or avoid doing any). Of course, they can inherit from CODENERIX for certain features.

For all the rest of us that don’t want to mess up with authentication, several mechanisms are working behind Django and CODENERIX to provide user-level access:

  • One of the next Authentication systems must perform to log a user in:
    • Django Authentication System will decide if the user is granted into the system. This
    is the normal & basic authentication system from Django, it will require a user and a password on the front end, and it will log the user in. The system will set a cookie on the user’s browser to make it work on successive requests. With this cookie, you can execute as many API requests as you want to, and you will get access to what you are granted.
    • CODENERIX‘s ActiveDirectory middleware will decide if the user is granted into the system. It will use an Active Directory server to determine if the user is granted. Some extra comments about this authentication method are at the end of the page.
    • CODENERIX‘s TokenAuth middleware will decide if the user is granted into the system. It is the system we will explain below since it is responsible for authenticating remote CODENERIX‘s API requests.
  • CODENERIX‘s LimitedAuth middleware will decide if the user is granted into the system right now

When installing those middlewares from CODENERIX, set any “codenerix.authbackend” middleware straight after Django‘s “AuthenticationMiddleware“. Example:

MIDDLEWARE = [
    "django.middleware.cache.UpdateCacheMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "codenerix.authbackend.TokenAuthMiddleware",    <--------------- It will be explained below
    "codenerix.authbackend.LimitedAuthMiddleware",  <--------------- It will be explained below
    "codenerix.authbackend.ActiveDirectoryGroupMembershipSSLBackend", <--- It will be explained at the end
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "codenerix.middleware.SecureRequiredMiddleware",   <---- This one will make sure the website is working with HTTPS (depending on your config)
    "codenerix.middleware.CurrentUserMiddleware",      <---- This will let to have the logged in user object everywhere
    "django.middleware.cache.FetchFromCacheMiddleware",
]

GenPerson

Remember that CODENERIX‘s TokenAuth and LimitedAuth backends will check if the user is disabled at a certain moment. This is an optional feature that is auto-checked on every authentication request. To make your life easier, you can import “GenPerson” from CODENERIX and inherit from it in your model, for example:

from codenerix.models_people import GenPerson

class Person(GenPerson, CodenerixModel):
    phone = models.CharField(_("Phone"), max_length=16, blank=True, null=True)

GenPerson will define a user, a name, a surname, a disabled, and a creator field. From models_people, you can import GenRole as well, which makes it easier to manage different roles for different people. We will talk about it in a different post.

If you would like to implement the disabled feature yourself, you must link the “User” model from Django against another model, which must contain a field named “disabled”, which will be a DateTimeField, that links between the “User” model and your new model must have a related_name “person” or “people” that are the ones CODENERIX will lookup to check if it can go forward to check if the user disabled, example:

class Person(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True, related_name='person')
    name = models.CharField(_("Name"), max_length=45, blank=False, null=False)
    surname = models.CharField(_("Surname"), max_length=90, blank=False, null=False)
    disabled = models.DateTimeField(_("Disabled from"), null=True, blank=True)

LimitedAuth

This auth-backend middleware is used to:

  • Check how long the user has been without activity; it will kick it out if it has been away too long.
  • Check if the user can be logged in at certain hours.

In your configuration, you can use the following:

  • SESSION_EXPIRE_WHEN_INNACTIVE: number of seconds the user can be inactive on the website without being logged out.
  • SESSION_SHIFTS: list of hours of the day when all users must be logged out.

This middleware you must install after Django‘s “AuthenticationMiddleware“:
django.contrib.auth.middleware.AuthenticationMiddleware

TokenAuth

The basics of TokenAuth are:

  • Please send a request to some URL that will make a CODENERIX view answer (GenList, GenCreate, GenDetail, GenUpdate, GenDelete, or derived classes).
  • The system will require you to include a few parameters in your request:
    • authtoken: this is the authentication token. We will extend the information below at “How does authtoken work“.
    • authuser: is the user we are authenticating against.
    • json: is the request we are trying to send to the server
    • force_rest_api: if it is defined (no matter the value), it will force the REST API. If it does not appear, this feature will be disabled (you may use any other way to enable REST API on your call, check below at “RESTful API“).
    • authjson_details: [optional, default=0] If we set it to “1” (or “true”, or “t”), it will return details included with the answer

How does authtoken work

To build the authtoken, we have several ways, and we must focus on our configuration since we can use several authtoken models for authentication.

First, we must check our configuration and make sure that “AUTHENTICATION_DEBUG” is enabled and AUTHENTICATION_TOKEN is a dictionary configured as you expect authentication to work. Example with debugging and all authentication methods enabled:

AUTHENTICATION_DEBUG = True
AUTHENTICATION_TOKEN = {
    "key": "hello",
    "master_unsigned": True,
    "master_signed": True,
    "user_unsigned": True,
    "user_signed": True,
    "otp_unsigned": True,
    "otp_signed": True,
}

The AUTHENTICATION_TOKEN dictionary has several entries. We will focus on the last 6, which are combinations of:

  • master, user & top: those are authentication models
  • unsigned & signed: those are variants to the authentication model

The first entry, “key“, is directly associated with the “master” authentication model.

Unsigned variants will try to match the user’s given authtoken directly with the chosen key by the authentication model. Each model will choose the key for matching differently.

Signed variants do exist to sign the “json” string together with the “authuser“, so they can not be changed by a man-in-the-middle. Signed requests will be denied if the signature fails.

NOTES:

  • We must mention that any request will be granted if just one of the authentication models answers positively.
  • All requests require authuser to be filled, and the user MUST EXIST.

Master authentication:

The “key” for authentication will be configured in your configuration’s “key” entry of the AUTHENTICATION_TOKEN dictionary.

  1. master_unsigned: the system will try to match “authtoken” with “key“. This is the most straight authentication method since all requests and users will match with the same “key” (the one in your configuration).
  2. master_signed: the system will try to match “authtoken” with sha1( authusername + json + key )
    • In your config, “key” is configured with a string: “hello“
    • In your request authuser is: “theuser”
    • In your request, json is: {}
    • The algorithm will be:
      sha1( "theuser" + "{}" + "hello" ) =
      = sha1( "theuser{}hello" ) =
      = 401339988b89ef71e34f614f78bba076550a1033

User authentication:

In every of our CODENERIX projects, we use a Person model to manage all the information about the people in the system. This model is linked 1to1 with the User model from Django. This means we don’t hold any real information from the user inside the User model from Django, neither “First name” nor “Last name“. All the rest of the fields are used as Django does “username“, “password“, “email“, … we make all of this simpler using GenPerson (explained at the beginning of this post).

Since we decided not to work with “First name” and “Last name” to hold personal information, we use the “First name” field from the User model from Django for the “User authentication” system. CODENERIX will use the string inside the “First name” field as a key. To show this example, we will configure “abcdefgh” as the theuser‘s first’s name.

In Django‘s administration panel, it would look like this:

  • user_unsigned: the system will try to match “authtoken” with the user’s First name field from Django’s User model.
  • user_signed: the system will try to match “authtoken” with sha1( authusername + json + First Name )
    • In your request, authuser is: “theuser” (and the First Name field from Django’s User model is “abcdefgh” )
    • In your request, json is: {}
    • The algorithm will be:
      sha1( "theuser" + "{}" + "abcdefgh" ) =
      = sha1( "theuser{}abcdefgh" ) =
      = 0da2a3f2f7cf0ae0cebe254767c3ebb1667fd8d3

OTP authentication:

This authentication method works in the same way as the User authentication method. Still, instead of the user’s First name directly, it will use the OTP number created from using First name as the seed for the OTP algorithm.

  • user_unsigned: the system will try to match “authtoken” with the user’s OTP( First name ) field from Django’s User model.
  • user_signed: the system will try to match “authtoken” with sha1( authusername + json + OTP( First Name ) )
    • In your request, authuser is: “theuser” (and the First Name field from Django’s User model is “abcdefgh” )
    • In your request, json is: {}
    • The algorithm will be:
      sha1( "theuser" + "{}" + OTP( "abcdefgh" ) ) =
      = sha1( "theuser" + "{}" + 633917 ) ) =
      = sha1( "theuser{}633917" ) =
      = cfb51398eeefd28814a5e70f81a153be1c2a0c40

Notes when using User and OTP authentication system:

When using those authentication methods the first time, you may get an OSError exception, like this one:

OSError: To use a user/otp key, you have to set user_signed, user_unsigned, otp_signed, or otp_unsigned to True and set the user key in the user’s profile to some valid string as your token (first_name field in the user’s model)

The system requests you fill in the user’s “First name” with the authentication key to ensure those authentication methods will work properly.

ActiveDiretoryGroupMembershipoSSLBackend

This is the authorization backend for Active Directory in Django.

This authentication method has been working in production for a long time on old servers. We are unsure how the compatibility is on servers nowadays since we have not tested it. The feature is here and can be improved or fixed if it lacks compatibility, so you are welcome to send Pull Requests.

We won’t explain much about this feature since we consider it to be an advanced feature. Anyway, some description is required so advanced users can use it.

To get it working, you must add it to middleware (check the example at the top of this post) and then set the configuration with the next fields:

# Authorization backend for Active Directory in Django

# Configuration parameters
# AD_SSL = True                             # Use SSL
# AD_CERT_FILE='/path/to/your/cert.txt'     # Path to SSL certificate
# AD_DEBUG_FILE='/tmp/ldap.debug'           # Path to DEBUG file (if none, Debugging will be disabled)
# AD_LDAP_PORT=9834                         # Port to use
# AD_DNS_NAME='NTDOMAIN.CODENERIX.COM'      # DNS nameserver if different than NT4 DOMAIN
AD_LOCK_UNAUTHORIZED=True                   # Unauthorized users in Active Directory should be locked in Django
AD_NT4_DOMAIN='NTDOMAIN.CODENERIX.COM'      # NT4 Domain name
AD_MAP_FIELDS= {                            # Fields to map:   left=Django   right=Active Directory
    'email':        'mail',
    'first_name':   'givenName',
    'last_name':    'sn',
}

The post Authentication system appeared first on Codenerix.

]]>
GenCreate, GenUpdate, GenDetail and GenDelete https://codenerix.com/en/gencreate-genupdate-gendetail-and-gendelete/?utm_source=rss&utm_medium=rss&utm_campaign=gencreate-genupdate-gendetail-and-gendelete Sat, 24 Mar 2018 08:39:00 +0000 https://codenerix.com/?p=718/ 🇪🇦 Leer en Español, “GenCreate, GenDetail, GenUpdate y GenDelete“ In the last article, we described GenList to start using CODENERIX listings. The time has come to see how to create, view, update and delete the information on those listings. In this article, we will talk about GenCreate, GenDetail, GenUpdate, and GenDelete. First, each one inherits from […]

The post GenCreate, GenUpdate, GenDetail and GenDelete appeared first on Codenerix.

]]>
🇪🇦 Leer en Español, “GenCreate, GenDetail, GenUpdate y GenDelete“

In the last article, we described GenList to start using CODENERIX listings. The time has come to see how to create, view, update and delete the information on those listings.

In this article, we will talk about GenCreate, GenDetail, GenUpdate, and GenDelete.

First, each one inherits from its Django equivalent, such that GenCreate inherits from CreateView, GenUpdate from UpdateView, GenDetail from DetailView, and GenDelete from DeleteView.

Let’s see first what the example model that we are going to use, “Contact“, would look like:

class Contact(CodenerixModel):
    first_name = models.CharField(verbose_name=_(u'Name(s)'), max_length=128)
    last_name = models.CharField(verbose_name=_(u'Last name'), max_length=128, blank=True, null=True)
    alias = models.CharField(verbose_name=_(u'Alias'), max_length=32, blank=True, null=True)
    organization = models.CharField(verbose_name=_(u'Organization'), max_length=64, blank=True, null=True)
    borndate = models.DateField(verbose_name=_(u'Borndate'), blank=True, null=True)
    address = models.TextField(verbose_name=_(u'Address'), blank=True, null=True)
    created_by = models.ForeignKey(User, verbose_name=_(u'Created by'), on_delete=models.CASCADE, related_name='contacts')

    def __fields__(self, info):
        return (
            ('first_name', _(u'Name(s)')),
            ('last_name', _(u'Last name')),
            ('alias', _(u'Alias')),
            ('organization', _(u'Organization')),
        )

and your “ContactForm” form, which will inherit from GenModelForm.

GenModelForm:

from codenerix.forms import GenModelForm

class ContactForm(GenModelForm):

    class Meta:
        model = Contact
        exclude = ['created_by']

    def __groups__(self):
        return [
            (
                _(u'Principal'), 6,
                ['first_name', 6],
                ['last_name', 6],
                ['alias', 6],
            ),
            (
                _(u'Principal'), 6,
                ['organization', 6],
                ['borndate', 6],
                ['address', 6],
            )
        ]

    @staticmethod
    def __groups_details__():
        return [
            (
                _(Contact'), 12,
                ['alias', 12],
                ['organization', 12],
                ['borndate', 12],
                ['address', 12],
            )
        ]

Since GenModelForm is new, I will only point out that it inherits from Django‘s BaseModelForm and that the only thing new compared to a Django ModelForm is the groups. Groups are the definition of how we want a form to look on the screen and are built with a list of tuples containing:

  1. Field block title
  2. Width in Bootstrap columns
  3. N-tuples refer to the fields of the form where each tuple will have as its first element the name of the field that will go in that position and its width in Bootstrap columns. There are more elements in these tuples that I will explain in future posts.

In this way, the form indicated above would be as follows:

Where the fields are self-validated on the user’s browser side and thus greatly reduce server calls. Said form explained to your group would be as follows:

Let’s discover the details of these 4 views that work like their Python counterparts with the same attributes and methods as these but offer much more functionality.

GenModify

To talk to GenCreate and GenUpdate, we first have to talk about GenModify, which manages the operation when a record is created and updated. It is not a view that we will use directly. However, this class will indirectly be part of GenCreate and GenUpdate, respectively. Since the creation and update of the record vary in minimal matters: the form coincides, and the validations are the same, the GenModify class is in charge of managing how GenCreate and GenUpdate act in each case, preloading the form with the record that is being edited in a GenUpdate and both cases storing the changes (new or updated) in the database.

Table of attributes allowed by GenModify

AttributeDescription
angular_deleteName of the angular method that will receive the action when the “Delete” button is pressed, by default “delete”.

angular_delete = "delete"
angular_submitName of the angular method that will receive the action when the form is submitted, by default, “submit”.

angular_submit = "submit"
buttons_bottomShow action buttons below the form, and defaults to True.

buttons_bottom = True
buttons_topIt shows the action buttons above the form and defaults to True.

buttons_bottom = True
extends_baseIt contains the base template path from which the List template will inherit. It usually goes to a “base/base.html“, but by changing this variable, you can tell it to load a different file to offer the user a different environment experience.

extends_base = "base/base.html"
form_groupsThe group to apply to this view (equivalent to __groups__) can be a method or a function.
form_ngcontrollerBy specifying this attribute, an extra controller will be added to the form that will serve to include extra functionalities accessory to the standard form.

form_ngcontroller = "nuevo_controlador"
__groups__The group to apply to this view (equivalent to form_groups) can be a method or a function.
hide_foreignkey_buttonWhen this attribute is activated, the option to work the fields with external relationships through modal windows is shown. By default this attribute is False. In the following example, you can see 2 fields, “Brand” (Marca) and “Category” (Categoría), in which since there is no element selected in “Brand”, the system shows a “+” symbol to add a new record since it assumes that none of those in the list is valid for the user to fill in that field. If there is a selected element, the system displays a “pencil” in order to allow the selected element to be edited. Both “creation” and “editing” occur in a modal window.



Sometimes we do not want to see these buttons because we do not want the user to access these modal windows, either because we do not want them visually or because they do not have permissions or they are not developed. Marking this attribute as “True” will hide these buttons.

hide_foreignkey_button = False
jsonIt will return a response in JSON format, by default, True.

json = True
json_detailsIt will trigger verbose responses in JSON responses, by default, True.

json_details = True
linkbackIt shows the “Back” button and defaults to True.

linkback = True
linkdeleteIt shows the “Delete” button and defaults to True. This attribute is only available in editing forms (it is not enabled for creation forms since there is no record to delete).

linkdelete = True
linksavehereIt shows the “Save Here” button, which defaults to True.

linksavehere = True
linksavenewIt shows the “Save and New” button, which defaults to True.

linksavenew = True
show_detailsAt the end of the execution of the form, the system will try to return to the list, however, if show_details is activated, the system will go to the details view instead of the list.

show_details = True
show_internal_nameWhen set to True, it will display a title on the form. By default, it is activated in normal forms and deactivated in “modal” forms.

show_internal_name = True
success_url_keysA correctly completed form always responds with a valid status and also with a JSON dictionary containing at least 2 keys:
  • __pk__ which includes the PK of the created or updated object__str__ that contains the representation in text format of said created or updated object.
The response system always overwrites these 2 keys. However, if other keys are included in the success_url_keys attribute, they will also be included in the form response, and this data can be used to obtain extra information on the object created/modified or on its status. end of the operation requested to the form.

The success_url_keys attribute should be a list of strings that can have the following format:
  • “key”: will be evaluated as if it were “key:key”“key1:key2”: will be evaluated as answer[key1]=object.key2

success_url_keys = ["id","name:title"]
titleIf show_internal_name is activated, a title will be shown, and the title will be calculated automatically by mixing the action, which can be “Adding” or “Editing”, and the form’s name. However, when modifying this attribute, the content of this attribute will be displayed directly, preventing it from being auto-calculated.

title = _("Nuevo título para el formulario")

These attributes are available in both the create and edit views.

GenCreate and GenCreateModal

from codenerix.views import GenCreate, GenCreateModal
class ContactCreate(GenCreate):
    model = Contact
    form_class = ConctactForm
class ContactCreateModal(GenCreateModal, ContactCreate):
    pass

GenCreate is a view that inherits Django‘s CreateView from GenModify. At its minimum, it needs the same fields as CreateView. These are “model” and “form_class“. Since GenCreate inherits from GenModify, its features will also be available.

To the views to which we include a GenCreateModal, we will get the render to prepare the result to be displayed in a modal window. In the background, what actually happens is that it adds the Bootstrap modal window marquee and ends the rendering at that point.

GenUpdate and GenUpdateModal

from codenerix.views import GenUpdate, GenUpdateModal
class ContactUpdate(GenUpdate):
    model = Contact
    form_class = ContactForm
class ContactUpdateModal(GenUpdateModal, ContactUpdate):
    pass

GenUpdate is a view that inherits Django‘s UpdateView from GenModify. At its minimum, it needs the same fields as UpdateView. These are “model” and “form_class“. Since GenUpdate inherits from GenModify, GenModify‘s features will also be available.

In the views to which we include a GenUpdateModal, we will get the render to prepare the result to be displayed in a modal window. In the background, what actually happens is that it adds the Bootstrap modal window marquee and ends the rendering at that point.

GenDetail and GenDetailModal

from codenerix.views import GenDetail, GenDetailModal
class ContactDetail(GenDetail):
    model = Contact
    groups = ContactForm.__groups_details__()
class ContactDetailModal(GenDetailModal, ContactDetail):
    pass

GenDetail is a view that inherits Django‘s DetailView and GenModify, used to display data from an object. At its minimum, it needs the same fields as the DetailView. These are “model” and “form_class“.

To the views to which we include a GenDetailModal, we will get the render to prepare the result to be displayed in a modal window. In the background, what actually happens is that it adds the Bootstrap modal window marquee and ends the rendering at that point.

Table of attributes allowed by GenDetail

AttributeDescription
exclude_fieldsA list of fields will be excluded when rendering the object’s data. GenDetail will always show all the fields of the object, it will use (just like forms) the groups to show the information organized by them, and the rest of the fields will go consecutively at the end of the group. However, if a field appears in the exclude_fields list, it will not be displayed in the details view.

exclude_fields = ["contact", "price"]
extra_contextIt is a dictionary that contains extra information that will be sent to the template.
groupsThey work like the GenCreate and GenUpdate view groups.
linkbackA list of fields will be excluded when rendering the object’s data. GenDetail will always show all the fields of the object. It will use (just like forms) the groups to show the information organized by them, and the rest of the fields will go consecutively at the end of the group. However, if a field appears in the exclude_fields list, it will not be displayed in the details view.

exclude_fields = ["contact", "price"]
linkeditIt shows the “Edit” button and defaults to True.

linkedit = True
linkdeleteIt shows the “Delete” button and defaults to True. This attribute is only available in editing forms (it is not enabled for creation forms since there is no record to delete).

linkdelete = True

GenDelete

from codenerix.views import GenDelete

class ContactDelete(GenDelete):
    model = Contact

It is the view in charge of deleting the records. The reason for inheriting from GenDelete is that the system does certain security checks for record deletion, including permissions and integrity, that Django itself does not. It also responds appropriately to the controllers that deal with the management of the forms.

So far, we have explained everything necessary to operate with the Generic views of CODENERIX.

The post GenCreate, GenUpdate, GenDetail and GenDelete appeared first on Codenerix.

]]>
GenList https://codenerix.com/en/genlist/?utm_source=rss&utm_medium=rss&utm_campaign=genlist Thu, 22 Mar 2018 20:13:00 +0000 https://codenerix.com/?p=664/ 🇪🇦 Leer en Español, “GenList“ Previously we talked about CodenerixModel to understand how a functional model is built with CODENERIX; however, for everything to work in Django, in addition to models you also have to define views. To allow web content to be viewed, a set of inheritable views is available to the programmer, all based […]

The post GenList appeared first on Codenerix.

]]>
🇪🇦 Leer en Español, “GenList“

Previously we talked about CodenerixModel to understand how a functional model is built with CODENERIX; however, for everything to work in Django, in addition to models you also have to define views. To allow web content to be viewed, a set of inheritable views is available to the programmer, all based on Django‘s Generic Views, which, following the CODENERIX policy, are as simple to use as to inherit from them.

In this article, we will talk about GenList, which is the generic view of CODENERIX that allows you to view data as a list from the model. GenList inherits directly from Django‘s ViewList, so all properties of a ViewList are available in GenList. Let’s see what the list of a “Contact” model would look like:

from codenerix.views import GenList
from app.models import Contact

class ContactList(GenList):
    model = Contact

As simple as that, and the visual result would be equivalent to something like this (if you use the CODENERIX Examples):

In this way we have managed to visualize the Contact model of the “agenda” example that you have here:

class Contact(CodenerixModel):
    first_name = models.CharField(verbose_name=_(u'Name(s)'), max_length=128)
    last_name = models.CharField(verbose_name=_(u'Last name'), max_length=128, blank=True, null=True)
    alias = models.CharField(verbose_name=_(u'Alias'), max_length=32, blank=True, null=True)
    organization = models.CharField(verbose_name=_(u'Organización'), max_length=64, blank=True, null=True)
    borndate = models.DateField(verbose_name=_(u'Cumpleaños'), blank=True, null=True)
    address = models.TextField(verbose_name=_(u'Dirección'), blank=True, null=True)
    created_by = models.ForeignKey(User, verbose_name=_(u'Creado por'), on_delete=models.CASCADE, related_name='contacts')

    def __fields__(self, info):
        return (
            ('first_name', _(Name(s)')),
            ('last_name', _(Last name')),
            ('alias', _(u'Alias')),
            ('organization', _(u'Organization')),
        )

You may have already noticed that CODENERIX has used the __fields__ method of the model to discover which fields it should display in the list. In addition, it felt free enough to automatically offer a list that enables cumulative ascending/descending sorting in each of its fields (see “Last name” column in the following screenshot) and if we press the filter icon (light blue colour in the following screenshot ) we can even see that it has also taken care of allowing us to search in each field one by one (see “Organization” column where we search for “Inc” limiting the list to 2 results):

In short, by inheriting from GenList we have achieved a great job with an excellent visual result for our users.

But GenList, like CodenerixModel, allows you to use the methods: __fields__, __limitQ__, __searchF__ and __searchQ__. In this way, when one of these methods is created in a GenList, the CodenerixModel or GenList method will be used as they exist. In fact, its operation is exactly the same as in CodenerixModel.

The following 3 tables show 3 columns:

  • The first indicates if the method is defined in CodenerixModel.
  • The second indicates if it is defined in GenList.
  • The third column indicates the result of applying these filters.

__fields__
CodenerixModelGenListApplicable
NONO— ERROR —
NOYES— ERROR —
YESNOCodenerixModel
YESYESGenList

__limitQ__
CodenerixModelGenListApplicable
NONONo filter is applied
NOYESGenList filter is applied
YESNOCodenerixModel filter is applied
YESYESGenList and CodenerixModel filters
are applied to put them together
with the logic operator “AND“.

__searchQ__ & __searchF__
CodenerixModelGenListApplicable
NONONo filter is applied
NOYESGenList filter is applied
YESNOCodenerixModel filter is applied
YESYESGenList filter is applied

So now we can decide that our view behaves differently from our model. This is done because sometimes we want to create more than one list of the same model where each list has different properties, shows different information depending on the user, or uses a different template.

GenList can also contain different attributes that allow you to configure its operation in many different ways. Here you have a table of what exists today:

Table of attributes allowed by GenList

AttributeDescription
annotationsIt is possible to introduce aggregators inside the Querysets used by CODENERIX (learn more about aggregators in Django). It is very useful when we want it to calculate maximums, minimums, averages, or simply group results by date, types, or other fields. Annotations may also work as a method of the class (see example):

annotations = { 'min_price': Min('books__price'), 'max_price': Max('books__price') } def annotations(self, info): anot = [] if info.user.is_superuser: anot['min_price'] = Min('books__price') anot['max_price'] = Max('books_price') return anot
appnameOverrides the automatic system to generate URLs so you can set your own app’s URL. This is commonly used to manage the same model over to different apps (for example several GenList). Be careful. This field alters the normal behaviour of CODENERIX, which can confuse you if used wrongly. You can find a fully working example on GitHub.
autofilteringIf set to False, it disables the automatic filter generation system. By default it is True.

autofiltering = False
client_contextIt is a dictionary and its content will be sent directly in the JSON response inside the “meta” structure as “context“. It is very useful to send data directly from the view to the AngularJS controller or template. Usage:

client_context = {"var1": "value1"}

The result will be embedded into the “meta” structure:
{ "filter": ..., "meta": { ... "context": { "var1": "value1", }, ... }, "table": ..., }
default_orderingThe attribute can be a string or a list of strings. The string may or may not start with “-”. This field indicates the field or fields that are going to be used in the sorting and the symbol “-” indicates that the sorting will be done in descending order (the reverse direction), if nothing is indicated it will be done in ascending order. If a list is given, the ordering will be applied scrupulously following the order in which the fields appear in this list.

default_ordering = '-name' default_ordering = ['-name', 'date', '-xz']
default_rows_per_pageUsed to indicate the number of rows per page that we want to display by default in this list. The standard value used in GenList is 50.

default_rows_per_page = 150
exportForce the download of a list as a file. Here is the format. The default is None.

export = "xlsx"
export_excelShows the export to Excel button. By default, it is True.

export_excel = False
export_nameName of the file resulting from the export. By default, it is a “list“.

export_name = "list_file"
extends_baseIt contains the base template path from which the List template will inherit. It usually goes to a “base/base.html“, but by changing this variable, you can tell it to load a different file to offer the user a different environment experience.

extends_base = "base/base.html"
extra_contextIt contains a dictionary that will be mixed with the final context that will be delivered to the render. During the GenList process, you can override the variables used here.

extra_context = { "variable1": "This is a CODENERIX variable that will be ready to use in the Template's Context", "variable2": { "a": 1, "b": 2}, "variable3": 3.4, }
field_checkActivates the display of the checkbox in the lists, it is a checkbox that when checked stores the pk (primary key) of the row and can be used in the AngularJS‘s $scope to do custom operations. This attribute has 3 possible states:

  • None: the checkbox is not displayed.
  • False: the checkbox is shown unchecked.
  • True: the checkbox is shown with everything checked.

field_check = True
field_deleteIt activates the display of the delete field in the lists, it is the icon of a trash can and when you click on it, the user is sent to delete the said record. By default it is False.

field_delete = True
haystackActivate support for Haystack in this listing. By default it is False.

haystack = True
jsonWhen this attribute is True, the view will always respond in JSON format. If the view responds in JSON format and you want to modify the response, you can work on the view’s json_builder() method, rewriting it or simply reprocessing its result. We must know that when the views receive a “json” parameter in GET/POST, the JSON response will automatically be activated. This attribute will also be activated when an “HTTP_X_REST” header is received and its value can be evaluated as a Boolean “True“. It is important to know that this attribute is set to True by default.

json = True
linkaddShows the “Add” button in the listings. By default, it is True.

linkadd = False
linkeditClicking on a list row goes to the editing mode of that specific record. By default it is True.

linkedit = False
modelModel to use.

model = Contact
modelnameOverrides the automatic system to generate URLs so you can set your own model’s URL. This is commonly used to manage the same model over different URLs (for example, several GenList). Be careful, this field alters the normal behaviour of CODENERIX which can confuse you if used wrongly. You can find a fully working example on GitHub.
must_be_staffWhether or not the user must be staff (ability to see /admin/ of Django according to the User model) to view this list content, its value is False by default.

must_be_staff = True
must_be_superuserWhether or not the user must be a superuser (according to Django’s User model) in order to view the content of this listing. By default its value is False.

must_be_superuser = True
ngincludesYou keep control over possible ng-includes that may appear in partials.

ngincludes = {'name':'path_to_partial'}
onlybaseIt will cause GenList to act only as a base file for another view. By default, it is False.

onlybase = True
permissionIt can be a string or a list of strings. Each string represents one permission. The user can see the list when they have at least one of the permissions in this attribute.

permission = 'permission1' permission = ['perm1', 'perm2', ...]
permission_groupIt can be a string or a list of strings. Each text string represents one group’s permission. The user will be able to see the list when any of the user’s groups have any of the permissions that appear in this attribute.

permission_group = 'permission1' permission_group = ['perm1', 'perm2', ...]
search_filter_buttonIf it is False, it disables the field filter button. By default it is True.

search_filter_button = False
show_detailsClicking on a list row goes to the detail mode of that specific record. By default it is False.

show_details = True
show_modalWhen on, it pushes the system to render in a modal window.

show_modal = True
static_app_rowLoad the AngularJS application file indicated here, otherwise use the default: codenerix/js/apps.js

static_app_row = "app/models_apps.js"
static_controllers_rowIt loads the AngularJS controller file indicated here. Otherwise, it does not load any.

static_controllers_row = "app/models_controllers.js"
static_filters_rowLoad the AngularJS filter file indicated here, otherwise use the default one: codenerix/js/rows.js

static_filters_row = "app/models_rows.js"
static_partial_headerCauses the indicated table “header partial” to be loaded, if not specified there will be no header partial.

static_partial_header = "app/models_header.html"
static_partial_rowCauses the row partial specified in this attribute to be loaded instead of the default partial: codenerix/partials/rows.html

static_partial_row = "app/models_rows.html"
static_partial_summaryCauses the “tail partial” of the table specified in this attribute to be loaded instead of the default partial: codenerix/partials/summary.html

static_partial_summary = "app/models_summary.html"
template_baseIt is the template that acts as a base for the rest. GenList generally renders through a series of templates that jump from one to another by inheritance. In the last step, the CODENERIX templates call a base template that is usually “base/base”, however, this can be changed with this attribute so that it uses another base template. Remember that CODENERIX will try to locate the rest of the name of the “web” file using the template detection algorithms.

template_base = 'frontend/web'
template_base_extExtension used for template_base.

template_base_ext = 'html'
template_modelThis is the template used as the entry point for the CODENERIX renderer. Generally, if the path doesn’t exist it will end up using “codenerix/list” (which will end up being “codenerix/list.html”) however it is possible to define our own entry point using this attribute. This is very useful when we want to add “extra_css” or “extra_js” in the rendering, and our base template supports these blocks.

template_model = 'app/contact_list'
template_model_extExtension used for template_model.

template_model_ext = 'html'
userAllows you to make a view behave specifically as a specific user. It is very useful when you want to view the list as if you were another user of the system. It’s a Django User object that will be used by all processes in the view and passed to all methods that request it.

IMPORTANT: the permissions management system is not affected by this variable. That is, it will continue to receive the user who has requested to view the list, and the access restriction policies will be applied to this user, not to the one that appears in this attribute.

user = User.objects.filter(is_superadmin=False).first()
vtableVTable is a technology by which the list becomes non-paged and CODENERIX does a proactive job to estimate the real width of the list on screen and virtualizes the environment in such a way that it preloads a few pages in the browser but not all and adjusts the scroll the same as it would be if all the records were loaded this way when we move in the list CODENERIX loads new pages and unloads old ones to allow the browser to work at an adequate rendering speed, but the user perceives the sensation of being working on a huge list and that all the records are there. This functionality is experimental because it has not been tested enough. By default this attribute is False.

vtable = True
ws_entry_pointThis attribute defines the route to the entry point for the operations that the list wants to carry out, for example, when loading the list, the route indicated by the “ws_entry_point” is used, and when editing its use is repeated. It is generally used in extra views that are added on top of an existing one on the model and when you want to introduce a new Angular controller or something else that modifies the standard behaviour of CODENERIX.

ws_entry_point = "planner/plane"

In addition to these attributes, we must know how GenList tries to locate the templates for rendering the page. GenList will try to build a series of URLs based on the user’s profile and language so that if the user is superadmin he will have an “admin” profile, and otherwise, he will not have any profile. The user’s language is detected by CODENERIX and will also be delivered to the template detection function.

The possible routes for the templates will be (following this order of priority):

  1. <path>/<file>.admin.<language>.html
  2. <path>/<file>.admin.html
  3. <path>/<file>.<username>.<language>.html
  4. <path>/<file>.<username>.html
  5. <path>/<file>.<language>.html
  6. <path>/<file>.html

In this way, if the user is “peter“, he is a superuser, and his language at the time of the query is English with code “en“, and the path to the file is “base/home“, the system will test the existence of the following files:

  1. base/home.admin.en.html
  2. base/home.admin.html
  3. base/home.peter.en.html
  4. base/home.peter.html
  5. base/home.en.html
  6. base/home.html

GenList also supports automatically detecting static files for loading partials and AngularJS files such as application files, controllers, or filters. To do this, GenList will try to locate these files in the application folder inside “/static” (or whatever the path of static files on disk is according to the STATIC_ROOT constant in Django‘s settings). For this detection, it will use the same algorithm that template detection uses. In this way, it will test for each static file the possible existence of this on disk and will load these instead of those that exist by default in CODENERIX. To generate the routes, the system will use the following:

  1. The path: it will be the path of the static files, the name of the APP where the model is located, and the name of the model ending in “s“.
  2. File type: it can be:
    • <none>: for the partial that declares the filters to display above the listing table, and generally to include the table with nginclude.
    • rows: for the partial of the rows
    • header: for the partial of the table header (below the declaration of the columns and above the rows).
    • summary: for the footer partial of the table (below the rows and above the closing table tags).
    • app: for application files.
    • controllers: for the controllers.
    • filters: for AngularJS filter files.
  3. The extension: will be that of each type of file:
    • html: for partials
    • js: for the rest
  4. The final result will be from the concatenation of the following:
    • The route
    • “_” plus file type
    • The extension.
  5. For an app called “base“, with a model called “Contact“, to obtain the partial rows of a user “peter“, who is a superuser and visits the site in English, the system would try the following routes:
    • static/base/contacts_rows.admin.en.html
    • static/base/contacts_rows.admin.html
    • static/base/contacts_rows.peter.en.html
    • static/base/contacts_rows.peter.html
    • static/base/contacts_rows.en.html
    • static/base/contacts_rows.html
    • static/codenerix/partials/rows.html (if the above fails)


Finally, we must talk about the json_builder() method since it is a GenList method that allows you to control the result that will be offered to the user. The method is defined with 2 parameters:

  • answer: contains the answer pre-calculated by GenList, which only lacks the “body” that should be placed in answer[“table”][“body”]
  • context: contains the context available for rendering the JSON generator in this case. Within the context is the “object_list” containing the QuerySet resulting from applying the filters and what GenList should theoretically respond to.

There are 3 techniques to work with json_builder():

Technique 1: “Body building on your own”

You build the entire body of the answer yourself:

def json_builder(self,answer,context):
    # The body is a list of records (body or body of the list)
    body=[]

    # Process each element of the context's object_list in order to process all rows
    for or in context['object_list']:
        t={}
        t['name']=o.name
        t['surname']=o.surname
        phones=[]
        for o2 in o.phone.all():
            phone={}
            phone['country']=o2.country
            phone['prefix']=o2.prefix
            phone['number']=o2.number
            phones.append(t2)
        t['phone']=phones
        t['address']=o.address
        body.append(t)

    # Insert the body into the response body
    answer['table']['body']=body

    # Returns the ready response
    return answer

In this example, we build a list manually where we are responsible for filling each row or record of the body. When we finish processing the rows that we want to send to the user’s browser, we load these rows (list) in the response and return them.

Technique 2: “Body building with bodybuilder()”

Use the bodybuilder() method to help you build the body of the response:

def json_builder(self,answer,context):
    # We fill directly using bodybuilder
    answer['table']['body']=self.bodybuilder(context['object_list'],{
        'id:user__register__id':None,
        'name': None,
        'surname':None,
        phone: {
            'country':None,
            'prefix':None,
            'number':None,
            },
        'address':None,
        })

    # Answer the new context
    return answer

When bodybuilder() is used, it expects to receive the list of objects to process and the form of the records it should build. What bodybuilder() does is that for each record of the object_list it generates an entry in the body, where each of those entries is dictionaries that have the form of the second parameter of the call, in this way each record of this example would have 5 keys in the dictionary:

  • id: would be the result of extracting the “user” field from the object and thus the “register” field and, from this, the “id” field. If “id:…” was not specified as an alias, the key would contain the full path, which would be “user__register__id“.
  • name: the result of extracting the name field from the object or the result of calling the name() method.
  • surname: the result of extracting the surname field from the object or the result of calling the surname() method.
  • phone: it will be a dictionary with 3 keys:
    • country: the result of extracting the phone field from the object, and from it the country field or the result of calling the country() method.
    • prefix: the result of extracting the phone field from the object, and from it the prefix field or the result of calling the prefix() method.
    • number: the result of extracting the phone field from the object, and from this the number field or the result of calling the number() method.
  • address: the result of extracting the address field from the object or the result of calling the address() method.

Technique 3: “Body building with autorules() and bodybuilder()”

Where you use autorules() and bodybuilder() to build the response:

def json_builder(self,answer,context):
    # Request the rules to autorules
    rules=self.autorules()
    # Get one of the keys from autorules (field we don't want in the response)
    rules.pop('id')
    # Add another key (field we want in the response, in this case an alias of user->id)
    rules['id:user__id']=None
    # Call bodybuilder the new set of rules
    answer['table']['body']=self.bodybuilder(context['object_list'],rules)

    # return the result
    return answer

In this case, we ask GenList for the rules we should use. We adopt that set of rules as we wish and deliver it to bodybuilder() so that it finishes the job of generating the response body.

Notes on the query optimizer

We must consider that GenList includes a query optimizer to reduce the work done in Python and pass part of it to the database manager. This optimizer does not work when data is involved in the result that the database cannot compute on its own, that is, generally, when methods are included in the results and they are not purely data stored in the objects.

Another important detail is that the optimizer converts the result rows into dictionary objects so that it only contains the data as-is and does not instantiate the model objects as would be normal in Django.

Custom QuerySet or customized QuerySet

Finally, when we cannot work with the filters or when introducing certain limitations (annotates for example) the result no longer works as we wish….we will always have an “ACE up our sleeve“, the method “custom_queryset(queryset, info)”. This method must be rewritten in your view in order for CODENERIX to use it since. Otherwise, it will operate normally. This method receives two parameters: the first is the QuerySet calculated by GenList, and the second is the MODELINF object that contains internal information about the query, the model, arguments, etc… and expects you to return a valid QuerySet. This is why you can return the QuerySet you received with a few more parameters taking advantage of the power of Django’s ORM, or it could even be a QuerySet from a different model.

The post GenList appeared first on Codenerix.

]]>
CodenerixModel https://codenerix.com/en/codenerixmodel/?utm_source=rss&utm_medium=rss&utm_campaign=codenerixmodel Wed, 28 Feb 2018 21:08:00 +0000 https://codenerix.com/?p=608/ 🇪🇦 Leer en Español, “CodenerixModel“ For any Django project to support CODENERIX properly, it is necessary to take some important steps to ensure a good start to the project. We will not repeat that using the CODENERIX Examples available on GitHub is the easiest way to get started. That is why this time, we will focus […]

The post CodenerixModel appeared first on Codenerix.

]]>
🇪🇦 Leer en Español, “CodenerixModel“

For any Django project to support CODENERIX properly, it is necessary to take some important steps to ensure a good start to the project. We will not repeat that using the CODENERIX Examples available on GitHub is the easiest way to get started.

That is why this time, we will focus on the CORE / KERNEL of CODENERIX, which we will know from now on as CodenerixModel.

CodenerixModel is an extended class from Django’s models.Model where a series of new functionalities are contemplated that we will explain below. First, we must bear in mind that most of the functionalities we will see in CODENERIX are achieved through the use of direct inheritance of classes of this framework. To do this, we are going to see a simple example of a class developed with CODENERIX:

from codenerix.models import CodenerixModel

from django.db import models

class Author(CodenerixModel):
    name = models.CharField(_(u'Name'), max_length=128, blank=False, null=False)
    birth_date = models.CharField(_(u'Birth Date'), max_length=128, blank=False, null=False)
    def __fields__(self, info):
        fields=[]
        fields.append(('name', _('Name'), 100, 'left'))
        fields.append(('birth_date', _('Birth Date')))
        return fields

In this example, we see several things that stand out to us compared to a normal declaration of a model in Django:

  1. We import CodenerixModel with:
    from codenerix.models import CodenerixModel

  2. The model inherits CodenerixModel (not from models.Model):
    class Author(CoderixModel):

  3. There is a special method that is required called __fields__ and takes an “info” argument:
    def fields(self, info):

    We must remember that this method must be defined in all the classes inherited from CodenerixModel since CODENERIX uses it to know how to show the information to the end-user of the application in such a way that it is clear, simple, and usable.
  4. The rest of the information in the class is simple to understand and responds to the general paradigm that Django uses. In fact, CODENERIX always inherits Django and passes its management to it, thus always ensuring that any improvements to Django are also available in CODENERIX.

What does the __fields__ method contain?

It collects what information from the model is useful to be shown when the user wants to work with that model. This method is usually called from lists since the fields that appear here will be used as columns in the listing.

def __fields__(self, info):
    fields=[]
    fields.append(('name', ('Name'), 100, 'left')) fields.append(('birth_date', ('Birth Date')))
    return fields

⚠ IMPORTANT: This method is mandatory in all models inherited from CodenerixModel.

The method receives an “info” argument that contains information about the query received (request), including, among other data, the user who makes it and other important meta information for decision-making that will be made within __fields__. This example is linear, but we can take advantage of this information to detect a user’s level of access and display some fields or others in the list, adapting the content of the list depending on the user or the system conditions.

This method is expected to respond with a list of tuples containing at least 2 elements. The first will be the field’s name according to Django’s model, and the second will be the translatable name of the field to be shown to the user in the column’s title referenced by that field.

Each tuple, therefore, consists of 2 mandatory elements and several optional elements:

  • Required: Model field name
  • Required: Translatable name of the field to be displayed to the user (it can be None to prevent Django from rendering that column so that we can receive this field in the JSON response of the list but without being displayed visually. It is very useful when you want to compose several fields into one)
  • Optional: Length of field width in pixels (deprecated)
  • Optional: Alignment of the text within the field (Ex: ‘centre‘)
  • Optional: Name of the filter to apply to the field (Ex: ‘skype‘, which will add the necessary information so that the output of the field is a clickable phone number)

3 other special methods provide different functionalities to the models. These are __limitQ__, __searchF__, and __searchQ__.

What is the __limitQ__ method?

It is a limiting method. Its objective is to limit the results to which the user has access. In this way, __limitQ__ allows you to control the result returned to the user based on the query environment so that if you are a user without privileges, you will not be able to see certain records because a filter will be applied. It is very useful when working with Roles since it allows you to control the records the user sees based on their role.

def __limitQ__(self, info):
    limits = {}
    if not info.user.is_admin:
        criterias = []
        criterias.append(Q(model__pk=pk_condition))
        criterias.append(Q(model__field1=condition))
        limits['profile_people_limit'] = reduce(operator.or_, criterias)
    return limits

The method expects to return a dictionary where the key indicates the line to operate on (in case an error occurs while processing the lookup), and the value, on the other hand, is a Django’s QObject. The QObject will be injected in the Queryset of the list when it is requested, applying or not the filter, depending on the query.

What is the __searchQ__ method?

It is the method used to filter the queries with the text entered in the listings’ upper box. In this way, everything that the user writes in the search box will arrive in the “text” variable, allowing filtering of the search with this text.

def __searchQ__(self, info, text):
    text_filters = {}
    text_filters['identifier1'] = Q(CharField1__icontains=text)
    text_filters['identifier2'] = Q(TextField1__icontains=text)
    text_filters['identifier3'] = Q(IntegerField=34)

    #If text have this a especific word can return another Q condition
    if text.find(u'magic') != -1:
        text_filters['identifier4'] = Q(identifier=34)

    return text_filters

The method expects to return a dictionary where the key indicates the line to operate on (in case an error occurs while processing the lookup), and the value, on the other hand, is a Django’s QObject. The QObject will be injected in the Queryset of the list when it is requested, applying or not the filter, depending on the query.

What is the __searchF__ method?

It is in charge of displaying the search filters and is used when we want filters to be displayed that facilitate the search. Specifically, its use refers to the personalized definition of these filters, for example, a selector that shows “A”, “M”, and “S” in such a way that if you press “A”, you will search for everything that begins with “A”, idem for M and S. Still, you will not be able to search for other letters. It is very useful to build combined searches, such as “give me those of type A” (green and purple together). It is also used to generate complex filters. CODENERIX automatically includes filters in all the fields of a list with which it knows how to operate natively so that filters will appear for text fields, numeric fields, BooleanFields, ChoiceFields, and dates.

def __searchF__(self, info):
    list1 = []
    for l1 in Model.objects.all():
        list1.append((l1.id, l1.field1 + ' ' + l1.field2))

    list2 = []
    for li in Model2.objects.all():
        list2.append((li.id, str(li.field)))

    text_filters = {}
    text_filters['field1'] = (_('Field1'), lambda x: Q(field1__startswith=x), [('h', _('Starts with h')), ('S', _('Starts with S'))])
    text_filters['field2'] = (_('Field2'), lambda x: Q(field2__pk=x), list1)
    text_filters['external'] = (_('Field3'), lambda x: Q(pk=x),list2)

    return text_filters

The method expects to return a dictionary where the key indicates the filter’s name. If the name of the filter matches a field in the list, then the filter will be shown in the hidden row below the list’s title, which is displayed with the icon “≡”. Otherwise, it will be displayed as an external filter.

The value of the key must be a tuple with 3 elements:

(('Field1'), lambda x: Q(field1__startswith=x), [('h', ('Starts with h')), ('S', _('Starts with S'))])

…in such a way that the first element will be the name of the filter in translatable format, the second a lambda function that receives the value of the filter and returns a QObject that helps the filter to perform as expected, and the third element should be a list of options to display in the filter. The QObject returned by the lambda function will be injected into the Queryset of the list when it is requested, applying or not the filter, depending on the query.

How do CodenerixModel and GenList interact?

Although later we will talk about GenList (view used to build lists), we must say that __fields__, __limitQ__, __searchQ__ and __searchF__ are methods that can appear indistinctly in the model and the view of a list. Here’s how filters interact when a model specifies a filter and a listing doesn’t, or vice versa.

The following 3 tables show 3 columns:

  • The first indicates if the method is defined in CodenerixModel.
  • The second indicates if it is defined in GenList.
  • The third column indicates the result of applying these filters.

__fields__
CodenerixModelGenListApplicable
NONO— ERROR —
NOYES— ERROR —
YESNOCodenerixModel
YESYESGenList

__limitQ__
CodenerixModelGenListApplicable
NONONo filter is applied
NOYESGenList filter is applied
YESNOCodenerixModel filter is applied
YESYESGenList and CodenerixModel filters
are applied to put them together
with the logic operator “AND“.

__searchQ__ & __searchF__
CodenerixModelGenListApplicable
NONONo filter is applied
NOYESGenList filter is applied
YESNOCodenerixModel filter is applied
YESYESGenList filter is applied

We will remember these tables again later when I explain GenList in detail.

And what else?

In addition to the previous methods, we must point out that CodenerixModel adds a series of extra functionalities to the standard Django models.

  1. By default, it adds the created and updated fields that CODENERIX automatically manages to remember when the record was created and when it was last edited.
  2. It allows the use of a new “Meta” class (equivalent to Django’s) called “CodenerixMeta“.
  3. The standard permissions are replaced by: add, change, delete, view and list. The new types are “view” and “list” to define if the record can be displayed or listed.
  4. Models also can use the lock_update and lock_delete methods to stop a record update or delete. An example is a record that depends on a specific circumstance of the stored data. These methods allow records to be capriciously blocked in a list, and the user is properly informed of the reason for said blocking. Check source code below (*)
  5. In this example, the deletion of a note is prevented when it has associated documents or when people are using it. Otherwise, the responsibility is delegated to the parent class.
  6. When a record is going to be deleted, CodenerixModel analyzes the relationships with other models and their deletion protections to respond in a “polite” way in case of trying to delete a record that by model definition (models.PROTECT) cannot be deleted.
  7. All classes that inherit from CodenerixModel can also inherit from GenLog. When doing so, CODENERIX will record in a log any operation that occurs in a record of that class.

(*)

def lock_delete(self):
     if self.documents.exists():
         return ("The note cannot be deleted, there is a document that blocks it")
     elif self.people.exists():
         return ("The note cannot be deleted, there are people still working with it")
     else:
         return super(Point, self).lock_delete

Now we are ready to learn how to use GenList.

The post CodenerixModel appeared first on Codenerix.

]]>