I was making a blog website, I am new to django and I don't know how to add comment without refreshing the page itself. I was trying to do with the help of tutorial but they are not helping anymore
here is my html file
<div class="row">
<div class="comment-section col-8">
{% for i in data %}
<li>{{i}}</li><br>
{% endfor %}
</div>
<div class="col-4">
<h4 class="m-3">{{comments.count}} Comments...</h4>
{% for j in comments %}
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">{{j.title}}</h5>
<h6 class="card-subtitle mb-2 text-muted">{{j.visitor.name}}</h6>
<p class="card-text">{{j.description}}</p>
</div>
</div>
{% endfor %}
<hr>
<h3>Comment here</h3>
<form method="post" id="comment-form">
{% csrf_token %}
<input type="hidden" id="contentId" name = 'contentId' value="{{ result.id }}">
<div class="form-group">
<input type="hidden" id="name" name="name" class="form-control" value="{{request.session.user.name}}" readonly>
</div>
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name="title" class="form-control">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" id="description" cols="30" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-secondary">Submit</button>
</form>
</div>
here is my views.py file
def addComment(request):
if request.method == 'POST':
post_id = request.POST['contentId']
title = request.POST['title']
description = request.POST['description']
user = request.session['user']['id']
con = Comment(
post_id=post_id,
title=title,
description=description,
visitor_id=user,
)
con.save()
print()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Related
This question already has answers here:
Flask view return error "View function did not return a response"
(3 answers)
Closed 8 months ago.
flask code
#bp.route('/delete/<int:id>')
#login_required
def delete_tracker(id):
if Trackers.user_id == current_user.id:
trackers = Trackers.query.filter_by(id=id).first()
print(trackers)
db.session.delete(trackers)
db.session.commit()
return redirect(url_for("authen.dashboard"))
Html code- look for /delete url t bottom there is the error
{% extends "base.html" %}
{% block title %} Dashboard {% endblock %}
{% block content %}
<nav class="sidenav">
<div class="main-buttons">
<a class="nav-link active" id="trackers" aria-current="page" href="/dashboard">Trackers</a>
<a class="nav-link active" id="goals" aria-current="page" href="/goals">Goals</a>
<div>
</nav>
<div id="dashbar">
<nav class="navbar bg-light">
<div class="container-fluid">
<button type="button" class="btn btn-outline-dark" data-bs-toggle="modal" data-bs-target="#exampleModal">
Add Tracker
</button>
<form method="POST">
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add a Tracker</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<label for="tracker_name" class="col-form-label">Tracker Name:</label>
<input type="text" class="form-control" id="tracker_name" name="tracker_name"
placeholder="Enter a Tracker name">
<div class="from-fieldset" style="width:200px;">
<label for="tracker_type" class="form-label">Choose a Tracker type:</label>
<select id="tracker_type" name="tracker_type">
<option value="">choose Tracker type</option>
{% for t in data_trackers %}
<option value="{{t.name}}">{{t.name}}</option>
{% endfor %}
<label for="tracker_description " class="col-form-label">Description</label>
<input type="text" class="form-control" id="tracker_description" name="tracker_description"
placeholder="Enter Description">
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-light border-dark">Submit</button>
</div>
</div>
</div>
</div>
</form>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</nav>
</div>
<div class="wrapper">
<div class="container-tracker">
{% for track in user.trackers %}
<div class="tra">
<h3 id="trackername"> {{track.tracker_name}}</h3>
<div class="dropdown-container" tabindex="-1">
<form method="GET" action="/delete/{{track.id}}">
<button type="submit" class="btn btn-outline-light">Delete</button>
</form>
<div class="three-dots"></div>
<div class="dropdown">
<a href="#">
<div>Records and Graphs</div>
</a>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
( in form method=GET , the delete url is there and the flask code is at top for that endpoint
if I remove if condition in the delete_tracker() fucntion that is if user.id==current_user.id then I will get a different error that is , this is for session 2nd but this is 3rd session something like this, so my file I want to delete is different session )
can you try to change your line
#bp.route('/delete/<int:id>')
to
#bp.route('/delete/<track.id>')
I am building a CRUD app on Django.
I can create, read, and delete just fine, but the update function does not work. I have edited the views.py file (it was a template) to print the error.
Here are the relevant pieces of my code:
#models.py
from django.db import models
class Item(models.Model):
id = models.AutoField(primary_key=True)
etype = models.CharField(max_length=100)
etitle = models.CharField(max_length=100)
eauthor = models.CharField(max_length=100)
estatus = models.CharField(max_length=20)
class Meta:
db_table = "Item"
#views.py
...
def edit(request, id):
item = Item.objects.get(id=id)
return render(request,'edit.html', {'item':item})
def update(request, id):
item = Item.objects.get(id=id)
form = ItemForm(request.POST, instance = item)
print(form.errors)
if form.is_valid():
try:
form.save()
except Exception as e: print(e)
return redirect("/items/show")
return render(request, 'edit.html', {'item': item})
...
I guess the problem has to be in edit.html file, but I cannot figure it out.
#edit.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Index</title>
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}"/>
</head>
<body>
<form method="POST" class="post-form" action="http://127.0.0.1:8000/items/update/{{item.id}}">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Type:</label>
<div class="col-sm-4">
<input type="text" name="etype" id="id_etype" required maxlength="100" value="{{ item.etype }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Title:</label>
<div class="col-sm-4">
<input type="text" name="etitle" id="id_etitle" required maxlength="100" value="{{ item.etitle }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Author:</label>
<div class="col-sm-4">
<input type="text" name="eatuhor" id="id_eauthor" required maxlength="100" value="{{ item.eauthor }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Status:</label>
<div class="col-sm-4">
<input type="text" name="estatus" id="id_estatus" required maxlength="20" value="{{ item.estatus }}" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</div>
</form>
</body>
</html>
P.S: I am new to both Django and Software Development, so any kind of feedback is welcome.
I advise you to use UpdateView, its really easier.
Show here Click
Example views.py
class ItemUpdate(UpdateView):
model = Item
template_name = 'edit.html'
Example edit.html:
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update">
</form>
Thanks for looking into my problem, I am a beginner with Django and Vue your assistance with this wil be extremely helpful. I am working on a Job portal and created the job search functionality in Django as backend for the same I have an app called job into my Django project. The browser Js console gives this error Failed to mount app: mount target selector returned null. For this app I have an add job view, through which an employer adds the jobs. For this I'm using Vue for validation and showing any errors if any non-null fields are not entered by the employer account. So this is not how it was supposed to look,Unexpected results snap shot so as you can see it wasn't supposed to give me [[error]] and company_size instead The company size is missing as per the Vue AddJobApp, given below. Also if were to add # within mount-function-createapp within Vue-AddJobApp, the page entirely disappears (blank page). what am I doing wrong here?
adding # in AddJob.mount() function is making the page go blank a
Add job template
{% extends 'core/base.html' %}
{% block content %}
<div id="add-job-app">
<h1 class="title"> Add Job</h1>
<form action="." method="POST" v-on:submit="validateForm">
{% csrf_token %}
{% if form.errors %}
{% for error in form.errors %}
<div class="notification is-danger">
{{ error }}
</div>
{% endfor %}
{% endif %}
<div class="notification is-danger" v-if ="error.length" >
<p v-for="error in errors" >
[[ error ]]
</p>
</div>
<div class="field">
<label for="">Title</label>
<div class="control">
<input class="input" type="text" name="title" id="id_title" v-model= "title">
</div>
</div>
<div class="field">
<label for="">Short description</label>
<div class="control">
<textarea name="short_description" id="id_short_description" class="textarea" v-model= "short_description" ></textarea>
</div>
</div>
<div class="field">
<label for="">Long description</label>
<div class="control">
<textarea name="long_description" id="id_long_description" class="textarea" v-model= "long_description" ></textarea>
</div>
</div>
<div class="field">
<label for="">Company name</label>
<div class="control">
<input class="input" type="text" name="company_name" id="id_company_name" v-model= "company_name" >
</div>
</div>
<div class="field">
<label for="">Company address</label>
<div class="control">
<input class="input" type="text" name="company_address" id="id_company_address" v-model= "company_address">
</div>
</div>
<div class="field">
<label for="">Company zipcode</label>
<div class="control">
<input class="input" type="text" name="company_zipcode" id="id_company_zipcode" v-model= "company_zipcode">
</div>
</div>
<div class="field">
<label for="">Company place</label>
<div class="control">
<input class="input" type="text" name="company_place" id="id_company_place" v-model= "company_place">
</div>
</div>
<div class="field">
<label for="">Company Country</label>
<div class="control">
<input class="input" type="text" name="company_country" id="id_company_country" v-model= "company_country">
</div>
</div>
<div class="field">
<label for="">Company Size</label>
<div class="control">
<div class="select">
<select name="company_size" v-model = "company_size">
<option value="">Choose Size</option>
<option value="size_1_9">1-9</option>
<option value="size_10_49">10-49</option>
<option value="size_50_99">50-99</option>
<option value="size_100">100+</option>
</select>
</div>
</div>
</div>
<div class="field">
<div class="control">
<button class="button is-success">Submit</button>
</div>
</div>
</form>
</div>
{% endblock %}
{% block scripts %}
<script >
const AddJobApp = {
data() {
return {
title:'',
company_name:'',
short_description:'',
company_size:'',
errors:[]
}
},
delimiters:['[[',']]'],
methods :{
validateForm(e){
this.errors = []
if( this.title ===''){
this.errors.push('The title field is missing')
}
if( this.short_description ===''){
this.errors.push('The short description field is missing')
}
if( this.company_name ===''){
this.errors.push('The company name field is missing')
}
if( this.company_size ===''){
this.errors.push('The company size is missing')
}
if(this.errors.length){
e.preventDefault()
return false
}else{
return true
}
}
}
}
Vue.createApp(AddJobApp).mount('add-job-app');
</script>
{% endblock %}
my views.py file inside of job app
from apps.job.forms import AddJobForm, ApplicationForm
from django.shortcuts import redirect, render
from .models import Job
from django.contrib.auth.decorators import login_required
from apps.notification.utilities import create_notification
def job_detail(request,job_id):
job = Job.objects.get(pk=job_id)
return render(request, 'job/job_detail.html',{'job':job})
def search(request):
return render(request,'job/search.html')
#login_required
def apply_for_job(request,job_id):
job = Job.objects.get(pk=job_id)
if request.method=='POST':
form = ApplicationForm(request.POST)
if form.is_valid():
application = form.save(commit=False)
application.job = job
application.created_by = request.user
application.save()
create_notification(request, job.created_by ,'application',extra_id=application.id)
return redirect('dashboard')
else:
form = ApplicationForm()
return render(request,'job/apply_for_job.html',{'form':form,'job':job})
#login_required
def add_job(request):
if request.method=='POST':
form = AddJobForm(request.POST)
if form.is_valid():
job = form.save(commit=False)
job.created_by = request.user
job.save()
return redirect('dashboard')
else:
form = AddJobForm()
return render(request,'job/add_job.html',{'form':form})
Hi I am trying to make a form submission app that just displays the entered information back to the user underneath the form they submitted. Unfortunately, I can't seem to load the context on the front end within the template.
Template:
You'll see under the form there is a for loop that is supposed to iterate the context, but nothing displays. I tried it with just email for now, but it does not work.
<!DOCTYPE html>
<html>
<head>
<title>Form Practice</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<form style="margin-top: 600px;" method="post" action="/form">
{% csrf_token %}
<div class="form-group row">
<label for="inputEmail3" class="col-sm-2 col-form-label" >Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail3" placeholder="Email" name="email">
</div>
</div>
<div class="form-group row">
<label for="inputPassword3" class="col-sm-2 col-form-label" >Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
<fieldset class="form-group">
<div class="row">
<legend class="col-form-label col-sm-2 pt-0">Radios</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio" name="gridRadios" id="gridRadios1" value="option1" checked>
<label class="form-check-label" for="gridRadios1">
First radio
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="gridRadios" id="gridRadios2" value="option2">
<label class="form-check-label" for="gridRadios2">
Second radio
</label>
</div>
</div>
</div>
</fieldset>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="customCheck1" name="check">
<label class="custom-control-label" for="customCheck1">Check this custom checkbox</label>
</div>
<select class="custom-select mr-sm-2 custom-select-lg mb-3" name="select" id="inlineFormCustomSelect">
<option selected>Choose...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<div class="custom-control custom-radio">
<input type="radio" id="customRadio1" name="customRadio" class="custom-control-input">
<label class="custom-control-label" for="customRadio1">Toggle this custom radio</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="customRadio2" name="customRadio" class="custom-control-input">
<label class="custom-control-label" for="customRadio2">Or toggle this other custom radio</label>
</div>
<div class="custom-file">
<input type="file" class="custom-file-input" name="customFile" id="customFile">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<button type="submit" class="btn-block btn btn-primary my-1">Submit</button>
</form>
{% for item in context %}
<h1>{{ item.email }}</h1>
{% endfor %}
</div>
<div class="col-md-2"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
views.py
def index(request):
try:
email = request.POST['email']
print(email)
password = request.POST['password']
print(password)
radio = request.POST['gridRadios']
print(radio)
select = request.POST['select']
print(select)
except:
print("error")
context = {'context': {'email': email, 'password': password, 'radio': radio, 'select': select}}
print(context)
return render(request, 'form.html', context)
Replace this:
{% for item in context %}
<h1>{{ item.email }}</h1>
{% endfor %}
To:
<h1>{{ context.email }}</h1>
An error message is not shown.I wrote in index.html
<main>
<div class="detailimg col-xs-8">
<div class="relative_ele">
<div class="container" id="photoform">
{% if form.errors %}
<div class="alert alert-danger" role="alert">
<p>At least 1 picture should be selected</p>
</div>
{% endif %}
<form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="file_select btn-lg">
File Select1
<input type="file" name="image">
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="btn-lg file_select">
File Select2
<input type="file" name="image2">
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<div class="col-xs-offset-2">
<div class="form-group">
<input type="submit" value="SEND" class="form-control">
</div>
</div>
</form>
</div>
</div>
</div>
</main>
in views.py
#login_required
#csrf_exempt
def upload_save(request):
if request.method == "POST":
form = UserImageForm(request.POST, request.FILES)
if form.is_valid():
data = form.save(commit=False)
data.user = request.user
data.image = request.cleaned_data['image']
data.save()
else:
print(form.errors)
else:
form = UserImageForm()
return render(request, 'registration/photo.html', {'form': form})
In my current code, when I select no image and put "SEND" button & I select the 1~2 image and put "SEND" button,photo.html is shown.I wanna show error message
{% if form.errors %}
<div class="alert alert-danger" role="alert">
<p>At least 1 picture should be selected</p>
</div>
{% endif %}
when I select no image, but now my system is not an ideal one. Why can't I do it? I think if I select no image,{% if form.errors %} become true. Do I misunderstand it? How should I fix this?
<main>
<div class="detailimg col-xs-8">
<div class="relative_ele">
<div class="container" id="photoform">
{% if form.errors %}
<div class="alert alert-danger" role="alert">
<p>At least 1 picture should be selected</p>
</div>
{% endif %}
<!--here change--><form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="file_select btn-lg">
File Select1
<!--here change--><input id="file1" type="file" name="image">
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="input-group">
<label class="input-group-btn" style="width: 80px;">
<span class="btn-lg file_select">
File Select2
<!--here change--><input id="file2" type="file" name="image2">
</span>
</label>
<input type="text" class="form-control" readonly="">
</div>
<div class="form-group">
<input type="hidden" value="{{ p_id }}" name="p_id" class="form-control">
</div>
<div class="col-xs-offset-2">
<div class="form-group">
<!--here channge --><input id="send" type="submit" value="SEND" class="form-control">
</div>
</div>
</form>
</div>
</div>
</div>
</main>
<script type="text/javascript" language="JavaScript">
window.onload = function () {
var a = document.getElementById("send");
var file1 = document.getElementById("file1");
var file2 = document.getElementById("file2");
a.onclick = function(){
if(file1.value=="" && file2.value==""){
alert ('You didn\'t choose any of the checkboxes!');
return false;
}
else {
return true;
}
}
}
</script>
Hope this will work