How to make my forms work in Django? - python

I just created a Bootstrap 3 website with Django. My website has 4 different pop-up modals in the following order: 1. Uploading your display image, 2. adding basic information, 3. choosing login credentials and 4. adding their personal biography.
These 4 modals all contain their own html form, so I have 4 different forms for the user to register their account. My question is how do I link all 4 forms together so I can pass the information to my Django server and generate the user in my database?
I've seen videos of people generating their forms through a Forms.py file, but I can't do it that way because I already have my forms. If I did not spend my time designing the frond end I would just delete the forms and generate them again through a Forms.py file, but I did.
Anyone who can help me out? I'm quite new to Django.

You misunderstand the concept of forms in django.
They're designed and created to validate user input before saving to database, and generating html from form classes is just additional feature, you mustn't use it.
To make your bootstrapped forms work, you must create django form with all the fields(all fields from your 4 forms), and then:
`............................
def my_view(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
form.save()
.....................`
And override form.save with user-creating functionality.

Related

how to make a data fetch form in django?

I want the user to have a form for fetching data from the database, for example, as in /admin:
Form in admin
So that the user can select multiple entries and, for example, delete them, how can I do this?
if you want to modify the django admin and add the functionality you need to use this package from django.contrib import admin to register your personal models by extending admin.ModelAdmin
To change the admin interface you need to override template files in .../site-packages/django/contrib/admin/templates/ Here is the full tutorial for more clarification
https://realpython.com/customize-django-admin-python/

Is there any way to link existing inputs to django form?

Working on an app, I initially started developing the UI via QT (PySide2) but I paused it to work on a full "online version" via Django.
The fact is that I'm learning/discovering the framework and how it works step after step.
For all HTML I'm building those on Bootstrap Studio which help me to save A LOT of time and of course make things totally easier for me.
My current problem is that I just discovered how not simply inputs/forms work in Django (My own opinion !). My app works with several bootstrap modals in order to Add/Edit "element" which are the kind of instances of my app and which will be write/read/edit in the database.
The problem here is I already created all HTML pages and related bootstrap-modals and I can't find any way on the internet to link my existing bootstrap-modals to Django forms.
As far as I understood Django forms "caricaturaly" works like this: Django generates a form that you have to dynamically integrate into your HTML.
The fact is it doesn't really arrange me because :
I already have my bootstrap-modals with their inputs looking how I want
I don't really want a bad looking forms as Django generates
I have other elements in the form which are not related to a form (progress bar)
Any other things I have no idea about since I am a beginner in Web!
Therefore, my main question here would be: Is there any simple/accessible way to get the inputs as it would be via QT, by this I mean :
Opening the modal
Filling Input_1, Input_2, Input_3
Any way in Django files to get those inputs and then saves those in DB (one by one)
My apologies if really looks dumb here but I am really new to Django/Web, I know CSS/HTML syntax, I have NO knowledge in JavaScript and I would say that my Python level is Intermediate (enough for all my back-end uses).
Thank you in advance for your help!
A simple example of using a form for validation/processing but not html generation.
Assume we have this existing form
<form action="/some-url" method="POST">
<input id="foo" name="foo" type="text"/>
<input id="bar" name="bar" type="text"/>
<input id="baz" name="baz" type="text"/>
</form>
you can represent it with this Django form:
class MyForm(forms.Form):
# Field names should match the 'name' attributes in the html inputs
foo = forms.CharField()
bar = forms.CharField()
baz = forms.CharField()
And use it in view like this
def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
# Do stuff
return HttpRedirectResponse('/success')
# No need to pass the a form to the template, because we aren't
# using it to generate html.
return render(request, 'view.html', {})
If you want to use a field from the html form separately, without using a Django form at all, access it directly:
some_val = request.POST['some_val']
(beware of false booleans and disabled fields, which will not be present in request.POST).

Handling input from an input field or form field with Django

So I'm trying to learn Django by building a very simple single-page site that just takes emails for subscriptions and stores it into djangos backend. I made an html page for the site that has form and input elements, and I've successfully rendered the page by following the documentation. I even built a model called 'subscriptions', to take email strings, but now i'm unsure about how to handle the input from the html page and store the emails in the backend.
All the documentation is kind of confusing cause it instructs me to build a separate .html file for the form, and handle it in another views and model page, which just seems unnecessary.
Does django necessitate handling input in a separate forms.html file? Or can i just use the index.html, and add views to 'views.py' or revise 'models.py'?
I'm pretty confused, all help and examples are very appreciated!
Django documentation on Working with forms mentions a lot of examples around what you want to do.
Create a forms.py as mentioned on the page and you can create an equivalent view for it in views.py which recieves form values.
Once you have your form data in the view as shown in example, you can save it to using, as something like:
s = Subscriptions(email=email)
p.save()
Refer more on models here.

Django - Form across multiple views with progress saving

