Categories
Python Answers

How to add File Upload with Python Django Rest Framework?

To add File Upload with Python Django Rest Framework, we can add a FileField into our model.

For instance, we write

class ExperimentViewSet(ModelViewSet):
    queryset = Experiment.objects.all()
    serializer_class = ExperimentSerializer

    def pre_save(self, obj):
        obj.samplesheet = self.request.FILES.get('file')

class Experiment(Model):
    notes = TextField(blank=True)
    samplesheet = FileField(blank=True, default='')
    user = ForeignKey(User, related_name='experiments')

class ExperimentSerializer(ModelSerializer):
    class Meta:
        model = Experiment
        fields = ('id', 'notes', 'samplesheet', 'user')

to create the ExperimentViewSet in Django that gets the file from self.request.FILES.get('file') in pre_save.

And then we create the Experiment model with the FileField that we use with ExperimentViewSet.

And then we add the ExperimentSerializer that has the samplesheet in the fields.

Categories
Python Answers

How to fix Python Django DB Settings ‘Improperly Configured’ Error?

To fix Python Django DB Settings ‘Improperly Configured’ Error, we can load the settings with settings.configure.

For instance, we write

from django.conf import settings

settings.configure()

to call settings.configure to load the settings for our Python Django app.

Categories
Python Answers

How to dynamically compose an OR query filter in Python Django?

To dynamically compose an OR query filter in Python Django, we can call filter with Q objects combined with |.

For instance, we write

values = [1,2,3]

queries = [Q(pk=value) for value in values]
query = queries.pop()
for item in queries:
    query |= item

Article.objects.filter(query)

to create the queries list with a list of Q object with the conditions we want to filter by.

Then we loop through the queries to combine them with |= into query.

Finally, we call filter with query to filter by all the conditions.

Categories
Python Answers

How to use use different serializers in the same ModelViewSet with Python Django rest framework?

To use use different serializers in the same ModelViewSet with Python Django rest framework, we can add the get_serializer_class into a mixin.

For instance, we write

    def get_serializer_class(self):
        try:
            return self.serializer_action_classes[self.action]
        except (KeyError, AttributeError):
            return super(MultiSerializerViewSetMixin, self).get_serializer_class()

to add the get_serializer_class method.

In it, we look for serializer class in self.serializer_action_classes, which should be a dict mapping action name (key) to serializer class (value).

And if there’s no entry for that action then just fallback to the regular get_serializer_class lookup by returning self.serializer_class, DefaultSerializer.

Categories
Python Answers

How to create email templates with Python Django?

To create email templates with Python Django, we use the EmailMultiAlternatives class.

For instance, we write

from django.core.mail import EmailMultiAlternatives

subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
text_content = 'This is an important message.'
html_content = '<p>This is an <strong>important</strong> message.</p>'
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()

to create a EmailMultiAlternatives instance with the subject, text_content, from_email, and to.

And then we add HTML content by calling attach_alternative with html_content and 'text/html'.

Finally, we call send to send the email.