I was curious if there was a way to replicate the Django admin interface - specifically the forms when adding an object - in the front end... Here's my scenario:
class Area(models.Model):
name = models.CharField(max_length=100)
class SubArea(models.Model):
name = models.CharField(max_length=100)
area = models.ForeignKey(Area)
class Product(models.Model):
name = models.CharField(max_length=150)
area = models.ForeignKey(Area, null=True, blank=True)
subarea = models.ForeignKey(SubArea, null=True, blank=True)
So If I setup a form in the frontend for the Product model, I have no way of adding Area or SubArea objects. In the Django admin, however, I'm able to easily add these objects by clicking the "+" next to the fields.
I am looking for the easiest possible solution (while still being secure) to allow for fronted creating of the Foreign Keys without having to setup separate forms. Not sure if that is even possible, but wanted to reach out to the community for advice.
Thanks!
J
Django admin makes extensive use of formsets, see below:
https://docs.djangoproject.com/en/1.6/topics/forms/formsets/
Regarding your query with adding the '+' a la Django admin, you can acheive this with the RelatedFieldWidgetWrapper which you can find here.
According to my experience the easiest way of adding, editing, updating corresponding(related) items on a Form on the front-end, same way like in the django-Admin, is using "django-addanother" which you can use from here. Easy, fast and clean solution on this problem and it works with Django 1.11 too. And it has good documentation, demo also.
django-form-admin (.. let enter more characters stackoverflow needs 30 for answer)
Related
I am trying to make an OfferUp-like web app using Django Framework. Everything has been going great until I ran into a problem. How could I make it so that users can upload multiple pictures, instead of just one using the models.ImageField() function? You know? We might have users that only have 5 pictures to upload, while another user might have 8. How could I make it so that users can upload into the database as many pictures as they want?
What I'm going to suggest isn't that much different from the comment above (i don't have enough reputation to make a comment), so I'm just going to add a code snippet:
class Item(models.Model):
name = models.TextField()
class ItemImage(models.Model):
name = models.TextField()
item = models.ForeignKey(Item, on_delete=models.CASCADE)
image = models.ImageField(upload_to='images/')
and say: If you have more than one model with many images, rather than repeating the code you can just make a model (class) that will be inherited as the foreign key.
If I wanted to setup comments for a blog in Django, and I wanted people to be able to reply to comments (like a normal blog), meaning each comment would have to know if it's a comment on another comment or not, would I set the model fields like this?
from django.db import models
from django.contrib.auth.models import User
class Comment(models.Model):
post = models.ForeignKey(Post)
user = models.ForeignKey(User)
text = models.TextField()
date = models.DateTimeField()
reply_to = models.ForeignKey(Comment, blank=True, null=True)
Is that correct? And how would I display them in a template?
Writing a hierarchical comments application seems too easy at first look but believe me it is not that simple. There are too many edge cases and security issues. So if this is a real project i would suggest you to use disqus, any other hosted solution or (now deprecated) comments framework.
On the other hand if you are just trying to learn how things done or playing around, your code seems fair enough so far. But you should consider Django's built-in content types framework instead of a direct foreign key relationship. That way you can relate a comment object to any other object. (a blog post or another comment). Take a look at comment frameworks models.py and you will see it.
class BaseCommentAbstractModel(models.Model):
"""
An abstract base class that any custom comment models probably should
subclass.
"""
# Content-object field
content_type = models.ForeignKey(ContentType,
verbose_name=_('content type'),
related_name="content_type_set_for_%(class)s")
object_pk = models.TextField(_('object ID'))
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
Also take a look at RenderCommentListNodein comment framework template tags. You should write a recursive function in order to get and display hierarchical comments.
You have to consider cases like:
What will happen if a user deletes a comment?
How should we delete comments? Should we actually remove it from database or should we set an attribute like deleted
How should we deal with permissions and level of user access?
If we let anonymous users to comment, what information do we need from them.
How to check human validation? Is captcha enough?
Happy hacking.
I'm trying to mimic the functionality from the Django Admin tool where it allows you to add objects for foreign keys (a little plus icon next to a dropdown). For example, let's say I have the following:
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Blog(models.Model):
name = models.CharField(max_length=50)
author = models.ForeignKey('Author')
When I go to add my first Blog using a ModelForm for Blog, it shows a dropdown next to Author. However, I have no Authors in the system so that dropdown is empty. In the admin tool, I believe it puts a little "+" icon next to the dropdown so you can quickly and efficiently add a record to the dropdown by opening up a popup.
That is extremely useful, and so I'd like to mimic it in my own app using ModelForms. Is that also built into Django's ModelForms? If so, how do I use it? I can't seem to find anything in the documentation.
You will need to work with: django.contrib.admin.widgets.RelatedFieldWidgetWrapper
This post certainly will guide you:
Django admin - How can I add the green plus sign for Many-to-many Field in custom admin form
Following up with the posting regarding reversed many-to-many look ups, I was wondering what the best practice for my project/picture problem is:
I want to register a number of projects and the users can upload (but not required) multiple project pictures.
Therefore I defined the following two classes:
from easy_thumbnails.fields import ThumbnailerImageField
class Project(models.Model):
name = models.CharField(_('Title'), max_length=100,)
user = models.ForeignKey(User, verbose_name=_('user'),)
...
class ProjectPicture(models.Model):
project = models.ForeignKey('Project')
picture = ThumbnailerImageField(_('Image'),
upload_to='user/project_pictures/', null=True, blank=True,)
def __unicode__(self):
return u'%s\'s pictures' % (self.project.name)
So for every user, I am displaying their projects in a "dashboard" via
projects = Project.objects.filter(user = logged_user)
which returns a list of projects with the names, etc.
Now I would like to display a picture of the project in the dashboard table. Therefore I have two questions I am seeking advice for:
1) Is the class setup actually the best way to do it? I split up the classes like shown above to allow the users to upload more than one picture per project. Would there be a better way of doing it?
2) How can I display the first picture of a project in the template, if a picture is available? Do I need to make a query on every ProjectPicture object which corresponds to a Project? Or is there an elegant Django solution for that problem?
It's not many-to-many relation, you use foreign keys. It's normal setup. To access first picture in template you can use {{ project.projectpicture_set.all.0 }}, it will generate additional query. To avoid it use prefetch_related.
Lets say I have a django model looking like this:
class question(models.Model):
order = models.IntegerField('Position')
question = models.CharField(max_length= 400)
answer = models.TextField()
published = models.BooleanField()
def __unicode__(self):
return self.question
In my view I show all of the questions ordered ascending by the order field.
My question is: Is there an easy way to edit the order field in the django admin interface? Right now, I have to go to edit the Question, then look up what number to put in the order field and maybe even reorder all the other items. What i really want would be some "up and down"-arrows on the admin page where all the questions are listed.
Is that possible?
Check this: django-orderedmodel.
This is a really simple implementation of abstract base class for items which can be ordered with admin interface. No external dependencies and easy to use.
Sure, here is an example of admin.py file with up and down links to change items order:
https://github.com/alexvasi/django-simplemenu/blob/master/simplemenu/admin.py
Basically, you just need to override get_urls method to add your custom views (move_up and move_down in this example).
More famous example would be django-treemenus, but there is some extra code to support older versions of django.
You can check:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_editable
In case someone else is seeking the solution for that issue in 2017, I found the great package Django Admin Sortable
You can use django-admin-sortable2 to easily change the order of items including inline items as well.