Django POST to other view - django

I have the following form that lives on the site root at /
<form action='/play/' method='post'>
{% csrf_token %}
{{ form.player_name }}
<input id='play' type='submit' value='Play'>
</form>
then I have the view that validates this form:
def login(request):
context = {}
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/play/')
else:
context.update(dict(form=form))
else:
context.update(dict(form=LoginForm(initial={'player_name':'Please tell us your name'})))
return render_to_response('login.html', context, context_instance=RequestContext(request))
And the actual play view:
def play(request):
p1 = briscola.Player(request.POST['player_name'])
The problem is that of course the redirect looses the POST data. But why doesn't it POST directly to the play view by itself when the form.is_valid?

Related

How can show variable in UI in django from view function?

I want to show value of pro in UI but not getting , here is my test view function code .value of pro is getting from previous function using django session variable.
#api_view(['GET', 'POST'])
def test(request):
pro = request.session.get('j')
print("Request ID from Index View : ", pro)
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
print("Form is Valid")
selected = form.cleaned_data.get('myfield')
print(selected)
else:
# rq = request_id["request_id"]
s = sql()
query = f"""update request_form_db.request_form_mymodel
set is_approved=1
where request_id = '{pro}' """
print(query)
s.update_query(query)
print("Updated Successfully")
form = TestForm()
else:
form = TestForm()
context = {'form': form, 'pro': pro}
return render(request, 'test.html', context)
Here is my html code test.html
<form action ="{% url 'test' %}" method="POST">
<div class="form_data">
{% csrf_token %}
<br><br>
{{form.myfield}}
<label><b>Git Id</b></label> <br><br>
<br><br>
{{form.pro}}
<input type="submit" value="Submit" class="btn btn-success" />
form.myfield returns what i want but value of pro variable not getting.please help
Just pass same key as you created in context. you dont have to use {{ form.pro }}
context = {'form': form, 'pro': pro}
In html you can render with:
{{ pro }}

django model based forms - why isn't form valid?

I'm trying to make model based form but something went wrong.
model:
class Topic(models.Model):
name = models.CharField(max_length=200)
icon = models.ImageField(upload_to = 'images/')
form:
class TopicCreationForm(ModelForm):
class Meta:
model = Topic
fields = '__all__'
view:
def TopicCreateView(request):
form = TopicCreationForm()
if request.method == 'POST':
form = TopicCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
print('aaa') # It displays in console
context = {'form':form}
return render(request, 'blog/topic_form.html', context)
my form html part
<form method="POST">
{% csrf_token %}
<fieldset >
<legend> New Topic</legend>
{{ form|crispy }}
</fieldset>
<div>
<input type="submit" value="submit" class="button-33" role="button">
</div>
</form>
where did i make mistake ?
You need to pass both request.POST and request.FILES [Django-doc], so:
def topic_create(request):
if request.method == 'POST':
form = TopicCreationForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('home')
else:
print('aaa') # It display in console
else:
form = TopicCreationForm()
context = {'form':form}
return render(request, 'blog/topic_form.html', context)
In the HTML form, you need to specify that the files should be encoded with the enctype="…" attribute [mdn]:
<form method="post" enctype="multipart/form-data">
…
</form>

Dango: form rendering empty fields when calling with POST and an instance of the model

