Django view not passing IP address data from form - python

Trying to do something simple here where I pass an IP address from a form to another view. Previously I had success following beginner tutorials. If someone could point me back to what I'm missing that would be a huge help.
model:
class GenericIP(models.Model):
name = models.CharField(max_length=50)
genericip = models.GenericIPAddressField()
def __str__(self):
return self.name
form:
class IpForm(forms.Form):
gateway = ModelChoiceField(queryset=GenericIP.objects.order_by('name').values_list('genericip', flat=True).distinct())
views:
def TestCreate(request):
if request.method == 'GET':
form1 = IpForm()
return render(request, 'create_test.html', {'form1' : form1} )
else:
if request.method == 'POST':
form1 = IpForm()
if form1.is_valid():
genericip = form1.cleaned_data
genericip.save()
return render(request, 'create_test.html', {'genericip' : genericip} )
def RunTest(request, genericip=""):
if request.method == 'POST':
Server = genericip
return HttpResponse(Server)
URLS:
urlpatterns = [
path('', views.TestCreate, name='create_test'),
path('run_test', views.RunTest, name='run_test',),
]
template:
{% block content %}
<form action="{% url 'run_test' %}"method='post'>
{% csrf_token %}
{{ form1 }}
<input type='submit' class="btn btn-success" value='Run Test'>
</form>
{% endblock %}
So what's happening is when I hit the button to run the test, I don't get anything for the httpresponse. The post data for the TestCreate view does show variable "genericip" and input "192.168.100.100" but that data is not posting correctly to the runtest view.

In the RunTest function, you are getting the genericip value as a function argument.But in your scenario you are sending the genericip vaule in the form of form submit. So you should try some thing like this,
def RunTest(request):
if request.method == 'POST':
ip = request.POST.get('gateway') # Some thing with form field name
Server = ip
return HttpResponse(Server)
Hope this helps you, if anything please let me know.

You aren't adding the POST data to the form instance in the post request - you're just instantiating an empty IpForm instance.
Try something like this in the appropriate section of your code:
if request.method == 'POST':
form1 = IpForm(data=request.POST)

Related

How to make a correct redirection in django app after user delete his message in website?

I am developing a website watching a video course and sometimes I don't agree with mentor decisions about solving some tasks. And while i am trying to figure this out, the problem has already taken really much time and i haven't still found how to solve this.
At first I show the necessary source code.
urls.py and the the error url:
path('delete-message/<str:pk>/', views.delete_message, name='delete-message')
views.py and function where error happens:
#login_required
def delete_message(request, pk):
message = Message.objects.get(id=pk)
room_id = message.room.id
if request.method == 'POST':
message.delete()
return redirect(f'room/{room_id}') ### WHAT DO I HAVE TO DO ???
return render(request, 'delete-message.html')
delete-message.html and error form:
<form method="POST">
{% csrf_token %}
<h2>
<p>Are you sure you want to delete this message ?</p>
</h2>
Go Back
<input type="submit" value="Confirm">
</form>
After redirect() works it sends me to the unexisted url: 127.0.0.1:8000/delete-message/10/room/5but it had to be http://127.0.0.1:8000/room/5...
Why is it not as such result as I've expected?
Also I've tried to do this:
In the views.py I change function where except of redirect I transfer room_id to the template:
#login_required
def delete_message(request, pk):
message = Message.objects.get(id=pk)
room_id = message.room.id
if request.method == 'POST':
message.delete()
return render(request, 'delete-message.html', {'id': room_id})
In the template delete-message.html I try to redirect back to the room by the "action" attribute:
<form method="POST" action="{% url 'room' id %}">
And this method also return an error:
IntegrityError at /room/5/
NOT NULL constraint failed: BaseApp_message.body
You can use reverse with url name space init like below :-
urls.py
path('room/<str:pk>/', views.room_message, name='room')
Then in your view will be :-
#login_required
def delete_message(request, pk):
message = Message.objects.get(id=pk)
room_id = message.room.id
if request.method == 'POST':
message.delete()
url = reverse('room', kwargs={'id': room_id})
return HttpResponseRedirect(url)
To redirect to a root-relative URL, add a leading forward slash:
# return redirect(f'room/{room_id}')
return redirect(f'/room/{room_id}')

