1

Im building a customized comments app for django, using django comments itself. Ive followed https://docs.djangoproject.com/en/dev/ref/contrib/comments/custom/ to the letter, and I have 2 issues, one is that my custom comments instances do not give content_object.

So when I try the following I get nothing

c = CommentWithFile.object.get(id)=1 
c.content_object

And two, my comments are not taking the uploading the files I add within the form of the customized comments.

Another thing that I would like to do is to notify by mail, a list of specific users every time someone comments on an specific topic, but I would like to add to the notification a url or the title of the topic the comment was posted on, how could I do this?

My custom comment model.

def upload_path(instance, filename):
    return '/'.join(['uploads','comment_archives', filename])

class CommentWithFile(Comment):

    comment_file = models.FileField(max_length=255, upload_to=upload_path, 
        blank=True, null=True)
    notify = models.BooleanField(_("Notificar usuarios"))

    @property
    def fileobject(self):
        if self.comment_file:
            return FileObject(self.comment_file.path)
        return None

My custom model form

class CommentFormWithFile(CommentForm):
    comment_file = forms.FileField(label=_("Archivo"), required=False)
    notify = form.BooleanField(label=_("Notificar usuarios"))

    def get_comment_model(self):
        # Use our custom comment model instead of the built-in one.
        return CommentWithFile

    def get_comment_create_data(self):
        # Use the data of the superclass, and add in the title field
        data = super(CommentFormWithFile, self).get_comment_create_data()
        data['comment_file'] = self.cleaned_data['comment_file']
        data['notify'] = self.cleaned_data['notify']
        return data

And in the init.py

from apps.comments.models import CommentWithFile
from apps.comments.forms import CommentFormWithFile

def get_model():
    return CommentWithFile

def get_form():
    return CommentFormWithFile

The admin file for my commentwithfile

from apps.comments.models import CommentWithFile

class CommentWithFileAdmin(admin.ModelAdmin):
    pass

admin.site.register(CommentWithFile, CommentWithFileAdmin)

Im using django 1.3.1, and have django notifications in order to notify user of comments.

Thank you everyone!

==== UPDATE ====

Here is the comment form template

{% load comments i18n %}
<form action="{% comment_form_target %}" method="post">{% csrf_token %}
  {% if next %}<div><input type="hidden" name="next" value="{{ next }}" /></div>{% endif %}
  {% for field in form %}
    {% if field.is_hidden %}
      <div>{{ field }}</div>
    {% else %}
      {% if field.errors %}{{ field.errors }}{% endif %}
      <p
        {% if field.errors %} class="error"{% endif %}
        {% ifequal field.name "honeypot" %} style="display:none;"{% endifequal %}>
        {% if field.label == 'Comentario' or field.label == 'Archivo' %}
        {{ field }}
        {% endif %}
      </p>
    {% endif %}
  {% endfor %}

  <div class="actions">
    <input type="hidden" name="next" value="{{ request.path }}" />
    <input type="submit" name="post" class="submit-post" value="{% trans "Post" %}" />
    <input type="submit" name="preview" class="submit-preview" value="{% trans "Preview" %}" />
  </div>
</form>

An heres how I render this form in other templates

    {% get_comment_form for archive as form %}
    <h4>Comentar</h4>

    <div class="main_comment" id="comment_form">
        {% render_comment_form for archive %}
    </div>
jpic
  • 32,891
  • 5
  • 112
  • 113
maumercado
  • 1,453
  • 4
  • 23
  • 47
  • Can you post your templates and everything we could need to reproduce your case ? TYIA :) – jpic Feb 20 '12 at 17:50

1 Answers1

2

2 things are necessary for your system to work:

  1. The tag has an enctype attribute allowing file uploads, e.g. <form enctype="multipart/form-data" method="post" action="">, or the browser will not send the file

  2. The form is instanciated with both request.POST and request.FILES, e.g. form = form_class(request.POST, request.FILES). Else the FileField will not have any value.

