简体   繁体   English

django.db.utils.IntegrityError:唯一约束失败:beachprofile_beach.beach_id

[英]django.db.utils.IntegrityError: UNIQUE constraint failed: beachprofile_beach.beach_id

I am setting up a review feature for the beach profile, and want to submit the review form in beach.html and redirect back to the original beach profile. 我正在为海滩配置文件设置评论功能,并想在beach.html中提交评论表并重定向回原始的海滩配置文件。

I am involving a addreview button and review list in beach profile but the thing is that when I open the beach profile I chose it told me that unique constraint failed for beachprofile_beach.beach_id. 我在海滩配置文件中包含一个addreview按钮和评论列表,但问题是,当我打开海滩配置文件时,我选择它告诉我,beachprofile_beach.beach_id的唯一约束失败。 So I thought it's because after user reviewed it go back to the beachProfile view again and stored the same beach info into the table again. 所以我认为这是因为在用户查看之后,再次返回到beachProfile视图,并将相同的海滩信息再次存储到表中。 But I don't really know how to fix it. 但是我真的不知道如何解决它。

This is a part in beachProfile view that I can store the beach info into my table Beach when I open the new beach profile page. 这是beachProfile视图中的一部分,当我打开新的海滩配置文件页面时,可以将海滩信息存储到表Beach中。

def beachProfile(request):    
    thisname = request.build_absolute_uri()
    name = thisname.split('=')[-1].replace("%20"," ")
    name2 = thisname.split('=')[-1].replace("%20","+")
    oldname = name
    #print(name  + 'hi testing')
    if oldname == '1' or oldname == '2':
        name = thisname.split('=')[2].replace("%20"," ")
        name = name.split('?')[0]
        print(name)
        name2 = thisname.split('=')[2].replace("%20","+")
        name2 = name2.split('?')[0]

    testsafe = thisname.split('=')[1]
    testsafe = int(testsafe[0])
    if testsafe == 0:
        safe=True
        halfsafe=False
    elif testsafe == 2:
        safe=False
        halfsafe=False
    else:
        safe=False
        halfsafe=True
    thisBeach = requests.get("https://maps.googleapis.com/maps/api/geocode/json?address="+name2+"&key=AIzaSyAH43dAThEg8WJge9cuFa3vbnBhLRSlJDQ")
    beachjson = thisBeach.json()
    latitude = beachjson["results"][0]["geometry"]["location"]["lat"]
    longitude = beachjson["results"][0]["geometry"]["location"]["lng"]


    response = requests.get("https://api.darksky.net/forecast/fef06c56fa2906ef3255d9b99bfb02de/"+str(latitude)+","+str(longitude))
    forecast = response.json()
    windspeedcurr = forecast["currently"]["windSpeed"]
    tempcurr = forecast["currently"]["temperature"]
    uvcurr = forecast["currently"]["uvIndex"]
    summary = []
    for i in range(len(forecast["daily"]["data"])):
        summary.append("/DarkSky-icons/PNG/"+forecast["daily"]["data"][i]["icon"]+".png")

    thumbnail = "https://maps.googleapis.com/maps/api/staticmap?center="+str(latitude)+","+str(longitude)+"&zoom=14&size=400x400&key=AIzaSyAH43dAThEg8WJge9cuFa3vbnBhLRSlJDQ"
     beach = Beach.objects.filter(
        beachname=name,
        safety=testsafe,
        lat=latitude,
        lng=longitude,
        ).first()

    if beach is None:
        beach = Beach.objects.create(
            beachname=name,
            safety=testsafe,
            lat=latitude,
            lng=longitude,
        )
    is_favourite=False
    if oldname =='1':
        """
        if beach.fav.filter(id=request.user.id).exists():
            pass
        else:
        """
        print('adding user')
        beach.fav.add(request.user)
        is_favourite=True
    if oldname =='2':
        if beach.fav.filter(id=request.user.id).exists():
            beach.fav.remove(request.user)
        else:
            pass

    return render(request, 'users/beach.html', {'latitude': latitude, 'longitude': longitude, 'summary': summary, 'thumbnail': thumbnail, 'wind': windspeedcurr, 'temp': tempcurr, 'uvindex': uvcurr, 'name': name, 'rating': 5, 'safe': safe, 'halfsafe': halfsafe, 'is_fav':is_favourite, 'safety':testsafe})

