__init__() 接受 1 个位置参数,但给定 2 个类型错误
__init__() takes 1 positional argument but 2 were given type error
我目前正在使用 Django 和 python 创建一个网络应用程序来为我的公司读取仪表。
我收到此错误(标题),但我不知道是什么原因造成的。我有
Urls.py:
urlpatterns = [
#Operational URLS
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path("",include("accounts.urls")),
path('home/' , views.home, name='home'),
#Complexes
#AVONLEA
path('avn', views.AvonleaView, name='Avonlea'),
path('cavn', views.currentavonleas, name='currentAvonleas'),
path('Avonleacsv', views.Avonleacsv, name='Avonleacsv'),
path('meter_readings/avonlea/<int:avonleas_pk>', views.viewavonlea, name='viewavonlea' ),
path('meter_readings/avonlea/<int:avonleas_pk>/delete', views.deleteavonlea, name='deleteavonlea' ),
Views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from .forms import AvonleaForm
from .models import AvonleaClass
from django.contrib import messages
from django.views import View
#Operational
def home(request):
return render(request, 'meter_readings/home.html' )
# Complexes
#AVONLEA
#
#
#
class AvonleaView( View):
def get(self,request):
created_nums= AvonleaClass.objects.all().values('unitNumber')
Aprev = AvonleaClass.objects.all().order_by('-unitDateEntered')
previousReading = Aprev[1].newReading
# created_nums= AvonleaClass.objects.all()
print(created_nums , previousReading)
created_nums =[int(i['unitNumber']) for i in created_nums]
print(created_nums , previousReading)
form = AvonleaForm()
return render(request,"meter_readings/avonlea.html",{'form':form , 'created_nums':created_nums , 'name':name, 'previousReading' : previousReading })
def post(self,request):
created_nums= AvonleaClass.objects.all().values_list('unitNumber')
print(created_nums)
form = AvonleaForm(request.POST)
if form.is_valid():
form.save()
return redirect('unt-url' , name )
messages.success(request , 'creates successfully ')
else:
return render(request, 'meter_readings/avonlea.html', {'form': form , created_nums:created_nums })
def currentavonleas(request):
avonleas = AvonleaClass.objects.all()
return render(request, 'meter_readings/currentavonleas.html', {'avonleas':avonleas})
def viewavonlea(request, avonleas_pk):
avonlea = get_object_or_404(AvonleaClass, pk=avonleas_pk)
if request.method == 'GET':
form = AvonleaForm(instance=avonlea)
return render(request, 'meter_readings/viewavonleas.html', {'avonlea': avonlea, 'form':form})
else:
try:
form = AvonleaForm(request.POST, instance=avonlea)
form.save()
return redirect('Avonlea')
except ValueError:
return render(request, 'meter_readings/viewavonleas.html', {'avonlea': avonlea, 'form':form, 'error':'Bad info'})
def deleteavonlea(request, avonleas_pk):
avonlea = get_object_or_404(AvonleaClass, pk=avonleas_pk)
if request.method == 'POST':
avonlea.delete()
return redirect('Avonlea')
import csv
def Avonleacsv(request):
data =AvonleaClass.objects.all()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="saved_file.csv"'
writer = csv.writer(response)
writer.writerow(['Unit', 'Number of Units'
])
for avonleaclass in data:
writer.writerow([
avonleaclass.unitNumber,
avonleaclass.newReading,
])
return response
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
AvonleaUnits = [tuple([x,x]) for x in range(1,73)]
class AvonleaClass(models.Model):
unitNumber = models.CharField(max_length=2 , default='1')
newReading = models.IntegerField( blank=True, null=True)
difference = models.IntegerField(blank=True, null=True)
unitNotes = models.TextField(blank=True)
unitDateEntered = models.DateTimeField(auto_now_add=True, null=True)
unitProblem = models.BooleanField(default=False)
image = models.ImageField(blank=True, null=True)
def __str__(self):
return ('Unit ' + self.unitNumber)
Forms.py
from django.forms import ModelForm
from .models import AvonleaClass
from django import forms
AvnUnits = [tuple([x,x]) for x in range(1,73)]
class AvonleaForm(ModelForm):
unitNumber = forms.ChoiceField(choices= AvnUnits)
class Meta:
model = AvonleaClass
fields = ['unitNumber','newReading','difference', 'unitNotes','unitProblem' , 'image']
widgets = {
'unitNotes': forms.TextInput(attrs={'size': 10}),
'unitReading': forms.IntegerField(),
'diffrence': forms.IntegerField(),
}
Admin.py
from django.contrib import admin
from .models import AvonleaClass
class AvonleaAdmin(admin.ModelAdmin):
readonly_fields = ('unitDateEntered',)
admin.site.register(AvonleaClass, AvonleaAdmin)
class Birchleigh_ViewAdmin(admin.ModelAdmin):
readonly_fields = ('unitDateEntered',)
Avonlea.html
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
{% extends 'meter_readings/base.html' %}
{% block content %}
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<div class="container">
<h1>{{name}} Meter Readings</h1>
{% for unit_number in form.unitNumber %}
<h6>{{ error }}</h6>
<form class="form-group mt-4" method="post" {% if unit_number.data.value in created_nums %} style="background-color: rgb(231, 224, 224); " {% endif %} >
{% csrf_token %}
<div class="container">
<div class="row mb-3">
<div class="col">
{{ unit_number.data.value}}
</div>
<input type="hidden" name="unitNumber" value="{{unit_number.data.value}}">
<div class="col" id="prev{{unit_number.data.value}}" >
{{ previousReading }}
</div>
<div class="col" id="readings{{unit_number.data.value}}">
{{ form.newReading }}
</div>
<div class="col" id="difference{{unit_number.data.value}}">
{{ form.difference }}
</div>
<div class="col">
{{ form.unitNotes }}
</div>
<div class="col">
{{ form.unitProblem }}
</div>
<div class="col" id="img{{unit_number.data.value}}">
{{ form.image }}
</div>
<div class="col">
<button class="btn btn-success " type="submit" {% if unit_number.data.value in created_nums %} disabled {% endif %} > Save</button>
</div>
</div>
</div>
<script>
document.getElementById("img{{unit_number.data.value}}").firstElementChild.disabled = true
document.getElementById("difference{{unit_number.data.value}}").firstElementChild.disabled = true
var last = document.getElementById('readings{{unit_number.data.value}}');
last.addEventListener('input' , (e)=>{
last = e.target.value
var first = document.getElementById('prev{{unit_number.data.value}}').firstElementChild.value;
var diff= document.getElementById('difference{{unit_number.data.value}}').firstElementChild.value= parseInt(last) - parseInt(first);
if (diff <= 0){
console.log(diff)
console.log("-ve")
document.getElementById("difference{{unit_number.data.value}}").firstElementChild.style.border="2px solid red";
document.getElementById("img{{unit_number.data.value}}").firstElementChild.disabled=false
}
else{
document.getElementById("difference{{unit_number.data.value}}").firstElementChild.style.border="2px solid ";
document.getElementById("img{{unit_number.data.value}}").firstElementChild.disabled=true
console.log("+ve")
}
})
</script>
</form>
{% endfor %}
<style>
.error {
border:2px solid red;
}
</style>
<form method="POST", action="{% url 'currentAvonleas' %}">
{% csrf_token %}
<button type="submit">View all Avonlea readings</button>
</form>
<form method="POST", action="{% url 'Avonleacsv' %}">
{% csrf_token %}
<button type="submit">Export readings to Excel</button>
</form>
{% endblock %}
<br>
<br>
<br>
home.html:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
{% extends 'meter_readings/base.html' %}
{% block content %}
{% csrf_token %}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
<div class="container">
<div class="jumbotron">
<h1 class="display-5 text-center" align-items-center>Meter Reading Application</h1>
<h3>Individual Unit Readings</h3>
</div>
<div class="container">
<a href="{% url 'Avonlea' %}" class="btn btn-info" >Avonlea </a>
<br>
<br>
</div>
</div>
{% endblock %}
给出的确切错误:
TypeError at /avn
init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://localhost:8000/avn Django Version: 3.2
Exception Type: TypeError Exception Value:
init() takes 1 positional argument but 2 were given Exception Location: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py,
line 181, in _get_response Python
Executable: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.4 Python Path:
['C:\Users\KylePOG\Desktop\meter-reading',
'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python39.zip',
'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\DLLs',
'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib',
'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39',
'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages']
Server time: Sun, 30 May 2021 19:14:46 +0000 Traceback Switch to
copy-and-paste view
C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py,
line 47, in inner
response = get_response(request) … ▶ Local vars C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py,
line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars
您需要与 .as_view(…)
method [Django-doc] 合作,将基于 class 的视图转换为可以处理请求的函数,因此:
path('avn', views.AvonleaView<b>.as_view()</b>, name='Avonlea'),
我目前正在使用 Django 和 python 创建一个网络应用程序来为我的公司读取仪表。
我收到此错误(标题),但我不知道是什么原因造成的。我有
Urls.py:
urlpatterns = [
#Operational URLS
path('admin/', admin.site.urls),
path('accounts/', include('django.contrib.auth.urls')),
path("",include("accounts.urls")),
path('home/' , views.home, name='home'),
#Complexes
#AVONLEA
path('avn', views.AvonleaView, name='Avonlea'),
path('cavn', views.currentavonleas, name='currentAvonleas'),
path('Avonleacsv', views.Avonleacsv, name='Avonleacsv'),
path('meter_readings/avonlea/<int:avonleas_pk>', views.viewavonlea, name='viewavonlea' ),
path('meter_readings/avonlea/<int:avonleas_pk>/delete', views.deleteavonlea, name='deleteavonlea' ),
Views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from .forms import AvonleaForm
from .models import AvonleaClass
from django.contrib import messages
from django.views import View
#Operational
def home(request):
return render(request, 'meter_readings/home.html' )
# Complexes
#AVONLEA
#
#
#
class AvonleaView( View):
def get(self,request):
created_nums= AvonleaClass.objects.all().values('unitNumber')
Aprev = AvonleaClass.objects.all().order_by('-unitDateEntered')
previousReading = Aprev[1].newReading
# created_nums= AvonleaClass.objects.all()
print(created_nums , previousReading)
created_nums =[int(i['unitNumber']) for i in created_nums]
print(created_nums , previousReading)
form = AvonleaForm()
return render(request,"meter_readings/avonlea.html",{'form':form , 'created_nums':created_nums , 'name':name, 'previousReading' : previousReading })
def post(self,request):
created_nums= AvonleaClass.objects.all().values_list('unitNumber')
print(created_nums)
form = AvonleaForm(request.POST)
if form.is_valid():
form.save()
return redirect('unt-url' , name )
messages.success(request , 'creates successfully ')
else:
return render(request, 'meter_readings/avonlea.html', {'form': form , created_nums:created_nums })
def currentavonleas(request):
avonleas = AvonleaClass.objects.all()
return render(request, 'meter_readings/currentavonleas.html', {'avonleas':avonleas})
def viewavonlea(request, avonleas_pk):
avonlea = get_object_or_404(AvonleaClass, pk=avonleas_pk)
if request.method == 'GET':
form = AvonleaForm(instance=avonlea)
return render(request, 'meter_readings/viewavonleas.html', {'avonlea': avonlea, 'form':form})
else:
try:
form = AvonleaForm(request.POST, instance=avonlea)
form.save()
return redirect('Avonlea')
except ValueError:
return render(request, 'meter_readings/viewavonleas.html', {'avonlea': avonlea, 'form':form, 'error':'Bad info'})
def deleteavonlea(request, avonleas_pk):
avonlea = get_object_or_404(AvonleaClass, pk=avonleas_pk)
if request.method == 'POST':
avonlea.delete()
return redirect('Avonlea')
import csv
def Avonleacsv(request):
data =AvonleaClass.objects.all()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="saved_file.csv"'
writer = csv.writer(response)
writer.writerow(['Unit', 'Number of Units'
])
for avonleaclass in data:
writer.writerow([
avonleaclass.unitNumber,
avonleaclass.newReading,
])
return response
Models.py
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
AvonleaUnits = [tuple([x,x]) for x in range(1,73)]
class AvonleaClass(models.Model):
unitNumber = models.CharField(max_length=2 , default='1')
newReading = models.IntegerField( blank=True, null=True)
difference = models.IntegerField(blank=True, null=True)
unitNotes = models.TextField(blank=True)
unitDateEntered = models.DateTimeField(auto_now_add=True, null=True)
unitProblem = models.BooleanField(default=False)
image = models.ImageField(blank=True, null=True)
def __str__(self):
return ('Unit ' + self.unitNumber)
Forms.py
from django.forms import ModelForm
from .models import AvonleaClass
from django import forms
AvnUnits = [tuple([x,x]) for x in range(1,73)]
class AvonleaForm(ModelForm):
unitNumber = forms.ChoiceField(choices= AvnUnits)
class Meta:
model = AvonleaClass
fields = ['unitNumber','newReading','difference', 'unitNotes','unitProblem' , 'image']
widgets = {
'unitNotes': forms.TextInput(attrs={'size': 10}),
'unitReading': forms.IntegerField(),
'diffrence': forms.IntegerField(),
}
Admin.py
from django.contrib import admin
from .models import AvonleaClass
class AvonleaAdmin(admin.ModelAdmin):
readonly_fields = ('unitDateEntered',)
admin.site.register(AvonleaClass, AvonleaAdmin)
class Birchleigh_ViewAdmin(admin.ModelAdmin):
readonly_fields = ('unitDateEntered',)
Avonlea.html
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
{% extends 'meter_readings/base.html' %}
{% block content %}
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<div class="container">
<h1>{{name}} Meter Readings</h1>
{% for unit_number in form.unitNumber %}
<h6>{{ error }}</h6>
<form class="form-group mt-4" method="post" {% if unit_number.data.value in created_nums %} style="background-color: rgb(231, 224, 224); " {% endif %} >
{% csrf_token %}
<div class="container">
<div class="row mb-3">
<div class="col">
{{ unit_number.data.value}}
</div>
<input type="hidden" name="unitNumber" value="{{unit_number.data.value}}">
<div class="col" id="prev{{unit_number.data.value}}" >
{{ previousReading }}
</div>
<div class="col" id="readings{{unit_number.data.value}}">
{{ form.newReading }}
</div>
<div class="col" id="difference{{unit_number.data.value}}">
{{ form.difference }}
</div>
<div class="col">
{{ form.unitNotes }}
</div>
<div class="col">
{{ form.unitProblem }}
</div>
<div class="col" id="img{{unit_number.data.value}}">
{{ form.image }}
</div>
<div class="col">
<button class="btn btn-success " type="submit" {% if unit_number.data.value in created_nums %} disabled {% endif %} > Save</button>
</div>
</div>
</div>
<script>
document.getElementById("img{{unit_number.data.value}}").firstElementChild.disabled = true
document.getElementById("difference{{unit_number.data.value}}").firstElementChild.disabled = true
var last = document.getElementById('readings{{unit_number.data.value}}');
last.addEventListener('input' , (e)=>{
last = e.target.value
var first = document.getElementById('prev{{unit_number.data.value}}').firstElementChild.value;
var diff= document.getElementById('difference{{unit_number.data.value}}').firstElementChild.value= parseInt(last) - parseInt(first);
if (diff <= 0){
console.log(diff)
console.log("-ve")
document.getElementById("difference{{unit_number.data.value}}").firstElementChild.style.border="2px solid red";
document.getElementById("img{{unit_number.data.value}}").firstElementChild.disabled=false
}
else{
document.getElementById("difference{{unit_number.data.value}}").firstElementChild.style.border="2px solid ";
document.getElementById("img{{unit_number.data.value}}").firstElementChild.disabled=true
console.log("+ve")
}
})
</script>
</form>
{% endfor %}
<style>
.error {
border:2px solid red;
}
</style>
<form method="POST", action="{% url 'currentAvonleas' %}">
{% csrf_token %}
<button type="submit">View all Avonlea readings</button>
</form>
<form method="POST", action="{% url 'Avonleacsv' %}">
{% csrf_token %}
<button type="submit">Export readings to Excel</button>
</form>
{% endblock %}
<br>
<br>
<br>
home.html:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
{% extends 'meter_readings/base.html' %}
{% block content %}
{% csrf_token %}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
<div class="container">
<div class="jumbotron">
<h1 class="display-5 text-center" align-items-center>Meter Reading Application</h1>
<h3>Individual Unit Readings</h3>
</div>
<div class="container">
<a href="{% url 'Avonlea' %}" class="btn btn-info" >Avonlea </a>
<br>
<br>
</div>
</div>
{% endblock %}
给出的确切错误:
TypeError at /avn init() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://localhost:8000/avn Django Version: 3.2 Exception Type: TypeError Exception Value:
init() takes 1 positional argument but 2 were given Exception Location: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response Python Executable: C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path:
['C:\Users\KylePOG\Desktop\meter-reading', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39', 'C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Sun, 30 May 2021 19:14:46 +0000 Traceback Switch to copy-and-paste view C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars
您需要与 .as_view(…)
method [Django-doc] 合作,将基于 class 的视图转换为可以处理请求的函数,因此:
path('avn', views.AvonleaView<b>.as_view()</b>, name='Avonlea'),