So really what's missing from your topic are:

  1. The form HTML and

  2. The view python code, hint: make sure you inspect request.FILES there BTW

For me to make a perhaps more specific answer.

jpic
  • 32,891
  • 5
  • 112
  • 113
  • Hello I've tested adding the following to the form enctype="multipart/form-data, and still there is no uploading of the file... also why should I create a view for this comment, when all Im doing is customizing the django comments, by adding a new field to the model. – maumercado Feb 22 '12 at 21:26
  • What about point 2. ? "The form is instanciated with both request.POST and request.FILES, e.g. form = form_class(request.POST, request.FILES). Else the FileField will not have any value" https://docs.djangoproject.com/en/dev/topics/http/file-uploads/ – jpic Feb 23 '12 at 13:54
  • but where should I change this in case is not instatiated as such? I dont think it has to be done directly on the django code, what I see on the django.contrib.comments view code is this data = request.POST.copy() and then along the lines form = form = comments.get_form()(target, data=data) so aparently it uses the full request – maumercado Feb 23 '12 at 16:11
  • As you can see in django 1.3.1 django/forms/forms.py line 72, the BaseForm constructor takes such arguments: def __init__(self, data=None, files=None [snip]). data != files. When comments view migrate to class based, you will be able to just override the get_form method and pass request.FILES there. Until then you have to copy the view or make another one. Sorry :/ – jpic Feb 23 '12 at 17:15
  • Ummm I was expecting not to... Ill guess Il make a new one! – maumercado Feb 23 '12 at 23:53
  • So I got a copy of the view, all I had to do was to add this comment.comment_file = request.FILES.get("comment_file", None) below the line that says #otherwise create the comment, also had to change the utils import in the beggining of the file to this from django.contrib.comments.views.utils import next_redirect, confirmation_view... And now I found that to show files on a form preview is not possible yet on django! THANK YOU @jpic – maumercado Feb 24 '12 at 04:50
  • @maumercado I'm trying to do what you did. But I receive this error: Reverse for 'django.contrib.comments.views.utils.confirmed' with arguments '()' and keyword arguments '{}' not found. I have django 1.3.1 as well. Do you have any idea on how to fix this? Or why this happens? – elif Jun 04 '12 at 19:19
  • 1
    @elif Maybe you could check this out and see whats different in your app... but it seems that what you have is a URL Reverse problem from the template it seems to pass nothing to the url and the url seems to be formed to get a variable, still heres my comment app, hope it guides you! https://gist.github.com/226b0d08dc81ec5dd0f4 – maumercado Jun 04 '12 at 19:37
  • I found the error with the help of the code you sent. The error was in the urls. I didn't include a url for comment_done. I added these lines to urls.py: `url(r'^notes/post/$','selectra.note_comment.views.post_comment', name='comments-post-comment'), url(r'^notes/posted/$', 'selectra.note_comment.views.comment_done', name='comments-comment-done'), ` – elif Jul 12 '12 at 15:59
  • @maumercado I added the line form.files = request.FILES under form = comments.get_form()(target, data=data) in the post_comment view. And removed comment.comment_file = request.FILES.get("comment_file", None). I did this because I needed to do some validation for the filename. I thought this will also solve your preview problem but I later found out that this is not possible for security reasons: http://stackoverflow.com/questions/3680603/does-django-repopulate-file-fields-on-form-error So it will probably never be possible. – elif Jul 18 '12 at 10:11
  • @elif great to know you got it working... oh and about the preview stuff its a bad thing that you cannot preview a comment with a file... yet you can review the filename and send some kind of message to the user, but the user has to submit the comment instead of just previewing... and then resend the file after fixing its name or something! – maumercado Jul 24 '12 at 01:58
  • @elif what I did in order to fix the filename thing is slugify the filename, so that the linux server my webapp is in does not have any problem getting the file. – maumercado Jul 24 '12 at 01:59