Categories
Python Answers

How to filter ForeignKey choices in a Python Django ModelForm?

To filter ForeignKey choices in a Python Django ModelForm, we set the quertset property to the queryset with the filtered data.

For instance, we write

class ClientAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ClientAdminForm, self).__init__(*args, **kwargs)
        # access object through self.instance...
        self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)

class ClientAdmin(admin.ModelAdmin):
    form = ClientAdminForm

to add the ClientAdminForm that sets the base_rate field’s queryset to the filtered Rate query set with

Rate.objects.filter(company=self.instance.company)

Then we add the ClientAdminForm form as the form to use in the ClientAdmin section of Django admin.

Categories
Python Answers

How to capture URL parameters in request.GET with Python Django?

To capture URL parameters in request.GET with Python Django, we can add a view to match a URL pattern that takes a URL parameter.

Then we can get the parameter value from the view function’s parameter.

For instance, we write

(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),

to add a view that matches the r'^user/(?P<username>\w{0,50})/$' route.

Then in our view file, we add a view with

def profile_page(request, username):
    # ...

to get the username URL parameter value from username.

Categories
Python Answers

How to make Python Django serve downloadable files?

To make Python Django serve downloadable files, we can return a response with some special values.

For instance, we write

from django.utils.encoding import smart_str

response = HttpResponse(content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path_to_file)
return response

to create a HttpResponse instance and assign it to response.

Then we set the Content-Disposition response header with

response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)

And then we set the X-Sendfile header to the path of the file with

response['X-Sendfile'] = smart_str(path_to_file)

And then we return the response in our view.

Categories
Python Answers

How to create a JSON response using Django and Python?

To create a JSON response using Django and Python, we can use the JsonResponse class.

For instance, we write

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

to create a JsonResponse instance with a dictionary that we want to return as the response JSON body.

Categories
Python Answers

How to check if a field has changed when saving with Python Django?

To check if a field has changed when saving with Python Django, we can override the `init method of the model class to keep a copt of the original value.

For instance, we write

class Person(models.Model):

    name = models.CharField()

    __original_name = None

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__original_name = self.name

    def save(
        self,
        force_insert=False,
        force_update=False,
        *args,
        **kwargs
        ):
        if self.name != self.__original_name:
            super().save(force_insert, force_update, *args, **kwargs)
            self.__original_name = self.name

to add the __init__ method that sets the __original_name variable to self.name to keep the original name value.

And then in the if block in save, we check self.name to see if it’s different from self.__original_name to see if it’s saved with a new value.