django - UNIQUE约束失败:one_file.user_id

时间:2017-12-23 20:26:14

标签: python mysql django sqlite

我正在建立一个用户可以上传文件的网站,这些文件会显示在用户的个人资料中。我在用户的个人资料中显示了一个文件,但是当我添加第二个文件时,它会出现错误:

  

/ profile

中的IntegrityError      

UNIQUE约束失败:one_file.user_id

models.py:

class file(models.Model):
    title = models.CharField(max_length=250)
    file_type = models.CharField(max_length=12)
    description = models.TextField(max_length=6000)
    user = models.OneToOneField(User, on_delete=models.CASCADE)


    def get_absolute_url(self):
        return reverse('one:user')

    def __str__(self):
        return self.title

views.py:

def profile(request):
    if request.user.is_authenticated():
        name= request.user.username
        form_class = file_form
        template_name = 'one/profile.html'
        content = file.objects.all()
        if request.method=='GET':
            form = form_class(None)
            return render(request,template_name,{'form':form,'name':name, 'content':content})
        elif request.method=='POST':
            form = form_class(request.POST)
            if form.is_valid():
                FILE = form.save(commit = False)
                FILE.user = request.user
                FILE.save()  
        return HttpResponseRedirect('/profile')

tempalte:

logged in as: {{name}}
<br>
<a href="/logout">logout</a>
<br>
<form method="post" action="">
    {% csrf_token %}
    {% include 'one/form-template.html' %}
    <button type="submit">
        add file
    </button>
</form>
<br>
<h3>my files</h3>
{% for files in content %}
<p>{{files.title}}</p>
<br>
{%endfor%}

0 个答案:

没有答案