def edit(request, adId):
  # get the specified ad, only if it's not active and this user owns it.
  ad = get_object_or_404(Ad, pk=adId, active=False, user=request.user)
  
  image_count = ad.category.images_max_count
  ImageUploadFormSet = inlineformset_factory(Ad, AdImage, extra=image_count, max_num=image_count, fields=('full_photo',))
  # enforce max width & height on images
  ImageUploadFormSet.clean = clean_adimageformset
  
  if request.method == 'POST':
    imagesformset = ImageUploadFormSet(request.POST, request.FILES, instance=ad)
    form = AdForm(ad, request.POST)
    if form.is_valid():# and imagesformset.is_valid():
      ad = form.save()
      if imagesformset.is_valid():
        imagesformset.save()
        for image in ad.adimage_set.all():
          image.resize()
          image.generate_thumbnail()
        
        return HttpResponseRedirect(reverse('classifieds.views.create.preview', args=[ad.pk]))
  else:
    imagesformset = ImageUploadFormSet(instance=ad)
    form = AdForm(ad)
  
  return render_category_page(request, ad.category, 'edit.html',
                              {'form': form, 
                               'imagesformset': imagesformset, 
                               'ad': ad, 
                               'create': True})
def edit(request, adId):
  # find the ad, if available
  ad = get_object_or_404(Ad, pk=adId, active=True)
  
  # make sure that only the owner of the ad can edit it
  if request.user != ad.user:
    return HttpResponseRedirect('%s?%s=%s' % (django_settings.LOGIN_URL, REDIRECT_FIELD_NAME, urlquote(request.get_full_path())))

  image_count = ad.category.images_max_count
  ImageUploadFormSet = inlineformset_factory(Ad, AdImage, extra=image_count, max_num=image_count, fields=('full_photo',))
  # enforce max width & height on images
  ImageUploadFormSet.clean = clean_adimageformset
  
  if request.method == 'POST':
    imagesformset = ImageUploadFormSet(request.POST, request.FILES, instance=ad)
    form = AdForm(ad, request.POST)
    if form.is_valid() and imagesformset.is_valid():
      form.save()
      imagesformset.save()
      for image in ad.adimage_set.all():
        image.resize()
        image.generate_thumbnail()
      return HttpResponseRedirect(reverse('classifieds.views.mine'))
  else:
    imagesformset = ImageUploadFormSet(request.POST, request.FILES, instance=ad)
    form = AdForm(ad)
  
  return render_category_page(request, ad.category, 'edit.html',
                              {'form': form, 
                               'imagesformset': imagesformset, 
                               'ad': ad})