Я работаю над проектом django, и у меня есть модель пользователя, и у каждого пользователя есть UserProfile.
Я хочу реализовать форму, чтобы пользователь мог обновить изображение своего профиля.
Это то, что у меня есть:
modely.py
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE)
following = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='followed_by')
image = models.ImageField(upload_to=upload_image_path,null=True,blank=True, default="False")
is_online = models.BooleanField(default=False,null=True,blank=True )
username = models.CharField(max_length=200,null=True,blank=True)
follows = models.CharField(max_length=400,null=True,blank=True)
objects = UserProfileManager()
views.py
def update_image(request,username):
response_data = {}
if request.method == 'POST':
image = request.POST.get('image')
response_data['image'] = image
UserProfile.objects.create(
image = image
)
return JsonResponse(response_data)
context = {
'image':image
}
return render(request, 'userprofile.html', context)
форм .py
class ProfileUpdateForm(forms.Form):
image = forms.ImageField(required=False,label='image')
def clean(self):
blocked_chars = set(punctuation)
cleaned_data = super(ProfileUpdateForm, self).clean()
image = cleaned_data.get('image')
filename, file_extension = os.path.splitext(image)
if not ".jpg" or '.png' in file_extension:
raise forms.ValidationError(filename + 'is not an image')
return image
urls.py
url(r'^(?P<username>[\w-]+)/update-image/$', update_image, name='update_image'),
index. html
<form id="profile_form" class="profile_form" method='POST' enctype="multipart/form-data" form_data="{{ request.user.profile.get_update_image_url }}">
{% csrf_token %}
<div class="profile_form_group">
<div class="profile_table">
<div class="utable_row">
<div class="utable_th_1">
<span class="user_detail"> {{ form }}</span>
</div>
<div class="utable_th_2">
<span class="user_detail">
<input class='profile_img_btn' type="submit" value="Update Image"/>
</span>
</div>
</div>
</div>
</div>
</form>
main. js
var i_link = $('.profile_form').attr('form_data');
console.log(i_link)
$(document).on('submit', '#profile_form',function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: i_link,
data:{
image :$('#id_image').val(),
csrfmiddlewaretoken :$('input[name=csrfmiddlewaretoken]').val(),
action : 'post'
},
success:function(json,data,i_link){
console.log("HEY, THIS IS WORKING !" + data + i_link)
document.getElementById("profile_form").reset();
},
error : function(xhr,errmsg,err) {
console.log("HEY, THIS IS NOT WORKING !")
console.log(xhr.status + ": " + xhr.responseText);
}
});
});
Я получаю эту ошибку:
NOT NULL constraint failed: accounts_userprofile.user_id
Как обновить отдельные поля модели?
Спасибо