In my django admin I have a database column with different urls in each row. These urls are displayed as simple texts and not as link. How can I make them links so that they redirect the user to the url when they click on it.
Set allow_tags on the method on the model to true:
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
color_code = models.CharField(max_length=6)
def colored_name(self):
return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
colored_name.allow_tags = True
from the django documentation.
If you have access to your templates:
If the contents of the field are something like:
http://www.google.com
You could output this in your template to make them clickable:
{{ field }}
If not:
I think this Stacko question is similar: How to add clickable links to a field in Django admin?
Related
I hope the title of this question is as it should be based on this explanation below.
I have a model as below:
class Setting(models.Model):
TYPE_CHOICES = (
('CONFIG', 'Config'),
('PREFS', 'Prefs'),
)
attribute = models.CharField(max_length=100, unique=True)
value = models.CharField(max_length=200)
description = models.CharField(max_length=300)
type = models.CharField(max_length=30, choices=TYPE_CHOICES)
is_active = models.BooleanField(_('Active'), default=True)
I use this to save settings. I have don't know all settings in advance and they can change in future. So I decided to save attributes and their values in this model instead of creating columns for each setting(attribute in the model).
Now the problem I am facing is how do I present form with all attributes as fields so that a user can fill in appropriate values.
Right now, as you can see, form shows columns 'Attribute' and "Value" as labels. I would like it to show value of column 'Attribute' as label and column 'Value' as field input.
For example, in Setting model I have this:
Attribute ------------ Value
'Accept Cash' ---------- 'No'
I would like to appear this on form as
<Label>: <Input>
'Accept Cash': 'No'
I think I will have to build form fields from the database(Setting model). I am new to this and have no idea how to begin with it any example or link to tutorial that would help me get started will be much appreciated.
Thank you
you can define a model form based on your Settings model. Check the django documentation on Django Model Forms. The basic definition of the model form should be something like this
Define a forms.py file in your current django app and put the following code in it.
from django import forms
from .models import Settings
class SettingsForm(forms.ModelForm):
class Meta:
model = Settings
fields = ['the fields you want to add'] # or use '__all__' without the parentheses for all fields
Then in your views.py file navigate to the function which renders the page containing the form and add this to it
from .forms import SettingsForm
def your_function(request):
....
context = {
....
'form':SettingsForm()
}
return render(request, 'template_name.html', context)
Now in your template add the form using
........
{{ form }}
.......
I'm new to django and using crispy-forms to render the form.How do i add placeholder text to a field e.g "please enter your address"
In my views.py
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['name', 'address']
In models.py
class Post(models.Model):
name = models.CharField(max_length=100, blank="true")
address = models.CharField(max_length=100, blank="true")
Every input field is Given an id by django; get the ids from inspect -- In the Html file and add a script tag some where and
Then use this JS code
document.getElementbyId('id of the field').setAtribute('placeholder','Your PH')
Btw use google for spelling errors and soory for them
I've added photologue to my project, because it does 99% of the things I was trying to achieve by myself.
Now I need to connect the uploaded images and images in galleries to my posts. This is why I've added a ManyToMany field to the photologue Photo model
Class ImageModel(models.Model):
post_images = models.ManyToManyField(Post, blank=True)
And will do the same to the Gallery model
class Gallery(models.Model):
post_gallery = models.ManyToManyField(Post, blank=True)
Now my idea is to be able to add a gallery and/or specific images to my post . Both options should be available.
The queryset I would like to have is to get all the individual images, that are attached to the post and also all the images in the gallery if a gallery is attached. Then to pass and render them to the page in some sort of gallery (Slider, carousel or something else).
I'd like to be able to get them in the template with one for loop, so I think the queryset have to be one.
I have a view that renders the specific page type and I don't know if I should include the queryset and context in this function or to create a new one for the images. And how to do it.
def post(request, slug):
post = get_object_or_404(Post, post_slug=slug)
context = {
'post': post,
}
return render(request, 'project_name/post.html', context)
I hope I have explained what I'd like to do. Django is new to me and querysets are still a bit complex.
Shouldn't you try adding galleriesto posts from posts?
from photologue.models import Gallery
class Post(models.Model):
gallery = models.ManyToManyField(Gallery, blank=True )
#Edit ___
#TwinDewey In this case you need to make a query in Views to get the Galleries when showing Post details.
galleries = gallery.posts.all()
gal = []
for excercise in excercises:
gal.append(Gallery.objects.filter(gallery__name=self.post.title))
Or you can make a query and merge it with the Post context using
from itertools import chain
list(chain(post_context,Gallery.objects.filter(gallery__name=self.post.title)))
That´s for gallery. Posts would have another query.
You can use union to group the photos tied to the post itself and inside the gallery. The trick is to get the right models so they are the same objects:
from django.db import models
from photologue.models import Gallery, Photo
class Post(models.Model):
title = models.CharField(max_length=100)
published_at = models.DateTimeField(blank=True, null=True)
text = models.TextField()
photos = models.ManyToManyField(Photo, related_name='posts')
galleries = models.ManyToManyField(Gallery, related_name='posts')
#property
def all_images(self):
# Create a number of querysets that have photos from selected galleries
# ..note:
# .only() is used to trim down on the fields fetched from the database.
# .prefetch_related() is used to eliminate extra queries during iteration
qs = []
for gallery in self.galleries.prefetch_related('photos').only('photos'): # type: Gallery
qs.append(gallery.photos.only('image', 'title'))
return self.photos.only('image', 'title').union(*qs)
Now you can use it in a template like so:
{% for photo in post.all_images %}
<img src="{{ photo.image.url }}" alt="{{ photo.title }}" />
{% endfor %}
I'm developing a small Django site and I'm using django.contrib.admin to handle content management. I'd like to capture the first name & last name of the author (an Admin user) of an Article on its initial save (and not update it if another user edits the Article).
ie.
class Article(models.Model)
title = models.CharField(max_length=50)
pub_date = models.DateTimeField('date published')
author = ForeignKey(???)
...
What do I need to write to grab this user's first name & last name fields when creating a new Article object? I'd default to their admin username if those fields are blank.
Have your model use the User object:
author = models.ForeignKey(User)
To prevent this field from being changeable on update, check out this other SO post:
Django admin: exclude field on change form only
To change the admin's Select field to use first/last name, you could try this snippet:
http://djangosnippets.org/snippets/1642/
To change the admin's view, assuming you are using the built-in templates, you could add a custom column as described on this post: How do I add a custom column with a hyperlink in the django admin interface?
class AuthorAdmin(admin.ModelAdmin):
list_display = ('author_name',)
def my_author_name(self, obj):
if obj.author.first_name and obj.author.last_name:
return '%s %s' % (obj.author.first_name, obj.author.last_name)
else:
return obj.author.username
my_author_name.allow_tags = True
my_author_name.short_description = 'Author'
I think you are looking for this:
author = models.ForeignKey(User)
It looks like the best way to handle a None or blank result from get_full_name is to just populate User.author with models.ForeignKey(User) and then — at the template level — use the following:
{{ user.get_full_name|default:user.username }}
... via this SO answer. This allows me to perform queries on a User's Articles, but still gracefully handles blank first_name & last_name fields if a User hasn't entered them yet, but will also update dynamically when they have).
sorry if this is an obvious question but I have been searching for a few days and have not been able to come up with a result.
I am creating a simple photo gallery app. There are four galleries, each containing a photo (the photo consists of a 'before' image, 'after' image and caption). I am trying to use django-admin to allow users to click on a gallery and then add photos.
I am using a TabularInline to edit the photos within each gallery. In addition to the default columns on the TabularInline, I would like to add a column that shows a thumbnail preview of the 'before' photo and 'after' photo (I am using easy-thumbnails for this). After much searching, it seems like the best way to do this is to override the django-admin tabularInline.html template and add the column myself - so I created another copy and am trying to edit it now.
What I would like to do is simply reference the Photo object within the Django admin template that I am overriding - but I don't know the appropriate tag to use. I need the reference so I can use it in conjunction with the easy-thumbnails thumbnail tag ... but for the life of me I cannot figure out the template tag that references the object. I have tried iterating through the ModelForm, FormSet, and FieldSet objects but none seem to give me a direct reference to the object.
# models.py
class Gallery(models.Model):
name = models.CharField(max_length=200)
url = models.CharField(max_length=200)
desc = models.TextField()
def __unicode__(self):
return self.name
class Photo(models.Model):
gallery = models.ForeignKey(Gallery)
before = models.ImageField(upload_to='gallery')
after = models.ImageField(upload_to='gallery')
caption = models.CharField(max_length=1000)
order = models.IntegerField(blank = True, null = True)
def __unicode__(self):
return "Photo " + str(self.order)
# admin.py
class GalleryForm(forms.ModelForm):
model = Gallery
class Media:
js = (
'/assets/js/jquery-1.4.2.min.js',
'/assets/js/jquery-ui-1.8.2.custom.min-admin-sortable.js',
'/assets/js/menu-sort.js',
)
class PhotoInline(admin.TabularInline):
model = Photo
extra = 1
template = "admin/tabular-thumbnails.html"
admin.site.register(Gallery,
inlines=[PhotoInline],
form = GalleryForm)
Thanks so much in advance and please let me know if there's any additional information I can offer. I am using Django 1.1
In Django 2.1 {{adminform.form.instance.field_name}} worked for me.
{{ form.instance }} will always be the model instance associated with a modelform, assuming there is one.
(Note that ``{{ formset.instance }}` is the instance of the parent model in an inline formset).