i have some forms at one page and I try to validate some fields too.
So if I enter wrong input at the test field, I get obviously the message ' invalid input', but also for each other field the messages 'This field is required.'.
How could I fix it? Override the clean function? But how?
class Example1Form(forms.ModelForm):
test = forms.CharField(max_length=30, validators=[RegexValidator(r'^[a-zA-Z0-9_-]+$'), MaxLengthValidator(30)])
And I also distinguish the different forms like:
class View(TemplateView):
def post(self, request, *args, **kwargs):
form_example1 = Example1Form(request.POST)
form_example2 = Example2Form(request.POST)
if form_example1.is_valid():
....
form_example2 = Example2Form()
return render(request, self.template, {'form_example1': form_example1, 'form_example2': form_example2})
if form_example2.is_valid():
....
Thank you very much for help!
First, you need a way to tell which form was submitted. You could name your submit buttons, for example:
<form>
{{ form_example1 }}
<input name="form_example_1" type="submit" value="Submit form 1">
</form>
<form>
{{ form_example2 }}
<input name="form_example_2" type="submit" value="Submit form 2">
</form>
Then, in your view, you should only bind your form to the POST data if that form was submitted. For example:
if "form_example1" in request.POST:
form_example1 = Example1Form(request.POST)
else:
form_example1 = Example1Form()
if "form_example2" in request.POST:
form_example2 = Example2Form(request.POST)
else:
form_example2 = Example2Form()
Related
I have an app project. I am able to save instances to the model in the database no problem. But I cannot pull in the instance by pk to the html form to edit and update. please see setup below can anyone provide any guidence or help, as to why this is not happening and how I can resolve?
views.py
def edit_properties(request, id):
properties = Properties.objects.get(pk=id)
context = {
'properties': properties,
'values': properties,
}
if request.method == 'GET':
return render(request, 'sub/edit_properties.html', context)
you better use ModelForm to update data in your models
class PropertiesEditForm(forms.ModelForm):
class Meta:
model = Properties
then you need to update your view to use this form
def edit_properties(request, id=None):
properties = Properties.objects.get(pk=id) if id else None
form = PropertiesEditForm(request.POST or None, instance=properties)
if request.POST:
if form.is_valid():
form.save()
return HttpResponseRedirect("url_to_show_your_new_data")
context = {
'form': form,
}
return render(request, 'sub/edit_properties.html', context)
and in html file you use this form
<form method="POST" action="URL_TO_EDIT_PROPERTIES_VIEW">{% csrf_token %}
{{ form }}
<input type="submit"/>
</form>
Found the issue, in my html the "{{values.address1}}" should be "{{values.Address1}}" as the attribute in the database is capital first letter.
Little less stressed now :)
<div class="form-row my-3">
<div class="form-group col-md-6">
<label for="Addressline1">Address line 1</label>
<input type="text" class="form-control" name="address1" id="address1Field"
value="{{values.address1}}">
</div>
Thank you all for your help,
I'am new to django.
I want to reate a webpage, and display information about a specific object and have a form to send a message about this object.
At the beginning, i used a detail view to display the info about the object.
Then a created a message form based on my Message Class
I used get_context_data to pass the form in the context for the template.
I would like to know if there is a way to manage the validation of the form in the same view or should i come back to a function view?
I've seen that FormMixin can help.
Could you tell me if it's the right solution.
Thank you for your help
My view:
class LoanDetailView(DetailView):
model = Loan
def get_context_data (self, **kwargs):
context = super(LoanDetailView, self).get_context_data(**kwargs)
msg_form = MessageForm()
context['msg_form'] = msg_form
return context
In my template:
<form method="POST">
{%csrf_token%}
<fieldset class="form-group">
{{ msg_form | crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit"> Envoyer </button>
</div>
</form>
You could use this pattern
class LoanDetailView(DetailView):
def get_context_data(self, **kwargs):
[...]
def post(self, request, *args, **kwargs):
form = MessageForm(request.POST)
if form.is_valid():
[...] # logic similiar as in function based view
I have multiple form fields, and multiple submit buttons on a same page. I want to detect by which form field a POST request is triggered.
I am using CBV and my post() method has this:
def post(self, request, **kwargs):
....
form1 = Form1(request.POST, instance=Model1.objects.filter(some_filtering...)
form2 = Form2(request.POST, instance=Model2.objects.filter(some_filtering...)
form3 = Form3(request.POST, instance=Model3.objects.filter(some_filtering...)
form4 = Form4(request.POST, instance=Model4.objects.filter(some_filtering...)
# this is the code I want to know
if POST request is triggered by form1...
# do something....
return super().post(request, **kwargs)
return super().post(request, **kwargs)
How can I detect which form triggered POST request?
I did it by using the input tag in HTML template instead of button tag for submitting the form
<form name="form-1" method="POST" action="{% url 'view_url_name'%}">
{% csrf_token %}
{{ form }}
<!--use input tag for submit button -->
<input class="btn mt-3 btn-primary" name="form-1-submit" value="Submit" type="submit"/>
</form>
Note: use the different name for each form submit input.
Now in your view, you can simply check for the name attribute of the button.
if 'form-1-submit' in request.POST:
form1 = Form1(request.POST, instance=Model1.objects.filter(some_filtering...)
...
# and so on
This implementation will also cover the scenario where you are
submitting the same form from different buttons to use that form data for different
purposes.
you can use an hidden input in your form like this
<input name="formId" value="1" type="hidden"/>
... <!-- in second form --!>
<input name="formId" value="2" type="hidden"/>
then in your view check which form submitted
if request.POST.get("formId") == "1":
form1 = Form1(request.POST, instance=Model1.objects.filter(some_filtering...)
elif request.POST.get("formId") == "2":
form1 = Form2(request.POST, instance=Model1.objects.filter(some_filtering...)
...
Who can help me with the following challenge?
I have a registration template where users can sign up. They are then redirected to an url with a payment button and activated when a successful payment is made. In the HTML template I store the username in a custom field within the payment button which is used to later activate the account. Now since the user is not activated/logged in yet, I can't call the user object yet like {{user.username}}. So I want to try sessions to solve this and capture the username during registration to retrieve this session variable and put it in my custom field on a different page. But how? I tried using request.session but I’m not sure where to fit this the files below and then how to call this variable in the html template.
Any advise or help is greatly appreciated!
Here is my regbackend.py
class MyRegistrationView(RegistrationView):
form_class = UserProfileRegistrationForm
def register(self, form_class):
user_package.username = form_class.cleaned_data['username']
And here my forms.py
class SignUpForm(forms.ModelForm):
class Meta:
model = SignUp
fields = ['username', 'email']
Here my registration.html
<form method="post" action=".">
{% csrf_token %}
{{ form.username|as_crispy_field }}
<input class="btn btn-success" type="submit" value="{% trans 'Submit' %}" /></form>
And finally my HTML Template for after registration with the payment button and custom field.
<form action="some-url" method="post" target="_top">
<input type="hidden" name="custom" value="{{ session.username? }}">
</form>
Im using Django 1.9x and Django-registration-redux
This is how I keep the session to use it on another view.
On your registration form :
def registration(request):
initial={'username': request.session.get('username', None)}
form = RegistrationForm(request.POST or None, initial=initial)
if request.method == 'POST':
if form.is_valid():
request.session['username'] = form.cleaned_data['username']
return HttpResponseRedirect(reverse('your_checkout_view'))
return render(request, 'registration.html', {'form': form})
Once the username field is completed and the form submited it goes to the second view in which you can take the username that is stored in your session.
Just like this :
def your_checkout_view(request):
username = request.session['username']
...
From there you can take the stored username and do what you have to do.
So I'm new to django and I'm struggling with the documentation for class based views. Not really sure what I'm doing wrong here, but this is the problem:
I fill in the appropriate data on the form, click submit and I'm redirected to the same url plus some get parameters that correspond to what I submitted in the form. Nothing new is added to the db. I would like to create a new Advertisement row in the db when I click submit.
I have a ModelForm as follows:
class NewAdForm(ModelForm):
class Meta:
model = Advertisement
exclude = ('campaign',)
def __init__(self, campaign, *args, **kwargs):
super(NewAdForm, self).__init__(*args, **kwargs)
self.campaign = campaign
I also have a FormView:
class AddAdvertView(FormView):
form_class = NewAdForm
template_name = 'advertisers/newad.html'
def get_form_kwargs(self):this
kwargs = super(AddAdvertView, self).get_form_kwargs()
kwargs['campaign'] = get_object_or_404(Campaign, id__exact = self.kwargs['campaign_id'])
return kwargs
def form_valid(self, form):
form.save(commit = True)
return super(AddAdvertView, self).form_valid(form)
And here's the template:
<form action="" method="get">
{{ form.as_p }}
<input type="submit" value="Submit"/>
</form>
Any reason why you're using method="get"? The FormView class is probably expecting a POST in order to trigger validation and saving. GET is usually just used to render the initial form.
It's possible that it's because you're missing the CSRF token, but it really should give you an error about that. Still, try:
<form action="" method="get">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit"/>
</form>
Also, while it doesn't explain why the form isn't saved, you need to specify a success_url on your FormView, the URL the user should be redirected to after successfully submitting the form. I've actually never tried leaving it off, but it's possible that the view is taking you back to the form simply because it doesn't know where else to go.