data cannot be saved in form

data cannot be saved in form.I wrote html like
<form action="/app/save" method="POST">
<input id="classname" name="classname">
<input id="score" name="score">
<input id="course" name="course">
<button type="submit">SEND</button>
</form>
in forms.py
from django import forms
from .models import Student
class SaveForm(forms.ModelForm):
class Meta:
model = Student
fields = ("classname", "score", "course")
in views.py
#csrf_exempt
def save(request):
save_form = SaveForm(request.POST or None)
print(save_form.is_valid())
if request.method == "POST" and save_form.is_valid():
item = save_form.save(commit=False)
classname = request.POST.get("classname", "")
score = request.POST.get("score", "")
course = request.POST.get("course", "")
item.classname = classname
item.score = score
item.course = course
item.save()
return render(request, 'index.html')
in models.py
from django.db import models
class Student(models.Model):
classname = models.CharField(max_length=100)
score = models.CharField(max_length=100)
course = models.CharField(max_length=100)
When I run this codes ,put data A in classname& 80 in score&Math in course of html and put SEND button,save method can be called but data cannot be saved.print(save_form.is_valid()) shows False.I really cannot understand why I can't send data.What is wrong in my codes?How should I fix this?
Okay a few things here;
Why is score a charfield? If it's a %, shouldn't it be an int?
Student model doesn't have any foreign keys, so there's really no need to use commit = false in your save.
Creating inputs for each item on your form in html is definitely the long way to do it. The best way to do this in your html is simply to use {{form}}. To do this, you'll need to pass the form as a variable in context in your views.py.
Without being mean, are you very early in to the django beginner tutorial? If so, I would recommend moving forward through that before trying to continue your current project. It'll really help you. Here's what I would suggest as a views.py
def save(request):
if request.method == "POST":
save_form = SaveForm(request.POST)
print(save_form.is_valid())
if(save_form.is_valid()):
save_form.save()
return HttpResponseRedirect('New-destination-URL')
save_form = SaveForm()
context['form'] = save_form
return render(request, context, 'index.html')
and in index.html:
form action="/app/save" method="POST">
{{form}}
</form>
You do it wrong, you have to handle both situations - when you are on page at first time, and time when form is filled with data.
Try to change your views to this :
if request.method == "POST":
save_form = SaveForm(request.POST)
...
else:
save_form = SaveForm()
return render(request, 'index.html', {'save_form': save_form)
and then try to put this in template:
<form action="/app/save" method="POST">
{{ save_form.as_p }}
<button type="submit">SEND</button>
</form>

Django - template build-in filter tags {% url %}

I am a new coder with Django. So, first apologize for it if this question is too easy.
class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.Textarea)
def save_comments_into_database(topic, user_id, content):
data = Comment(topic=topic, commenter_id=user_id, content=content)
data.save()
this is the code for form
<form action = "{% url 'post:comment' the_topic=topic user_id=1 %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">submit</button>
</form>
I am trying to use url tag to call a function is views.py.
topic is a variable I passed in when this page is created.
this is my code in urls.py
url(r'^(?P<topic_id>[0-9]+)/comment/$', views.comment, name="comment"),
then this is how I do in views.py
def comment(request, the_topic, user_id):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CommentForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
text = form.cleaned_data['comment']
args = {'form': form, 'text': text, 'topic': the_topic}
# save the data in database
save_comments_into_database(the_topic.id, user_id, text)
# redirect to a new URL:
return render(request, 'post/detail.html', args)
# if a GET (or any other method) we'll create a blank form
else:
form = CommentForm()
return render(request, 'post/detail.html', {'form': form, 'topic': the_topic})
I get the NoReserveMatchException:
I really don't get where it goes wrong.
Your comment URL only has one var, the topic_id, but you passed two vars, the_topic and user_id. You need to pass just the topic ID. Also, in views you would normally access the current user via request.user.
you should to change declare the urls, added second parameter and change name of the first
url(r'^(?P<the_topic>[0-9]+)/comment/(?P<user_id>[0-9]+)/$', views.comment, name="comment"),
# ^^^^^^^^^ ^^^^^^
It's better to serve the action redirection using Django built in HttpResponseRedirect in the views.py and combine it with reverse of your url Django docs ref, check bellow and change yourapp_path with your app path and name_space with url name like "blog".
main urls.py with "name_space"
like namepsace="blog"
url(r'^', include('yourapp_path.urls', namespace='name_space))
# ^^^^^^^^^^^^ ^^^^^^^^^^
app urls.py with name="name"
like name="comment"
url(r'^(?P<topic_id>[0-9]+)/comment/$', views.comment, name="name")
# ^^^^^^
reverse with name_space:name
will return the complete path of the url taking name_space:name lets say blog:comment
reverse('name_space:name')
reverse with kwargs or args
reverse('name_space:name', kwargs={'kw1': 'val1'})
reverse('name_space:name', args=['val1'])
HttpResponseRedirect()
302 redirect to a given url in that case we will pass the reverse url.
like: HttpResponseRedirect(reverse('blog:comment', kwargs={'topic_id': topic.id}))
HttpResponseRedirect(reverse('name_space:name', kwargs={'kw1': 'val1'}))
views.py
#import HttpResoneRedircet and reverse
from django.shortcuts import HttpResponseRedirect, reverse
def comment(request, the_topic, user_id):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CommentForm(request.POST)
# check whether it's valid:
if form.is_valid():
# your is_valid()
return HttpResponseRedirect(reverse('name_space:name', kwargs={'the_topic': the_topic.id}))
template
<form action="{{ action }}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">submit</button>
</form>

Django form.py not updating

I have been going through the Django forms 'tutorial'. Once I had read through the tutorial, I tried modifying it to suit my needs and customize it to learn it Django forms well. I discovered whenever I modified the form, the website would not update. I assume its an error with my code, but I have not been able to find it.
# views.py
def contact(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ContactForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/message_recived/')
# forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(label='Name', max_length=100)
email = forms.EmailField(label='Email', max_length=100)
message = forms.CharField(label='Message', max_length=500)
# models.py
from django.db import models
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
message = models.CharField(max_length=500)
and here is the contact.html template:
#contact.html
{% extends "BlogHome/headerAndFooter.html" %}
{% block content %}
<script>
document.title = "Pike Dzurny - Contact"
</script>
<form action="/message_recived/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
Did I do something wrong? I have tried clearing my browsers cache, using a new browser, and obviously refreshing it.
Looks like your forget to render response inside your view.
Also you need to include form into context to render template right.
Try to change view as follow:
def contact(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ContactForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/message_recived/')
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})

My form is not displaying fields and I cant figure out why

I am creating a contact form in django to send an email but the form is not displaying on the webpage. I think the issue may be because the form object may have never been passed to the context correctly, but I have no idea where it is going wrong. The code below is what I have so far.
from .forms import *
My Views
def email(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
email = form.cleaned_data['email']
first_name = form.cleaned_data['first_name']
message = form.cleaned_data['message']
try:
send_mail(first_name + ": " + subject, message, email,
['flavioandersites#gmail.com'])
except BadHeaderError:
return HttpResponse("Invalid Header.")
return redirect('thankyou')
return render(request, 'Index-App/contact.html', {'form': form})
My Form Class
class ContactForm(forms.Form):
subject = forms.CharField(required=True)
from_email = forms.EmailField(required=True)
first_name = forms.CharField(max_length=200, required=True)
message = forms.CharField(widget=forms.Textarea)
Urls
url(r'^contact/$', views.email, name='contact'),
My Template
{% block contact %}
<form method="POST" action="{% url 'Index-App:contact' %}">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn-success" value="Send"/>
</form>
{% endblock %}
Because you are not instantiating your form when method is GET. Also, you need to change self param to request
Try the following:
def email(request): # pass request for your view param, not self
form = ContactForm() # You should instantiate your form for GET method
if request.method == 'POST':
form = ContactForm(request.POST)
# ...
return render(request, 'Index-App/contact.html', {'form': form})

Categories

Resources