How to use Django build-in comment framework on any template - django

I just begin to study Django build-in comments function. at first I think the comment template should work well on any page just with get_comment_form or render_comment_form .but now it really annoying when i add these code to a ordinary page. It doesn't work. maybe in a other word. I don't know how to specify the object to attached to when it come to a normal page. below is the detail message :
models.py
class Entry(models.Model):
title = models.CharField(max_length=250)
body = models.TextField()
pub_date = models.DateTimeField()
enable_comments = models.BooleanField()
urls.py
urlpatterns = patterns('',
url(r'^profile/','django.views.generic.simple.direct_to_template',{
'template' : 'admin_ryu_blog/profile.html'},name='profile'),
)
now i just want to using comment framework on template profile.html. what should i do ? you could regard profile.html as a blank page now. then you can add any code you want if you can get a comment form displayed with build-in comment framework.
btw I have tried the below method :
{% load comments %}
{% render_comment_form for profile %}
then it prompt a error message. the same traceback on my previous question .
click here!

You can't. The comments framework expects an object to reference.
But an easy solution that comes to mind is building a model that maps to URLs like so:
class CommentAnchor(models.Model):
path = models.CharField(max_length=256)
Build a context processor that builds these objects and adds them to all template context . Remember to add your context processor to your settings.TEMPLATE_CONTEXT_PROCESSORS, and remember to use RequestContext when rendering templates.
def CommentAnchorProcessor(request):
comment_anchor, created = CommentAnchor.objects.get_or_create(path=request.path)
return {
'comment_anchor': comment_anchor, # now, this is available in every template.
}
Now you can render comments via these new objects.
{% render_comment_form for comment_anchor %}

Related

Django: defining a model to make a template

I am new to creating models in Django and I want to make a model, which allows you to fill in the title, some texts for on the template and the path to this template. I am trying to get the answer off of the Django Example Project, but I just don't understand the models, is there anybody who can help me on how to write such a model?
My code in the models.py
class Project(models.Model):
project_name = models.Charfield(max_length=20)
project_title = models.Charfield(max_length=100)
project_information = models.Charfield(max_length=400)
where project_name is the link to the template
I don't know if this is a correct begin or that it should be something completely different.
I'm assuming that you're asking ways to use the information in a model (object data) in a template.
If so, template isn't created in a model, you can send your object(s) to a template by rendering a template in the corresponding view of the model. You'll append the necessary information (queryset and other optional dict elements) in the view and send it to the template.
How you can use the information in the template depends on your view method. For function based views like this:
def home_view(request):
contests = Contests.objects.filter(id<5)
context={'contests':contests}
return render(request, 'home/home.html', context)
You can access the data in a queryset in the template, like this:
{% for contest in contests %}
//do something with the single contest data
{% endfor %}
You can directly access the non-plural values like this:
{% if not random_contest == None %}
//do something with the random contest data
{% endif %}
Additionally, there are class based views but it looks like you are at a very early stage of learning Django, so you won't need it for now.
See the docs about views.
See the docs about shortcut functions.

How to display multiple forms of a single model in Django templates?

I have this model Note:
class Note(models.Model):
category = models.ForeignKey(Category)
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=40)
text = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
And I want to display this form:
class NoteEditForm(forms.ModelForm):
class Meta:
model = Note
fields = ('title', 'text')
in a template, but I want it to appear for each existing Note object in the database (it has to be that way). I've done something like that but then I hardcoded the form, pointing to the edit view URL with each object pk as a parameter; but I'm sure it has to be a clearer way, just I haven't found it. Could you guys help me with that? Thanks!
The easiest way to do this is to use a formset (also see model formsets).
For your Note model and NoteEditForm you could do something like this. You'd usually put this wherever you've defined your NoteEditForm but it can go in another file, such as views.py.
from django.forms import modelformset_factory
NoteEditFormSet = modelformset_factory(Note, form=NoteEditForm)
Using NoteEditFormSet in a view and template is almost the same as using a regular form, but there are a few differences to be aware of if you want to do anything complicated so have a look at the docs (view and template). If that's not clear enough, add a few details of what you're trying to do in your view and template and I'll try to help.
By default the formset will use Note.objects.all() as its queryset, which is what you say you want, but you can change that (details are covered in the docs).
Update:
To save an individual Note with an AJAX request I would add a second view to handle those requests. So if your formset for all Notes is served by a view at /notes/, you could add a view to handle your AJAX request at /notes/<note_id>/ (obviously just an example, adjust to fit your URL structure).
Then your JS on the /notes/ page is responsible for serializing the data for a single note and making the request to /notes/<note_id>/ (remember the CSRF token).
The HTML inputs generated for the formset have their IDs prefixed with something like id_form-<number>- and there are hidden inputs containing Note primary keys which will let you work out which ID prefix applies to each note.
I would think about doing it like this
{% for note in Notequeryset %}
<form action={% url 'url_name_to_form' pk={{note.pk}} %}>
{{form.as_p}}
</form>
{% endfor %}
Let me know what you think

