How to use “get_or_create()” in Django?

From the documentation get_or_create: # get_or_create() a person with similar first names. p, created = Person.objects.get_or_create( first_name=”John”, last_name=”Lennon”, defaults={‘birthday’: date(1940, 10, 9)}, ) # get_or_create() didn’t have to create an object. >>> created False Explanation: Fields to be evaluated for similarity, have to be mentioned outside defaults. Rest of the fields have to be included … Read more

Sorting a Django QuerySet by a property (not a field) of the Model

Use QuerySet.extra() along with CASE … END to define a new field, and sort on that. Stops.objects.extra(select={‘cost’: ‘CASE WHEN price=0 THEN 0 ‘ ‘WHEN type=:EXPRESS_STOP THEN price/2 WHEN type=:LOCAL_STOP THEN price*2’}, order_by=[‘cost’]) That, or cast the QuerySet returned from the rest to a list, then use L.sort(key=operator.attrgetter(‘cost’)) on it.

How to limit queryset/the records to view in Django admin site?

In your admin definition, you can define a queryset() method that returns the queryset for that model’s admin. eg: class MyModelAdmin(admin.ModelAdmin): def queryset(self, request): qs = super(MyModelAdmin, self).queryset(request) return qs.filter(user=request.user) Then only objects with user=request.user will be visible in the admin.

Django admin file upload with current model id

I ran into the same problem. Okm’s answer sent me on the right path but it seems to me it is possible to get the same functionality by just overriding the save() method of your Model. def save(self, *args, **kwargs): if self.pk is None: saved_image = self.image self.image = None super(Material, self).save(*args, **kwargs) self.image = … Read more

How to assign currently logged in user as default value for a model field?

If you want to achieve this within the admin interface, you can use the save_model method. See below an example: class List(models.Model): title = models.CharField(max_length=64) author = models.ForeignKey(User) class ListAdmin(admin.ModelAdmin): fields = (‘title’,) def save_model(self, request, obj, form, change): obj.author = request.user obj.save()

django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug

The reason for this constrain could be that you didn’t have any field called slug in Category class when you have initially migrated it (First Migration), and after adding this field in the model, when you ran makemigrations, you have set default value to something static value(i.e None or ” etc), and which broke the … Read more

Django: Validate file type of uploaded file

Validating files is a common challenge, so I would like to use a validator: import magic from django.utils.deconstruct import deconstructible from django.template.defaultfilters import filesizeformat @deconstructible class FileValidator(object): error_messages = { ‘max_size’: (“Ensure this file size is not greater than %(max_size)s.” ” Your file size is %(size)s.”), ‘min_size’: (“Ensure this file size is not less than … Read more

tech