django image upload forms

Posted by gramware on Stack Overflow See other posts from Stack Overflow or by gramware
Published on 2010-03-21T15:10:29Z Indexed on 2010/03/21 15:11 UTC
Read the original article Hit count: 455

Filed under:

I am having problems with django forms and image uploads. I have googled, read the documentations and even questions ere, but cant figure out the issue. Here are my files

my models

class UserProfile(User):
    """user with app settings. """
    DESIGNATION_CHOICES=(
    ('ADM', 'Administrator'),
    ('OFF', 'Club Official'),
    ('MEM', 'Ordinary Member'),
    )
    onames = models.CharField(max_length=30, blank=True)
    phoneNumber = models.CharField(max_length=15)
    regNo = models.CharField(max_length=15)
    designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES)
    image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True)
    course = models.CharField(max_length=30, blank=True, null=True)
    timezone = models.CharField(max_length=50, default='Africa/Nairobi')
    smsCom = models.BooleanField()
    mailCom = models.BooleanField()
    fbCom = models.BooleanField()

    objects = UserManager()

    #def __unicode__(self):
    #   return '%s %s ' % (User.Username, User.is_staff)


    def get_absolute_url(self):
        return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id)

    def get_download_url(self):
        return u'%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name)

...

class reports(models.Model):
    repID = models.AutoField(primary_key=True)
    repSubject = models.CharField(max_length=100)
    repRecepients = models.ManyToManyField(UserProfile)
    repPoster = models.ForeignKey(UserProfile,related_name='repposter')
    repDescription = models.TextField()  
    repPubAccess = models.BooleanField()
    repDate = models.DateField()
    report = models.FileField(max_length=200,upload_to='files/%Y/%m/%d' )
    deleted = models.BooleanField()

    def __unicode__(self):
        return u'%s ' % (self.repSubject)

my forms

from django import forms
from django.http import HttpResponse
from cms.models import *
from django.contrib.sessions.models import Session
from django.forms.extras.widgets import SelectDateWidget

class UserProfileForm(forms.ModelForm):
        class Meta:
        model= UserProfile
        exclude = ('designation','password','is_staff', 'is_active','is_superuser','last_login','date_joined','user_permissions','groups')

...

class reportsForm(forms.ModelForm):
    repPoster = forms.ModelChoiceField(queryset=UserProfile.objects.all(), widget=forms.HiddenInput())
    repDescription = forms.CharField(widget=forms.Textarea(attrs={'cols':'50', 'rows':'5'}),label='Enter Report Description here')
    repDate = forms.DateField(widget=SelectDateWidget())
    class Meta:
        model = reports
        exclude = ('deleted')

my views

@login_required
def reports_media(request):
    user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
    if request.user.is_staff== True:
        repmedform = reportsForm(request.POST, request.FILES)
        if repmedform.is_valid():
            repmedform.save()
            repmedform = reportsForm(initial = {'repPoster':user.id,})

       else:
            repmedform = reportsForm(initial = {'repPoster':user.id,})
       return render_to_response('staffrepmedia.html', {'repfrm':repmedform, 'rep_media': reports.objects.all()})

    else:

        return render_to_response('reports_&_media.html', {'rep_media': reports.objects.all()})

...

@login_required
def settingchng(request):

user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
    form = UserProfileForm(instance = user)
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES, instance = user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/settings/')

    else:
        form = UserProfileForm(instance = user)

    if request.user.is_staff== True:    
        return render_to_response('staffsettingschange.html', {'form': form})   
    else:
        return render_to_response('settingschange.html', {'form': form})    

...

@login_required 
def useradd(request):

    if request.method == 'POST':

        form = UserAddForm(request.POST,request.FILES )

        if form.is_valid():
            password = request.POST['password']
            request.POST['password'] = set_password(password)
            form.save()

    else:
        form = UserAddForm()

    return render_to_response('staffadduser.html', {'form':form})

Example of my templates

{% if form.errors %}
 <ol>
    {% for field in form %}
      <H3 class="title">
      <p class="error"> {% if field.errors %}<li>{{ field.errors|striptags }}</li>{% endif %}</p>
      </H3>
    {% endfor %}
</ol>
  {% endif %} 
 <form method="post" id="form" action="" enctype="multipart/form-data" class="infotabs accfrm">
    {{ repfrm.as_p }}
   <input type="submit" value="Submit" />
</form> 

© Stack Overflow or respective owner

Related posts about django-forms