开发者

What is the best (=easiest) way to populate django-textfield with values from other models in the admin-interface?

开发者 https://www.devze.com 2023-03-12 21:27 出处:网络
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 abstra

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号