GCBV Generic Class Based View, Django Classes Issue - django

$ Hello, I was trying to use "GCBV Generic Class Based View" for edit a post, but it seems not working and event it django can't find my HTML and I don't know why , Hope I get some support ….
$ edit button link
{% if post.created_by == user %}
<div class="mt-3">
<a class="btn btn-success float-end"
href="{% url 'edit_post' post.topic.board.pk post.topic.pk post.pk %}">Edit</a>
</div>
{% endif %}
$ edit HTML Page
{% extends 'base.html' %}
{% load static %}
{% block title %}Edit Post{% endblock %}<!-- | Page-title-->
{% block content %}
<link rel="stylesheet" href="{% static 'css/boards.css' %}">
<div class="newtopic">
<div class="container container-newtopic w-50">
<h1>Edit Post</h1>
<br>
{% include 'parts/alerts.html' %}
<div aria-label="breadcrumb">
<ol class="breadcrumb n1-head">
<li class="breadcrumb-item">Boards</li>
<li class="breadcrumb-item"><a href="{% url 'topics' post.topic.board.pk
%}">
{{post.topic.board.name}}</a></li>
<li class="breadcrumb-item active" aria-current="page"><a href="">Edit
Post</a></li>
</ol>
</div>
<form method="POST" action="" novalidate class="mb-4">
{% csrf_token %}
{% include 'includes/form.html' %}
<button type="submit" class="btn main-btn w-100 rounded-pill mt-5">
Save Changes
</button>
</form>
</div>
</div>
{% endblock %}
$ Views.py
#method_decorator(login_required, name='dispatch')
class PostUpdateView(UpdateView):
model = Post
fields = ('message',)
template_name = 'edit_post.html'
pk_url_kwarg = 'post_id'
context_object_name = 'post'
def form_valid(self, form):
post = form.save(commit=False)
post.updated_by = self.request.user
post.updated_date = timezone.now()
post.save()
return redirect('topic_posts', board_id=post.topic.board.pk, topic_id=post.topic.pk)
$ Urls.py
urlpatterns = [
path('<int:board_id>/topics/<int:topic_id>/posts/<int:post_id>/edit',
views.PostUpdateView.as_view(), name="edit_post"),
]
$error message
TemplateDoesNotExist at /boards/4/topics/24/posts/28/edit
edit_post.html
Request Method: GET
Request URL: http://localhost:8000/boards/4/topics/24/posts/28/edit
Django Version: 4.0.5
Exception Type: TemplateDoesNotExist
Exception Value: edit_post.html

Related

Django- Template not found

I can't seem to get my delete, edit and add review functionality working. The errors come as soon as I try to navigate to the urls I have set up. When I try and add a new review using my link on the reviews page I get the below message:
TemplateDoesNotExist at /reviews/add
I don't understand why because I have linked the url above to the template, which I have created.
The issue I have with my edit/delete views is that the url it searches for when I click the button is just /edit/ or /delete/ rather than reviews/edit/int:pk or reviews/delete/int:pk as per my urls.
I have pasted my code below, any help would be much appreciated! I have the feeling I am going to kick myself when I realise!
reviews.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid home-container">
<div class="row align-items-center">
<div class="col-sm-12 text-center mt-4">
<h2><strong>Reviews</strong></h2>
</div>
</div>
{% for review in reviews %}
<hr class="hr-1">
<div class="row featurette">
<div class="col-sm-12">
<h2 class="featurette-heading">{{ review.title }}</h2>
<p class="lead">{{ review.content }}</p>
<div class="row justify-content-between mx-1">
<p>By: {{ review.user }}</p>
<p>Created on: {{ review.created }}</p>
<p>Last Updated: {{ review.updated }}</p>
</div>
<!-- Add user authentication if -->
<div class="text-center">
<a href="edit/{{ review.id }}" class="mx-2">
<button class="positive-button mb-2">Edit</button></a>
<a href="delete/{{ review.id }}" class="mx-2 mb-2">
<button class="negative-button">Delete</button></a>
</div>
</div>
</div>
{% endfor %}
<div class="row">
<div class="col-sm-12 text-center py-4">
{% if user.is_authenticated %}
<a href="{% url 'home:add_review' %}">
<button class="positive-button-lg">Add a review</button>
</a>
{% else %}
<p>If you would like to add your own review, please login or sign up if you haven't already!</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
add_review.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{{ review_form }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
</div>
</div>
{% endblock %}
views.py:
from django.shortcuts import render
from django.views import View
from django.urls import reverse_lazy
from django.views.generic import UpdateView, DeleteView
from .models import Reviews
from .forms import ReviewForm
def home(request):
''' Returns the home page.'''
return render(request, 'home/index.html')
def reviews(request):
''' Returns the reviews page.'''
serialized_reviews = []
reviews = Reviews.objects.all()
for review in reviews:
serialized_reviews.append({
"title": review.title,
"content": review.content,
"user": review.user,
"created": review.created,
"updated": review.updated,
})
context = {
"reviews": serialized_reviews
}
print(serialized_reviews)
return render(request, 'home/reviews.html', context)
class AddReview(View):
'''View which allows the user to add a new review.'''
def get(self, request, *args, **kwargs):
review = Reviews
review_form = ReviewForm
context = {
'review': review,
'review_form': review_form,
'user': review.user,
'title': review.title,
'content': review.content,
}
return render(request, 'add_review.html', context)
def post(self, request, *args, **kwargs):
review_form = ReviewForm(data=request.POST)
if review_form.is_valid():
obj = review_form.save(commit=False)
obj.user = request.user
obj.save()
return redirect("home:reviews")
class DeleteReview(DeleteView):
'''View which allows the user to delete the selected review.'''
model = Reviews
template_name = 'delete_review.html'
success_url = reverse_lazy('reviews')
class EditReview(UpdateView):
'''View which allows the user to edit the selected review.'''
model = Reviews
template_name = 'edit_review.html'
fields = ['title', 'content']
urls.py:
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.home, name='home'),
path('reviews', views.reviews, name='reviews'),
path('reviews/add', views.AddReview.as_view(), name='add_review'),
path('reviews/delete/<int:pk>', views.DeleteReview.as_view(), name='delete_review'),
path('reviews/edit/<int:pk>', views.EditReview.as_view(), name='edit_review'),
]
The main difference is my app name, which is 'core'. Also, I forgot to add the content field to the model, but that is easily done, the form will just handle it as soon as you do the migration. (except on list.html)
models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
class Reviews(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
title = models.CharField(max_length=128)
created_at = models.DateTimeField(auto_now_add=timezone.now())
updated_at = models.DateTimeField(auto_now=timezone.now())
forms.py
from django import forms
from core.models import Reviews
class ReviewsForm(forms.ModelForm):
class Meta:
model = Reviews
fields = '__all__'
views.py
from core.models import Reviews
from core.forms import ReviewsForm
from django.shortcuts import render, redirect
def list_reviews(request):
reviews = Reviews.objects.all()
context = {
"reviews": reviews
}
return render(request, 'reviews/list.html', context)
def add_review(request):
if request.method == 'POST':
form = ReviewsForm(request.POST)
if form.is_valid():
form.save()
return redirect('/reviews/')
else:
form = ReviewsForm()
context = {
'form': form
}
return render(request, 'reviews/detail.html', context)
def edit_review(request, pk):
if request.method == 'POST':
form = ReviewsForm(request.POST)
if form.is_valid():
obj = Reviews.objects.get(id=pk)
obj.title = form.cleaned_data['title']
obj.user = form.cleaned_data['user']
obj.save()
return redirect('/reviews/')
else:
obj = Reviews.objects.get(id=pk)
form = ReviewsForm(instance=obj)
context = {
'form': form
}
return render(request, 'reviews/detail.html', context)
def delete_review(request, pk):
obj = Reviews.objects.get(id=pk)
obj.delete()
return redirect('/reviews/')
urls.py
from django.urls import path
import core.views as views
app_name = 'core'
urlpatterns = [
path('reviews/', views.list_reviews, name='list-reviews'),
path('reviews/add', views.add_review, name='add-review'),
path('reviews/edit/<int:pk>/', views.edit_review, name='edit-review'),
path('reviews/delete/<int:pk>/', views.delete_review, name='delete-review'),
]
list.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid home-container">
<div class="row align-items-center">
<div class="col-sm-12 text-center mt-4">
<h2><strong>Reviews</strong></h2>
</div>
</div>
{% for review in reviews %}
<hr class="hr-1">
<div class="row featurette">
<div class="col-sm-12">
<h2 class="featurette-heading">{{ review.title }}</h2>
<p class="lead">{{ review.content }}</p>
<div class="row justify-content-between mx-1">
<p>By: {{ review.user }}</p>
<p>Created on: {{ review.created_at }}</p>
<p>Last Updated: {{ review.updated_at }}</p>
</div>
<!-- Add user authentication if -->
<div class="text-center">
<a href="{% url 'core:edit-review' pk=review.id %}" class="mx-2">
<button class="positive-button mb-2">Edit</button></a>
<a href="{% url 'core:delete-review' pk=review.id %}" class="mx-2 mb-2">
<button class="negative-button">Delete</button></a>
</div>
</div>
</div>
{% endfor %}
<div class="row">
<div class="col-sm-12 text-center py-4">
{% if user.is_authenticated %}
<a href="{% url 'core:add-review' %}">
<button class="positive-button-lg">Add a review</button>
</a>
{% else %}
<p>If you would like to add your own review, please login or sign up if you haven't already!</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
detail.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{% csrf_token %}
<table>
{{ form }}
</table>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</div>
</div>
{% endblock %}
According to your urls, It is a review/edit/<int:pk>.
So you must add same thing in href tag.
Change this:
<a href="edit/{{ review.id }}"
To this:
<a href="review/edit/{{ review.id }}"
That's why you are getting that error
I've fixed it, firstly the path in my add_review view was wrong, which I have amended and it now works (thanks Ivan).
I also was not actually bringing the ID through on my 'reviews' view in the first place, so when following the links on my edit and review buttons, it didn't know what I meant by 'id', as I hadn't specified what that was in the view context.
Thanks for the help all!
I think you're writing in your urls the wrong way, like this below your div text-center:
<a href="edit/{{ review.id }}" class="mx-2">
It should be:
<a href="{% url 'yourappname:edit' review.id %}">

Django error NoReverseMatch at / Reverse for 'add-to-fav-songs' with arguments '('',)' not found

So I want users to be able to add songs to a section called 'Favorite songs'(just like adding products to a cart in an e-commerce website) but I'm getting this error NoReverseMatch at / Reverse for 'add-to-fav-songs' with arguments '('',)' not found. 1 pattern(s) tried: ['add\\-to\\-fav\\-songs/(?P<pk>[0-9]+)/$']. Can anyone correct my code and show me how can I add songs to favorite songs.
Thanks in advance!
My models.py:
class Songs(models.Model):
title = models.CharField(max_length = 100)
lyrics = models.TextField()
author = models.CharField(max_length = 100)
track_image = models.CharField(max_length=2083)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('/', kwargs={'pk': self.pk})
My views.py:
def home(request):
context = {
'songs': Songs.objects.all()
}
return render(request, 'home.html', context)
#login_required
def add_to_fav_songs(request):
fav_song = get_object_or_404(Songs)
class Fav_songs(ListView):
model = Songs
template_name = 'fav_songs.html'
context_object_name = 'fav_song'
paginate_by = 2
def get_queryset(self):
return Songs.objects.filter(id=self.kwargs.get('pk'))
My urls.py:
path('add-to-fav-songs/<int:pk>/', views.add_to_fav_songs, name='add-to-fav-songs'),
path('favourite-songs/', Fav_songs.as_view(), name='favourite-songs'),
My home.html:
{% for song in songs %}
<article class="media content-section">
<div class="media-body">
<h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ song.title }}</a></h2>
<div class="article-metadata">
<a class="mr-2" href="{% url 'author-songs' song.author %}">{{ song.author }}</a>
</div>
<br>
<img class="card-img-bottom" height="339px" width="20px" src="{{ song.track_image }}">
</div>
<!-- <button> Add To Favourite Songs</button> -->
<form class="form" method="POST" action="{% url 'add-to-fav-songs' song.id %}">
{% csrf_token %}
<div class="action">
<button class="like btn btn-danger" type="button"><span class="fa fa-heart"></span></button>
</div>
</form>
</article>
{% endfor %}
My fav_songs.html:
{% for fav_song in songs %}
<article class="media content-section">
<div class="media-body">
<h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ fav_song.title }}</a></h2>
<div class="article-metadata">
<a class="mr-2" href="{% url 'author-songs' song.author %}">{{ fav_song.author }}</a>
</div>
<br>
<img class="card-img-bottom" height="339px" width="20px" src="{{ fav_song.track_image }}">
</div>
</article>
{% endfor %}
The first issue in your code was that you wrote:
{% url 'add-to-fav-songs' object.id %}
Here the problem is that there is no variable object in the context and hence object.id just resolves to an empty string, giving you an error. You need to replace this with song.id:
{% url 'add-to-fav-songs' song.id %}
Next you tried this comment to remove that faulty code:
<!-- <button> Add To Favourite Songs</button> -->
Here the problem is that Django does not care about HTML comments, it will try to render them and once again give you the same error. You can either remove this code or use the comment template tag [Django docs] to make Django actually consider it as a comment:
{% comment %}
<button> Add To Favourite Songs</button>
{% endcomment %}

Django template tags conditionals

Right, am struggling with my blog app when trying to render some logic through the template view. So the idea is to render a one time only button for the newly authenticated users that do not have a post published and after the user has published its first post the button will be rendered within a for loop so he/she'll be able to create/delete a new one from there.
views.py
#login_required(login_url='app_users:login')
#allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
posts = BlogPost.objects.all().order_by('date_posted')
context = {'title': 'Blog', 'posts': posts}
return render(request, 'app_blog/blog.html', context)
models.py
class BlogPost(models.Model):
title = models.CharField(max_length=100, null=True)
content = models.TextField(null=True)
date_posted = models.DateTimeField(default=timezone.now, null=True, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
blog.html
{% block content %}
{% if request.user not in posts|last %}
<div class="container" style="float: left;">
<a class="btn btn-primary btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_create' user.id %}"><h5>C'mon {{ request.user.username }}, don't be shy! Create Your First Blog Post!</h5></a>
</div>
{% endif %}
<br>
<br>
{% for post in posts %}
<br>
<div class="container">
<article class="media content-section">
<img class="rounded-circle account-img" src="{{ post.author.profile.image.url }}" alt="Image could not be uploaded!">
<div class="card-body media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'app_blog:blog_user_detail' post.id %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"d F Y" }}</small>
</div>
<div class="article-metadata">
{% if post.author == request.user %}
<div>
<a class="btn btn-primary btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_create' post.id %}">Create New Post</a>
<a class="btn btn-primary btn-danger btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_delete' post.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2><a class="article-title" href="{% url 'app_blog:blog_detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content|safe }}</p>
</div>
</article>
</div>
<br>
{% endfor %}
{% endblock %}
So, again, end question would be about what sort of conditionals to use here:
{% if request.user not in posts|last %}
Thanks.
Not quite sure I fully understand but I will suggest something. A user who was a saved post should not see that button? If so, maybe something like this would work:
{% if request.user not in posts.authors.all %}
EDIT original solution won't work. posts is a queryset object
views.py
#login_required(login_url='app_users:login')
#allowed_users(allowed_roles=['admin', 'staff', 'users'])
def blog(request):
posts = BlogPost.objects.all().order_by('date_posted')
new_user = len(posts.filter(author=request.user)) == 0
context = {'title': 'Blog', 'posts': posts, 'new_user': new_user}
return render(request, 'app_blog/blog.html', context)
blog.html (just the condition)
{% if new_user %}

Django : How can I update my views? url problem

Like below code, I made update view but it doesn't work. after I click the , it doesn't work an just
"GET /moneylogs/update/7/ HTTP/1.1" 200 6243
console log printed. the page remain like just refresh.
How can I update my moneylog?
views.py
class moneylog_update(UpdateView):
model = moneylog_models.Moneylog
form_class = forms.UpdateMoneylogForm
template_name = "moneylogs/update.html"
def form_valid(self, form):
moneylog = form.save(commit=False)
moneybook = moneybook_models.Moneybook.objects.get(
pk=self.kwargs["pk"])
moneylog.save()
form.save_m2m()
return redirect(reverse("moneybooks:detail", kwargs={'pk': moneybook.pk}))
urls.py
app_name = "moneylogs"
urlpatterns = [
path("create/<int:pk>/",
views.moneylog_create.as_view(), name="create"),
path("update/<int:pk>/",
views.moneylog_update.as_view(), name="update"),
path("<int:moneybook_pk>/delete/<int:moneylog_pk>/",
views.moneylog_delete, name="delete"),
]
moneylog_form_update.html
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.memo.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.memo}}
</div>
</div>
{% if form.memo.errors %}
{% for error in form.memo.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<a href="{% url 'moneylogs:update' moneylog.pk %} ">
<div class="px-2 py-1 rounded bg-red-500 text-white">{{cta}}</div>
</a>
Since Update view processes the form on a post request, you need HTML form with post request to submit your data.
<form method="post" action="{% url 'moneylogs:update' moneylog.pk %}">
<div class="input {% if field.errors %}has_error{% endif %}">
<div class="flex">
<div class="w-1/4">
{{form.memo.label}}
</div>
<div class="w-3/4 border-b my-2 py-3">
{{form.memo}}
</div>
</div>
{% if form.memo.errors %}
{% for error in form.memo.errors %}
<span class="text-red-700 font-medium text-sm">{{error}}</span>
{% endfor %}
{% endif %}
</div>
<input type="submit" value="{{cta}}" />
</form>
<a></a> will hit the server using the GET request.

add text field on button click and pack into jsonfield with django

I have a jsonfield in my django project and i was wondering how i can have button to add textfields
for example:
i have a list of steps and i want to click a button to add a step (simillarly to adding attachments in email) and then i want to pack all of these into a jsonfield
so my two questions are
how do i add a text field via button and how do i pack the text fields together into a jsonfield
thanks a lot no code is included because i don't think it is necessary
katie
edit: added code:
here is thew view where I create a new recipe object for my cookbook. this is also the view that handles the form that would contain the jsonfields:
def createrecipe(request):
if request.method == 'POST':
form = RecipeForm(request.POST)
if form.is_valid():
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
form = form.save()
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form': form,
})
data = {
'replace': True,
'form': t.render(c),
'success': True,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
else:
form = RecipeForm(request.POST)
t = loader.get_template('cookbook/create_form.html')
c = RequestContext(request, {
'form':form,
})
data ={
'form': t.render(c),
'success': False,
}
json = simplejson.dumps(data)
return HttpResponse(json, mimetype='text/plain')
here is the model.py for my recipe (where the jsonfields are located):
class Recipe(models.Model):
def __unicode__(self):
return self.name
original_cookbook = models.ForeignKey(Cookbook)
name = models.CharField(max_length=200)
author = models.CharField(max_length= 100)
picture = models.ImageField(upload_to = 'Downloads', blank=True)
pub_date = models.DateTimeField('date published', auto_now_add=True, blank=True)
type = models.CharField(max_length = 2, choices=TYPE_CHOICES)
ingredients = JSONField()
steps = JSONField()
prep_time = models.IntegerField()
here is my account view:
def account(request):
user = request.user
if request.user.is_authenticated():
cookbooks = user.cookbooks
if cookbooks.all().exists():
cookbook = cookbooks.all()[0]
form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})
recipe_list = cookbook.recipes.all()
else:
raise Http404
else:
return HttpResponseRedirect('/accounts/login')
t = loader.get_template('cookbook/account.html')
c = RequestContext(request, {
'form': form,
'recipe_list': recipe_list
})
return HttpResponse(t.render(c))
this is the template for the form:
create_form.html the action of the form points to the create recipe view
<body>
<form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform">
<table>
{% csrf_token %}
{{ form.as_table }}
</table>
<p><input type="submit" value="Submit"></p>
</form>
<form class="task-form" action="." method="POST">
<button class=".task-add-button" value="Add Task">
{% csrf_token %}
{{ TaskFormSet.as_p }}
</form>
</body>
here is the template for the account page that handles the create_recipe page...
account.html
{% extends "cookbook/base.html" %}
{% load pagination_tags %}
{% load comments %}
<h1>{{ user }}'s Cookbook</h1>
<ul>
{% block nav-cookbooks %}
<li><a class="nav-inactive" href="/cookbooks/">Cookbooks</a></li>
{% endblock %}
{% block nav-account %}
<li><a class="nav-active" href="/account/">My Cookbook</a></li>
{% endblock %}
</ul>
{% block content %}
{% autopaginate recipe_list 6 %}
<div id="recipe_cont">
{% for recipe in recipe_list %}
<div class="recipe">
<div class="button">
<img src="{{ STATIC_URL }}chicknbraw.jpg" alt="" height="70" width="70" style="display:inline;" />
<h4>{{ recipe.name }}</h4>
</div>
<h5>{{ recipe.author }}</h5>
<h5>Prep Time: {{ recipe.prep_time }} minutes</h5>
<h6>Add Recipe
Remove Recipe</h6>
</div>
{% endfor %}
</div>
<div id="popupContact" class="popup">
<a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
<p id="contactArea">
<h1 style="text-align:center">Create New Recipe</h1>
{% include 'cookbook/create_form.html' %}
</p>
</div>
<div id="backgroundPopup">
</div>
<div id="col2-footer">
{% paginate %}
<p id="recipe_order_text"> order by: abc|date
</div>
{% endblock %}
{% block footer %}
<a class="create" style="cursor:pointer" >Create New Recipe</a>
{% endblock %}
base.html:
{% load i18n %}
{% block doctype %}<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
{% endblock %}
{% block head %}
<head>
<title>{% block title %}Recipeek{% endblock %}</title>
<script type="text/javascript">
$(document).ready(function(){
var form = $('form#createrecipeform');
form.submit(function(e) {
e.preventDefault();
console.log('ajax form submission function called successfully.');
//form = $(this);
console.log(form)
var serialized_form = form.serialize();
$.ajax({ type: "POST", 
url: $(this).attr('action'),
data: serialized_form, 
success: (function(data) { 
console.log('ajax success function called successfully.');
data = $.parseJSON(data);
if (data.success) {
console.log('success');
var newForm = data.form;
form.replaceWith(newForm);
} else {
console.log('failure');
var newForm = data.form;
form.replaceWith(newForm);
}
})
});
return false;
});
});
</script>
</head>
{% endblock %}
{% block body %}
<body>
{% block header %}
<div id="header"></div>
{% endblock %}
<div id="left_pane">
<div id="left_pane-container">
<div id="logo"><img src= "/static/recipeek_logo.png" style="padding-left:10px;" /></div>
<div id="left_pane-items">
<div id="nav_out">
<ul id="nav_outlist">
<li>about us</li>
<li>contact</li>
<li>glossary</li>
</ul>
</div><!--nav_out-->
</div><!--left_pane-items-->
</div><!--left_pane-container-->
</div><!--left_pane-->
{% block container %}
<div id="container">
<div id="container_header">
<div id="horz_nav">
<ol>
<li id="cookbook_link">{% block nav-cookbooks %}Cookbooks {% endblock %}</li>
<li id="account_link">{% block nav-account %}My Cookbook{% endblock %}</li>
</ol>
</div>
<div id="container_header-items">
{% trans "Home" %} |
{% if user.is_authenticated %}
{{ user.username }}
({% trans "Log out" %} |
{% trans "Change password" %})
<form action="/search/" method="get">
<input type="text" name="q" id="id_q" value="Search" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
</form>
{% else %}
{% trans "Log in" %}
{% endif %}
</div><!--header-items-->
</div><!--header-->
<div id="col2">
<div id="col2-header"></div>
{% block content %}{% endblock %}
</div>
<div id="footer">
{% block footer %}
{% endblock %}
</div>
</div>
{% endblock %}
</body>
{% endblock %}
</html>
i think that is all of the relevant code.
i think i should also mention I am using ajax to submit the form - im not sure this will make any difference in how to implement this idea. thanks again for the help tom :)
Well katie, what you're going to want to do is set up some javascript on the frontend.
<form class="task-form" action="." method="POST">
<button class=".task-add-button" value="Add Task">
{{ TaskFormSet.as_p }}
</form>
<script>
var $form = $('.task-form')
, $button = $form.find('.task-add-button')
, template = '{{ TaskFormSet.empty_form.as_p }}'
, num_formsets = $form.find('input[name=TOTAL_FORMS]').val();
$button.on('click', function(){
var formset_html = template.replace('__prefix__', 'form-'+(++num_formsets);
$(formset_html).appendTo($form); // Creates new input
return false;
});
</script>
Then you will want a form that will be able to process this list.
https://docs.djangoproject.com/en/dev/topics/forms/formsets/
from django.forms.formsets import formset_factory
class TaskForm(Form):
title = CharField()
... any number of extra fields
TaskFormSet = formset_factory(TaskForm, can_order=True, can_delete=True, extra=1)
# In your view
instance = TaskModel.objects.get(...)
tasks_formset = TaskFormSet(request.POST, initial=instance.tasks_json)
context['TaskFormSet'] = tasks_formset
if request.method == 'POST' and tasks_formset.is_valid():
instance.tasks_json = [task.cleaned_data for task in tasks_formset]
instance.save()
I Hope this helps you, and welcome to StackOverflow!