Не могу найти решение для моей проблемы онлайн. Я получаю сообщение об ошибке, касающееся проблемы ----- Ошибка целостности в / add_user_address / UNIQUE ограничение не выполнено: users_useraddress.user_id ------ вся помощь очень ценится!
views.py import re
from django.urls import reverse
from django.shortcuts import render, redirect, Http404, HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .forms import UserRegisterForm, UserAddressForm
from .models import EmailConfirmed
def register(request):
if request.method == 'POST':
form = UserRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f'Your registration has been successful! Please check your email to confirm account.')
return redirect('login')
else:
form = UserRegisterForm()
return render(request, 'users/register.html', {'form': form})
SHA1_RE = re.compile('^[a-f0-9]{40}$')
def activation_view(request, activation_key):
if SHA1_RE.search(activation_key):
print("activation key is real")
try:
instance = EmailConfirmed.objects.get(activation_key=activation_key)
except EmailConfirmed.DoesNotExist:
instance = None
messages.success(request, f'There was an error with your request.')
return HttpResponseRedirect("/")
if instance is not None and not instance.confirmed:
page_message = "Confirmation successful, welcome to Fuisce! "
instance.confirmed = True
instance.activation_key = "Confirmed"
instance.save()
elif instance is not None and instance.confirmed:
page_message = "Already Confirmed"
else:
page_message = ""
context = {"page_message": page_message}
return render(request, "users/activation_complete.html", context)
else:
raise Http404
@login_required
def profile(request):
return render(request, 'users/profile.html')
**def add_user_address(request):
print(request.GET)
try:
redirect = request.GET.get("redirect")
except:
redirect = None
if request.method == "POST":
form = UserAddressForm(request.POST)
if form.is_valid():
new_address = form.save(commit=False)
new_address.user = request.user
new_address.save()
if redirect is not None:
return HttpResponseRedirect(reverse(str(redirect)))
else:
raise Http404**
html file
{% extends "fuisce/base.html" %}
{% block content %}
<form method="POST" action='{% url "add_user_address" %}?redirect=checkout'>{% csrf_token %}
{{ address_form.as_p }}
<input type='submit' class='btn btn-primary' value='Add Address'/>
</form>
{% endblock content %}
Мой html и файл views прилагаются, дайте мне знать, если для решения проблемы требуется что-то еще.
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import User
from django.conf import settings
from django.template.loader import render_to_string
from django.urls import reverse
from localflavor.ie.ie_counties import IE_COUNTY_CHOICES
class UserAddress(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
address = models.CharField(max_length=150 )
address2 = models.CharField(max_length=150, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
county = models.CharField(max_length=100, choices=IE_COUNTY_CHOICES)
country = models.CharField(max_length=100)
postalcode = models.CharField(max_length=30)
phone = models.CharField(max_length=60)
shipping = models.BooleanField(default=True)
billing = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return str(self.user.username)