用户从图像列表中选择的Python / Django表单

时间:2015-08-11 17:24:20

标签: python django django-userena

我是django的新手,想要制作一个允许用户使用单选框选择三个图像中的一个的表单,一旦用户选择了保存到他们的个人资料并显示在他们的个人资料页面上的图像。

我正在使用: django 1.8.3 userena 1.4.1

任何帮助或指向文档的链接都会很有用。

2 个答案:

答案 0 :(得分:1)

如果图像集很小且固定,最好的选择是在定义模型中图像的字段中使用choice attribute

图像字段可以是文件系统上图像文件的路径。

class UserProfile(models.Model):
    GOOD = 'Good.jpg'
    UGLY = 'Ugly.jpg'
    BAD = 'Bad.jpg'
    AVATAR_CHOICES = (
        (GOOD, 'Good'),
        (UGLY, 'Ugly'),
        (BAD, 'Bad'),
    )
    avatar_img = models.CharField(max_length=255,
                                  choices=AVATAR_CHOICES,
                                  default=GOOD)

另一种选择是使用FilePathField as your model field

FilePathField(path="/path/to/avatar_images", match="*.jpg", recursive=False)

另一种方法是在实例化表单时动态填充表单字段。 有关详情,请参阅此SO QA

然而,正如Django文档所说

  

但如果你发现你自己选择了动态的选择,你就是   最好使用带有ForeignKey的正确数据库表

要指定用于表单字段的Radiobuttons,请参阅official docs有关如何设置正确的小部件的信息。

答案 1 :(得分:1)

基本示例。机型:

def get_upload(instance, filename):
    return "uploaded_files/user_%s_%s_%s" % (instance.user, datetime.datetime.today().strftime("%d-%m-%Y %H-%M-%S"), filename)

class UserModel():
    # your fields
    image = models.FileField(upload_to=get_upload, default='')

FileField

形式:

class UploadForm(forms.ModelForm):
    """Auxiliary class to make file uploading more convenient."""
    def __init__(self, *args, **kwargs):
        super(UploadForm, self).__init__(*args, **kwargs)

    class Meta:
        model = UserModel
        fields = ('image')

查看:

def upload(request):
    if request.method == "POST":
        profile = request.user.profile
        image_type = request.POST.get("image_type", None)
        if image_type == "blah":
            profile.image = request.FILES[image_type]
        else:
            return HttpResponse("Error")
        request.user.profile.save()
        return HttpResponse('OK')

request.FILES

JS与soem Jquery:

var SIZE_RESTRICT = 10*1024*1024;       //10 Mbytes

$(document).ready(function()
{
    $(".upload_file").find(".upload_button").click(send_file);
    $(".upload_file").find(".upload_file_form").find("input[type='file']").click(enable_upload);
});

function send_file()
{
    if ($(this).attr("enabled") != "true") return;
    // Prevent double-triple clicks with multiple upload.
    $(this).attr("enabled", "false");
    var form = $(this).parent().find(".upload_file_form").get(0);
    var formData = new FormData(form);
    var file = $(form).find("input[type='file']").get(0).files[0];
    // Not sure about this
    // Prevent attack with HUGE files, that will smash server memory
    // TODO: Restrict file types (Ex. MIME-image, pdf, doc)
    if (file.size > SIZE_RESTRICT)
    {
        alert("File is too big.");
        return;
    }
    formData.append("proof_type", $(this).attr("upload-type"));
    var xhr = new XMLHttpRequest();
    var that = this;
    // TODO: Define another events like error, abort
    xhr.upload.onprogress = function(e) {
        // TODO: Progressbar as e.loaded / e.total
        if (e.lengthComputable)
            console.log((e.loaded / e.total) * 100);
        else
            console.log("Cant count length");
      };

    xhr.onload = function(e){
          // TODO: Show success confirmation to user.
        if (this.response == "Success")
        {
            // pass
            alert(this.response);
        }
        else if (this.response == "Error")
        {
            // pass
            alert(this.response);
        }
        else
        {
            // pass
        }
      };

    xhr.open('POST', '/upload_proof');
    xhr.send(formData);
}

function enable_upload()
{
    $(this).parent().parent().find(".upload_button").attr("enabled", "true");
}

实际上,另一个简单的例子可以在docs

中建立