Django Models and Admin interface question - django

I am preparing a Examination website for my students. Simple website, with use of Django's admin interface to create the Question paper.
I have following models:
class Paper(models.Model):
name = models.CharField(max_length=2000, unique=False)
short_desc = models.TextField(unique=False)
class Question(models.Model):
text = models.TextField(unique=False)
order = models.IntegerField(unique=True)
paper = models.ForeignKey(Paper, unique=False)
While adding questions to the paper, I want that I should be able to add the question from the Paper's admin interface itself, by clicking a "+" sign or some kind of "add more questions" etc.
In my current setup, I have to first create the paper and then go into Question interface and add them one by one (and heaven's forbid) if I lose their order number.
Remember, each Question belongs to a Paper and it is not a ManyToMany thing here.
Do I have to modify the admin in any way or am I doing it wrong?
Thanks.

The admin interface has the ability to
edit models on the same page as a
parent model. These are called
inlines. See InlineModelAdmin
Create a QuestionInline:
class QuestionInline(admin.TabularInline):
model = Question
and in PaperAdmin add:
class PaperAdmin(admin.ModelAdmin):
...
inlines = [
QuestionInline,
]

InlineModelAdmin is what you're after. See http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects for the details

Related

django share document with user

I have a my django site where admin user will have to share documents with other user type called accountant.for example admin has something called documents in the sidebar when clicked it shows the list of documents related to the admin beside every document we will have a button share when clicked it shows the list of accountants when selected and shared the documents will be listed on the accountant's documents list page.there are two different login interfaces.how can i achieve this i have model called Document and the user type model Accountant.how should the relations should be and what should be the logic in views.
class Document(models.Model):
name = models.Charfield()
file = model.Filefield()
class Accountant(models.Model):
name = models.Charfield()
your question is general you have to ask more specifically where exactly your problem is.
I guess you dint know how the relationship between models is going.
you can use many-to-many relationships to solve your problem.
something like this:
class Document(models.Model):
name = models.Charfield()
file = model.Filefield()
has_access_to = models.ManyToManyField(Accountant)
add like this:
# document_instance is a document object and accountant instace is the same
document_instance.has_access_to.add(accountant_instance)
for showing use this :
accountant_instance.document.all()
I hope this helps you.

Django Admin not limiting choices on ManyToMany field

I suddenly am having a problem with my django admin panel.
I have the following models:
class Role(models.Model):
name = models.CharField("Name", max_length=32)
class Person(models.Model):
name = models.CharField("Name", max_length=64)
role = models.ForeignKey(Role)
class Team(models.Model):
rep = models.ManyToManyField(
Person,
related_name="rep_on",
limit_choices_to={'role__name': 'Sales Rep'})
eng = models.ManyToManyField(
Person,
related_name="eng_on",
limit_choices_to={'role_id__name': "Engineer"})
(The two options in the limit_choices_to dictionaries are the two methods I've tried. In the past it seemed like role_id__name worked, but now it doesn't.)
If I create roles for the Sales Rep and Engineer, and create a bunch of people and attach roles, when I create a Team in the admin, I get dropdowns like I expect:
There are two problems. Each dropdown contains every Person object, so limit_choices_to doesn't seem to work at all, and of course these relationships are generic "TEAM-PERSON RELATIONSHIPS" and I'd like to be able to at least label those correctly.
I swear this worked before, and now it's not working. Any ideas as to what could be causing this?
EDIT:
I created a toy application to explore this and tried to slowly recreate the full issue. In my real app I am using two Inlines in the admin interface for the Team object and excluding the model fields. I added them into my test code and managed to recreate the issue.
class RepInline(admin.TabularInline):
model = Team.rep.through
class EngInline(admin.TabularInline):
model = Team.eng.through
class TeamAdmin(admin.ModelAdmin):
inlines = [RepInline, EngInline]
admin.site.register(Role)
admin.site.register(Person)
admin.site.register(Team, TeamAdmin)
And my admin screen looks like:
The given HTML Select fields are filtered, but the dropdowns are not, So the issue lies in the TabularInline, so I have to decide if I want to keep them or not.

How to save a model record as a template for reuse later

I have a basic blog app that has a Post model:
class Post(models.Model):
author = models.ForeignKey(
get_user_model(), null=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=30)
content = models.CharField(max_length=30)
template_specific_entry = models.CharField(max_length=30)
I need users to be able to create a Post template with template_specific_entry field values, and then other users to use these templates to create new post records, updating title and content but not template_specific_entry.
See the example use case below:
I would like to retain the original Post templates in their original form, so multiple versions of that template can be used.
My question is: what's the most efficient way to go about creating this structure?
Should I create two models, PostTemplate and Post and somehow link the template_specific_values between them?
Since this is 'row level' functionality, is it better to do this via model methods, so templates and posts are stored in the same model? E.g. def createTemplate(self): and def createPost(self): referencing the same model?
In each case how would I actually implement this?
Your drawing is a very good way to understand the problem you're trying to solve. And in fact, it's also clearly showing how your models should be constructed. You have templates and posts and each post needs to be linked to one and only one template.
You can almost see your drawing as the blueprint for your models:
PostTemplate has a ForeignKey to User (since there's an author, in your example "Author1") and has some specific characteristics (template_specific_values although I would try to name this field differently). Note that you use plural here, so I'm wondering if this should be a CharField and not something else, like an ArrayField.
Post has a ForeignKey to User (the author) and to PostTemplate, so that one template can "have" many posts, but each posts only one template.
When the user has selected a template, and then writes the post, the fk of the post gets set to the chosen template.

AbstractClass ForeignKey reference to AbstractClass

I am building a compliance management system where I have the following requirements for most models in my project:
My Requirements
Users with certain roles can change fields, but this has to lead to a new "version" with a draft status
After approval through certain other roles (i.e. managers) this version of the model has to be published
History has to be accessible for all roles
Current Situation
Because available django-apps did not meet all these requirements I created to following constuct:
Every model (e.g. Policy) has one Master and one Detail model.
The Master model has the following fields:
id
deleted
currentActiveDetail (ForeignKey)
The Detail model has the following fields:
id
majorVersion
minorVersion
author
masterModel (ForeignKey to Master)
user (ForeignKey to auth.User)
lifecycleStatus (Choice, i.e. 'Draft', 'Waiting Approval', 'Approved', 'Obsolete')
a lot of content fields (e.g. Description, Text,...)
a lot of methods
Challenges/Questions
Because I have a lot of such use cases I want to make a MasterAbstractClass and a DetailAbstractClass but I can't find a solution to the following challanges:
How to "reserve" the ForeignKey fields in the abstract class (I know that I can't define them because there is no table in the database). I thought if using the contenttype framework but it seems to be inadequate because
it's a reference from one AbstractClass (Master) on one hand to another AbstractClass (Detail) on the other hand
for the user foreign key I know exactly to what model I want to reference
EDIT 1: Just realized that the 3rd challange is no problem at all, the following works:
class ContentLifecycleDetailClassModel (models.Model):
author = models.ForeignKey('auth.User', null=True)
class Test(ContentLifecycleDetailClassModel):
pass
CLI
from polls.models import Test
from django.contrib.auth.models import User
test = Test()
user = User.objects.first()
test.author=user
test.save()
x = Test.objects.first()
print x.author.username # <-- Working
EDIT 2:
This issue was already discussed in 2009 but only a solution for one abstract class is used in one implementation which does not fit these needs: http://djangotricks.blogspot.co.at/2009/02/abstract-models-and-dynamicly-assigned.html
EDIT 3:
I ended up using the ContentType Framework to solve (1) and (2)
masterModel_type = models.ForeignKey(ContentType, blank=True, null=True)
masterModel_id = models.PositiveIntegerField(blank=True, null=True)
master_Model = GenericForeignKey('masterModel_type', 'masterModel_id')
Solved the challenges by steps mentioned in the three edits. It was not the clean solution I expected but it is working..

Setting up a weird model in django?

This may be difficult to explain.
I'm a little new to django and the whole idea of models.
Let's say I'm making an article app, where each article has a creator, but other users can edit the article at will. I'm having a little difficult on how to create the models for this.
Firstly,
I extend the user profile with the following:
class UserProfile(models.Model):
#Required field:
user = models.OneToOneField(User)
#Other Fields:
headline = models.CharField()
industry = models.CharField()
article= models.ForeignKey(articleModel.article)
Here is the first place I'm getting confused, do I put the foreignkey field in the user model? My reasoning for it being placed here is because each article can have many editors.
Now here is my article model:
class article(models.Model):
#primary key is already true
creator = models.ForeignKey(userModel.UserProfile)
title = models.CharField()
text = models.TextField()
Over here, I put the ForeignKey field so it would relate back to the creator, because every article has a single creator. (As a side note, I do want to make it so an article can have multiple creators, but I don't know what to do in this scenario).
I'm finding it a bit odd that the UserProfile model is referencing the article model, and the article is referencing it back. Can someone please help me unjumble my brain?
Thank you.
:)
As simple as possible
from django.db.models import *
from django.contrib.admin.models import User
# UserProfile should be provided by django-profiles
class UserProfile(User): # Subclassing user creates an automatic 1-1 called user
headline = CharField()
industry = CharField()
class Article(Model):
# ALWAYS primary key to User, not UserProfile
creator = ForeignKey(User, related_name='articles_created')
contributors = ManyToManyField(User, related_name='articles_edited')
created = DateTime(auto_now_add=True)
modified = DateTimeField(auto_now=True)
title = CharField()
text = TextField()
class Meta:
order = ['created', 'title']
fun stuff:
creator = Article.objects.all()[:1][0].creator.getUserProfile().headline
considder using django-versions if you want to keep track of edits.
class Article(VersionedModel)
EDIT: actually subclasses user
Nothing "weird" here. This is no such a django problem than a database structure problem. You need to read about 1 to 1, 1 to n and n to n relationships between tables.
Do you really need to record all editors of an article ? An article has many editors, and a user can edit many articles, so this is a many to many relationship. Here's how do do it in django.
Perhaps another field in your article model for last editor would provide you with the information you need.
lastEditor = models.ForeignKey(userModel.UserProfile)
If you really want to keep all editors you will need to implement another model which records something like: article_id, editor and edit time (maybe even the article text if you are interested in changes). You could then query this medel based on the current article to obtain a list of all editors.
you could do the same with: article_id and creator to obtain a list of creators of an article (this would replace the article field in your UserProfile class)