I have been trying to create a to do list app and there has been no problems until when i was adding an edit button, when i press the edit button, it shows the edit page with the text that has to be edited but the submit button that is suposed to change the database is not working, I think I need to add something to the views.py file but I dont know what.
viws.py
def edit(request, id):
created_items = Create.objects.get(id=id)
return render(request, 'my_app/edit.html', {"created_items": created_items})
urls.py
urlpatterns = [
path('edit/<int:id>/', views.edit, name='edit'),
]
models.py
class Create(models.Model):
added_date = models.DateTimeField()
text = models.CharField(max_length=200)
edit.html
{% extends 'index.html' %}
{% block body %}
<div align="center">
<h1>Edit your post!</h1>
<div class="container form-group">
<h1>↓</h1>
<form method="POST">{% csrf_token %}
<textarea class="form-control" name="content" id="id" rows="3" style="text-align: center;">{{ created_items.text }}</textarea>
<button type="submit" class="btn btn-outline-success" style="margin-top: 5px;">Submit</button>
</form>
</div>
</div>
{% endblock %}
You will send POST request when you click submit and need to catch that request in some function like:
if request.method == 'POST':
edited_text = request.POST.get('text') ## 'text' might be changed. I don't know how you handle the request.
related_id = request.POST.get('id') ## You need to take updated id. (somehow?)
Create.objects.filter(id=related_id).update(text=edited_text) ## That will do the job.
Hope it helps,
Related
please am new to django, and am trying to save user radio button input of an html form to my database by category have created for different post using CBV, i really don't know how to go about please i need help , thanks in advance
here is my models.py
'
class Data(models.Model):
'name= models.CharField(max_length=50, default='')
data=models.CharField(max_length=50 ,blank=True,null=True)
`class Category(models.Model):
name =models.CharField(max_length=200,default='')
class CandidateForm(models.Model):
image= models.ImageField(upload_to='images/', width_field=None,default=0)
data=models.ForeignKey(Data,blank=True,null=True,on_delete=models.PROTECT)
category=models.ForeignKey(Category,blank=True,null=True,on_delete=models.PROTECT)
Nickname=models.CharField(max_length=100,default='')
Name=models.CharField(max_length=100,)
def __str__(self):
return self.Nickname
here is my views.py
def vote_data(request):
if request.method == 'POST':
post=models.Data()
post.data=models.Category.objects.filter(name='category')
post.name=request.POST['candidate']
post.save()
return redirect('Home')
and lastly, the category.html page
<form action="{%url 'data' %}" method="POST" name="">
{% csrf_token %}
{% for candidate in Post.candidate %}
<div class=".col-md-4-flex" data-aos="zoom-out">
<div class="position-relative">
<img src="{{candidate.image.url}}">
<p>{{candidate.Name}}</p>
<label for="candidates_{{candidate.Nickname}}" class="radio-inline">
<input type="radio" name="candidate" value="{{candidate.Nickname}}"
id="candidates_{{candidate.Nickname}}">{{candidate.Nickname|upper}}
</label>
</div>
{% endfor %}
</div>
<input type="submit" value="submit">
sorry for uneccessary information.
I have a Django form that receives a text (that I copy from Google Classroom: a bunch of student comments). I use these comments to make student's attendance. What I want to achieve is:
Accessing /insertion/ url via GET user receive the page form as a response, to choose the class (class01, class02, etc) and to past the text
When the user clicks on submit in this form (post method), it is redirect to the same /insertion/ url, but now the form is bound to the data submited, and the page shows a preview page (based on a boolean variable I'm passing through context), showing what students are present and what are absent based on the text informed. At that page, a new submit button will be shown below a text like "if everything's ok, hit the ok button".
After click this ok button, a pdf will be generated and the user will be redirected to /files/ url, to see the generated pdf and previous generated pdf.
views.py
def insertion(request):
context = {}
if request.method == 'GET':
form = AttendanceDataForm()
context.update({"form": form})
if request.method == 'POST':
form = AttendanceDataForm(request.POST)
context.update({"form": form})
if form.is_valid():
lesson = form.cleaned_data['lesson']
raw_text = form.cleaned_data['raw_text']
# Get course students
course_students = md.Student.objects.filter(course_id=lesson.course_id)
# Get present students based on raw text informed
present_students = [s for s in course_students if s.full_name in raw_text]
# Get absent students based on raw text informed
absent_students = [s for s in course_students if s.full_name not in raw_text]
context.update({
"present_students": present_students,
"absent_students": absent_students,
"render_preview": True
})
context.update({"active_freq": True})
return render(request, 'core/insertion.html', context)
def files(request):
context = {}
if request.method == 'POST':
# How can I access all expensive calculation I did in the previous view?
context.update({"active_gen": True})
return render(request, "core/files.html", context)
insertion.html
<div class="row">
<div class="col-12 col-md-6">
<h3>Informar Frequência</h3>
{% crispy form %}
</div>
<div class="col-12 col-md-6">
{% if render_preview %}
<div class="container">
<div class="row p-4 bg-white rounded mt-4">
<div class="col-12 col-sm-6">
<h5>Alunos presentes</h5>
<ul class="previewer-list">
{% for student in present_students %}
<li>{{ student.id }} - {{ student.full_name }}</li>
{% endfor %}
</ul>
</div>
<div class="col-12 col-sm-6">
<h5>Alunos ausentes</h5>
<ul class="previewer-list">
{% for student in absent_students %}
<li>{{ student.id }} - {{ student.full_name }}</li>
{% endfor %}
</ul>
</div>
</div>
<p class="mt-3">If everything's ok, hit the OK button</p>
<form method="post" action="{% url "core:files" %}">
{% csrf_token %}
<button type="submit" class="btn btn-primary">OK</button>
</form>
</div>
{% endif %}
</div>
</div>
I could get to implement 1 and 2, but 3 is a mistery right now. What I couldn't get is how I can access the expensive calculations I did in insertion view in the files view. How can I do that?
Here's a solution using session framework.
We'll save the calculations in the session and access those values in another view later.
For starters, we'll just save the ids (pk) of the students instead of the student instances because they are not JSON serializable [See note below].
def insertion(request):
# do expensive calucations ...
present_ids = [s.pk for s in present_students]
absent_ids = [s.pk for s in absent_students]
request.session['attendance_data'] = {
'present_ids': present_ids,
'absent_ids': absent_ids
}
def files(request):
attendance_data = request.session.get('attendance_data')
if not attendance_data:
# show error or something else ...
pass
present_students = md.Student.objects.filter(
pk__in=attendance_data['present_ids']
)
absent_students = md.Student.objects.filter(
pk__in=attendance_data['absent_ids']
)
# generate the pdf ...
Note: If you wish, you can also save the student instances in the session but you'll have to change the SESSION_SERIALIZER setting to use the PickleSerializer. See notes about session serialization.
You could submit the primary keys as form data in hidden fields. Just choose an appropriate delimiter based on your primary key (for example, don't delimit with a hyphen if you use a GUID primary key).
<form method="post" action="{% url "core:files" %}">
{% csrf_token %}
<input type="hidden"
name="present"
value="{% for s in present_students %}{{ s.pk }},{% endfor %}"
>
<input type="hidden"
name="absent"
value="{% for s in absent_students %}{{ s.pk }},{% endfor %}"
>
<button type="submit" class="btn btn-primary">OK</button>
</form>
Then in the view you can pick up the PKs in the view from the form data then request.
def files(request):
context = {}
if request.method == 'POST':
present_pks = request.POST.pop('present').split(',')[:-1]
absent_pks = request.POST.pop('absent').split(',')[:-1]
# do type conversions if needed
...
# Because we already have the pks separated, we can combine them
# for the query in order to do just 1 query
course_students = md.Student.objects.filter(pk__in=present_pks + absent_pks).all()
absent_students = []
present_students = []
for student in course_students:
if student.pk in absent_pks:
absent_students.append(student)
else:
present_students.append(student)
I am using Cryptocompare.com api to load news from cryptocurrencies world. In the template I am looping through it show it on the home-page. I would like to add feature that if you click send button it will send an email to you with the link for the news you just clicked. What is the best way to do it? I tried that, but I dont know how to link the clicked element with the url in views.
def home(request):
# Grab Crypto News
api_request = requests.get('https://min-api.cryptocompare.com/data/v2/news/?lang=EN')
api = json.loads(api_request.content)
return render(request, 'crypto/crypto_home.html', {'api': api})
def SendLink(request):
if request.method == 'POST':
subject = 'Link to crypto news'
from_email = 'test#gmail.com'
message = 'Hello {}, here is your link:'.format(request.user)
to_email = [request.user.email]
send_mail(
subject,
message,
from_email,
to_email
)
return HttpResponseRedirect(reverse('crypto-home'))
Template:
{% for x in api.Data %}
<div class='col-sm'>
<div class="card">
<img class="card-img-top" src="{{ x.imageurl }}" alt="{{ x.source }}">
<div class="card-body">
<h5 class="card-title">{{x.title}}</h5>
<p class="card-text">{{ x.body|safe }}.</p>
<div class="btn-group btn-group-sm" role='group'>
Read More
<form method="post" action="{% url 'send_link' %}">
{% csrf_token %}
<button id="{{x.id}}" target="_blank" class="btn btn-primary">Send to e-mail</button>
</form>
</div>
</div>
</div>
</div>
{% endfor %}
I would like to add link from template 'x.url' to views to be able to add the link to the message variable. I also tried to link it via ID of the news but I am not able to pass it to the views. Any idea how I can do that? Thanks
It looks like you need to add a hidden field to your form for the URL you'd like to pass to your view:
<input type="hidden" id="URL" name="URL" value="{{x.url}}">
Once you have that variable in your view you should be able to add it to your email template.
I have a Django formset that I wish to display inline using bootstrap3, but I keep getting the error ManagementForm data is missing or has been tampered with. I've included the {{formset.management_form}} in my html template so I'm not sure why I'm getting this error. Can anyone help me out?
My form looks like this:
class MasterForm(forms.Form):
def __init__(self,*args,**kwargs):
initial_date_start = kwargs.pop('initial_start')
initial_date_end = kwargs.pop('initial_end')
sc_arg_list = kwargs.pop('sc_arg_list')
sc_section_label = kwargs.pop('sc_section_label')
tt_arg_list = kwargs.pop('tt_arg_list')
tt_section_label = kwargs.pop('tt_section_label')
super(MasterForm,self).__init__(*args,**kwargs)
self.fields['WINDOW_START'].initial=initial_date_start
self.fields['WINDOW_END'].initial=initial_date_end
self.fields['sc_ID'].choices=sc_arg_list
self.fields['sc_ID'].label=sc_section_label
self.fields['scID'].choices=sc_arg_list
self.fields['scID'].label=sc_section_label
self.fields['tasktype'].choices=tt_arg_list
self.fields['tasktype'].label=tt_section_label
WINDOW_START = forms.CharField(required=True,label="WINDOW_START")
WINDOW_END = forms.CharField(required=True,label="WINDOW_END")
sc_ID = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple)
scID = forms.ChoiceField(required=True, widget=forms.RadioSelect)
tasktype = forms.MultipleChoiceField(required=True, widget=forms.CheckboxSelectMultiple)
The view that uses it looks like this:
FormSet = formset_factory(MasterForm)
keys = {'initial_start':"1/2/2015",'initial_end':"1/20/2015",'sc_arg_list':sat_list,'sc_section_label':"Please Select A Satelite",'tt_arg_list':task_type,'tt_section_label':"Please Select Task Type"}
if request.method == 'POST':
formset = FormSet(request.POST,keys)
if(formset.is_valid()):
message = "Thank you"
for form in formset:
print form
form.save()
else:
message = "Something went wrong"
else:
formset = FormSet(keys)
return render(request, 'InterfaceApp/gantt_search.html', {'formset': formset})
And the Django template that I am using looks like this:
<form action="/InterfaceApp/gantt_search/" method="post" class="form">
{{ formset.management_form }}
{% csrf_token %}
{% bootstrap_formset formset %}
{% buttons %}
<div class="text-center">
<span class="btn-group">
<button type="submit" class="btn btn-primary center-block" value="Submit" name="All_Planning">
{% bootstrap_icon "fire" %} All Planning
</button>
<button type="submit" class="btn btn-primary center-block" value="Submit" name="Ops_Only">
{% bootstrap_icon "filter" %} Ops Only
</button>
</span>
</div>
{% endbuttons %}
</div>
</form>
I'm not missing the {{formset.management_form}} tag so I'm not sure why Django is telling me that it's not there.
Thanks.
i am not able to upload an image from html page but it is possible from admin page
here is my models.py:
def get_upload_file_name(instance,filename):
return "image/%s_%s"%(str(time()).replace('.','_'),filename)
class Company_Profile(models.Model):
user = models.ForeignKey(User)
name = models.CharField(_('Company Name'), max_length= 30)
logo = models.FileField(_('Company Logo'), upload_to=get_upload_file_name)
address = models.TextField(_('Contact Address'), max_length=50)
phone_no = models.IntegerField(_('Contact No'), max_length=12)
my views.py:
def company_prof(request):
if request.method == 'POST':
comp_prof = Company_Prof(request.POST, request.FILES)
if comp_prof.is_valid():
save_prof = comp_prof.save(commit=False)
save_prof.user = request.user
save_prof.save()
messages.success(request, 'Thank you for Registration')
return HttpResponseRedirect('company/'+str(save_prof.id))
else:
comp_prof =Company_Prof()
variables = RequestContext(request, {
'comp_form': Company_Prof()})
return render_to_response("comp_profile.html",
locals(),
context_instance = RequestContext(request))
my settings.py is:
MEDIA_ROOT ='G:\Mini project\Pycharm projects\project4\static/'
MEDIA_URL = ''
html page is:
<form enctype="application/x-www-form-urlencoded" class="global_form" action="" method="post"><div><div><h3>Create Account</h3>
<div id="connect_signup_box" class="connect_box_form clearfix">
<form method="POST" enctype="multipart/form-data">{% csrf_token %}
{{ comp_prof.as_p }}
<input type="submit" class="btn btn-success" value="submit">
{% if save_prof %}
<h3>The details are submitted</h3>
{% endif %}
<input type="reset" class="btn" value="cancel">
{% if value == 'cancel' %}
<h3>Canceled</h3>
{% endif %}
</form>
</div>
</div>
</div>
</form>
when i submit it says no files are chosen. but from admin page there is no problem.
help me..
I think the problem is you have nested forms, which isn't supported by browsers (Can you nest html forms?).
So I am assuming that the browser is just using the first form definition, which has the wrong enctype. Try removing the first form declaration and just keeping this one: <form method="POST" enctype="multipart/form-data">.