I created a blog with Django and my model post is like this:
class Post(models.Model):
title = models.CharField(max_length=255, unique=True, db_index=True)
content = RichTextField()
# ...
In my template, I display the content of posts like this: {{ post.content|safe }}
What I want is to execute code that is in the content of the post. Let say I want to add a link to the "about me" page, so logically I would add this in the content of the post:
# some text here
about me
# another text here
This doesn't work. if I hover the URL I can see the URL 127.0.0.1:8000/post/21/{% url 'about' %}.
How can I do that.
Edit
Actually, to redirect to the about me page I can simply do about me
But what if I want to redirect to another post? I have to specify the id or the slug of the post but I can't do:
post
"|safe" filter renders only html code.
To render django template from db you should use render or render_to_string in your view. But note that this is an extremely insecure practice cause to many contexts are available to get and execute in django template language
Related
I have a simple snippet using Django Wagtail. I would like to be able to update the logo from a "CreateView" but when it renders in my view it's expecting a foreign key. I would imagine it would be easy to create a from to do this but it's not.
#register_snippet
class MerchantSnippet(models.Model):
name = models.CharField(max_length=255, blank=False, null=False, unique=True)
logo = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
)
def __str__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
panels =[
FieldPanel('name'),
ImageChooserPanel('logo'),
]
edit_handler = TabbedInterface([
ObjectList(panels, heading='Content'),
])
class ProductCreateView(CreateView):
model = ProductSnippet
fields = ['name','logo']
class ProductUpdateView(UpdateView):
model = ProductSnippet
fields = ['name','logo']
When I use the default example in the template I ended up just getting a drop down.
{% render_field field class+="form-control" %}
How would I be able to see an image preview in the event I am updating the snippet and the ability to upload a different one . In the event I am creating a new item the ability to select an upload an image.
The logo field is a foreign key and points to Wagtail Image. Therefore it is a select. If you change the logo field to a ImageField you probably have the behaviour you desire. However, uploaded logos will not appear in the Wagtail Images. That ain't a bad thing. Whenever you want to display a logo, you'd just use the ​Merchant snippet.
If storing the logo as a Wagtail Image is a must, there are two alternatives:
Alternative 1: Custom form
CreateView and UpdateView are Django generic views and inherit the FormMixin. This means you can specify a custom form_class. Create a custom form with a logo = ImageField(...) and on submit, handle the image data, create a Wagtail Image, and store the Wagtail Image pk on the snippet.
Alternative 2: Multiple forms
Django can handle multiple forms inside a single form tag with a prefix to avoid field name collisions. So you can present both the snippet and the Wagtail image within the same view.
Note: #register_snippet is needed for Wagtail to display CRUD views and enable the snippet chooser in the Wagtail admin interface. But a snippet is a regular Django model. Wagtail Image is a regular Django model too. Forms and generic views are also pure Django concepts. If you dive into this some more, leave Wagtail out of your search queries.
I have a personal blog written with Django. I want to make my social links/usernames dynamic so I can change them whenever I want.
I'm doing this with charfields. I'm adding new charfield for each social username/link field then my template's getting these usernames to show them in a tags. It's okay but I think it's not the easiest way.
Am I wrong or there is a better way to do this?
Maybe it would be easier to create a model for it. That way you would be able to add/remove social links without having to touch the code.
from django.conf import settings
from django.db import models
class SocialProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='social_profiles')
network = models.CharField(max_length=100)
username = models.CharField(max_length=100)
url = models.URLField(max_length=500)
Then if you are using Django Admin, you could add this model as a TabularInline of the User model for example.
In your templates you could render the links dynamically:
{% for profile in request.user.social_profiles.all %}
{{ profile.username }}
{% endfor %}
Something like that.
I have 4 models: Blogger, User, Post and Comment.
Here is the blogger model.
class Blogger(models.Model):
username = models.OneToOneField(User, related_name='bloggers')
blogger_bio = models.CharField(max_length=1000)
Now, I want to display username and blogger_bio depending to the URL.
For example, is someone is using: /testuser, the template will filter username and blogger_bio of only user named testuser.
How to filter this Dynamically?
Use URL dispatcher in django to pass the username to your views. You can render the response template as you wish through views. Try it and post if there are any issues.
https://docs.djangoproject.com/en/1.8/topics/http/urls/
I'm a newbie for program and study django now. I have one question.
example:
my product title: classic photo frame
my url: url(r'^(.+)/$', products, name='products'),
I open through url with www.xxx.com/classic photo frame/
it works,but the this url has space, I know it's not correct.
I add - to parameter,such as classic-photo-frame. It works too.
But this way, - will show in front-end page.
How can I resolve?
url shows /classic-photo-frame but the front-end page is classic photo frame
Thank you.
the best way use SlugField .
For more information check this link. https://docs.djangoproject.com/en/1.10/ref/models/fields/#slugfield
and you can add this line prepopulated_fields = {'slug': ('title',), } to your custom django admin class for auto generate slug in admin.
after this you can use slug in your urls
I have a portfolio application that lists projects and their detail pages. Every project generally has the same information (gallery, about etc. ), but sometimes the user might want to add extra information for a particularly large project, maybe an extra page about the funding of that page for example.
Would it be possible to create an overwritten flatpages model within my portfolio app that forces any flatpages created within that application to always begin with /portfolio/project-name/flat-page. I could then simply pass the links to those flatpages associated with the project to the template so any flatpage the user generates will automatically be linked to from the project page.
EDIT
I have it somewhat working now
So I overwrite the FlatPage model in my portfolio app as described:
from django.contrib.flatpages.models import FlatPage
from project import Project
from django.db import models
from django.contrib.sites.models import Site
class ProjectFlatPage(FlatPage):
prefix = models.CharField(max_length=100)
project = models.ForeignKey(Project)
which allows me to associate this flatpage with a particular project,
Then I overwrite the save method to write all the extra information when a user saves (needs to be tidied up):
def save(self, force_insert=False, force_update=False):
self.url = u"%s%s/" % (self.project.get_absolute_url(),self.prefix)
self.enable_comments = False
self.registration_required = False
self.template_name = 'project/project_flatpage.html'
super(FlatPage, self).save(force_insert, force_update)
and I scaleback the admin to just allow the important stuff:
class ProjectFlatPageForm(forms.ModelForm):
prefix = forms.RegexField(label=_("Prefix"), max_length=100, regex=r'^[a-z0-9-]+$'),
class Meta:
model = ProjectFlatPage
class ProjectnFlatPageAdmin(admin.ModelAdmin):
form = ProjectFlatPageForm
so now the user can add a flat page inside my app and associate it with a particular project.
In the admin, they just enter a slug for the page and it automatically gets appended through the save() method like: /projects/project-name/flat-page-name/
The remaining problem is on the template end. I can access the normal flatpage information through the given template tags {{ flatpage.title }} and {{ flatpage.content }} put I have no access to the extra fields of the inherited model (i.e. the project field)
Is there anyway around this?
EDIT2
Having thought about it, the easiest way is to write a template tag to find the projectFlatPage associated with the flatpage and get access to it from there. A bit like overwritting the default flatpages template tags
re the 'Edit 2' part of your question... since your custom flatpage model inherits from FlatPage there is an automatic one-to-one field relation created between them by Django.
So in your template, if you know that the flatpage object passed in is one of your customised ones you can access your extra attributes by:
{{ flatpage.projectflatpage.project }}
Of course. Just write your own flatpage-model, for example:
from django.contrib.flatpages.models import FlatPage
class MyFlatPage(FlatPage):
prefix = models.CharField(max_length=100, editable=False)
url = models.CharField(_('URL'), max_length=100, db_index=True, editable=False)
Then add a proper MyFlatPageAdmin to your admin.py file (if you want to, you can import the flatpageadmin from django.contrib.flatpages.admin and inherit from it). After all, you're using the flatpage-model, but overwrite the urls-field. Now add a signal, which concats the prefix and a automatically generated url suffix to the url (like the object id). You can now add the custom flatpage like:
flatpage = MyFlatPage(prefix='/portfolio/my-super-project/')
Everything clear now?
edit 1
As you can read in the documentation, every flatpage should be a projectflatpage and vice versa.