How to Ignore Required Fields when updating user account details Django-Rest, ReactJS
I have made a field for profile image in database:
serializers.py
class UserCreateSerializer(UserCreateSerializer):
class Meta(UserCreateSerializer.Meta):
model=User
fields=('id','username','email','password','first_name','last_name','profile_image')
models.py
I have made the following function for upload
def upload_path(instance, pos, filname):
return '/'.join(['profiles', filname])
User Class
class User(AbstractBaseUser):
email = models.EmailField(max_length=255, unique=True)
username = models.CharField(max_length=255, unique=True)
first_name = models.CharField(max_length=255, unique=False, default='')
last_name = models.CharField(max_length=255, unique=False, default='')
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
objects = UserAccountManager()
profile_image = models.ImageField(
blank=True, null=True, upload_to=objects.upload_path)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
views.py
My post method is:
def post(self, request):
serializer = PostCreateSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
items = Post.objects.all()
serializer = PostCreateSerializer(items, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
serializer_class = UserCreateSerializer
if serializer_class.is_valid():
serializer_class.save()
queryset = User.objects.all()
profile_image = request.data['profile_image']
User.objects.create(queryset, profile_image=profile_image)
return HttpResponse({'message':'profile image uploaded'}, status = 200)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
On my ReactJS frontend, I am doing the following:
I have made the following axios post method:
export const uploadProfile = (profile_image, id) => async (dispatch) => {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify({ profile_image });
alert("1234");
console.log(body)
try {
await axios.post(
`${process.env.REACT_APP_API_URL}auth/users/`,
body,
config
);
console.log(Response);
dispatch({
type: UPLOAD_SUCCESS,
});
} catch (err) {
dispatch({
type: UPLOAD_FAIL,
});
}
};
This is the form I am using it on:
const ChoosePhotoWidget = ({ title, photo, uploadProfile }) => {
// const [requestSent, setrequestSent] = useState(false);
const [data, setdata] = useState({
profile_image: "",
});
const onchangeEvent = (event) => {
const value = event.target.value;
const name = event.target.name;
setdata((preValue) => {
return {
...preValue,
[name]: value,
};
});
};
const { profile_image } = data;
const onsubmit = async (event) => {
event.preventDefault();
uploadProfile(profile_image);
};
return (
<Form onSubmit={onsubmit}>
<Card border="light" className="bg-white shadow-sm mb-4">
<Card.Body>
<h5 className="mb-4">{title}</h5>
<div className="d-xl-flex align-items-center">
<div className="user-avatar xl-avatar">
<Image fluid rounded src={profile_image} />
</div>
<div className="file-field">
<div className="d-flex justify-content-xl-center ms-xl-3">
<div className="d-flex">
<span className="icon icon-md">
<FontAwesomeIcon icon={faPaperclip} className="me-3" />
</span>
{/* profile image */}
<div>
<input type="file" name='profile_image' onChange={onchangeEvent} />
<div className="d-md-block text-start">
<div className="fw-normal text-dark mb-1">
Choose Image
</div>
<div className="text-gray small">
JPG, GIF or PNG. Max size of 800K
</div>
<div>
<p></p>
<Button variant="tertiary text-white" type="submit">
Change
</Button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</Card.Body>
</Card>
</Form>
);
};
const mapStateToProps = (state) => ({
isAuthenticated: state.auth.isAuthenticated,
pagestate: state.auth.pagestate,
});
export default connect(mapStateToProps, { uploadProfile })(ChoosePhotoWidget);
It obviously gives me required fields error
Is there any way where I can post current values for required fields. Or would that register a new user instead? I have no ideas on how to do it without making another table for profile images in my database.