Categories
Python Answers

How to clone a Python Django model instance object and save it to the database?

To clone a Python Django model instance object and save it to the database, we can use the get method.

For instance, we write

obj = Foo.objects.get(pk=<some_existing_pk>)
obj.pk = None
obj.save()

to get the object with Foo.objects.get.

And then we set pk to None.

Finally, we call save to save the data.

Categories
Python Answers

How to concatenate strings in Python Django templates?

To concatenate strings in Python Django templates, we can use the | operator.

For instance, we write

{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}

to use | and add to concatenate the shop_name variable between 'sho/' and '/base.html' in our template.

Categories
Python Answers

How to use permission_required decorators on Python Django class-based views?

To use permission_required decorators on Python Django class-based views, we add the views.

And then we use the method_decorator to add the permissions required.

For instance, we write

urlpatterns = [
    path('view/',login_required(ViewSpaceIndex.as_view(..)),
    #...
]

to register the views.

Then we add

from django.utils.decorators import method_decorator

@method_decorator(login_required, name='dispatch')
class ViewSpaceIndex(TemplateView):
    template_name = 'secret.html'

to apply the method_decorator decorator and use the login_required function we created to let us enforce login on the ViewSpaceIndex view.

Categories
Python Answers

How to add ModelForm for Many-to-Many fields with Python Django?

To add ModelForm for Many-to-Many fields with Python Django, we can add an intermediary table into our database that has the many to many relationships.

For instance, we write

class Pizza(models.Model):
    name = models.CharField(max_length=50)

class Topping(models.Model):
    name = models.CharField(max_length=50)
    ison = models.ManyToManyField(Pizza, through='PizzaTopping')

class PizzaTopping(models.Model):
    pizza = models.ForeignKey(Pizza)
    topping = models.ForeignKey(Topping)

to add the PizzaTopping model that has the pizza and topping fields that references Pizza and Topping.

Then in admin.py, we add

class PizzaToppingInline(admin.TabularInline):
    model = PizzaTopping

class PizzaAdmin(admin.ModelAdmin):
    inlines = [PizzaToppingInline,]

class ToppingAdmin(admin.ModelAdmin):
    inlines = [PizzaToppingInline,]

admin.site.register(Pizza, PizzaAdmin)
admin.site.register(Topping, ToppingAdmin)

to create the PizzaToppingInline class that has model set to PizzaTopping to let us modify PizzaTopping from PizzaAdmin and ToppingAdmin.

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.