Django

Django

Explore django code snippets and tutorials

Django

get request data in django

<p>The provided Python function <code>get_request_data(request)</code> appears to be a Django view function for handling HTTP GET requests and extracting the data from the request&#39;s query parameters. It parses the query …

python
1
2
3
4
5
6
7
8
9
def get_request_data(request):
    context = {}
    for key in request.GET.items():
        values = request.GET.getlist(key)
        if len(values) > 1:
            context[key] = [item for item in values]
        else:
            context[key] = values[0]
    return context
Django

django get model urls with namespace

<p>This code appears to be a method called <code>get_urls</code> inside a Django model class. The purpose of this method is to generate URLs for various views related to the model. …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def get_urls(self):
        from django.urls import reverse_lazy
        app_label = self._meta.app_label
        klass = self.__class__.__name__.lower()
        list_url = reverse_lazy('{}:{}-list'.format(app_label, klass))
        create_url = reverse_lazy('{}:{}-create'.format(app_label, klass))
        detail_url = reverse_lazy('{}:{}-detail'.format(app_label, klass),
                                  kwargs={"pk": self.id})
        update_url = reverse_lazy('{}:{}-update'.format(app_label, klass),
                                  kwargs={"pk": self.id})
        delete_url = reverse_lazy('{}:{}-delete'.format(app_label, klass),
                                  kwargs={"pk": self.id})
        return {
            'list_url': list_url,
            'create_url': create_url,
            'detail_url': detail_url,
            'update_url': update_url,
            'delete_url': delete_url
        }
Django

Django custom decorator example

<p>In the code you provided, you have defined a custom decorator <code>dec</code>, which prints a message before and after calling the decorated function. You have applied this decorator in two …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from django.views.generic import TemplateView
from django.utils.decorators import method_decorator
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin


def dec(func):
    def wrapper(request, *args, **kwargs):
        print('decorating')
        v = func(request, *args, **kwargs)
        print('end decorating')
        return v
    return wrapper


@method_decorator(dec, name='dispatch')
class HomeView(TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        return context

@dec
def hello_view(request):
    return HttpResponse('hello')
Django

django bootstrap4 form snippets

<p>The provided Python code defines a custom form and formset classes for creating Bootstrap-styled forms and formsets in Django. Let&#39;s go through each class and function to understand what they …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class BootstrapForm:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        fields = ['CheckboxInput', 'ClearableFileInput', 'FileInput']
        for field in self.fields:
            widget_name = self.fields[field].widget.__class__.__name__
            if widget_name not in fields:
                self.fields[field].widget.attrs.update({
                    'class': 'form-control'
                })


class BootstrapFormSet(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        fields = ['CheckboxInput', 'ClearableFileInput', 'FileInput']
        for form in self.forms:
            for field in form.fields:
                widget_name = form.fields[field].widget.__class__.__name__
                if widget_name not in fields:
                    form.fields[field].widget.attrs.update({
                        'class': 'form-control'
                    })
    def add_fields(self, form, index):
        super().add_fields(form, index)
        fields = ['CheckboxInput', 'ClearableFileInput', 'FileInput']
        for field in form.fields:
            widget_name = form.fields[field].widget.__class__.__name__
            if widget_name not in fields:
                form.fields[field].widget.attrs.update({
                    'class': 'form-control'
                })


def unique_bootstrap_field_formset(field_name):
    class UniqueFieldBootstrapFormSet(BootstrapFormSet):
        def clean(self):
            if any(self.errors):
                # Don't bother validating the formset unless each form is valid on its own
                return
            values = set()
            for form in self.forms:
                if form.cleaned_data:
                    value = form.cleaned_data.get(field_name)
                    if value:
                        if value in values:
                            form[field_name].field.widget.attrs['class'] += ' is-invalid'
                            form.add_error(field_name, "{} {} cannot be added multiple times.".format(
                                field_name, value))
                        values.add(value)
    return UniqueFieldBootstrapFormSet
Django

Override BaseInline Formset

<p>The code you provided seems to define a custom formset called <code>BootstrapFormSet</code> that inherits from Django&#39;s <code>BaseInlineFormSet</code>. This custom formset is intended to add the &#39;form-control&#39; class to form fields&#39; …

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django.forms import BaseInlineFormSet

class BootstrapFormSet(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        fields = ['CheckboxInput', 'ClearableFileInput', 'FileInput']
        for form in self.forms:
            for field_name, field in form.fields.items():  # Corrected iteration to access field instances
                widget_name = field.widget.__class__.__name__
                if widget_name not in fields:
                    field.widget.attrs.update({
                        'class': 'form-control'
                    })

    def add_fields(self, form, index):
        super().add_fields(form, index)
        fields = ['CheckboxInput', 'ClearableFileInput', 'FileInput']
        for field_name, field in form.fields.items():  # Corrected iteration to access field instances
            widget_name = field.widget.__class__.__name__
            if widget_name not in fields:
                field.widget.attrs.update({
                    'class': 'form-control'
                })