Home > Net >  Django Form is not updating the database
Django Form is not updating the database

Time:11-26

I am making a form website. but my inputs are not being added to the database. It worked before but not anymore. the last change I made that stopped it from working was the URL from my form so it could go to another page when I submit the form.

my html template was like this

<div class="form-container">
    <form enctype="multipart/form-data" action="/succes/" method="POST">
    .....

after I added this it stopped working after adding the {%url 'Form:thank'%} everything went down hill.

<div class="form-container">
    <form enctype="multipart/form-data" action="{%url 'Form:thank'%}" method="POST">
    ......

I am honestly lost right now. and don't know how to fix this. I am a beginner Django developer (so maybe I missed something)

urls.py

 app_name =  'Form'
 urlpatterns = [
   path('', FormPage, name = "Home"),
]

of course I removed the thanks page to revert to what i had before. And the thanks page was working. if you are wondering

models.py

class Form(models.Model):
company_name = models.CharField(max_length=200, null=False, blank=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
AIB_number = models.CharField(max_length=100)
position_title = models.CharField(max_length=200)
telephone = models.CharField(max_length=20)
email = models.EmailField()
job_duties = models.TextField() 
access_justification = models.TextField()
wap_roa = models.CharField(max_length=255)
required_access = models.CharField(choices=RequestAccessChoices, max_length=200)
start_time = models.DateField(blank=True, null=True)
end_time = models.DateField(blank=True, null=True)
main_communications_room = models.ManyToManyField(MainCommunicationRoom, blank=True)
new_terminal_building = models.ManyToManyField(NewTerminalBuilding, blank=True)
old_terminal_building = models.ManyToManyField(OldTerminalBuilding, blank=True)
building = models.ManyToManyField(OtherBuilding, blank=True)
other_locations = models.TextField(blank=True )
specify_system_list = models.TextField(blank=True)
specify_equipment_list = models.TextField(blank=True)
specify_server_list = models.TextField(blank=True)
Specify_cables = models.TextField(blank=True)
agreed_to_terms = models.BooleanField(default=False)
submitted_date_time = models.DateTimeField(default=timezone.now)

def __str__(self):
    return self.last_name


class FormFiles(models.Model):
files = models.FileField(upload_to = "uploaded_files", null=True, blank=True)
form_fk = models.ForeignKey(Form, on_delete=models.CASCADE, null=True, blank=True)

views.py

def FormPage(request):

if request.method == "POST":
    form = Form(request.POST)
    if form.is_valid():
        bigform = form.save(commit=False) 
        print(f'is this even working {form}')
        for f in request.FILES.getlist('files'):
            inputs = FileInput(request.FILES, request.POST)
            if inputs.is_valid():
                fileinp = inputs.save(commit=False)
                fileinp.files = f
                fileinp.form_fk = bigform
                fileinp.save()
            else:
                print(inputs.is_valid())
                print(inputs.is_bound)
                print(inputs.errors)
        return HttpResponseRedirect('/success/') 
    else:
        print(form.is_bound)
        print(form.is_valid())
        print(form.errors)
else:
    form = Form()
    inputs = FileInput()

dic = {
    'form': form,
    'fileinputs': FileInput
}
return render(request, 'formpage.html', {'dic': dic})

forms.py

class Form(forms.ModelForm):

class Meta:
    model=Form
    fields='__all__'
    exclude = ['submitted_date_time']
    error_css_class = 'error'
    required_css_class = 'required'
  
    widgets = {
        'main_communications_room' : forms.CheckboxSelectMultiple(attrs={'class':'checkbox'}),
        'new_terminal_building':forms.CheckboxSelectMultiple(attrs={'class':'checkbox'}),
        'old_terminal_building': forms.CheckboxSelectMultiple(attrs={'class':'checkbox'}),
        'building': forms.CheckboxSelectMultiple(attrs={'class':'checkbox'}),
        'start_time':forms.DateInput(attrs={'type': 'date'}),
        'end_time':forms.DateInput(attrs={'type': 'date'}),
        'agreed_to_terms': forms.CheckboxInput(attrs={'required':True})
    }

class FileInput(forms.ModelForm):

class Meta:
    model = FormFiles
    fields = '__all__'

    widgets ={
        'files': forms.ClearableFileInput(attrs={'multiple':True}),
    }

CodePudding user response:

The action="…" should refer to the FromPage, since that is the view that handles a POST request of that form. This thus means that you specify this as:

<form enctype="multipart/form-data" action="{% url 'Form:Home' %}" method="POST"></form>

In the view you then handle the logic to save the data to the database, and then you can return a redirect response to the thank-you page with:

from django.shortcuts import redirect

def FormPage(request):
    if request.method == 'POST':
        form = Form(request.POST)
        if form.is_valid():
            bigform = form.save(commit=False) 
            print(f'is this even working {form}')
            for f in request.FILES.getlist('files'):
                inputs = FileInput(request.FILES, request.POST)
                if inputs.is_valid():
                    fileinp = inputs.save(commit=False)
                    fileinp.files = f
                    fileinp.form_fk = bigform
                    fileinp.save()
            # redirect to the Form:thank view
            return redirect('Form:thank')
    else:
        form = Form()
        inputs = FileInput()
    
    dic = {
        'form': form,
        'fileinputs': FileInput
    }
    return render(request, 'formpage.html', {'dic': dic})

The redirect('Form:thanks') will thus redirect the browser to the thank you page.

  • Related