I am trying to pass the id of a todolist item to my html code so that everything works when I am editing the todolist item and I click submit.
In views.py:
def edit(request, id):
todo = Todo.objects.get(id=id)
context = {
'todo': todo
}
if(request.method == 'POST'):
title = request.POST['title']
text = request.POST['text']
todo.title = title
todo.text = text
todo.save()
return redirect('/todos')
else:
return render(request, 'edit.html', context)
In urls.py:
url(r'^details/(?P<id>\w{0,50})/edit/$', views.edit, name='edit')
In HTML:
<h2>Edit Todo- {{ todo.title }}</h2>
<form action="{% url 'edit' request.todo.id %}" method="post">
{% csrf_token %}
<label for="title">Title</label> <br/>
<input type="text" name="title" id="title"/>
<br>
<label for="text">Text</label> <br/>
<textarea type="text" name="text" id="text"></textarea>
<br><br>
<input type="submit" value="Submit"/>
</form>
I think the problem is in my url in the html code. I can't figure out how to pass my todolist item's id parameter.
The error I keep getting is
invalid literal for int() with base 10: ''
Please help
The problem is there:, do not use "request", the object sent through context is "todo":
<form action="{% url 'edit' todo.id %}" method="post">{% csrf_token %}
Or you may leave it blank. Blank means the current displayed views
<form action="" method="post">{% csrf_token %}
Related
I'm trying to build a django app and the app works, great so far.
Right now i'm in the middle of making sure the user needs a login so they can log in.
if the user is logged in than the user can use an machine-learning model to solve a problem.
The error message I'm getting is 'float' object has no attribute 'user' and this started after I used the #login_required function in django.
NOTE: The user is login in via the localhost:8000/admin/ panel Django provides.
(later I will change that) after I fix this bug
views.py
def home(request):
return render(request, 'home.html')
#login_required
def dashboard(request):
return render(request, 'index.html')
#login_required
def getPredictions(temp_normal, hour,hour_x,hour_y):
import pickle
model = pickle.load(open("test_model.sav", "rb"))
prediction = model.predict([[temp_normal, hour,hour_x,hour_y]])
return prediction
#login_required
def result(request):
temp_normal = float(request.GET['temp_normal'])
hour = float(request.GET['hour'])
hour_x = float(request.GET['hour_x'])
hour_y = float(request.GET['hour_y'])
result = getPredictions(temp_normal, hour,hour_x,hour_y)
return render(request, 'result.html', {'result': result})
html code
index.html
{% extends "base.html" %}
{% block content %}
<div class="content">
<div class="row">
<div class="col-lg-4">
<div class="card card-tasks">
<h1> </h1>
<form action="{% url 'result' %}">
{% csrf_token %}
<p>temp_normal:</p>
<input class="form-control" type="text" name="temp_normal">
<br>
<p>Weging:</p>
<input class="form-control" type="text" name="Weging">
<br>
<p>str:</p>
<input class="form-control" type="text" name="straling">
<br>
<p>hour:</p>
<input class="form-control" type="text" name="hour">
<br>
<p>hour_x:</p>
<input class="form-control" type="text" name="hour_x">
<br>
<p>hour_y:</p>
<input class="form-control" type="text" name="hour_y">
<br>
<input class="form-control" type="submit" value='Bereken'>
</form>
</div>
</div>
</div>
</div>
{% endblock content %}
results.html
{% extends "base.html" %}
{% block content %}
<h1>Prediction</h1>
{{ result }}
<p>resultaat</p>
{% endblock content %}
the decorator login_required is just for views and expects a request object as first param, thats why the error, getPredictions is not a view is just a function. remove the decorator login_required to getPredictions and will work.
I am making todo application and i am having problem doing the update operation
views.py
def update(request, task_id):
task = Task.objects.get(pk=task_id)
if request.method == 'POST':
form = TaskForm(request.POST or None, instance=task)
if form.is_valid():
form.save()
return redirect('/')
return render(request, 'update.html', {'task': task})
forms.py
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = '__all__'
urls.py
path('update/<int:task_id>', views.update, name='update'),
update.html
{% extends 'base.html' %}
{% block content %}
{% if task %}
<form class="form-inline my-2 my-lg-0" method="POST" >
{% csrf_token %}
<input type="search" class="form-control mr-sm-2" name="task" value="{{task.text}}">
<input type="hidden" name="completed" value="{{task.completed}}">
<button type="submit" class="btn btn-outline-secondary my-2 ">Edit Task</button>
</form>
{% endif %}
{% endblock %}
I am able to get the Value of the selected item in textbox but when i edit it and press Edit Task Nothing happens .
# The url name is update, so your action submit should go to 'update'
<form action="{% url 'update' task_id=task.pk %}" method="POST" class="form-inline my-2 my-lg-0">
…
</form>
I want to build a website in which users can send words to each other using Django. When a user deletes a word, that word will be deleted for only that user. I have a working website; the only problem is when a word is deleted, it is deleted for all users. How can I fix this problem, is it a problem which is related to ManyToMany relationships?
Django word model:
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User
class Word(models.Model):
definition = models.CharField(max_length=350)
turkish = models.CharField(max_length=50)
english = models.CharField(max_length=50)
users = models.ManyToManyField(User)
creator = models.CharField(max_length=50)
def __str__(self):
return self.english
def summary(self):
return self.definition[:50] + "..."
The share view function:
#login_required
def send(request):
users_list = User.objects.all().exclude(username=request.user.username)
user = request.user
small = user.username.title()
send_to_str = request.POST['user']
sent_word_str = request.POST['word']
send_to = User.objects.get(username=send_to_str)
sent_word = Word.objects.get(id=sent_word_str)
if not users_list:
sendmessage = 'You have no friends'
else:
sendmessage = ''
sent_word.users.add(send_to)
words = Word.objects.filter(users=user).order_by('-english')
return render(request, 'intro.html', {'sendmessage': sendmessage, 'words': words, 'small' : small})
The delete view function:
#login_required
def delete(request):
if request.method == 'POST':
current_id = request.POST['word_id']
current_word = Word.objects.get(id=current_id)
current_word.delete()
messages.add_message(request, messages.INFO, 'Succesfully deleted.')
return redirect('translater:home')
else:
return render(request, 'intro.html', {'message': 'there is a problem'})
Redirected to this html:
{% if words %}
<h3 style="color:gray;font-weight:bold">My Word List</h3>
<br>
{% endif %}
{% for word in words %}
<h4 style="color:red">{{ word.english }} / {{ word.turkish }} </h4>
<h4 style="color:green">{{ word.summary }} / {{ word.creator }}</h4>
<br>
<button type="button" onClick="document.getElementById('deleterForm').submit()" class="btn btn-warning">Delete!</button>
<button type="button" onClick="document.getElementById('sharerForm').submit()" class="btn btn-primary">Share!!</button>
<form id="deleterForm" action="{% url 'translater:delete' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="word_id" value="{{ word.id }}">
</form>
<br>
<form id="sharerForm" action="{% url 'translater:share' %}" method="POST">
{% csrf_token %}
<input type="hidden" name="word_id" value="{{ word.id }}">
</form>
<form id="senderForm{{ word.id }}" action="{% url 'translater:send' %}" method="POST">
{% csrf_token %}
{% for user in users_list %}
<input type="submit" name="user" value="{{ user }}">
<input type="hidden" name="word" value="{{ word.id }}">
{% endfor %}
{{ sendmessage }}
</form>
<br>
{% endfor %}
I've been working to make an edit form where shows data saved in db and user can edit it like jsp model and view. When user click button it shows add form but all the relevant information in db is already filled up in the form, so user can modifying old data and once they click submit button it redirect to main.
I succeeded to display a form when user click edit button but failed to get data.
this is views.py
#login_required
def update_article(request, article_no):
article = get_object_or_404(Article, no=article_no)
if request.method == "POST":
form = ArticleForm(request.POST, instance=article)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('blog.views.detail', no=article.no)
else:
form = ArticleForm(instance=article)
return render(request, 'blog/update_article.html', {'form': form})
urls.py
url(r'^update_article/(?P<article_no>[0-9]+)/$', views.update_article, name='update_article'),
update_article.html
{% extends 'blog/base.html' %}
{% block body %}
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<button type="submit" class="button-primary">submit</button>
</form>
list
{% endblock %}
detail.html
This is part of the page send users to update_article.html
<form action="{% url 'blog:update_article' item.no %}" method="post" style="display: inline;">
{% csrf_token %}
<input type="hidden" name="no" value="{{ item.no }}" />
<button type="submit" class="button-primary">edit</button>
</form>
form_template.html
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2" for="title">{{ field.label_tag }</label>
<div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
In update_article views
pass article object with form
return render(request, 'blog/update_article.html', {'form': form, 'article': article})
and then form in html page
<form class="form-horizontal" role="form" action="create_article.html" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'blog/form_template.html' %}
<input class="u-full-width" type="text" name="title" value="{{article.title}}"/>
<textarea class="u-full-width" name="content" value="{{article.content}}"></textarea>
<button type="submit" class="button-primary">등록</button>
</form>
I think this would help your problem
also I guess your action link is not valid
I'm handling input file in my project and passing processed text to another html for user approvement
def vm_to_csv_upload(request):
if request.method == "POST":
some code here
br_work_string = re.sub('\\n', '<br>', work_string)
page_text = 'Here\'s what gonna be uploaded to crowdin:<br><br><br>' + br_work_string + '<br><br><br>Is that okay?'
return render(request, 'upload_crowdin_check.html', {'page_text': page_text, 'csv_text': work_string})
On this page i show passed data:
<body>
<div id="text_check">
{% autoescape off %}
{{ page_text }}
{% endautoescape %}
</div>
<form action="/crowdin_approve/" method="POST" value={{ csv_text }} id="csv">
{% csrf_token %}
<input type="submit" class="btn btn-xs btn-danger" value="Okay">
</form>
</body>
And trying to pass it to another view to process it again.
def crowdin_approve(request):
if request.method == "POST":
return HttpResponse(request.POST)
else:
return HttpResponse('nope')
But only thing i get is csrfmiddlewaretoken. What am i doing wrong? How should i pass {{ csv_text }} value to view? Thx.
You can pass the content of csv_text using an hidden input field:
<form action="/crowdin_approve/" method="POST" id="csv">
{% csrf_token %}
<input type="hidden" name="csv_text" value="{{ csv_text }}">
<input type="submit" class="btn btn-xs btn-danger" value="Okay">
</form>
Then you can access it in the view this way:
def crowdin_approve(request):
if request.method == "POST":
csv_text = request.POST.get('csv_text', None)