Problem while creating a mofelform and editing a particular field in the modelform

Viewed 20

I am in a middle of a project. The problem is arising from here :

class PatientCreation(forms.ModelForm):

    class Meta:
        model = Patient
        fields = ['user','contact','dob']

    dob = forms.DateField(widget=forms.SelectDateWidget(years=range(1960,2022)))

Whenever i try to save the form by using the frontend its creating an error. The model for this form is :

class Appointments(models.Model):
    doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
    app_time = models.DateTimeField()
    diognoses = models.TextField(max_length=1000)
    prescriptions = models.TextField(max_length=250)


    class Meta:
        unique_together = ('doctor', 'patient', 'app_time')

    def __str__(self):
        st = (str(self.doctor.user.name)+str(self.patient.user.name)).lower().strip()
        return st

I am not sure if i can even define a particular field in a model form or not else the widget is working fine. So how can I implement the logic such that I get the date time widget in dob field. Also how can i default the value of the user field as the currently logged in user. Also when i am submitting the form i get this error

    AttributeError at /register_user/
    'DateField' object has no attribute 'is_hidden'
    Request Method: POST
    Request URL:    http://127.0.0.1:8000/register_user/
    Django Version: 4.0.5
    Exception Type: AttributeError
    Exception Value:    
    'DateField' object has no attribute 'is_hidden'
    Exception Location: E:\env\lib\site-packages\django\forms\boundfield.py, line 214, in is_hidden
    Python Executable:  E:\env\Scripts\python.exe
    Python Version: 3.10.7
    Python Path:    
    ['E:\\Projects\\redoc-git\\redoc',
    'C:\\Program '
    'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\python310.zip',
    'C:\\Program '
    'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\DLLs',
    'C:\\Program '
    'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\\lib',
    'C:\\Users\\Pradyumna\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0',
    'E:\\env',
    'E:\\env\\lib\\site-packages']
    Server time:    Fri, 23 Sep 2022 01:44:25 +0000

enter code here
1 Answers

you can set your initial value in your view

form.initial = form.initial = {"user": loggedInUser}

In your form you have to put dob in fields = []

Related