For my review model and review model (partial): 对于我的评论模型和评论模型(部分):

class Beach(models.Model):
    beach_id = models.AutoField(primary_key = True)
    beachname = models.CharField(max_length=50, unique = True)
    safety = models.IntegerField(default=0) #default is safe? 
    lat = models.IntegerField()
    lng = models.IntegerField()
    fav = models.ManyToManyField(User, related_name="fav",blank=True)
    class Meta:
        unique_together = ["beachname", "safety", "lat", "lng"]
    def __str__(self):
        return self.beachname

    def average_rating(self):
        all_ratings = map(lambda x: x.rating, self.review_set.all())
        return np.mean(all_ratings)

class Review(models.Model):
    review_id = models.AutoField(primary_key = True)
    beach = models.ForeignKey(Beach, on_delete = models.CASCADE)
    pub_date = models.DateTimeField('date published')
    user_reviewed = models.ManyToManyField(User, related_name="reviewer",blank=True)
......

The urls.py related to beach in the main is like: 与沙滩相关的urls.py像这样:

    url(r'^beachProfile/', beach_views.beachProfile, name='beachProfile'),
    url(r'(?P<beach_id>\d+)/fav/$', beach_views.fav, name="fav"),

    url(r'^$', beach_views.review_list, name='review_list'),
    url(r'(?P<beach_id>\d+)/(?P<review_id>[0-9]+)/$', beach_views.review_detail, name='review_detail'),
    url(r'(?P<beach_id>\d+)/add_review/$', beach_views.add_review, name='add_review'),#add review to the user with same id
    url(r'^user/(?P<username>\w+)/$', beach_views.user_review_list, name='user_review_list'),

The code below is my code for adding a review. 下面的代码是我添加评论的代码。 I don't really know how to direct back to my profile page before review so I just put the profile page link directly but excluding favorite number (fav = 1 or 2)cause I don't know how to access the fav number from the beachProfile. 我真的不知道如何在审阅之前直接回到我的个人资料页面,所以我只是直接放置个人资料页面链接,但不包括喜欢的号码(收藏夹= 1或2),因为我不知道如何从beachProfile。 I really want to know how to return to the original profile page. 我真的很想知道如何返回原始的个人资料页面。 Danger is a calculated number called safety in Beach model, and beachname is the name of the beach. 危险是一个经过计算的数字,在海滩模型中称为安全性,海滩名称是海滩的名称。

@login_required
def add_review(request, beach_id):
    beach = get_object_or_404(Beach, beach_id=beach_id)
    form = ReviewForm(request.POST)
    if form.is_valid():
        rating = form.cleaned_data['rating']
        comment = form.cleaned_data['comment']
        user_name = request.user.username
        review = Review()
        review.beach = beach
        review.user_name = user_name
        review.rating = rating
        review.comment = comment
        review.pub_date = datetime.datetime.now()
        review.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        #?danger={{safety}}?name={{name}}?fav=1
        #"beachProfile?danger='+danger+'?name='+marker.title+'" is this correct way???
        return HttpResponseRedirect("beachProfile?danger='+beach.safety+'?name='+beach.beachname+'")

    return render(request, 'users/beach.html', {'beach': beach, 'form': form})

In beach.html, Add your review is a button to go to a form to submit user's review 在beach.html中,“添加您的评论”是一个进入表单以提交用户评论的按钮

