Getting this error in my python code when attempting to delete a created topic.
Here are the url, views, and template snippets.
path('delete_topic/<int:topic_id>/', views.delete_topic, name='delete_topic')
def delete_topic(request, topic_id):
topic = Topic.objects.get(id=topic_id)
if request.method == 'POST':
topic.delete()`enter code here`
return redirect('online_diaries:topics', topic_id=topic.id)
context = {'topic': topic}
return render(request, 'online_diaries/delete_topic.html', context)
{% extends "online_diaries/base.html" %}
{% block content %}
<p>Are you sure to delete the topic <b><u>{{ topic }}?</b></u></p>
<form method="POST" action = "{% url 'online_diaries:delete_topic' topic.id %}">
{% csrf_token %}
cancel
<input type = "submit" name = "Confirm" class="btn btn-secondary btn-sm">
</form>
{% endblock content %}
Related
I have this add page which uses a django form to get information which i am trying to store within "tasks" list and display in the todo html page.
i believe all my syntax is correct but it is not displaying the list of tasks when I submit the form.
on cmd it detects a GET request every time i submit the form, shouldnt it be saying post?
views:
from django.shortcuts import render
from django import forms
tasks = []
class newTaskForm(forms.Form):
task = forms.CharField(label="new task")
# Create your views here.
def index(request):
return render(request, "tasks/todo.html", {
"tasks": tasks
})
def add(request):
if request.method == "POST":
form = newTaskForm(request.POST)
if form.is_valid():
task = form.cleaned_data["task"]
tasks.append(task)
else:
return render(request, "tasks/add.html", {
"form": form
})
return render(request, "tasks/add.html", {
"form": newTaskForm
})
add:
{% extends "tasks/layout.html" %}
{% block body %}
<form action="{% url 'tasks:add' %}">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
Veiw list
{% endblock %}
todo:
{% extends "tasks/layout.html" %}
{% block body %}
<h1> To Do List</h1>
<ul>
{% for task in tasks %}
<li> {{ task }}</li>
{% endfor %}
</ul>
Add items
{% endblock %}
as #Iain Shelvington suggested, you need to put method="post" as
{% block body %}
<form method="post" action="{% url 'tasks:add' %}">
{% csrf_token %}
{{ form }}
<input type="submit">
</form>
Veiw list
{% endblock %}
I am trying to create form using FilteredSelectMultiple widget. I managed to get it showing on my page, but faced difficulties receiving user input from it. For now, after I click submit button page just refresh and shows same form again instead of going to designated page. What I am doing wrong?
My code so far:
forms.py
class DrgSkaiciuokle(forms.Form):
drg_pasirinkimas = forms.ModelMultipleChoiceField(queryset=DRGkodas.objects.all(),
label="Pasirinkite atvejį sudarančius DRG",
widget=FilteredSelectMultiple("DRG kodai", is_stacked=False),
required=True)
class Media:
css = {
'all': ('/static/admin/css/widgets.css',),
}
js = ('/admin/jsi18n',)
#I have no idea if this part is right:
def clean_drg_pasirinkimas(self):
drg_pasirinkimas = self.cleaned_data['drg_pasirinkimas']
return drg_pasirinkimas
views.py
def DRG_skaiciuokle(request):
if request.method == 'POST':
form = DrgSkaiciuokle(request.POST)
pasirinkti_DRG = form.cleaned_data['drg_pasirinkimas']
context = {
'pasirinktiDRG': pasirinktiDRG,
}
#This page should be opened after submitting form instead of refresh
return render(request, 'DRGskaiciuokle_valid.html', context)
else:
form = DrgSkaiciuokle()
context = {
'form': form,
}
return render(request, 'DRGskaiciuokle.html', context)
my html file:
{% extends "base_generic.html" %}
{% block content %}
<div id='frame'>
<div id='sk_head'>
<h3>Kaštų konvertavimo skaičiuoklė</h3>
<h4>Pagal DRG metodiką</h4>
</div>
<form>
<div id='sk_body'>
<fieldset>
<legend>Įveskite duomenis</legend>
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.media }}
{{ form.as_table }}
<script type="text/javascript" src="{% url 'jsi18n' %}"></script>
</table>
<input type="submit" value="Skaičiuoti">
</form>
</fieldset>
</div>
</form>
</div>
{% endblock %}
You need to update your code as follow
Update html file.
There is a form inside a form. You need to remove the inner form and update the outer form as suggested below.
{% extends "base_generic.html" %}
{% block content %}
<div id='frame'>
<div id='sk_head'>
<h3>Kaštų konvertavimo skaičiuoklė</h3>
<h4>Pagal DRG metodiką</h4>
</div>
<form action="" method="post"> # <-----------------add action and method here
<div id='sk_body'>
<fieldset>
<legend>Įveskite duomenis</legend>
<form>
{% csrf_token %}
<table>
{{ form.media }}
{{ form.as_table }}
<script type="text/javascript" src="{% url 'jsi18n' %}"></script>
</table>
<input type="submit" value="Skaičiuoti">
</form>
</fieldset>
</div>
</form>
</div>
{% endblock %}
Inside views.py
Add form.is_valid() the method call to check whether the form is valid or not.
def DRG_skaiciuokle(request):
if request.method == 'POST':
form = DrgSkaiciuokle(request.POST)
if form.is_valid():
pasirinkti_DRG = form.cleaned_data['drg_pasirinkimas']
context = {
'pasirinktiDRG': pasirinktiDRG,
}
#This page should be opened after submitting form instead of refresh
return redirect('redirect_to_view') # <------------ redirect ot url on success
context = {
'form': form,
}
return render(request, 'DRGskaiciuokle.html', context)
else:
form = DrgSkaiciuokle()
context = {
'form': form,
}
return render(request, 'DRGskaiciuokle.html', context)
I think this would help. For clarification DM.
Receiving the above error when trying to create a page to update my model using a serializer. Unable to use pk in edit_team view. Any ideas where I am going wrong? Delete button is working fine with the pk not sure why the update is not.
urls.py
path('teams/', views.TeamInfo.as_view(), name='teams'),
path('delete_team/<int:pk>/', views.delete_team, name='delete_team'),
path('edit_team/<int:pk>/', views.edit_team, name='edit_team'),
teams.html
<div class="team">
<h3>Team Details</h3>
<p>
{% csrf_token %}
{% for info in teams %}
<li>{{ info.club_id }}</li>
<li>{{ info.team_name }}</li>
<li>{{ info.manager_name }}</li>
<form action="{% url 'clubs:delete_team' info.pk %}">
<input type="submit" value="Delete">
</form>
<form action="{% url 'clubs:edit_team' info.pk %}">
<input type="submit" value="Edit">
edit_team.html
{% extends 'club_main_page.html' %}
{% load rest_framework %}
{% load staticfiles %}
{% block body_block %}
<div class="editteam">
<h3>Edit Team</h3>
<form action="{% url 'clubs:edit_team' pk=instance.pk %}" method="POST">
{% csrf_token %}
{% render_form serializer %}
<input type="submit" name="" value="Update">
</form>
</div>
{% endblock %}
views.py
def delete_team(request, pk):
team = Team.objects.filter(pk=pk)
team.delete()
return redirect('clubs:teams')
def edit_team(request, pk):
instance = Team.objects.filter(pk=pk)
if request.method == 'POST':
serializer = TeamSerializer(request.POST, instance=instance)
if serializer.is_valid():
serializer.save()
return redirect('/')
else:
return redirect('/')
else:
serializer = TeamSerializer(instance=instance)
return render(request, 'edit_team.html', {'serializer': serializer})
Trackback: \clubkit\clubs\views.py in edit_pitch
return render(request, 'edit_pitch.html', {'serializer': serializer})
In your template you write:
<form action="{% url 'clubs:edit_team' pk=instance.pk %}" method="POST">
but there is no instance variable, you pass to the rendering process, you thus should add this one as well, so:
def edit_team(request, pk):
instance = Team.objects.filter(pk=pk)
if request.method == 'POST':
serializer = TeamSerializer(request.POST, instance=instance)
if serializer.is_valid():
serializer.save()
return redirect('/')
else:
return redirect('/')
else:
serializer = TeamSerializer(instance=instance)
return render(
request,
'edit_team.html',
{'serializer': serializer, 'instance': instance})
I'm not sure however, if redirecting to / is a good idea, certainly not if the serializer is not valid. In that case, one typically wants to render the page again, but with the errors. Therefore it is probably also a better idea to make use of forms [Django-doc].
You didn't pass the PK to the template, so it can't be used to generate the URL there. Change the last line of your view:
return render(request, 'edit_team.html', {''pk': pk, serializer': serializer})
Would have liken to figure this out using the serializer. But just went with a form here solution just in case any one needs it:
def edit_team(request, pk):
instance = Team.objects.filter(pk=pk).first()
if request.method == 'POST':
form = TeamForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('clubs:teams')
else:
return redirect('clubs:teams')
else:
form = TeamForm(instance=instance)
return render(request, 'edit_team.html', {'form': form,
'instance': instance})
Then in the template:
{% extends 'club_main_page.html' %}
{% block head %}
<title>Edit Pitch</title>
{% endblock %}
{% block body_block %}
<div class="container">
<form method="post">
{% csrf_token %}
{{ form.as_p}}
<button type="submit">Submit</button>
</form>
</div>
{% endblock %}
My form inputs are not showing. It's just a button. i think homepage.html doesn't getting this form
Forms.py
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
Views.py
def get_name(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 = NameForm(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('/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'mainApp/homepage.html', {'form': form})
homepage.html
{% extends "mainApp/wrapper.html" %}
{% block title %}Главная{% endblock %}
{% block content %}
<h1>Main page</h1>
{% include "mainApp/includes/somehtml.html" %}
<br>
<form action="/account/username/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
<br>
{% endblock %}
It shoes only "Submit" button. How can I fix it?
Please change
{{form}}
to {{form.as_p}}
Views.py
from app_name.forms import * # Change app_name with your app name
def get_name(request):
temp_context = {} # Check here
if request.method == 'POST':
acc_form = NameForm(request.POST) # Check here
temp_context["acc_form"] = acc_form # Check here
if acc_form.is_valid(): # Check here
return HttpResponseRedirect('/')
else:
temp_context[“acc_form”] = NameForm() # Check here
return render(request, 'mainApp/homepage.html', temp_context) # Check here
homepage.html
{% extends "mainApp/wrapper.html" %}
{% block title %}Главная{% endblock %}
{% block content %}
<h1>Main page</h1>
{% include "mainApp/includes/somehtml.html" %}
<br>
<form action="/account/username/" method="post">
{% csrf_token %}
{{ acc_form }} # Check here;
# you can also try {{ acc_form.as_table }} or {{ acc_form.as_p }} if there any issue
<input type="submit" value="Submit" />
</form>
<br>
{% endblock %}
My apologies if the question is stupid, I am a newbie to this. I am creating a django web application. I have created a form inside it. When I submit the form, it says 'url' not found even though the same URL loads fine for the first time when opening the form. This is whats confusing me. Here is my code:
#forms.py
class Recipe_ruleForm(forms.ModelForm):
class Meta:
model = Recipe_rule
fields = ('content',)
#urls.py
url(r"^create_recipe_rule/(?P<recipe_pk>[0-9]+)/$",views.create_recipe_rule, name="create_recipe_rule"),
#views.py
def create_recipe_rule(request, recipe_pk):
form = Knowledgebase_ruleForm
selected_recipe = Recipe.objects.get(pk = recipe_pk)
if request.method == 'POST':
form = Recipe_ruleForm(request.POST)
if form.is_valid():
#current_user = request.user
data = form.cleaned_data
recipe_rule_data=Recipe_rule.objects.create(recipe=selected_recipe, content=data['content'])
recipe_rule_data.save()
recipe_rule = Recipe_rule.objects.get(pk = recipe_rule_data.pk)
recipe=selected_recipe
recipe = Recipe.objects.get(pk = recipe.pk)
return redirect('recipe_detail', pk=recipe.pk)
else:
messages.error(request, "Error")
return render(request, 'create_recipe_rule.html' , {'form': form})
Here is the error when I submit the form:
Page not found (404) Request Method: POST Request
URL: http://[ip_adress]:[port]/create_recipe_rule/
UPDATE:
Here is my template:
{% extends "account/base.html" %}
{% load i18n %}
{% load bootstrap %}
{% block body_class %}applications{% endblock %}
{% block head_title %}{% trans "Create recipe" %}{% endblock %}
{% block body %}
<form action="/create_recipe_rule/" method="post">
{% csrf_token %}
<div class="form-group">
<label for="{{ form.content.label }}">{{ form.content.label }}:</label>
<textarea type="{{ form.content.type }}" name="{{ form.content.name }}" max_length="500" class="form-control" id="{{ form.content.id }}"></textarea>
</div>
<input class="btn btn-default" type="submit" value="submit">
</form>
{% endblock %}
You have action="/create_recipe_rule/", which is missing the recipe id.
One option is to simply remove the action from the form, then your browser will submit the request to the current url.
<form method="post">
If you do want to include the form action, then first you need to update your view so that it includes the recipe id in the template context.
return render(request, 'create_recipe_rule.html' , {'form': form, recipe_id: recipe_id })
Then you can update the form action to include the recipe id.
action="/create_recipe_rule/{{ recipe_id }}"
It's good practice to use the {% url %} tag, so that you are not hardcoding urls in the template:
action="{% url 'create_recipe_rule' recipe_id %}"