Django custom url structure

Is there any built-in or 3rd party app for custom styled urls?
I'd like to have custom urls such as:
example.com/article-type/article-name-2015-24-12
Where article-type would be a created from a foreign key and at the end of the url there would be the published date.
And in templates I'd call them using {% url 'article' article.pk %}. (So in the future when my boss decides to change the url structure I don't have to change it everywhere)
Is there anything like that? If not could anyone kick me to the right direction how to implement a such feature?
You could build the URL on the model, overriding the get_absolute_url() method.
Something like this
def Something(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField()
created = models.DateTimeField()
article_type = models.ForeignKey(ArticleTypes)
def get_absolute_url(self):
return '/{}/{}-{}-{}-{}'.format(
self.article_type, self.slug, self.created.year,
self.created.month, self.created.day)
And in the template, you'd use
{{ something.name }}

Displaying alert in the main template

In my application I have set up a main template, all other templates are an extension for it. The main template only includes static data.
Objective: I want an alert - small crimson bar at the top - to be displayed at all pages served by the app.
Current solution is to just write it in raw HTML in the main template.
My views are all set up as follows:
urls.py:
url(r'^exam/(?P<exam_id>[0-9]+)/$', views.exam, name='exam'),
url(r'^person/(?P<person_id>[0-9]+)/$', views.person, name='person'),
...
views.py:
def exam(request, exam_id):
exam = get_object_or_404(Exam, pk=exam_id)
return render(request, 'exam.html', {'exam': exam})
def person(request, person_id):
...
I.e. all are quite primitive and main_template itself is not mentioned anywhere except for in the templates themselves.
To make alert dynamic and configurable from django-admin, I am planning to:
Create a model for it:
Makes sense, since the alert might have some properties beyond base 'message content'
Somehow design and write a view that would populate the main template with dynamic content.
Question:
How do I refactor the views to reach the objective - make the main template dynamic - while breaking current views as little as possible?
My suggestions would be to create a model for storing your alert. The create an inclusion tag (check here). In this way you can add this tag to whichever template you want (possibly base.html create an alert block and use this tag inside that block). This will ensure that with minimal refactor of your code you'll get the feature you want following the best practice. Hope this helps .. :)
I assume that you want to have a small alert on your exams page.(exams.html)
Create a simple model,
class Alert(models.Model):
message = models.CharField(max_length=255, blank=False, null=False)
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
get_latest_by = "date_added"
In your current views.py,
def exam(request, exam_id):
exam = get_object_or_404(Exam, pk=exam_id)
alert = Alert.objects.latest() # Get latest alert message
# Pass alert object along with other variables.
return render(request, 'exam.html', {'exam': exam, 'alert': alert})
In your exams.html template
<div class='alert'>
<p>{{ alert.message }}</p>
</div>
Hope this helps.

Overiding placholders in django cms?

Hey im using the placeholder fields from django cms in some of my custom cms apps. Basically what im trying to achieve is specific styles and filters for the same placeholder fields being used in different templates.
for example if i have a model for vacancies that looks something like this:
from django.db import models
from cms.models.fields import PlaceholderField
# Create your models here.
class Vaccancy(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique = True)
ref_number = models.CharField(max_length=255)
info = PlaceholderField('info')
active = models.BooleanField(default=True, verbose_name="posistion active?")
and another model that also utilizes the placeholder field in a similar way. What i hoped i could do is overide the tex.html template then have some conditional logic to detect the name of the placeholder like so
{% ifequal placeholder "info" %}
{{ body|truncatewords:200|safe }}
{% endifequal %} the aim of this is so i can specify different filters like truncatewords etc as i dont want to apply this to every placeholder that uses a text plugin!
hope that was clear enough! cheers for any help!
If you use placeholder fields, you have to check for placeholder.slot, also note that {% if placeholder.slot == "info" %} seems a bit nicer than ifequal :D