Объект Django Forms AttributeError ‘NoneType’ не имеет атрибута «отключено»

#django #django-models #django-views #django-forms #django-templates

Вопрос:

У меня по-прежнему возникают проблемы с пользовательской формой Django, которую я пытаюсь реализовать. Я действительно не знал никакого способа получить данные с интерфейса , кроме как пытаться вытащить данные силой request.POST.get() , но как только я начал это делать, я столкнулся с ошибкой атрибута, которая продолжала повторяться 'NoneType' object has no attribute 'disabled' , и ошибка указывала на form.save() строку как на проблему в моем views.py . Вот код для views.py

 @login_required
def volunteer_instance_creation(request):
    form = VolunteerInstanceForm(request.POST or None, request.FILES)
    values_dict = {
        "organization": request.POST.get('organization'),
        "supervisor_Name": request.POST.get('supervisor_Name'),
        "supervisor_Phone_Number": request.POST.get('supervisor_Phone_Number'),
        "volunteering_Duration": request.POST.get('volunteering_Duration'),
        "volunteering_Date": request.POST.get('volunteering_Date'),
        "description": request.POST.get('description'),
        "scanned_Form": request.POST.get('scanned_Form'),
    }
    for i in values_dict:
        form.fields[i] = values_dict[i]
    if form.is_valid:
        obj = form.save(commit = False)
        obj.student_id = get_student_id(str(User.objects.get(pk = request.user.id)))
        obj.grad_year = get_grad_year(str(User.objects.get(pk = request.user.id)))
        obj.save()
        return redirect("submission_success")
    return render(request, "members_only/yes_form.html")
 

Вот мой models.py

 class VolunteerInstance(models.Model):
student_id = models.CharField(
    blank = True, 
    editable = True, 
    default = 'No Student ID Provided',
    max_length = 255
)
grad_year = models.CharField(
    blank = True, 
    max_length = 255,  
    default = 'No Graduation Year Provided', 
    editable = True
)
organization = models.CharField(
    blank = False,
    max_length = 255
)
description = models.TextField(
    blank = False, 
)
supervisor_Name = models.CharField(
    blank = False, 
    max_length = 255
)
supervisor_Phone_Number = models.CharField(
    blank = True, 
    null = True, 
    max_length = 10
)
volunteering_Date = models.DateField()
volunteering_Duration = models.FloatField()
scanned_Form = models.FileField(
    null = True,
    blank = True, 
    upload_to = 'scanned_files', 
)
approved = models.BooleanField(
    default = False, 
    blank = True
)
 

И вот шаблон, который вызывает у меня проблемы.

 <form action = '.' method = "POST"> 
    {% csrf_token %}
    <div class="form-group row">
        <label class="col-sm-12 col-md-2 col-form-label">Nonprofit Agency</label>
        <div class="col-sm-12 col-md-10">
            <input class="form-control" type="text" placeholder = "Nonprofit Agency" name = "organization"> 
        </div>
    </div>
    <div class="form-group row">
        <label class="col-sm-12 col-md-2 col-form-label">Supervisor Name</label>
        <div class="col-sm-12 col-md-10">
            <input class="form-control" placeholder="Johnny Brown" type="text" name = "supervisor_Name">
        </div>
    </div>
    <div class="form-group row">
        <label class="col-sm-12 col-md-2 col-form-label">Organization Phone Number</label>
        <div class="col-sm-12 col-md-10">
            <input class="form-control" value="" type="tel" placeholder="Phone number without dashes or parenthesis" name = "supervisor_Phone_Number">
        </div>
    </div>
    <div class="form-group row">
        <label class="col-sm-12 col-md-2 col-form-label">Volunteering Duration</label>
        <div class="col-sm-12 col-md-10">
            <input class="form-control" placeholder="Duration in hours" type="number" name = "volunteering_Duration">
        </div>
    </div>
    <div class="form-group row">
        <label class="col-sm-12 col-md-2 col-form-label">Service Date</label>
        <div class="col-sm-12 col-md-10">
            <input class="form-control date-picker" placeholder="Select Date" type="text" name = "volunteering_Date">
        </div>
    </div>
    <div class="form-group">
        <label>Service Description</label>
        <textarea class="form-control"></textarea>
        
    </div>
    <div class="form-group">
        <label>Upload PDF File</label>
        <input type="file" class="form-control-file form-control height-auto" name = scanned_Form>
    </div>
    <div class="custom-control custom-checkbox mb-5">
        <input type="checkbox" class="custom-control-input" id="customCheck1" disabled = "" name = "approved"> 
        <label class="custom-control-label" for="customCheck1">Approved by Admin</label>
    </div>
    <input type = "submit" class = "btn btn-success" value = "Submit" name = "submit"/> 
</form>
{% if form.non_field_errors %}
        {% for error in form.non_field_errors %}
            <p class="text-danger">{{ error }}</p>
        {% endfor %}
{% endif %}
 

Мой forms.py

 today = dt.datetime.today()

class VolunteerInstanceForm(forms.ModelForm):
volunteering_Date = forms.DateField(
    input_formats = DATE_INPUT_FORMATS, 
    widget = forms.TextInput(
        attrs = {
            "placeholder":"month/day/year"
        }
    )
)
volunteering_Duration = forms.FloatField(
    validators=[
        MinValueValidator(
            limit_value = 0.5,
            message = 'Minimum value in this field must be 0.5',
        )
    ]
)
supervisor_Phone_Number = forms.CharField(
    label = 'Supervisor Phone Number',
    widget = forms.TextInput(
        attrs = {
            "placeholder": "Please the 10 digit phone number exculding dashes and parenthesis"
        }
    ), 
    validators=[
        RegexValidator(
            regex = '^(dddddddddd)


Комментарии:

1. Можете ли вы обновить вопрос, чтобы включить VolunteerInstanceForm его в forms.py?

2. Да, я могу это сделать

,
message = "Please enter the phone number excluding any dashes and parenthesis",
code = "invalid_phone_number"
)
]
)
approved = forms.BooleanField(
label = 'Approved by Supervisor',
initial = False,
required= False,
)

def get_service_date(self):
date = self.cleaned_data.get('date')
return str(date)

scanned_Form = forms.FileField(
label = "Please upload scanned YES Form here",
help_text = "max. 50 megabytes",
)

class Meta:
model = VolunteerInstance
fields = [
"organization",
"description",
"supervisor_Name",
"supervisor_Phone_Number",
"volunteering_Date",
"volunteering_Duration",
"scanned_Form",
"approved"
]

Комментарии:

1. Можете ли вы обновить вопрос, чтобы включить VolunteerInstanceForm его в forms.py?

2. Да, я могу это сделать