0

Im working on a django project and I have a user model and each user has a UserProfile.

I want to implement a form so that a user can update his profile picture.

This is what I have so far:


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) 

forms.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); 
    }
    });
});

I get this error:

NOT NULL constraint failed: accounts_userprofile.user_id

How can I update individual fields of a model?

Thank you

pyjama
  • 135
  • 1
  • 8

2 Answers2

0

You're missing your model. Could you please share that information.

Likely the issue is that your model is expecting this id to be filled in the profile but your form is not setting the value. The fix is probably just adding a default value or setting null or blank to True

jcirni
  • 57
  • 4
  • seems to be a decently common issue this is likely related: https://stackoverflow.com/questions/16589069/foreignkey-does-not-allow-null-values – jcirni Feb 24 '20 at 16:48
  • added to the post – pyjama Feb 24 '20 at 16:51
  • Yes, it's pretty much what I expected. Your Profile model is expecting you to be providing a user field, which in your error message is identified as [app]_[model].[field] in your case it is "accounts_userprofile.user_id" by default the suffix _id is added in update_image() your UserProfile.objects.create() needs to provide all the required model fields. Good luck! – jcirni Feb 24 '20 at 17:26
0

The problem is in your update_image view.

you are attempting to create and new profile without providing the required model fields

UserProfile.objects.create(
        image = image
        )

you should get the desired instance with the provided user in the request and then update the image field before saving/creating

jcirni
  • 57
  • 4