I want to add an edit option to a template that just retrieves data from a model and displays it. When the edit button is clicked, the form that has been previously filled and saved, should show up being populated with saved data. But in my case, the form is rendering with empty fields and showing "This field is required" above each field. How do i render the form in editable mode with fields pre-populated?
This is the view for first time data saving:
#login_required
def addprofileView(request):
if request.method == "POST":
form = UserProfileForm(request.POST, request.FILES)
if form.is_valid():
new_user_profile = form.save(commit=False)
new_user_profile.user = request.user
new_user_profile.save()
return redirect('add_license')
else:
form = UserProfileForm()
return render(request, 'addprofile.html', {'form': form})
And this is the view for editing and which should return pre-populated form:
#login_required
def editprofileView(request, pk):
ac = get_object_or_404(Account, pk=pk)
if request.method == "POST":
form = UserProfileForm(request.POST, instance=ac)
if form.is_valid():
ac = form.save(commit=False)
ac.user = request.user
ac.save()
return redirect('view_profile', ac.pk)
else:
form=UserProfileForm(instance=ac)
return render(request, 'addprofile.html', {'form': form})
#login_required
def ProfileView(request, pk):
profile = Account.objects.filter(pk = pk)
return render(request, 'userprofile.html', {'pr': profile})
What am I doing wrong?
The template that redirects to the editprofileView:
 {% block content %}
{% for p in pr %} 
Name: {{ request.user.username }} 
Mobile: {{ p.mobile }} 
city: {{ p.city }} 
building no: {{ p.building_no }} 
state: {{ p.state }} 
ZIP: {{ p.zip }} 
Country: {{ p.country }} 
Sex: {{ p.sex }} 
<form action="{% url 'edit_profile' p.pk %}" method="post">
{% csrf_token %}
<input type="submit" value="Edit">
</form>
{% endblock %}
The action URL in this template sends the Account attribute pk to the editprofileView.
Well, the issue is that you are POSTing to that view in the first place. You shouldn't; a POST is for submitting the data. You don't show that button, but it should either be a simple link, or part of a form with method="GET".

invalid PasswordChangeForm

Heyho,
I created a model Profile with a OnetoOneField to User. In account_settings view I want to either give the possibility to change the profile information or reset the password. Changing Profile-Information works fine, but when I try to change the password, my PasswordChangeForm is always invalid. Can somebody tell me where my mistake is?
Here's the view:
def account_settings(request, id):
user = Profile.objects.get(id=id)
if request.method == 'POST' and 'passwordchange' in request.POST:
user_form = PasswordChangeForm(request.user, prefix='password')
if user_form.is_valid():
user_form.save()
update_session_auth_hash(request, user)
messages.success(request, 'Your password was successfully updated!')
else:
messages.error(request, 'Please correct the error below.')
return redirect('profile', user.id)
elif request.method == 'POST' and 'profilechange' in request.POST:
profile_form = ProfileForm(request.POST, instance=request.user.profile,prefix='profil')
if profile_form.is_valid():
profile_form.save()
return redirect('account_settings',user.id)
#else:
#messages.error(request, _('Please correct the error below.'))
else:
user_form = PasswordChangeForm(user=request.user, prefix='password')
profile_form = ProfileForm(instance=request.user.profile,prefix='profil')
return render(request, 'app/accountform.html', {'profileuser': user,'user_form': user_form,'profile_form': profile_form})
the template:
<div class="col-md-9">
<div class="profile-content">
<form method="post" >
{% csrf_token %}
{{ profile_form.as_p }}
<button type="submit" name="profilechange">Änderungen speichern</button>
</form>
<form method="post" >
{% csrf_token %}
{{ user_form.as_p }}
<button type="submit" name="passwordchange">Passwort ändern</button>
</form>
Abbrechen
</div>
</div>
You are not passing the POST data to the form, which is why it is failing to validate. You need to pass the POST data when initialising it:
user_form = PasswordChangeForm(request.user, data=request.POST, prefix='password')
if user_form.is_valid():
# This should work now

How to pass a form value to another view

How to get a form value form one view to another.
for example i would like to get the 'web_input' value from InputWebView() and pass it into DisplayWebView()
<form method="POST" action="">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.web_input }}
<input type="submit">
</form/>
def InputWebView(requests)
form = WebInputForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
return redirect('add_web', web_url=request.POST['web_input'])
def DisplayWebView(request, web_url):
url = web_url
You can use sessions to pass data from one view to another. In InputWebView:
def InputWebView(requests)
form = WebInputForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
request.session['web_input'] = request.POST['web_input']
return redirect('add_web')
In DisplayWebView:
def DisplayWebView(request):
url = request.session.get('web_input')