<div id="reviews">
      <h2>Add your Review</h2>
      <form action="{% url 'add_review' beach.beach_id %}" method="post" class="form">
        {% csrf_token %}
        {% bootstrap_form form %}
        {% bootstrap_form form layout='inline' %}
        {% buttons %}
        <button type="submit" class="btn btn-primary">
        {% bootstrap_icon "star" %} Add
        </button>
        {% endbuttons %}
      </form>
    </div>

I am not sure where I am wrong here, cause I am still new to learn these. 我不确定我在哪里错了,因为我仍然不了解这些知识。 Please anyone can help with resolving these error. 请任何人都可以帮助解决这些错误。

I am wondering the problem of IntegrityError happened is because maybe I saved any beach instance twice but I checked all my code, The only place I save instance is in beachProfile view and above you can see the code. 我想知道发生IntegrityError的问题是因为也许我两次保存了任何海滩实例,但是我检查了所有代码,所以唯一保存实例的地方是在beachProfile视图中,上面可以看到代码。 But I don't know why it's wrong. 但是我不知道为什么这是错误的。 The error message is: 错误消息是:

Apply all migrations: admin, auth, beachprofile, contenttypes, sessions
Running migrations:
  Applying beachprofile.0007_auto_20190411_0432...Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: beachprofile_beach.beach_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle
    fake_initial=fake_initial,
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\schema.py", line 309, in add_field
    self._remake_table(model, create_field=field)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\schema.py", line 274, in _remake_table
    self.quote_name(model._meta.db_table),
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\base\schema.py", line 133, in execute
    cursor.execute(sql, params)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 298, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: beachprofile_beach.beach_id

The error did not change after I change get "beach otherwise create it" to 我更改后的错误未更改,请获取“海滩否则创建它”

beach = Beach.objects.filter(
        beachname=name,
        safety=testsafe,
        lat=latitude,
        lng=longitude,
        ).first()

    if beach is None:
        beach = Beach.objects.create(
            beachname=name,
            safety=testsafe,
            lat=latitude,
            lng=longitude,
        )

So I think the problem maybe is not here. 所以我认为问题可能不在这里。 I put my urls.py above. 我把我的urls.py放在上面。 And I have other htmls: review_details.html for get the details of a review in review list, review_list.html to get a list of latest reviews, and user_review_list.html(this just add a head with user name of reviews to extends review_list) to get the details of a review in review list (you can get it by clicking the user name in a review of review list for a beach) 我还有其他htmls:review_details.html用于在评论列表中获取评论的详细信息,review_list.html用于获取最新评论的列表,以及user_review_list.html(这只是添加带有评论用户名的头以扩展review_list)以获得评论列表中评论的详细信息(您可以通过在海滩的评论列表中单击用户名来获取评论)

Also in review_detail.html: 同样在review_detail.html中:

<!--go back to the profile page bug here = no idea of fav number ??????-->>
<h2><a href="{% url '?danger={{review.beach.safety}}?name={{review.beach.beachname}}?fav=1' %}">{{ review.beach.beachname }}</a></h2>

I want to go to profile page when I click the beachname. 当我单击海滩名称时,我想转到个人资料页面。 But the redirect url maybe not that correct as well which got the same problem with add_reviews function. 但是重定向URL可能不是那么正确,而add_reviews函数也遇到了同样的问题。

Welcome to StackOverflow! 欢迎来到StackOverflow!

It looks like when you are specifying your model you have a default value for your primary keys. 看起来,当您指定模型时,主键具有默认值。 Primary keys have to be unique. 主键必须是唯一的。 So with your default=1 constraint, if the key isn't specified it will be set to 1 . 因此,在您的default=1约束下,如果未指定键,则将其设置为1 The beauty of AutoField is that it will handle the setting the primary key. AutoField在于它将处理主键的设置。

https://docs.djangoproject.com/en/2.2/ref/models/fields/#autofield https://docs.djangoproject.com/zh-CN/2.2/ref/models/fields/#autofield

