简体   繁体   English

我正在尝试使用Django实现博客应用。我创建了带有个人资料照片上传的注册表单,但返回IntegrityError

[英]I am trying to implement blog app with Django.I created registration form with profile pic upload.But its returning IntegrityError

I am trying to implement blog app with Django.I created registration form with profile pic upload.But its returning integrity error null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (7, pics/P_Wk6m1b3.png, null). 我正在尝试使用Django实现博客应用。我创建了带有个人资料图片上传的注册表单。但其在“ user_id”列中返回的完整性错误null值违反了非空约束DETAIL:失败行包含(7,pics / P_Wk6m1b3.png,空值)。

   #models.py
class Profile(models.Model):
  user = models.OneToOneField(User,on_delete=models.CASCADE)
  image = models.ImageField(default='default.jpg',upload_to='pics')

#views.py
def register(request):
   if request.method == "POST":
      form = Register(request.POST,request.FILES)
      if form.is_valid():
        profile = Profile()
        email = form.cleaned_data['Email']
        User_name=form.cleaned_data['Username']
        Password=form.cleaned_data['Password']
        Confirm_Password=form.cleaned_data['Confirm_Password']
        firstname=form.cleaned_data['Firstname']
        user=User.objects.create_user(username=User_name,
                  password=Password,email=email,first_name=firstname)
        user.save();
        insert = Profile(image = request.FILES['picture'],
                                        user_id=request.user.id)
        insert.save()
        return redirect('/')
    else:
        form = Register()
    return render(request,'register.html',{'form': form})

  #forms.py
  class Register(forms.Form):
    Email = forms.EmailField(widget=forms.TextInput(attrs= 
                                           {"class":"inputvalues"}))
    Username = forms.CharField(widget=forms.TextInput(attrs= 
                                           {"class":"inputvalues"}))
    Password = forms.CharField(widget=forms.PasswordInput(attrs= 
                                           ({"class":"inputvalues"})))
    Firstname = forms.CharField(widget=forms.TextInput(attrs= 
                              {"class":"inputvalues"}),max_length=30)
    Lastname = forms.CharField(widget=forms.TextInput(attrs= 
                              {"class":"inputvalues"}),max_length=40)
    Confirm_Password = forms.CharField
         (widget=forms.PasswordInput(attrs=({"class":"inputvalues"})))
    Image = forms.ImageField()

  def clean_Email(self):
   if validate_email(self.cleaned_data['Email']):
    raise forms.ValidationError("Email is not in correct format!")
   elif User.objects.filter(email = self.cleaned_data['Email'])
                                                   .exists():
    raise forms.ValidationError("Email aready exist!")
   return self.cleaned_data['Email']
  def clean_Username(self):
   if User.objects.filter(username = 
                    self.cleaned_data['Username']).exists():
    raise forms.ValidationError("Username already exist!")
   return self.cleaned_data['Username']
  def clean_Confirm_Password(self):
   pas=self.cleaned_data['Password']
   cpas = self.cleaned_data['Confirm_Password']
   if pas != cpas:
    raise forms.ValidationError("Password and Confirm Password are not 
                                                 matching!")
   else:
    if len(pas) < 8:
        raise forms.ValidationError("Password should have atleast 8 
                                                     character")
    if pas.isdigit():
        raise forms.ValidationError("Password should not all numeric")

  <!-------register.html>
  {% extends 'layout.html' %}
  {% block content %}
  <div class="box">
    <h2>
        <center>Register</center>
    </h2><br>
    <form action='register' method='POST'>
        {% csrf_token %}
        <div>
            <label class='labe'>Image:</label>
            {{ form.Image }}
        </div>
        <div>
            <label class='labe'>First name:</label>
            {{ form.Firstname }}
        </div>
        <div>
            <label class='labe'>Last name:</label>
            {{ form.Lastname }}
        </div>
        <div>
            <label class='labe'>Email:</label>
            {{ form.Email }}
            {{ form.Email.errors }}
        </div>
        <div>
            <label class='labe'>Username:</label>
            {{ form.Username }}
            {{ form.Username.errors }}
        </div>
        <div>
            <label class='labe'>Password:</label>
            {{ form.Password }}

        </div>
        <div>
            <label class='labe'>Confirm Password:</label>
            {{ form.Confirm_Password }}
            {{ form.Confirm_Password.errors }}
        </div>
        <input type="Submit" id="lg"/><br>
        <center><a href="login" >Already have an account.Login here. 
                                         </a></center>
    </form>
  </div>

  <div>
    {% for message in messages%}
        <h1>{{message}}</h1>
    {% endfor %}
  </div>
  {% endblock %}

It returns integrity errorand i want to know what is that 7.It increases one by one if enter data and click on submit each time 它返回完整性错误,我想知道那是什么7.每次输入数据并每次单击提交时,它都会一一增加。

request.user is the currently logged in user. request.user是当前登录的用户。 But there isn't a logged-in user, because this is the registration form. 但是没有登录用户,因为这是注册表格。 You need to use the user you just created. 您需要使用刚创建的用户。

    user=User.objects.create_user(username=User_name,
              password=Password,email=email,first_name=firstname)
    insert = Profile(image = request.FILES['picture'],
                user=user)
    insert.save()

You are creating the user record in register but using request.user.id which i expect is None since the user hasn't logged in yet. 您正在register中创建用户记录,但是使用request.user.id,我希望它是None,因为用户尚未登录。

Instead just pass user directly : 而是直接通过用户:

insert = Profile(image = request.FILES['picture'], user=user)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试用Django实现博客应用程序。我创建了配置文件pic上传的注册表。但是它没有提交数据? - I am trying to implement blog app with Django.I created registration form with profile pic upload.But its not submitting data? 我正在尝试用django实现博客应用程序。在应用程序的主页上会有一些帖子列表旁边我需要显示那里的个人资料图片? - I'm trying to implement blog app with django.In homepage of app there will be list of posts alongside i need show there profile picture? 我通过 django 表单创建了注册表单。但它没有渲染? - I created registration form through django forms.But its not rendring? 我正在尝试使用django表单创建注册表单。但是当我输入数据时,它会在/ register返回ValueError? - I am trying to create registration form with django forms.But when i enter data it returns ValueError at /register? 我正在尝试使用forms.py通过Django构建注册表单 - i am trying to build a registration form by Django using forms.py Django个人资料图片上传表单将图片保存在两个文件夹中 - Django profile pic upload form saves picture in two folders 尝试使用 Django 构建用户注册表单时出现属性错误 - I am getting an attribute error while trying to build a user registration form using Django 我正在尝试使用 Django Rest Framework 创建用户注册 - I am trying to create a user registration with Django Rest Framework 更新用户的个人资料图片但不要求用户上传图片 - Updating profile pic of user but its not requesting user to upload the pic 我收到 django 的 IntegrityError UNIQUE 约束失败 - I am getting a IntegrityError UNIQUE constraint failed for django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM