IntegrityError в /password-manager/user/17/add_password/

Я пытаюсь реализовать приложение password-manager для хранения паролей. Здесь я пытаюсь добавить пароль для текущего пользователя. Я получаю следующую ошибку:

IntegrityError at /password-manager/user/17/add_password/ Ограничение FOREIGN KEY не сработало

Вот такой вид:

def user_add_password(request,id):
    obj = get_object_or_404(UserModel, id=id)
    form = PasswordForm(request.POST or None, user=obj)
    if form.is_valid():
        form.instance.user = obj
        form.save()
        return redirect(reverse('password:user_home_page', kwargs={'id': obj.id}))

    context = {
        'form': form,
        'object': obj
    }    
    return render(request, 'add_password.html', context)

Это форма:

class PasswordForm(forms.ModelForm):
    class Meta:
        model = Password
        fields = ['user', 'platform', 'password']
        widgets = {
            'user': forms.HiddenInput(),
        }        

    def __init__(self, *args, **kwargs):
        # Get the user from the initial data or set it to None
        user = kwargs.pop('user', None)
        print(user,'@@@@@@@@@@@@@@@@@@@@22')
        
        # Call the parent constructor
        super(PasswordForm, self).__init__(*args, **kwargs)
        
        # Set the initial value for the user field
        if user:
            self.fields['user'].initial = user

Вот модели:

secret_key = settings.SECRET_KEY
f = settings.FERNET_INSTANCE
salt = settings.SALT


# Create your models here.
class UserModel(models.Model):
    username = models.CharField(max_length=100, unique=True)
    password = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse('password:user_detail', kwargs={'id': self.id})

    def save(self, *args, **kwargs):
        self.password = bcrypt.hashpw(self.password.encode('utf-8'), salt).decode('utf-8')
        super().save(*args, **kwargs)
    

class Platform(models.Model):
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.name
    
    @staticmethod   
    def initialize_platforms():
        Platform.objects.all().delete()
        platforms= ['Facebook' , 'Instagram' , 'Twitter' ,'Google' , 'LinkedIn' , 'Snapchat' , 'Pinterest' , 'Reddit']
        for platform in platforms:
            Platform.objects.create(name=platform)
    

class Password(models.Model):
    user = models.ForeignKey(UserModel, on_delete=models.CASCADE, related_name='passwords')
    platform = models.ForeignKey(Platform, on_delete=models.CASCADE)
    password = models.CharField(max_length=255) # encrypted password


    def save(self, *args, **kwargs):
        # Hash the password before saving
        print(args,'###\n###' , kwargs)
        self.password = self.encrypted_password()
        print(self.decrypted_password(), '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%')
        super().save(*args, **kwargs)

    def encrypted_password(self):
        password_bytes = self.password.encode('utf-8')   # encode the password to bytes
        return f.encrypt(password_bytes).decode('utf-8')  

    def decrypted_password(self):
        return f.decrypt(self.password).decode('utf-8')  

Это html-форма:

{% extends 'base.html' %}
{% block content %}
    <h2>Add Password for {{ object.username }}</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        {% url 'password:user_add_password' object.pk as user_add_password_url %}
        <button type="submit" class="btn btn-primary" onclick="window.location='{{ user_add_password_url }}'" class="btn btn-success">Add</button>
    </form>

{% endblock %}




I tried to fill this form up, and after I submitted it I got this error.
I want to initial the hiddenfield user so I won't get error for missing value.
Вернуться на верх