python 请,我有一个AttributeError错误要修复,请帮助我

8e2ybdfx  于 2023-02-02  发布在  Python
关注(0)|答案(2)|浏览(137)

我在Django项目中创建了一个地址项目,它运行良好,但我希望该程序避免用户查看他们的账单地址,并更新地址页面,如果他们还没有创建地址。
这是运行良好的代码的视图:
views.py

def register_address(request):
    instance = ""
    try:
        if request.method == "POST":
           form = AddressForm(request.POST)
            if form.is_valid():
                instance = form.save(commit=False)
                instance.user = request.user 
                instance.save()
                messages.success(request, "You have successfully added a shipping address!")
                return redirect('address:billing_address')
    except:
        pass
    
    return render(request,'address/register_address.html',{'form':form})


def billing_address(request):
    address = "" 
    try:
        address = UserAddress.objects.get(user=request.user)
    except:
        pass

    return render(request,'address/billing_address.html',{'form':address})

def update_address(request):
    form = UpdateForm()
    try:
        if request.method == "POST":
            form = UpdateForm(request.POST)
            if form.is_valid():
                address = UserAddress.objects.get(user=request.user)
                address.user = request.user
                address.country = request.POST.get("country")
                address.state = request.POST.get("state")
                address.area = request.POST.get("area")
                address.city = request.POST.get("city")
                address.street_name = request.POST.get("street_name")
                address.save()
                messages.error(request, "You have successfully updated address.")
                return redirect('address:billing_address')
    except:
        pass
    
    return render(request,'address/update_address.html',{'form':form})

urls.py

urlpatterns = [
    path('register_address/',views.register_address,name="register_address"),
    path('billing_address/',views.billing_address,name="billing_address"),
    path('update_address/',views.update_address,name="update_address"),
]

register_address.html

<h2>Register Adress</h2><br>
<form action="" method="POST" onsubmit="myButton.disabled = true; return true;">
{% csrf_token %}
{{form.as_p}}
<input type="submit" class="btn btn-success" name="myButton" value="Submit">
</form><br><br>

<button class="btn btn-primary" onClick = "window.location= '{% url 'address:bi lling_address'%}';">View Billing Address</button>  <button class="btn btn-secondary" onClick = "window.location= '{% url 'address:update_address' %}';">Update Address</button><br><br>

</div>

billing_address.html

<br><h1><center>Billing Address page!</center></h1><br>

<div class="container">

<h2>Username:</h2> {{form.user|capfirst}}<br>
<h2>Address:</h2> {{form.street_name|capfirst}}, {{form.area|capfirst}}, {{form.city|capfirst}}, {{form.state|capfirst}}, {{form.country|capfirst}}<br><br>
<button class="btn btn-success" onClick = "window.location= '{% url 'address:update_address' %}';">Edit me</button><br><br><br>

但这里是一个扩展的代码,我想让用户无法查看他们的账单地址和更新地址,除非他们已经创建了地址。
views.py

def register_address(request):
    instance = ""
    user = ""
    try:
        form = AddressForm()
        if request.method == "POST":
            form = AddressForm(request.POST)
            if form.is_valid():
                instance = form.save(commit=False)
                instance.user = request.user 
                instance.save()
                user = UserAddress.objects.get(user=instance.user)
                messages.success(request, "You have successfully added a shipping address!")
                return reverse('address:billing_address',args=[user.pk])
        
            try:
                user = UserAddress.objects.get(user=request.user)
                if user is not None:
                    return reverse('address:billing_address',args=[user.pk])
            except:
                pass
    except:
        pass
    
    return render(request,'address/register_address.html',{'form':form,'pk':user})



def billing_address(request,pk):
    user = ""
    try:
        user = UserAddress.objects.get(pk=pk)
        if user is not None:
            return user
    except AttributeError:
        messages.error(request, "Please, create an address before viewing address!")
        return redirect('address:register_address')
    except:
        messages.error(request, "Please, create an address before viewing address!")
        return redirect('address:register_address')

    return render(request,'address/billing_address.html',{'form':user})

urls.py

urlpatterns = [
    path('register_address/',views.register_address,name="register_address"),
    path('<int:pk>billing_address/',views.billing_address,name="billing_address"),
    path('update_address/',views.update_address,name="update_address"),
]

register_addres.html

<h2>Register Adress</h2><br>
<form action="" method="POST" onsubmit="myButton.disabled = true; return true;">
{% csrf_token %}
{{form.as_p}}
<input type="submit" class="btn btn-success" name="myButton" value="Submit">
</form><br><br>

<button class="btn btn-primary" onClick = "window.location= '{% url 'address:billing_address' pk=user.pk %}';">View Billing Address</button>  <button class="btn btn-secondary" onClick = "window.location= '{% url 'address:update_address' %}';">Update Address</button><br><br>

billing_address.html

<div class="container">

<h2>Username:</h2> {{form.user|capfirst}}<br>
<h2>Address:</h2> {{form.street_name|capfirst}}, {{form.area|capfirst}}, {{form.city|capfirst}}, {{form.state|capfirst}}, {{form.country|capfirst}}<br><br>
<button class="btn btn-success" onClick = "window.location= '{% url 'address:update_address' %}';">Edit me</button><br><br><br>

</div>

错误

AttributeError at /address/register_address/
'str' object has no attribute 'get'
Request Method: POST
Request URL:    http://127.0.0.1:8000/address/register_address/
Django Version: 4.0.4
Exception Type: AttributeError
Exception Value:    
'str' object has no attribute 'get'
Exception Location: C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py, line 27, in process_response
Python Executable:  C:\Users\USER\AppData\Local\Programs\Python\Python310\python.exe
Python Version: 3.10.0
Python Path:    
['C:\\Users\\USER\\Documents\\ADi meals mobile\\my_site',
 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip',
 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python310\\DLLs',
 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python310\\lib',
 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python310',
 'C:\\Users\\USER\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages']
Server time:    Thu, 02 Feb 2023 09:17:24 +0000
eqfvzcg8

eqfvzcg81#

视图应该总是返回**HttpResponse(…)**[Django-doc]或它的一个子类,但您从视图返回字符串,即return reverse('address:billing_address',args=[user.pk])将返回字符串。因此在视图中返回响应对象而不是字符串,如下所示

from django.urls import reverse
from django.http import HttpResponseRedirect

return HttpResponseRedirect(reverse('address:billing_address', args=[user.pk]))

在其他return reverse中也进行相应更改。

w8f9ii69

w8f9ii692#

有许多小错误,如:
1.路由应该是billing_address/<int:pk>/,而不是<int:pk>billing_address/
1.在register_address视图中,pkGET请求的情况下是一个空字符串,所以如果它是当前登录的用户(假设已经通过ForeignKey,AbstractUser或AbstractBaseUser或任何东西与Django的内置用户模型有关系),那么你怎么能将一个空字符串发送到billing_address视图呢?
尝试使用下面的代码。
urls.py:

urlpatterns = [
    path('register_address/',views.register_address,name="register_address"),
    path('billing_address/<int:pk>/',views.billing_address,name="billing_address"),
    path('update_address/',views.update_address,name="update_address"),
]

register_address.html

<form method="POST" onsubmit="myButton.disabled = true; return true;">
{% csrf_token %}
{{form.as_p}}
<input type="submit" class="btn btn-success" name="myButton" value="Submit">
</form><br><br>

<button class="btn btn-primary" onClick = "window.location= '{% url 'address:billing_address' pk=request.user.id %}';">View Billing Address</button>

相关问题