ss7
ss7

Reputation: 3012

Django Uploading Files

I have a dashboard where you upload files and can see the files you uploaded. Strangely enough, when you go to upload a second file, it uploads but gives the error: IntegrityError at /dashboard/ column client_id is not unique I'm not sure why. My database is fresh and clean. What would cause this? The first file uploads and displays correctly redirecting you to the dashboard. The second file uploads, but doesn't display in the file list and displays that error. Any ideas why this is occurring or how to fix this error? I'm really stuck here so any help would save me big time.

Here is the view:

@login_required(login_url='/dashboard-login/')
def dashboard(request):
    current_user = request.user
    current_client = request.user.client

    files = ClientUpload.objects.filter(client=current_client)
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = ClientUpload(client=current_client, file_upload = request.FILES['file_upload'])
            new_file.save()

        return HttpResponsePermanentRedirect('/dashboard/')
    else:
        form = UploadFileForm()

    data = {'form': form, 'client': current_client, 'files': files}
    return render_to_response('dashboard.html', data, context_instance=RequestContext(request))

The models:

@python_2_unicode_compatible
class Client(models.Model):
    user = models.OneToOneField(User)
    company = models.CharField(max_length=100)

    def __str__(self):
        return self.company

    class Meta:
        verbose_name_plural = _("Clients")
        verbose_name = _("Client")
        permissions = (
            ("can_upload", _("Can upload files.")),
            ("can_access_uploads", _("Can access upload dashboard.")),
            ("is_client", _("Is a client.")),
        )

def generate_filename(self, filename):
    name = "uploads/%s/%s" % (self.client.company, filename)
    return name

@python_2_unicode_compatible
class ClientUpload(models.Model):

    client = models.OneToOneField(Client)
    created_at = models.DateTimeField(auto_now_add=True)

    file_upload = models.FileField(upload_to=generate_filename)

    def __str__(self):
        return self.client.company

    class Meta:
        verbose_name_plural = _("Client Uploads")
        verbose_name = _("Client Upload")

The form:

class UploadFileForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.add_input(Submit(_('submit'), _('Submit')))
        super(UploadFileForm, self).__init__(*args, **kwargs)

    class Meta:
        model = ClientUpload
        fields = ('file_upload',)

And lastly, the templates:

Upload file:

{% load i18n %}
{% load crispy_forms_tags %}
{% crispy form %}

File list:

{% load i18n %}

<table class="table">
<tr>
    <th>{% blocktrans %}Filename{% endblocktrans %}</th>
    <th>{% blocktrans %}Size{% endblocktrans %}</th>
    <th>{% blocktrans %}Upload Time{% endblocktrans %}</th>
</tr>
{% for file in files %}
    {% with uploaded_file=file.file_upload %}  
 <tr>
    <th><a href='{{ uploaded_file.url }}'>{{ uploaded_file.name }}</a></th>
    <th>{{ uploaded_file.size }}</th>
    <th>Uploaded At</th>
    {% endwith %}
{% endfor %}
</tr>
</table>

And the one that ties them together, dashboard:

{% extends "base.html" %}
{% load i18n %}

{% block title %}Shenkan &amp; Associates - {% trans 'Dashboard' %}{% endblock title %}

{% block css %}
    {{ block.super }}
{% endblock css %}

{% block extra_css %}
{% endblock extra_css %}

{% block ie_shim %}
    {{ block.super }}
{% endblock ie_shim %}

{% block header %}
    {{ block.super }}
{% endblock header %}

{% block slider %}
{% endblock slider %}

{% block page_header %}{% endblock page_header %}

{% block content %}
    <!--=== Content ===-->
    <a href="{% url 'dashboard-logout' %}">{% trans 'Logout' %}</a>
    <div class="container content-md">
    {% include "upload_file.html" %}
    </div>
    <div class="container content-md">
    {% include "file_list.html" %}      
    </div>
    <!--=== End Content ===-->
{% endblock content %}

{% block footer %}
    {{ block.super }}
{% endblock footer %}

{% block js %}
    {{ block.super }}
{% endblock js  %}

{% block ie_js %}
    {{ block.super }}
{% endblock ie_js %}

{% block extra_js %}
{% endblock extra_js %}

You don't need to see base.html obviously.

If someone could help me solve this mystery it would help a ton as I am having tons of problems with this and have been stuck for days.

Thanks a bunch.

Upvotes: 1

Views: 215

Answers (1)

Javier Clavero
Javier Clavero

Reputation: 447

I think you should use "get_or_create" in the views.

I hope this can help: get_or_create throws Integrity Error

Upvotes: 1

Related Questions