I'm working on a Django project and to make the forms experience far smoother I want to spread a ModelForm across a few pages. It would be ideal if users who are logged in can save their progress in the form without actually posting the content (in this case, a JobApplication where users can come back to filling in info without actually sending off the application).
Currently I have looked at other answers on SO such as this one; but this only shows me how to utilise caching to store information between the views where the form is present.
Models.py (models, forms and views have been simplified for readability):
class JobApplication(models.Model):
job = models.ForeignKey(JobPost,on_delete=models.SET_NULL,...)
user = models.ForeignKey(AUTH_USER_MODEL,...)
details = models.CharField(max_length=300)
skills = models.CharField(max_length=300)
feedback = models.CharField(max_length=300)
#... [insert more fields] ...
Forms.py:
class Application(forms.ModelForm):
details = forms.CharField() # To go in page 1 of the form process
skills = forms.CharField() # To go in page 2
feedback = forms.CharField() # To go in page 3
class Meta:
model = JobApplication
fields = ['details','skills','feedback']
Views.py:
from . import forms
def view1(request):
form = forms.Application()
if request.method == 'POST':
form = forms.Application(data=request.POST)
... some logic here which I am not sure of ...
return render(request, 'view1.html', {})
def view2(request):
form = forms.Application()
if request.method == 'POST':
form = forms.Application(data=request.POST)
...
return render(request, 'view2.html', {})
def view3(request):
form = forms.Application()
if request.method == 'POST':
form = forms.Application(data=request.POST)
...
return render(request, 'view3.html', {})
Note that I'm happy to edit my forms or models to achieve this multi-page, save progress effect that you may see on job sites.
Let me know if there's any more code I can add that will be useful, since I'm not too sure what else will be required.
Thanks!
I had a similar use case in my application what I did was created
multiple forms out the models and a central view controlling the
progress of the form.
The view has a list of forms it has to propagate through
GET : /form/<index> => form/0
POST : Save data to the form
Initially the form will have no initial data, for index > 0 the
initial data will be the previously saved model object
When user clicks on next increment the URL index counter, Decrease
it for prev, Don't save anything on skip
Here is a gist of how it would look.
https://gist.github.com/bhavaniravi/b784c57ae9d24fce359ae44e2e90b8e3
I don't know if this is the best optimized method of all times but this is what I did. Any suggestions on improvement is most welcomed
You will need a Form for each action you need. With it on hands, you can use a feature from Django 1.7 called Form Wizard (Yes, it is built in), the best way achieving this is using Class-Based Views, that is way more flexible, clean and cohesive than FBV in this case.
https://docs.djangoproject.com/en/1.7/ref/contrib/formtools/form-wizard/#
Basically you will define a list of steps and forms, both tied to the same URL. You can use customized templates for each form:
https://docs.djangoproject.com/en/1.7/ref/contrib/formtools/form-wizard/#using-a-different-template-for-each-form
[EDITED]
As jayt said in comments, the formtools was deprecated since version 1.8 and is now apart from core package and can be found in https://github.com/django/django-formtools/
Good luck. =)
I'm working on a Django project and to make the forms experience far
smoother I want to spread a ModelForm across a few pages. It would be
ideal if users who are logged in can save their progress in the form
without actually posting the content (in this case, a JobApplication
where users can come back to filling in info without actually sending
off the application).
You are mixing UI/UX concepts with technical implementation here.
Your overall process is a job application where you have these states:
create a new applicant (user) if not yet done
create a new application for that user
work on that application until the user says they are done (allowed to span multiple (browser) sessions)
mark application as done -> actually apply to the job
How the data for the application is collected (in whatever forms or such) and "submitted" in a web development sense is independent of the actual job application action - it just need to happen beforehand.
So rather than just use one single Django form, you have these possibilities:
(A) Create smaller models that represent a certain content section of the form and that should get their own form. Create ModelForms for those and make them accessible in their own views.
(B) Stick with the single model as you have now but create custom Django forms for each of the separate pages as you have planned. You can still use ModelForm and model=JobApplication but each form has to specify the set of fields it covers and validate only these fields.
Progress Tracking
(A) or (B): You could track how much information has been input (in percent, e.g. by simply counting all fields and all non-empty fields and calculating their percentage.
(A): With different django models you could add a last modified timestamp to each model and show if and when this section was edited.
Main Page
In an overview page you could collect all the data for the user so that they can see what the application will look like (to someone else maybe even) - and there they can also click a button "apply to the job!", or they can open each specific form if they see that any of the data is not yet complete.
Actual Job Application
Once the user clicks on "apply to the job" a different POST happens that for example sets a datetime field on the JobApplication model. This way you can identify all applications that have reached this process step.
Same with any other steps that happen after that. Maybe the user can create another application by copying an existing one. Or their accepted status is also entered in that system and they can log in and check that. Or the system sends out email notifications or similar. Just add fields for anything that is of interest, then you can also reflect that in the UI if you want to.

Django : Storing user steps with django admin form

I am doing a workflow app that forces the users to go through a set of forms and save some data.
They can leave the process of filling that form and log-out at any point of time.
When they log in back, they should be redirected to the same form/page where they left last time.
What is the best way to approach this problem ? Should I have a model in this app which stores such data every step ?
UPDATE:
By form I mean admin forms.
Django form wizard is what you want.
You can use SessionWizardView for more easily display the wizard when user comes back again.

Categories