An IntegerField that automatically increments according to available IDs. 一个IntegerField,它根据可用的ID自动递增。 You usually won't need to use this directly; 您通常不需要直接使用它; a primary key field will automatically be added to your model if you don't specify otherwise. 如果没有另外指定,主键字段将自动添加到模型中。

So I would recommend removing default=1 from your Model's primary key definition 因此,我建议从模型的主键定义中删除default=1

class Beach(models.Model):
    beach_id = models.AutoField(primary_key=True)
    ...,

Same with Review: 与评论相同:

class Review(models.Model):
    review_id = models.AutoField(primary_key=True)
    ...,

So I'm seeing some issues with this code block if I'm understanding what you are trying to do. 因此,如果我了解您要执行的操作,则会发现此代码块存在一些问题。

beach = Beach(Beach.objects.get(), beachname=name, safety=testsafe, lat=latitude, lng=longitude)
    if beach.beach_id == None and beach.beachname == None:
        beach.save()
    else:
        pass

When you call beach = Beach(Beach.objects.get(), beachname=name, safety=testsafe, lat=latitude, lng=longitude) you are creating a new Beach model in memory and beach_id won't be set because it hasn't been saved to your database. 当您调用beach = Beach(Beach.objects.get(), beachname=name, safety=testsafe, lat=latitude, lng=longitude)您正在内存中创建新的Beach模型,并且beach_id尚未设置beach_id因此不会对其进行设置尚未保存到您的数据库。

It looks like you want to check if the Beach already exists. 您好像要检查Beach已经存在。

You could do that with: 您可以使用以下方法做到这一点:

# check if beach exists
# first will return none if no records are returned
beach = Beach.objects.filter(
    beachname=name,
    safety=testsafe,
    lat=latitude,
    lng=longitude,
).first()

if beach is None:
    beach = Beach.objects.create(
        beachname=name,
        safety=testsafe,
        lat=latitude,
        lng=longitude,
    )

Feel free to elaborate if I'm not understanding what you are trying to do here. 如果我不明白您要在这里做什么,请随时进行详细说明。

暂无
暂无

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

相关问题 Django 表单错误:django.db.utils.IntegrityError:唯一约束失败:legal_useragreedtolegal.user_id - Django form error: django.db.utils.IntegrityError: UNIQUE constraint failed: legal_useragreedtolegal.user_id django.db.utils.IntegrityError:唯一约束失败: - django.db.utils.IntegrityError: UNIQUE constraint failed: django.db.utils.IntegrityError:唯一约束失败:core_profile.user_id - django.db.utils.IntegrityError: UNIQUE constraint failed: core_profile.user_id django.db.utils.IntegrityError:唯一约束失败:new__vacancies_company.owner_id 错误 - django.db.utils.IntegrityError: UNIQUE constraint failed: new__vacancies_company.owner_id error Django抛出错误django.db.utils.IntegrityError:唯一约束失败:mediaSort_userdata.user_id - Django throwing error django.db.utils.IntegrityError: UNIQUE constraint failed: mediaSort_userdata.user_id django.db.utils.IntegrityError:唯一约束失败:auctions_bids.item_id - django.db.utils.IntegrityError: UNIQUE constraint failed: auctions_bids.item_id django.db.utils.IntegrityError:唯一约束失败:mode_setting.user_id - django.db.utils.IntegrityError: UNIQUE constraint failed: mode_setting.user_id django.db.utils.IntegrityError:UNIQUE约束失败:rango_page__new.category_id - django.db.utils.IntegrityError: UNIQUE constraint failed: rango_page__new.category_id django.db.utils.IntegrityError:唯一约束失败:new__bank_profile.fname_id - django.db.utils.IntegrityError: UNIQUE constraint failed: new__bank_profile.fname_id Django 令牌对象更新错误:django.db.utils.IntegrityError:唯一约束失败:authtoken_token.user_id - Django Token objects update error : django.db.utils.IntegrityError: UNIQUE constraint failed: authtoken_token.user_id
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM