Plasma
Plasma

Reputation: 2439

How to populate a field in a django model

I have a Django project in which I have a view subclassed from the Django CreateView class. This view is used to upload a file to the server, and uses an UploadedFile model which I have created. The UploadedFile also needs to be associated with a project.

The project id is passed in as part of the URL: (r'^projects/(?P<proj_key>\d+)/$', UploadedFileCreateView.as_view(), {}, 'upload-new')

The problem is that I am not sure where the appropriate place is to associate this key with my model. Is there a method of CreateView or one of its ancestors that I should override that creates the model, or can this be done anywhere in my code in one of the methods I already override (this feels hacky though).

Furthermore, the project attribute of my UploadedFile is defined as a ForeignKey of type Project. How do I get the Project to associate with it?

Here is my model definition:

class Project(models.Model):
    """This is a project that is owned by a user and contains many UploadedFiles."""
    name = models.CharField(max_length=200)

class UploadedFile(models.Model):
    """This represents a file that has been uploaded to the server."""
    STATE_UPLOADED = 0
    STATE_ANNOTATED = 1
    STATE_PROCESSING = 2
    STATE_PROCESSED = 4
    STATES = (
        (STATE_UPLOADED, "Uploaded"),
        (STATE_ANNOTATED, "Annotated"),
        (STATE_PROCESSING, "Processing"),
        (STATE_PROCESSED, "Processed"),
    )

    status = models.SmallIntegerField(choices=STATES,
        default=0, blank=True, null=True) 
    file = models.FileField(upload_to=settings.XML_ROOT)
    project = models.ForeignKey(Project)

    def __unicode__(self):
        return self.file.name

    def name(self):
        return os.path.basename(self.file.name)

    def save(self, *args, **kwargs):
        if not self.status:
            self.status = self.STATE_UPLOADED
        super(UploadedFile, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        os.remove(self.file.path)
        self.file.delete(False)
        super(UploadedFile, self).delete(*args, **kwargs)

Here is my view definition:

class UploadedFileCreateView(CreateView):
    model = UploadedFile

    def form_valid(self, form):
        logger.critical("Inside form_valid")
        self.object = form.save()
        f = self.request.FILES.get('file')
        data = [{'name': f.name,
            'url': settings.MEDIA_URL + "files/" + f.name.replace(" ", "_"),
            'project': self.object.project.get().pk,
            'delete_url': reverse('fileupload:upload-delete',
                args=[self.object.id]),
            'delete_type': "DELETE"}]
        response = JSONResponse(data, {}, response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return super(UploadedFileCreateView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(UploadedFileCreateView, self).get_context_data(**kwargs)
        return context

Upvotes: 1

Views: 1968

Answers (1)

jproffitt
jproffitt

Reputation: 6355

You could do it right where you are calling form.save(). Just pass commit=False so that it won't save it to the db until you add the project id. For example:

self.object = form.save(commit=False)
self.object.project_id = self.kwargs['proj_key']
self.object.save()

Just make sure your form excludes the project field.

EDIT: to exclude the field, add an excludes variable to the form meta class:

class UploadedFileForm(forms.ModelForm):
    class Meta:
        model = UploadedFile
        excludes = ('project',)

Upvotes: 1

Related Questions