Button in django template doesn't put data in database - django

I have a app named "mysite". I want it to execute a python script,when button is clicked, that will put dummy data in database(add row) for now(originally i will be pulling data from a API) but nothing happens when button is clicked.
urls.py
path('', views.index),
views.py
from .fetch_data import get_data
def index(request):
if (request.method == 'POST' and 'script' in request.POST):
get_data()
return render(request, 'mysite/index.html')
index.html in "mysite/templates/mysite" folder
<form method="POST" name='script'>
{% csrf_token %}
<button type="submit" >Fetch data from source</button>
</form>
fetch_data.py
from .models import Hosts
import time, sys
def get_data():
print('here in function')
p = Hosts(hostname="first data")
p.save()
But when i click button, nothing happens. View should remain the same even after successful button click.
Note: fetch_data.py is on same folder as views.py and urls.py.

The name attribute in the form does not send anything to server as post data.
You should change the button like this:
<button type="submit" name="script">Fetch data from source</button>

try this may be this will help you
from .fetch_data import get_data
def index(request):
if (request.method == 'POST'):
script = get_data.objects.all()
script.save()
return render(request, 'mysite/index.html')

Related

Django update view only seems to work with regex urls

I am getting my hands dirty with Django and have a simple use case in which i have to create a function based view for updating a Model. Below is my function based view function:
def update_post(request, id=None):
obj = get_object_or_404(PostModel, id=id)
form = PostModelForm(request.POST or None, instance=obj)
if form.is_valid():
obj = form.save(commit=False)
print(f"The object that i am going to save is {form.cleaned_data}")
obj.save()
messages.success(request, f"Updated object with id {id}")
return HttpResponseRedirect(f"/blog/read/{id}")
context = {
"form": form
}
return render(request, "blog/update-post.html", context)
Below is my update-post.html:
<html>
<form method="POST" action="."> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="Change">
</form>
</html>
And this is my urls.py file :
from django.urls import path, include
from django.conf.urls import url
from .views import list_posts, read_post, create_post, update_post
app_name = "blog"
urlpatterns = [
path('posts/', list_posts, name="list"),
path('read/<int:id>', read_post, name="read"),
path("create/", create_post, name="create"),
#url(r'^(?P<id>\d+)/edit/$', update_post, name="update")
path("update/<int:id>", update_post, name="update"),
]
The update view only seems to work when i use the above regex url pattern for editing the post .
Otherwise i get the below error message:
Can someone please tell me where i am going wrong with this.

Django: form works in index but not in a particular page

I'm having multiple forms around my website.
However, a have a particular form that is working in the home page (index.html), but when coping this particular form in a section of my site it doesn't work anymore (on this section, if I return to home everything works as expected).
What am I missing?
Views.py:
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from .models import Treasure, TamaniosCantidades
from .forms import TreasureForm, TamaniosCantidadesForm, LoginForm
from django.contrib.auth import authenticate, login, logout
# Create your views here.
def index(request):
treasures = Treasure.objects.all()
form = TreasureForm()
tamanioscantidades_form = TamaniosCantidadesForm()
return render(request, 'main_app/index.html', {'treasures': treasures,
'form': form,
'tamanioscantidades_form': tamanioscantidades_form})
def productos(request):
treasures = Treasure.objects.all()
form = TreasureForm()
return render(request, 'main_app/productos.html', {'treasures': treasures,
'form': form})
def die_cut(request):
tamanioscantidades_form = TamaniosCantidadesForm()
return render(request, 'main_app/die-cut-stickers.html', {'tamanioscantidades_form': tamanioscantidades_form})
def post_tamanioscantidades(request):
form = TamaniosCantidadesForm(request.POST)
if form.is_valid():
tamanioscantidades = TamaniosCantidades(tamanios=form.cleaned_data['tamanios'],
cantidades=form.cleaned_data['cantidades'])
# tamanioscantidades = tamanioscantidades_form.save(commit = False)
# tamanioscantidades.usuario = request.user
tamanioscantidades.save()
return HttpResponseRedirect('/')
def post_treasure(request):
form = TreasureForm(request.POST)
if form.is_valid():
treasure = Treasure(name=form.cleaned_data['name'],
value=form.cleaned_data['value'])
treasure.save()
return HttpResponseRedirect('/')
urls.py:
app_name = 'main_app'
urlpatterns = [
path('', views.index),
path('productos/', views.productos),
path('productos/die-cut-stickers', views.die_cut, name='die-cut-stickers'),
path('post_url/', views.post_treasure, name='post_treasure'),
path('post_url_tamanioscantidades/', views.post_tamanioscantidades, name='post_tamanioscantidades'),
]
*html**:
<div class="col-md-6 border border-primary rounded border-3">
<div class="m-5">
<div class="row">
<form action="post_url_tamanioscantidades/" method="post">
{% csrf_token %}
{{ tamanioscantidades_form.as_p }}
<input type="submit" value="Submit"/>
</form>
</div>
</div>
As I said, this form works in home, but when coping the same code in a section of my site the submit button does not save the form in database.
It returns:
Page not found (404)
Request Method: POST
Request URL: http://127.0.0.1:8000/productos/post_url_tamanioscantidades/
Using the URLconf defined in gallito.urls, Django tried these URL patterns, in this order:
admin/
productos/
productos/die-cut-stickers [name='die-cut-stickers']
post_url/ [name='post_treasure']
post_url_tamanioscantidades/ [name='post_tamanioscantidades']
accounts/
The current path, productos/post_url_tamanioscantidades/, didn't match any of these.
The problem is the form is being submitted to http://127.0.0.1:8000/productos/post_url_tamanioscantidades/ which does not exist instead you want it to submit at http://127.0.0.1:8000/post_url_tamanioscantidades/
So in your form html start the form action with /
<form action="/post_url_tamanioscantidades/" method="post">

