How do I access the max_length of a model field in Django? I am writing a serializer with the REST framework and I want to write a custom validation function to validate the length. Note that i am using SQLite, so the database itself does not enforce the max_length.
You can use the Model _meta API for accessing details of your model's fields.
Here's an example:
class MyModel(models.Model):
title = models.CharField(max_length=200)
# retrieve the max_length
MyModel._meta.get_field('title').max_length
The _meta became a formal API in Django version 1.8. The documentation can be found at https://docs.djangoproject.com/en/stable/ref/models/meta/
Related
How to sanitize the charfield in Django Rest Framework Using Serializer Or Django models itself. No idea how to secure
This value can be makes my app vulnerable.... Like XSS
<script>alert('Hacked')</script>
Check the serializer code
class Meta:
model = MyDB
fields = ['id','name','price','isAvailable','isVeg','hotelID']
read_only_fields = ['id']
I Have seen Bleach. But it feels like not dynamic, i.e cant be applied to all input field at same time.
Is any option that can be used dynamic. I'm not pro in Django so please suggest me
I've written my first application Django 2.0.
Everything is working fine and the application is almost ready when I realized to replace id primary key field from default integer type to UUID to make database entry more secure.
When I searched for this how to change id of user table to UUID I got many tutorials extending AbstractBaseUser.
Here is I have written own User model.
account/models.py
class User(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
But I'm confused more with examples on different sources.
Every example is adding few more fields in extended model like
first_name
last_name
is_staff
is_admin
active
and functions as
def get_fullname(self):
def get_shortname(self):
etc.
I think all these fields and functions are there by default in AUTH_USER_MODEL.
Does extending AbstractBaseUser overwrites AUTH_USER_MODEL and it is required to add all fields which is there by default?
also, I'm using settings.AUTH_USER_MODEL as foreign key in different models. Should It be replaced by account.User model?
I'm also using django-allauth plugin to enable login using the social network and use email only for authentication. Do I require to add email field in the extended model with unique=True?
Django AbstractBaseUser provides only following fields: password, last_login, is_active. So if you are using custom User model inherited from AbstractBaseUser you need to define all other fields such as email manually.
As another part of question just adding AUTH_USER_MODEL = 'users.User' to your settings.py file should make everything works without replace code in your project.
UPD
If you need field like first_name, last_name, etc. to be includet to the model you can use AbstractUser instead of AbstractBaseUser.
As the Django documentation indicates, it's difficult to extend the User table after-the-fact, and not recommended at all for apps. A better way is to create an auxiliary table which has a 1:1 relationship with the user-id. Leave Django's user-table alone and just use this other table to pony-up to it.
The "Django Annoying" project, at https://github.com/skorokithakis/django-annoying#autoonetoonefield, has some very useful "juice" to make this much easier: an AutoOneToOneField. Whereas Django's foreign-key field will throw an error if an record doesn't exist, this field will automagically create one on-the-fly, thereby side-stepping the entire issue. (The documentation page linked-to above shows exactly how this is done.)
How do you enforce a required field when using POST in django view or django-rest-framework view other than this:
required_field = ['id', 'email', 'name']
for f in required_field:
if not f in request.POST:
print "Required field missing"
Is there a better way?
Django REST Framework allows you to specify required=True when initializing the field. If you are using a model, Django REST Framework will automatically detect if the field is required based on if the field has empty=False specified when it was initialized.
When working outside of Django REST Framework, there is no better way of checking for required fields than doing what you are currently doing.
Using Django Rest Framework I am trying to update a model with an image field. When I try to update the other fields on the model I get this error:
{"image": ["No file was submitted. Check the encoding type on the form."]}
Here is a simply idea of the serializer. The image field it returns on a GET call just has the file name.
class ModelWithImageSerializer(serializers.ModelSerializer):
image = serializers.ImageField('image', required=False)
class Meta:
model = models.Level
fields = ('id','name', 'image')
How do I update my model without resubmitting the file?
Django REST allows to submit partial PATCH requests (docs). Just make sure to use an UpdateAPIView (or variant of this) which automatically allows this. The idea of partial updates is that they do not require you to submit all model fields which will accomplish the behavior you need.
I was having the same issue with a FileField. I had to delete the FileField property on the PUT request so that it won't override the stored value. Just make sure that blank=True on the Model so that it's an optional field. I'm using DRF 2.4.4.
Make the ImageField as read_only then it will work but when you have post method , then it won't work.
I need a model field composed of a numeric string for a Django app I'm working on and since one doesn't exist I need to roll my own. Now I understand how "get_db_prep_value" and such work, and how to extend the Model itself (the django documentation on custom model fields is an invaluable resource.), but for the life of me I can't seem to figure out how to make the admin interface error properly based on input constraints.
How do I make the associated form field in the admin error on incorrect input?
Have a look at the Form and field validation section in the Django documentation, maybe that's what you're looking for?
You would have to make a new type of form field for your custom model field.
All you need to do is define a custom modelform which uses your new field, and then tell the admin to use that form to edit your models.
class MyModelForm(forms.ModelForm):
myfield = MyCustomField()
class Meta:
model = MyModel
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm