【发布时间】:2015-10-16 17:19:48
【问题描述】:
在开始我的项目后,我正在用一个简单的博客玩 django 和 python3。
事情是这样的。我有一个模型。
class Post(models.Model):
post_text = models.TextField()
post_likes = models.BigIntegerField()
post_author = models.ForeignKey(User)
pub_date = models.DateTimeField('date published')
class Comments(models.Model):
post = models.ForeignKey("Post")
comment= models.TextField(max_length=100)
我需要在我的视图中复制这两个元素。我正在使用此代码。
def duplicate(request):
post_id = request.POST.get('post_id')
post = Post.objects.get(id = post_id)
new_post = deepcopy(post)
post.id = None
post.save()
response_data = {}
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
javascript。
$(function() {
function create_post() {
console.log("create post is working!") // sanity check
$.ajax({
url : "add_post/",
type : "POST",
data : { post_text: $('#text_area').val()},
success : function(json) {
$('#text_area').val(''); // remove the value from the input
console.log(json); // log the returned json to the console
$("#posts").append("<tr><td class='card'>"+json.id+"</td><td>"+json.author+"</td><td>"+json.text+"</td><td class='remove-post-button'><button>Borrar</button></td><td class='duplicar'><button onClick='window.location.reload()'>Duplicar</button></td>");
console.log("success"); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>");
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
但它只是从我的类“Post”中复制所有属性。
我的看法是。
<tbody id='posts'>
{% for post in posts %}
<tr class="post-card" data-post-id="{{ post.id }}">
<td>{{ post.id }}</td>
<td class="post-author">{{ post.post_author }}</td>
<td class="post-content">{{ post.post_text }}</td>
{% for comment post.comments_set.all %}
<td class="post-comments">{{comment.comments}}</td>
{%endfor%}
<td class="remove-post-button"><button>Borrar</button></td>
<td class="duplicar"><button onClick='window.location.reload()'>Duplicar</button></td>
</tr>
{% endfor %}
如何从帖子和评论中复制并在视图中显示?
【问题讨论】:
标签: javascript python django python-3.x copy