Categories
Python Answers

How to add optional URL parameters with Python Django?

To add optional URL parameters with Python Django, we call add multiple rules for the same URL.

For instance, we write

urlpatterns = patterns('',
    url(r'^project_config/$', views.foo),
    url(r'^project_config/(?P<product>\w+)/$', views.foo),
    url(r'^project_config/(?P<product>\w+)/(?P<project_id>\w+)/$', views.foo),
)

to add 3 URL patterns that has no URL parameters, the product parameter only, and the product and project_id` parameters.

And we map all 3 to the same view.

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.