I am working on a small newsletter-app for a custom-Blog-Django-project (just for me). One main feature of the project is the defined set of Article-Types. All Article-types are children of the abstract base class "Article". Two examples of article-types are "event-article" and "video-article". In the newsletter-app I have a "content"-Field (=email-message). Now I want to choose several articles (of any type) to be included in the newsletter. It may be easier if I just create a function that searches all articles which are not featured in a newsletter yet. Then I would collect all needed inform开发者_Python百科ation, combine them into a text and set the function as default for the field. But I rather choose the articles by myself. I thought about a m2m-field, but how can I choose some articles (inline in the edit-form of the object) and have the content-field filled with the needed information (like absolute_url or headline) immediately? Thanks for your help in advance.
Only option is AJAX. Setup a view that returns an article as JSON. Make the AJAX call to that view when user selects an article. Then, parse the returned JSON with and populate the text field with JavaScript.
views.py
from django.core import serializers
from django.http import HttpResponse
def json_get_article(request, article_id):
article = get_object_or_404(MyModel, id=article_id)
data = serializers.serialize("json", article)
return HttpResponse(data, mimetype='application/json')
script.js (using jQuery for simplicity)
$.getJSON('/my/ajax/url/', function (data, textStatus, jqXHR) {
$('#id_my_text_field').val(data[0]['field_containing_text'])
});
You'll obviously have to tweak that somewhat, but that's the basic process.
精彩评论