2nd Screenshot of APIAPI Sample Screenshot
I'm New in Django, i want to help regarding validations in screenshot there is company_name, location, title and user_location fields except user info with proper validation
but i want to remove validations from company_name, location, title and user_location fields how to do?
Please find the above api screenshot and
Please find the below scripts,
views.py
class UserRegistrationView(generics.CreateAPIView):
"""
Register a new user.
"""
queryset = User.objects.all()
permission_classes = (permissions.AllowAny, )
def get_serializer_class(self, user_type=None):
if user_type == 'student':
return StudentRegistrationSerializer
return ProfessionalRegistrationSerializer
def post(self, request, user_type=None, format=None):
serializer_class = self.get_serializer_class(user_type)
serializer = serializer_class(data=request.data, context={'request': request})
if serializer.is_valid(raise_exception=True)
user = serializer.save(work_status=user_type)
token, created = Token.objects.get_or_create(user=user)
data = BasicUserSerializer(user, context={'request': request}).data
data.update({"token": token.key})
return Response(data)
serializes.py
class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):
password = serializers.CharField(max_length=20, write_only=True)
experiences = ExperienceSerializer(required=False)
email = serializers.EmailField()
first_name = serializers.CharField(max_length=30)
last_name = serializers.CharField(max_length=30)
class Meta:
model = User
fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
'experiences', 'headline')
def validate_email(self, value):
from validate_email_address import validate_email
if User.all_objects.filter(email=value.lower()).exists():
raise serializers.ValidationError('User with this email already exists.')
# if not validate_email(value.lower(), check_mx=True):
# raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
return value.lower()
def create(self, validated_data):
experiences = validated_data.pop('experiences')
password = validated_data.pop('password')
email = validated_data.pop('email')
user = User.objects.create(
username=email.lower(),
email=email.lower(),
role_id=1)
user.set_password(password)
user.save()
user_location = experiences.pop('user_location')
if hasattr(user, 'location'):
user.location.location = user_location
user.save()
else:
UserLocation.objects.create(user=user, location=user_location)
Experience.objects.create(user=user)
return user
Another serializes.py for Experiance
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):
user_location = LocationField()
location = LocationField()
class Meta:
model = Experience
fields = ('id', 'company_name', 'company', 'description', 'location',
'title', 'start_date', 'end_date', 'is_current', 'user_location')
I want to Remove Validation from company_name, company, description, location, title, start_date, end_date, user_location
actually these fields are second page means after complete the first step users move on second step so second step fields are optional
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):
user_location = LocationField()
location = LocationField()
class Meta:
model = Experience
fields = ('id', 'company_name', 'company', 'description', 'location',
'title', 'start_date', 'end_date', 'is_current', 'user_location')
def create(self, validated_data):
return Experience.objects.create(field_a='value', field_b='value')
in the above class, what should be do to remove validation of
"error_msg": {
"location": [
"Expected a dictionary of items but got type \"str\"."
],
"start_date": [
"Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
],
"end_date": [
"Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]."
],
"user_location": [
"Expected a dictionary of items but got type \"str\"."
]
}
Experience Model
class Experience(models.Model):
"""
"""
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='experiences')
company_name = models.CharField(max_length=200, db_index=True, blank=True)
company = models.ForeignKey('organisations.Organisation', null=True, blank=True, on_delete=models.SET_NULL)
description = models.TextField(null=True, blank=True)
location = models.ForeignKey('regions.Location', null=True, blank=True, on_delete=models.SET_NULL)
start_date = models.DateField(null=True, blank=True)
end_date = models.DateField(null=True, blank=True)
title = models.CharField(max_length=200, db_index=True, blank=True)
is_current = models.BooleanField(default=False)
is_associated = models.BooleanField(default=False)
created_at = models.DateTimeField(_('created at'), auto_now_add=True)
modified_at = models.DateTimeField(_('modified at'), auto_now=True)
class Meta:
db_table = 'experience'
verbose_name = _('experience')
verbose_name_plural = _('experiences')
ordering = ('-start_date',)
def __str__(self):
return getattr(self, 'title', '')
#property
def experience(self):
if self.end_date:
return (self.end_date - self.start_date).days
else:
return (datetime.datetime.now().date() - self.start_date).days
def get_formated_experience(self):
days = self.experience
total_months = round(days/30)
years = int(total_months/12)
months = round(((total_months/12)%1)*12)
year_txt = 'years' if years > 1 else 'year'
month_txt = 'months' if months > 1 else 'month'
return "%s %s %s %s" %(years, year_txt, months, month_txt)
Location Model
class Location(models.Model):
"""
"""
id = models.TextField(primary_key=True)
display_name = models.TextField(null=True, blank=True)
latitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
longitude = models.DecimalField(max_digits=15, decimal_places=10, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
objects = LocationManager()
You are getting Two types of validation error according to snapshot.
Field is required
Expected a dictionary and got a string
The required field error occurs when you have set field as required in your model. You can change this by adding blank=True in your model for that field.
For second error, your serializer is expecting a dictionary and you are sending a string. You can remove this validation by writing your custom create method.
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):
user_location = LocationField()
location = LocationField()
class Meta:
model = Experience
fields = ('id', 'company_name', 'company', 'description', 'location',
'title', 'start_date', 'end_date', 'is_current', 'user_location')
def create(self, validated_data):
# you create code for that models.
Your seriailzers will be like this
class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer):
password = serializers.CharField(max_length=20, write_only=True)
experiences = ExperienceSerializer(required=False)
email = serializers.EmailField()
first_name = serializers.CharField(max_length=30)
last_name = serializers.CharField(max_length=30)
class Meta:
model = User
fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password',
'experiences', 'headline')
def validate_email(self, value):
from validate_email_address import validate_email
if User.all_objects.filter(email=value.lower()).exists():
raise serializers.ValidationError('User with this email already exists.')
# if not validate_email(value.lower(), check_mx=True):
# raise serializers.ValidationError('It looks like you may have entered an incorrect email address.')
return value.lower()
def create(self, validated_data):
experiences = validated_data.get('experiences')
password = validated_data.get('password')
email = validated_data.get('email')
user = User.objects.create(
username=email.lower(),
email=email.lower(),
role_id=1)
user.set_password(password)
user.save()
user_location = experiences.get('user_location')
location_object = None
if user_location:
location_object, created = Location.objects.get_or_create(display_name=user_location.get('display_name'), latitude= user_location.get('latitude'), longitude=user_location.get('longitude'))
user_experience = Experience.objects.create(user=user, company_name=experiences.get('company_name'), location=location_object)
return user
class ExperienceSerializer(serializers.HyperlinkedModelSerializer):
user_location = LocationField()
location = LocationField()
class Meta:
model = Experience
fields = ('id', 'company_name', 'company', 'description', 'location',
'title', 'start_date', 'end_date', 'is_current', 'user_location')
Related
I joined a project where the code is written on django 2+.
It's a system for patient and doctors.
When a doctor registered a patient, this one gets an email confirmation with a link.
Once he clicks on it she can use the platform.
On her user interface in settings, a patient can update her email and she will get a new link to her new email to confirm that it is her email. Before she clicks on the confirmation link, the email attribute is not changed. only the email candidate is updated and to this one the email is sent.
(if I change the email attribute to the email_candidate one so if she made a mistake on the her email_candidate she won't be able to log in anymore)
Then after the click, the patient email will become the email candidate one.
All this works
on the Patient Support Admin interface, an agent can help patients to update their email also.
But when the action is requested of send an email confirmation the email candidate is not chosen. only the user email is chosen and to it the email confirmation is sent.
I really don't understand how to call maybe the same function of update email.
models.py User
class User(AbstractUser):
objects = UserManager()
is_physician = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
title = models.CharField(choices=TITLE_CHOICES,
max_length=10,
blank=True,
null=True)
first_name = models.CharField(max_length=254, blank=True, null=True, )
last_name = models.CharField(max_length=254, blank=True, null=True, )
birthdate = models.DateField(null=True, blank=True)
home_phone = PhoneNumberField(blank=True, null=True)
mobile_phone = PhoneNumberField(blank=True, null=True)
gender = models.CharField(max_length=1,
choices=GENDER_CHOICES,
blank=True,
null=True)
language = models.CharField(max_length=4,
choices=settings.LANGUAGES,
default='en',
blank=True,
null=True)
email = models.EmailField(unique=True, db_index=True,
error_messages={
'unique': "Email already exists."
}
)
email_candidate = models.EmailField(
max_length=254,
blank=True,
null=True,
default=None)
username = models.CharField(
max_length=30,
unique=True,
blank=True,
null=True,
validators=[
validators.RegexValidator(
r'^\w+$',
'Enter a valid username. This value may contain only '
'letters, numbers and _ character.',
'invalid'
),
],
error_messages={
'unique': "Username already exists."
}
)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
ordering = ('created',)
class Meta(object):
verbose_name = 'User'
verbose_name_plural = 'Users'
# abstract = False
permissions = u_perm.user_permissions
#property
def name(self):
return '{} {}'.format(self.last_name, self.first_name, )
models.py Patient has a OneToOne field user
class Patient(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
physician = models.ForeignKey(Physician,
related_name='patients',
null=True,
blank=True,
on_delete=models.SET_NULL)
address = models.TextField(blank=True, null=True)
city = models.CharField(max_length=85, null=True, blank=True)
country = CountryField(null=True, blank=True)
postal_code = models.CharField(max_length=32, null=True, blank=True)
reminder_hour_default = models.TimeField(
'Send Reminder Time',
default=settings.REMINDER_HOUR_DEFAULT)
is_eligible = models.BooleanField(default=True)
def __str__(self):
return self.user.email
#receiver(post_save, sender=Patient)
#receiver(post_save, sender=User)
def update_status(sender, **kwargs):
def update_patient(instance):
# from pending/disabled to active
current_status = instance.user.status
instance.save()
instance.user.save()
return
def update_user(instance):
pass
instance = kwargs.get('instance')
method_name = get_inner_method(sender)
if instance and method_name:
method_name(instance)
models.py Patient Support
class PatientSupport(Patient):
class Meta:
proxy = True
# Add verbose name
verbose_name = 'Patient Support'
verbose_name_plural = 'Patients Support'
serializers.py UserSerializer with the working endpoint from the patient UI called
update_candidate_email
class UserSerializer(serializers.ModelSerializer):
permission_list = serializers.SerializerMethodField()
permissions = serializers.SerializerMethodField()
user_messages = serializers.SerializerMethodField()
class Meta:
model = User
fields = (
'pk',
'title',
'first_name',
'last_name',
'birthdate',
'email',
'email_candidate',
'home_phone',
'mobile_phone',
'gender',
'language',
'username',
'password',
'is_patient',
)
extra_kwargs = {
'email': {'required': False,
'validators': [],
#'read_only': True,
},
'email_candidate': {'required': False,
'validators': [],
#'read_only': True,
},
'home_phone': {'required': False,
'validators': [], },
'mobile_phone': {'required': False,
'validators': [], },
'is_patient': {'required': False},
'username': {'read_only': True, },
}
def update_candidate_email(self, instance, validated_data, email_candidate):
# if email candidate is None (and changed) -> search for tokens and delete token sent
if instance.email_candidate and email_candidate == None:
instance.email_candidate = email_candidate
instance.save()
ResetPasswordToken.objects.filter(user=instance).delete()
# if email candidate is same to current email -> error - email in use !
if instance.email_candidate == instance.email:
raise serializers.ValidationError(
{'email':
"email candidate cannot be same to current mail"}
)
# if email candidate is not None and already not in use-> save it (email candidate) and send new email replace_email_mail
if email_candidate and email_candidate != instance.email_candidate:
if User.objects.filter(email=email_candidate):
raise serializers.ValidationError(
{'email': "email in use"}
)
ResetPasswordToken.objects.filter(user=instance).delete()
instance.email_candidate = email_candidate
instance.save()
site_domain = Site.objects.filter(name__icontains='admin').first()
# create pass token send mail
token = ResetPasswordToken.objects.create(
user=instance,)
tiny_link = shortener.create(instance,
'https://{}/api/users/verifyMail/?lang={}&token={}®ion={}&patient={}'.format(
site_domain.domain,
instance.language if instance.language else "en",
token.key,
settings.REGION_PREFIX,
instance.is_patient
)
)
from messaging.notify import Notify
activate(instance.language)
msg_name = 'EMAIL_VERIFICATION'
if not instance.is_patient:
msg_name = 'EMAIL_VERIFICATION_STAFF'
notify = Notify()
notify.send_notification(
msg_name=msg_name,
users_pk=[instance.pk, ],
context={
'tiny_link': 'https://{}/s/{}/?lang={}®ion={}'.format(
site_domain.domain,
tiny_link,
instance.language if instance.language else "en",
settings.REGION_PREFIX),
'email_candidate': email_candidate
})
return
admin.py PatientSupportAdmin from there I need to update the email by sending an
email confiramtion to the email_candidate
class PatientSupportAdmin(admin.ModelAdmin):
list_display = ['pk', 'patient', 'patient_email', 'email_candidate' ]
list_display_links = ('pk', 'patient')
def get_queryset(self, request):
qs = super(PatientSupportAdmin, self).get_queryset(request)
return qs.filter(support_consent=True)
fieldsets = (
('User', {
'fields': (
'patient',
'get_gender',
'birthdate',
'home_phone', 'mobile_phone', 'language',
'email', 'username',
'date_modified',
'date_joined',
'status',
'user',
)}),
('Patient', {'fields': ('physician',
'country',
'id_number',
)}),
def patient(self, obj):
return obj.user.get_full_name()
def patient_email(self, obj):
return obj.user.email
def email_candidate(self, obj):
return obj.user.email_candidate
def birthdate(self, obj):
return obj.user.birthdate or ''
def home_phone(self, obj):
return obj.user.home_phone
def mobile_phone(self, obj):
return obj.user.mobile_phone
def email(self, obj):
return obj.user.email
def username(self, obj):
return obj.user.username or ''
actions = [resend_email_verification,
]
admin.py resend_email_verification(), the one i could use but it takes only the
email still registered as user email and not the candidate email to send to
it the email confirmation
def resend_email_verifcation(modeladmin, request, queryset):
for user in queryset:
if 'users/patient' in request.path:
user = user.user
if user.is_patient and not user.patient.is_eligible:
continue
site_domain = Site.objects.filter(name__icontains='admin').first()
token = ResetPasswordToken.objects.create(
user=user, )
reset_password_token_created.send(
sender=modeladmin.__class__, reset_password_token=token)
So the important part to send email in UserSerializer is
if email_candidate and email_candidate != instance.email_candidate:
You can cheat a little bit to reuse that method with a new action in admin
def send_verification_email_for_email_candidate(modeladmin, request, queryset):
for user in queryset:
email_candidate = user.email_candidate
if not email_candidate:
continue # defensive a little bit to ignore other use cases in UserSerializer
user.email_candidate = f'{email_candidate}random' # to trigger the condition above
UserSerializer().update_candidate_email(user, {}, email_candidate)
But I will recommend rewriting the function or copying that logic part here instead
I have a User model and a phone model the phone model has a foreign key relation with the user model I read the docs on NestedSerializers and tried it to no avail.
The model
class Phone(models.Model):
phone = models.CharField(
_("phone number"), max_length=13, blank=True, null=True)
otp = IntegerRangeField(min_value=6, max_value=6, blank=True, null=True)
def __str__(self):
return self.phone
class User(AbstractBaseUser, PermissionsMixin):
phone = models.ForeignKey(
Phone, on_delete=models.CASCADE, related_name="userphone", blank=False, null=True)
this is my serializers.py file
class PhoneSerializer(serializers.ModelSerializer):
# opt = serializers.IntegerField(read_only=True)
class Meta:
model = Phone
fields = ['phone']
class RegisterSerializerBase(serializers.ModelSerializer):
phone = PhoneSerializer(allow_null=True)
# otp = PhoneSerializer(many=True, read_only=True)
email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())])
password = serializers.CharField(
write_only=True, re
quired=True, validators=[validate_password])
password2 = serializers.CharField(write_only=True, required=True)
class Meta:
model = User
fields = ('email', 'firstname', 'lastname', 'password', 'password2',
'phone',)
extra_kwargs = {'password': {'write_only': True},
'password2': {'write_only': True},
'firstname': {'required': True},
'lastname': {'required': True},
}
def validate(self, attrs):
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError(
{"password": "Password fields didn't match."})
return attrs
def create(self, validated_data):
phones = validated_data.pop('phone')
instance = User.objects.create(
email=validated_data['email'],
firstname=validated_data['firstname'],
lastname=validated_data['lastname'],
is_active='True',
type=User.TYPES.OWNER,
)
instance.set_password(validated_data['password'])
for phone in phones:
Phone.objects.create(instance=instance, **phone)
instance.save()
return instance
when I go the the Browsable API and create a user with the credentials an error comes up saying
django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() argument after ** must be a mapping, not str
Check if this helps you -
Models -
User model is already defined.
class Phone(models.Model):
user = models.Foerienkey(User, related_name="abc")
phone = models.CharField(max_length=13, blank=True, null=True)
Serializer -
from rest_framework import serializers
from django.contrib.auth.models import User
class CurrentUserSerializer(serializers.Serializer):
abc = phoneserializer(many=True, required=False)
## define phone serializer before currentuser serializer
class Meta:
model = User
fields = ('username', 'email', 'id', 'abc')
Views -
##user create method
def create(self, validated_data):
phones = validated_data.pop('recievedPhoneDataArray')
instance = User.objects.create(
email=validated_data['email'],
firstname=validated_data['firstname'],
lastname=validated_data['lastname'],
is_active='True',
type=User.TYPES.OWNER,
)
instance.set_password(validated_data['password'])
for phone in phones:
Phone.objects.create(user=instance, **phone)
instance.save()
return instance
You will have to extend the registeruserserializer from rest frameowrk. may be.
I have the following Model, ModelForm and View:
class Clinic(models.Model):
clinicid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=60)
label = models.SlugField(max_length=25)
# logo =
email = models.EmailField(max_length=50, default='')
mobile = models.CharField(max_length=15, default='')
alternate = models.CharField(max_length=15, default='', blank=True)
about = models.CharField(max_length=250, blank=True)
state = models.CharField(max_length=25)
city = models.CharField(max_length=35)
locality = models.CharField(max_length=35)
pincode = models.IntegerField(default=0)
address = models.TextField(max_length=80, default='', blank=True)
website = models.URLField(blank=True)
class ClinicMetaForm(ModelForm):
class Meta:
model = Clinic
fields = [
'name',
'label',
'email',
'mobile',
'alternate',
'about',
'state',
'city',
'locality',
'pincode',
'address',
'website'
]
unique_together = ["name", "mobile", "email"]
def newclinic(request):
if request.method == 'POST':
print('New clinic setup')
form = ClinicMetaForm(request.POST)
form.save()
msg = "Successfully saved new clinic"
print(msg)
else:
form = ClinicMetaForm()
msg=''
return render(request, 'clinic/newclinic.html', {'form': form, 'msg': msg})
The problem is that when the same data is submitted, I get duplicate entries being saved, even though I am using unique_together. Why is this happening? How can I avoid it?
You should move unique_together to model.
And if you want to add some logic in your form just overwrite validate_unique
def validate_unique(self):
#your logic here
try:
self.instance.validate_unique(exclude=exclude)
except ValidationError, e:
self._update_errors(e.message_dict)
I've simplified my code to make problem more clear.
I have two related models in my Django REST project. In my models.py:
class ClinicalResearch(models.Model):
name = models.CharField(max_length=150, null=True)
description = models.TextField(blank=True, null=True)
class Patient(models.Model):
research = models.ForeignKey(ClinicalResearch, on_delete=models.CASCADE, blank=True)
first_name = models.CharField(max_length=50)
second_name = models.CharField(max_length=50, blank=True, null=True)
middle_name = models.CharField(max_length=50, blank=True, null=True)
location = models.CharField(max_length=50, blank=True)
birth_date = models.DateTimeField(blank=True, null=True)
observation_date = models.DateTimeField(blank=True, null=True)
desease = models.CharField(max_length=50, blank=True, null=True)
desease_date = models.DateTimeField(blank=True, null=True)
gender = models.CharField(max_length=10)
Then I create a serialiser:
class PatientSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Patient
fields = ('id', 'research_id', 'first_name', 'second_name', 'middle_name', 'location', 'birth_date', 'observation_date', 'desease', 'desease_date', 'gender')
def create(self, validated_data):
# for tests only
print(validated_data)
return Patient(**validated_data)
View set:
class PatientViewSet(viewsets.ModelViewSet):
queryset = Patient.objects.all()
serializer_class = PatientSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('id', 'research_id', 'first_name', 'second_name', 'middle_name', 'location', 'birth_date', 'observation_date', 'desease', 'desease_date', 'gender')
Router:
router.register(r'patients', ItemViewSet)
This implementation works fine for models without foreign keys. But when I post something like:
{
'id': null,
'research_id': 1,
'first_name': "john",
'second_name': "doe",
'middle_name', "",
'location': "Love Street",
'birth_date': "...",
'observation_date': "...",
'desease': "Lovefool",
'desease_date': "...",
"gender": "male to fem"
}
(the project with id=1 exists)
my ItemSerializer doesn't pass { research_id: 1 } to validated_fields.
The project_id field is completely lost during validation.
How to configure Serializer or ViewSet to make it workable?
Looks like problem related to HyperlinkedModelSerializer in this case Django expecting url for related object instead of id. Try to override type of serializer's field research:
class PatientSerializer(serializers.HyperlinkedModelSerializer):
research = serializers.PrimaryKeyRelatedField()
class Meta:
model = Patient
fields = ('id', 'research', 'first_name', 'second_name', 'middle_name', 'location', 'birth_date', 'observation_date', 'desease', 'desease_date', 'gender')
def create(self, validated_data):
# for tests only
print(validated_data)
return Patient(**validated_data)
# If you need URLs for representation use this method
def to_representation(self, instance):
"""Set field type for output only"""
self.fields['research'] = serializers.HyperlinkedRelatedField()
return super().to_representation(instance)
You have to link it:
accept
Looks like problem related to HyperlinkedModelSerializer in this case Django expecting url for related object instead of id. Try to override type of serializer's field research:
class PatientSerializer(serializers.ModelSerializer):
research = serializers.PrimaryKeyRelatedField(queryset=ClinicalResearch.objects.all())
class Meta:
model = Patient
fields = ('id', 'research', 'first_name', 'second_name', 'middle_name', 'location', 'birth_date', 'observation_date', 'desease', 'desease_date', 'gender')
def create(self, validated_data):
# for tests only
print(validated_data)
return Patient.objects.create(**validated_data)
I'm using Django 2.0 and Django REST Framework to write REST API.
My contacts/models.py contains
class Contact(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100, blank=True, null=True)
date_of_birth = models.DateField(blank=True, null=True)
avatar = models.ImageField(upload_to='contact/%Y/%m/%d', blank=True)
class Meta:
db_table = 'contacts'
class ContactPhoneNumber(models.Model):
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
phone = models.CharField(max_length=100)
class Meta:
db_table = 'contact_phone_numbers'
and contacts/serializers.py
class ContactPhoneNumberSerializer(serializers.ModelSerializer):
class Meta:
model = ContactPhoneNumber
fields = ('id', 'phone', 'primary', 'created', 'modified')
class ContactSerializer(serializers.HyperlinkedModelSerializer):
phone_numbers = ContactPhoneNumberSerializer(source='contactphonenumber_set', many=True)
url = serializers.HyperlinkedRelatedField(
view_name='contacts:detail',
read_only=True
)
class Meta:
model = Contact
fields = ('url', 'id', 'first_name', 'last_name', 'date_of_birth', 'avatar', 'phone_numbers')
def create(self, validated_data):
print(validated_data)
instance = Contact.objects.create(**validated_data)
instance.save()
return instance
I want to be able to create contact along with phone_number and one contact can have many phone_numbers.
But when I send POST request with only contact data, it gives error as
'contactphonenumber_set' is an invalid keyword argument for this function
on calling contacts only is showing all associted mobile numbers in json response but unable to create record.
print(validated_data) gives following data
{'first_name': 'Anshuman', 'last_name': 'Upadhyay', 'date_of_birth': datetime.date(2018, 5, 15), 'contactphonenumber_set': [], 'user_id': <SimpleLazyObject: <User: anuj>>}
How can I create related multiple fields with REST Framework?
You cannot pass contactphonenumber_set to objects.create() method directly. You should create each related phonenumber separately, like this:
def create(self, validated_data):
print(validated_data)
phone_numbers = validated_data.pop('contactphonenumber_set')
instance = Contact.objects.create(**validated_data)
for phone_data in phone_numbers:
ContactPhoneNumber.objects.create(contact=instance, **phone_data)
return instance
See details about writable nested serializers here.
Give you a demo with drf-writable-nested
models.py:
class UnitGroup(models.Model):
name = models.CharField(max_length=255,
verbose_name='名称')
class Unit(models.Model):
unit_group = models.ForeignKey('medicine.UnitGroup',
related_name='unit_unit_group',
null=True,
on_delete=models.SET_NULL,
verbose_name='unit_group')
name = models.CharField(max_length=255,
verbose_name='name')
display_name = models.CharField(max_length=255,
verbose_name='display_name')
serializers.py:
class UnitCreateSerializer(ModelSerializer):
class Meta:
model = Unit
fields = ('name', 'display_name', 'ratio', 'is_active')
class UnitGroupCreateSerializer(WritableNestedModelSerializer):
unit_unit_group = UnitCreateSerializer(many=True)
class Meta:
model = UnitGroup
fields = ('unit_unit_group', 'name')
tests.py:
class UnitGroupTests(APITestCase):
def setUp(self):
try:
self.user = User.objects.get(tel='18094213198')
except User.DoesNotExist:
self.user = User.objects.create_user(tel='18094213198', password='123456')
self.user.user_permissions.add(*get_model_permission(UnitGroup))
token, _ = Token.objects.get_or_create(user=self.user)
self.access_token = token.access_token
def test_create(self):
"""create"""
url = reverse('unitgroup-list')
self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.access_token)
data = {'name': 'Widget', 'unit_unit_group': [{'name': '1', 'display_name': 'yi'}]}
response = self.client.post(url, data, format='json')
print([(x, x.unit_group) for x in Unit.objects.all()])
print('create', json.dumps(response.data, ensure_ascii=False, indent=2))
self.assertEqual(response.status_code, status.HTTP_200_OK)
test output:
[(<Unit: 1>, <UnitGroup: Widget>)]
create{
"id": 1,
"name": "Widget",
"create_time": "2018-05-08 16:59:51",
"update_time": "2018-05-08 16:59:51"
}