Form Field not displaying in Template

I'm new to Django and am having a bit of trouble with forms. I'm trying to display a single text input so that users can enter their phone number and it will be sent to my email. I'm actually going to have it stored in a postgre database but want to get the basics down first. The submit button is being displayed but the text input field isn't. I tried putting the forms.py inside of the views.py to see if the PhoneForm() function and file wasn't importing but that didn't do anything.
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.core.mail import send_mail
from .forms import PhoneForm
# Create your views here.
def index(request):
# Render the index.html template with a context dictionary
return render(request, "index.html")
def get_number(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
#create a form instance
form = PhoneForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['phone_form'],
['siteadmin#example.com'],
)
return HttpResponseRedirect('/thanks/')
else:
form = PhoneForm()
return render(request, 'index.html', {'form': form})
index.html
<form action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
forms.py
from django import forms
class PhoneForm(forms.Form):
phone_form = forms.CharField(widget=forms.TextInput())
EDIT: Adding urls.py (the one in the app)
from django.conf.urls import include, url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.get_number, name='get_number'),
]
Both urls in urls.py have the same expression r'^$' and django looks for them in order, therefore the first one (index) will always be selected. This links to the index view not the get_number view. This means the form is not passed to the template and the form does not show up.
To solve this move url(r'^$', get_number), to the top of 'urlpatterns'.
Change from {{form}} to {{form.phone_form}} in index.html

Django rendering issue

I am facing a problem while building a Django web app. I want that if a user logs into his account, his session should be stored and when he agains visits the login page ,he should be redirected to his home page.
Here is my code.
Views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
def index(request):
return HttpResponse("Index Page")
#login_required
def home(request):
ctx = {}
return render_to_response('auth/home.html',ctx, context_instance = RequestContext(request))
def login_page(request):
if request.user.is_authenticated():
return redirect('cc_home')
else:
return render_to_response(request,'auth/cc.html')
Urls.py
from django.conf.urls.defaults import *
from django.contrib.auth.views import login, logout
urlpatterns = patterns('',
url(r'cc/', 'apps.auth.views.login_page', name = 'cc_login'),
url(r'logout/', logout, name = 'cc_logout'),
url(r'home/','apps.auth.views.home', name = 'cc_home'),
)
And here is my template cc.html
<form action ="." method = POST>
{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value = "login">
</form>
</body>
home.html
{{ user }} 's profile
Logout
When I browse to CC url it should first asks the user's credentials. After successful login, it should redirect to the user's home url, which is running fine. But, when the user again browse to CC url (), he should be redirected it to his home page.
While Debugging, I found that it is not able to render the form when the user is not authenticated. It does not shows the Django's inbuilt form provided in the CC.html, it just shows the Login button.
How do I render the form. Kindly suggest.
Thanks
But you haven't passed any form to the template to render! You need to instantiate the login form and pass it to the template context, otherwise {{ form }} doesn't refer to anything.
You should be able to use the default form if you replace;
url(r'cc/', 'apps.auth.views.login_page', name = 'cc_login'),
with;
url(r'cc/', login, {template_name: 'cc.html'}),
May be the error is in the login_page method. try to fix it like this
def login_page(request):
if request.user.is_authenticated():
return redirect('cc_home')
else:
return render_to_response('auth/cc.html',{} context_instance = RequestContext(request))
i believe that the request in your render_to_response cause the problem

Django: save() method for ModelForm is not updating the database

I'm having a problem with saving and updating a value to my database.
View:
def code_prof_edit(request, ampCode):
user_code = get_object_or_404(CodeUser, pk=ampCode)
if request.method =='POST':
form = CodeUserForm(request.POST, instance=user_code)
if form.is_valid():
form.save()
return HttpResponseRedirect('/codes/' + user_code.ampCode)
else:
form = CodeUserForm(instance=user_code)
return render_to_response('edit_code_user.html', {'user_code':user_code, 'form':form})
Relevant template form tag:
<form action="." method="POST"> {% csrf_token %}
{{form.as_p}}
<input type="submit" value="Save" />
</form>
Using the post method, the form correctly renders in the browser with all of the original values pre-populated, but if I change the values and click submit, none of the changes are made. Everything seems to work correctly in that the user is redirected to the correct page which means the save must have been called, but the info typed isn't being saved. Any and all help would be appreciated.
Edit entire view function:
from django.shortcuts import render_to_response, get_object_or_404
from django.http import *
from django.template import RequestContext
from codeuser.models import CodeUser
from codeuser.forms import CodeUserForm
import pdb
def code_prof_edit(request, ampCode):
user_code = get_object_or_404(CodeUser, pk=ampCode)
if request.method =='POST':
pdb.set_trace()
form = CodeUserForm(request.POST, instance=user_code)
if form.is_valid():
form.save()
return HttpResponseRedirect('/codes/' + user_code.ampCode)
else:
return render_to_response('home.html')
else:
form = CodeUserForm(instance=user_code)
return render_to_response('edit_code_user.html', {'user_code':user_code, 'form':form})
Edit: Figured it out. In the html form tag, the action attribute was incorrect. "." wasn't working, I needed "./edit" to get the correct result. Also, excluding that attribute all together worked perfectly too.