Categories
Python Answers

How to pull a random record using Python Django’s ORM?

To pull a random record using Python Django’s ORM, we can use the first method with order_by.

For instance, we write

MyModel.objects.order_by('?').first()

to call order_by with '?' to return the MyModel objects in random order.

And then we call first to pick the first one.

Categories
Python Answers

How to build multiple submit buttons in a Python Django form?

To build multiple submit buttons in a Python Django form, we can render the buttons conditionally.

For instance, we write

if 'newsletter_sub' in request.POST:
    # do subscribe
elif 'newsletter_unsub' in request.POST:
    # do unsubscribe

to render one submit button if the newletter_sub key is in request.POST.

And we render another submit button if the newsletter_unsub key is in request.POST.

Categories
Python Answers

How to add Multiple ModelAdmins/views for same model in Python Django admin?

To add Multiple ModelAdmins/views for same model in Python Django admin, we can call register with different ModelAdmin and model classes.

For instance, we write

class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'pubdate','user')

class MyPost(Post):
    class Meta:
        proxy = True

class MyPostAdmin(PostAdmin):
    def get_queryset(self, request):
        return self.model.objects.filter(user = request.user)


admin.site.register(Post, PostAdmin)
admin.site.register(MyPost, MyPostAdmin)

to call admin.site.register with the Post model and PostAdmin model admin classes.

And we call admin.site.register with the MyPost model and MyPostAdmin model admin classes.

Categories
Python Answers

How to add CSS styling in Python Django forms?

To add CSS styling in Python Django forms, we can call attrs.update.

For instance, we write

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'})

to call attrs.update with a dict with the class key set to the class with the styles we want to apply on the myfield field.

Categories
Python Answers

How to show form with error message if not valid with Python Django Forms?

To show form with error message if not valid with Python Django Forms, we can use form.errors to check for errors.

For instance, we write

{% if form.errors %}
    {% for field in form %}
        {% for error in field.errors %}
            <div class="alert alert-danger">
                <strong>{{ error|escape }}</strong>
            </div>
        {% endfor %}
    {% endfor %}
    {% for error in form.non_field_errors %}
        <div class="alert alert-danger">
            <strong>{{ error|escape }}</strong>
        </div>
    {% endfor %}
{% endif %}

to use form.errors in the if block to check for errors.

If there’re any errors, then we loop through the form errors and render the field.errors with a for loop.

And we render non-field errors by looping through form.non_field_errors with another for loop.