Django from Submit button doesn't do anything - python

I'm new to Django, and I'm trying to submit a form to process the data in a view function, but I can't find why when I press the Send button it doesn't do anything. i read many other questions but were syntax related problems, which I believe is not my case.
Here's my form. It is in the new.html template:
<from action="{% url 'notes:create' %}" method="post">
{% csrf_token %}
<input type='text' name='note_name' id='note_name' placeholder='Title...'>
<input type='date' name='note_date' id='note_date'>
<input type="submit" value="Send">
</form>
Here it is urls.py:
app_name = 'notes'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('new/', views.new_note, name='new'),
path('output/', views.create_note, name='create')
]
And here the views.py file. Currently the create_note view only redirects to the index. I'm going to process the entered data once the form works correctly.
class IndexView(generic.ListView):
template_name = 'notes/index.html'
context_object_name = 'all_notes'
def get_queryset(self):
return Note.objects.all()
def new_note(request):
return render(request, 'notes/new.html')
def create_note(request):
return HttpResponseRedirect(reverse('notes:index'))

Related

Django Form-Model issue;

I am having trouble working with models and forms in Django. A little clarification and help will be highly appreciated!
I am really confused because I do not see the form in my html url page. I see everything else but not the form. I assume, I'm missing something.
This is my forms.py
from django import forms
from .models import TwitterContainer
class TwitterUpdateForm(forms.ModelForm):
class Meta:
model = TwitterContainer
fields = ["Twitter_API_key", "Twitter_API_key_secret", "Twitter_API_token", "Twitter_API_token_secret"]
This is my models.py
from django.db import models
from django.contrib.auth.models import User
class TwitterContainer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Twitter_API_key = models.fields.CharField(max_length=100)
Twitter_API_key_secret = models.fields.CharField(max_length=100)
Twitter_API_token = models.fields.CharField(max_length=100)
Twitter_API_token_secret = models.fields.CharField(max_length=100)
def __str__(self):
return f'{self.user.username} Twitter Container'
This is my views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import TwitterUpdateForm
#login_required
def twitter(request):
tw = TwitterUpdateForm(request.POST, instance=request.user)
if tw.is_valid():
tw.save()
messages.success(request, f'NICE!')
return redirect ('home')
else:
tw = TwitterUpdateForm(request.POST, instance=request.user)
context = {'tw': tw}
return render(request, 'twitter_container/twitter_container.html', context=context)
And last but not least, this is my html file.
{% extends 'home/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
</div>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset="form-group">
<legend class="border-bottom mb-4">Profile Information</legend>
{{ u_form|crispy }}
{{ p_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
</div>
{% endblock content %}
Oh, and my urls.py as well.
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
path('register/', user_views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('profile/', user_views.profile, name='profile'),
path('twitter/', twitter_views.twitter, name='twitter'),
]
The issue, I'm facing is that I'm unable to display the form fields from the model to the html. I want to be able to import information into the fields and update it to the database.
Please, do not judge me hard, I am completely newbie.
Thanks in advance.
First of all, you need to add action attribute in your form tag to call the view function when form gets submitted.
It should be like this:
<form method="POST" action ="{% url 'twitter' %}" enctype="multipart/form-data">
Second thing that i found wrong in your html code is, why did you use u_form and p_form as a context variable? it should be 'tw' as per your view.
Try it out with above changes, it might help you out with your requirements.

Django giving "Reverse for 'view' not found" error when view is defined

While using django 4.0.4 I have encountered the error "Reverse for 'upload' not found. 'upload' is not a valid view function or pattern name". It was working earlier in the day, and I can't figure out the problem for the life of me. I'll include my views.py, urls.py, and the relevant section of my html file, all three of which are in the same folder of the project. If anyone has any advice I would greatly appreciate it.
Views.py
def welcome(request):
return render(request, 'welcome.html')
def contact(request):
return render(request, 'contact-us.html')
def how(request):
return render(request, 'How-to-use.html')
def upload(request):
if request.method == 'POST':
if 'scatter_plot' in request.POST:
form = UploadFileForm(request.POST.get, request.FILES)
file=request.FILES['document']
csv = CSV.objects.create(doc=file)
os.system('python ../scatter_plot.py')
if 'line_plot' in request.POST:
form = UploadFileForm(request.POST.get, request.FILES)
file=request.FILES['document']
csv = CSV.objects.create(doc=file)
os.system('python ../line_plot.py')
return render(request, 'uploaded.html')
else:
form = UploadFileForm
Urls.py
urlpatterns = [
path('', views.welcome),
path('admin/', admin.site.urls),
path('contact-us/', views.contact),
path('upload.html', views.upload),
path('upload/', views.upload),
path('welcome/', views.welcome),
path('How-to-use/', views.how),
path('contact-us.html', views.contact),
path('welcome.html', views.welcome),
path('How-to-use.html', views.how)
]
Welcome.html
<form method="POST" enctype="multipart/form-data" action="{% url 'upload' %}">
{% csrf_token %}
<input type='file' name='document' accept='.csv'>
<button type='submit' name='line_plot'>Graph as a line Graph</button>
<button type='submit' name='scatter_plot'>Graph as a Scatter Plot</button>
</form>
you need to put the name for the URL
path('upload/', views.upload, name='upload'),
Refer this
https://docs.djangoproject.com/en/4.0/topics/http/urls/#reversing-namespaced-urls
https://docs.djangoproject.com/en/4.0/topics/http/urls/

requestsession not working in Django to pass html form variable to another function

I am trying to use request.session to pass a html form variable into another function in Django, I am currenlty having trouble because the result from the session is resulting in None. Would appreciate help fixing it or another suggestion to pass the html form variable from to another function as a string.
Here is my views.py file
def home(request):
input_email = request.POST.get('emailvalue')
request.session["input_email"] = input_email
return render(request, 'file1.html')
def pre_que_ip(request):
actual_email = request.session["input_email"]
print(actual_email)
urls.py
path('admin/', admin.site.urls),
path('', views.home, name = 'login'),
path('home/', views.home, name = 'home'),
path('add_ipaddress/', views.pre_que_ip, name = 'pre_que_ip')
file1.html
<form action="/add_ipaddress/" method="post">
{% csrf_token %}
<input type="text" name="emailvalue" required><br><br>
<input type="submit" value="Submit"><br><br>
</form>

django HTTP 405 Method Not Allowed in html form

I am new to Django and I've been trying to develop a simple site that asks the user for their email address and height. It then saves it in the database and sends an email to the user and redirects them to a page saying that it was successful.
Now the problem is whenever I press 'Submit', I get a HTTP 405 method not allowed error.
# urls.py
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
#url(r'^success/$', views.SuccessView.as_view(), name='success'),
]
# forms.py
class HeightForm(forms.ModelForm):
class Meta:
model = Height
fields = ['email', 'height']
# views.py
class IndexView(generic.ListView):
form_class = HeightForm
template_name = 'heights/index.html'
def get_queryset(self):
return Height.objects.all()
class HeightFormView(View):
form_class = HeightForm
template_name = 'heights/success.html'
def get(self, request):
form = form_class(None)
def post(self, request):
print('a' * 1000)
form = form_class(request.POST)
if form.is_valid:
email = form.cleaned_data['email']
height = form.cleaned_data['height']
form.save()
return HttpResponseRedirect(template_name)
#render(request, template_name, {'form': form})
# index.html
{% extends 'heights/base.html' %}
{% block body %}
<h1>Collecting Heights</h1>
<h3>Please fill the entries to get population statistics on height</h3>
<form action="" method="post">
{% csrf_token %}
<input type="email" name="email" placeholder="Enter your email address" required="true"/><br />
<input type="number" min="50" max="300" name="height" placeholder="Enter your height in cm" required="true" /><br /><br />
<input type="submit" name="submit" />
</form>
Click to view all heights in database
{% endblock body %}
The code doesn't even get to the print('a' * 1000) line without generating an error. Chrome just goes to a This page isn't working page and displays HTTP ERROR 405.
I have Googled this error, but haven't found anthing helpful. Any help is appreciated
Thanks
You don't seem to have any URL defined for the HeightFormView. The form is rendered by the IndexView and posts back to itself; that view does not allow a POST method.
You would need to define a URL for HeightFormView and refer to it in the action via the {% url %} tag.
Add a route for your form to get submitted in urls.py and use the same in action. should work fine.
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^saveForm/$', views.HeightFormView.as_view(), name='form'),
]
And in your html form,
<form action="/saveForm" method="post">

Why are my Django form fields not rendering in the template?

I'm receiving no errors and everything seems fine but the fields to my form will not show up.
My form:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(required=False, max_length=100, help_text='100 characters max')
email = forms.EmailField(required=True)
comment = forms.CharField(required=True, widget=forms.Textarea)
My view:
from .forms import ContactForm
def contact(request):
form = ContactForm(request.POST or None)
if form.is_valid():
print(request.POST)
context = {'form': form}
return render(request, 'contact.html', context)
contact.html template:
<form method="POST" action=""> {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" class="btn btn-default" />
</form>
base.html template:
{% block content %}
{% endblock content %}
{% include "contact.html" %}
</div>
What am I missing? The template housing the form is not surrounded by any block tags because the template is being {% include[d] %} into my base.html.
Additional details: The form and view are in their own separate 'contact' app, and I haven't configured any urls for the contact app as I planned on simply including the template into base.html
Edit--adding urls config:
main urls.py for the project:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include("projects.urls", namespace='projects')),
]
urls.py for my 'project' app:
urlpatterns = [
url(r'^$', projects_home, name='home'),
url(r'^(?P<slug>[\w-]+)/$', project_detail, name='detail'),
]
As for the 'contact' app, I have not configured any urls--would this be wrong? I thought I'd be able to simply make the views/form(as displayed in original post) for the 'contact' app and bring the form into my templates.

Categories