0

I am a beginner Django user and have been stuck with this problem for weeks now.

Consider the following model

class Post(models.Model):
    title = models.CharField(max_length=65)
    author = models.ForeignKey(User)
    date = models.DateField(auto_now_add=True)
    content = models.TextField()
    tags = models.ManyToManyField(Tag)
    images = models.ManyToManyField(Image)

def __unicode__(self):
    return self.title

I would like the User to be able to upload pictures to the with his model. I would like to be able to validate if

  1. The user has at least uploaded one image and limit the maximum number of images to a certain number.

  2. Basically do the same for tags. But with tags I would also like Django to check if the tags already exists and if so add it to the model.

  3. Let the user push a button that says add Tag / add Image to make a new field pop up.

Problems I have encountered so far.

  1. I am required to save a model before I can add many to many relations. This is a bit annoying because if an error occurs halfway down the road is might be possible that half the model is saved and the other is invalid.

  2. I know that I can add extra field to the DOM using js however I got no clue how to process those in the View function.

4

1 回答 1

1

对于问题 1,这是有道理的,因为如果您创建一个由其他模型引用的模型,则该模型键必须存在。我建议您做的是研究使用事务保存多个模型

2 非常简单,只需使用 jQuery/Javascript 根据用户的选择事件在浏览器中显示/隐藏相应的字段。

根据您的评论,这是我如何处理进出服务器的数据的示例

//Submit data to server, assuming you have already extracted out the relevant data values
$("some_button").click(function(e){
  $.ajax({
    url : "someUURLLocation/",
    type : "POST",
    data : {"data" : JSON.stringify({"field1" : var1, "field2" :var2}),
    dataType : "json",
    success : function(results){
      if (results.success == "true") {
        //handle DOM insertion and other stuff
      } else 
        alert(results.message);
    }
  });
}

网址.py:

from django.conf.urls import patterns, url
from $APPNAME import views

urlpatterns = patterns("",
  ...
  ...
  url(r'^someURLLocation/$', views.handleDataSubmission),
  ...
)

视图.py:

from django.http import HttpResponse
from django.utils import simplejson

def handleDataSubmission(request):
  data = simplejson.loads(request.POST.get("data", None))

  if data is not None:

    newPost = Post.objects.create( field1 = data["field1"], field2 = data["field2"])
    dataReturn  = [{"val1" : newPost.title, "val2" : newPost.date}]

    return HttpResponse(simplejson.dumps({"success" : "true", "data" : dataReturn}), mimetype = "application/json")

  else:
    return HttpResponse(simplejson.dumps({"success" : "false", "message" : "Invalid data received by server"}), mimetype = "application/json")
于 2013-08-21T13:09:57.730 回答