2013-04-03 45 views
0

我有以下模型,我需要創建一個允許更新現有響應的表單(以前用slug生成,然後通過電子郵件發送給答覆者)以及創建Rating對於CV.objects.all()中的每個CV。 Django中最簡單的方法是什麼?目前我有一個基於類的UpdateView for Response,就是這樣。將基於類的UpdateView擴展到速率對象

class Response(models.Model): 
    first_name = models.CharField(max_length=200, null=True, blank=True) 
    last_name = models.CharField(max_length=200, null=True, blank=True) 
    email = models.EmailField(max_length=254) 
    slug = models.SlugField(max_length=32) 
    submited = models.BooleanField(default=False) 
    submit_time = models.DateTimeField(null=True, blank=True) 
    creation_time = models.DateTimeField(auto_now_add=True) 


class CV(models.Model): 
    title = models.CharField(max_length=200) 
    image = models.ImageField(upload_to=content_file_name) 


class Rating(models.Model): 
    cid = models.ForeignKey('CV') 
    rid = models.ForeignKey('Response') 
    score = models.IntegerField() 
    comment = models.TextField() 

回答

0

我終於搞清楚瞭如何做到這一點。我的代碼如下,以防有人感興趣。

def add_response(request): 
    CVs = CV.objects.all() 
    if request.method == "POST": 
     ResForm = ResponseForm(request.POST, instance=Response()) 
     RatForms = [RatingForm(request.POST, prefix=str(cv.id), instance=Rating(cid=cv)) for cv in CVs] 
     if ResForm.is_valid() and all([rf.is_valid() for rf in RatForms]): 
      new_response = ResForm.save(commit=False) 
      new_response.submit_time = datetime.now() 
      new_response.submited = True 
      new_response.save() 
      for rf in RatForms: 
       new_rating = rf.save(commit=False) 
       new_rating.rid = new_response 
       new_rating.save() 
      return HttpResponseRedirect('/thanks/') 
     else: 
      for i, _ in enumerate(RatForms): 
       RatForms[i].cv = CV.objects.filter(id=int(RatForms[i].prefix))[0] 
       print RatForms[i].cv 
      return render(request, 'response.html', {'response_form': ResForm, 'rating_forms': RatForms}) 
    else: 
     ResForm = ResponseForm(instance=Response()) 
     RatForms = [RatingForm(prefix=str(cv.id), instance=Rating(cid=cv)) for cv in CVs] 

     for i, _ in enumerate(RatForms): 
      RatForms[i].cv = CV.objects.filter(id=int(RatForms[i].prefix))[0] 
      print RatForms[i].cv 

     return render(request, 'response.html', {'response_form': ResForm, 'rating_forms': RatForms})