I have an area where teachers can put homeworks for students.
Students can see these homeworks and when they click "send homework" button. they can fill a form so Teachers can see the homeworks from admin panel.
I have class to post homework.
I have 4 fields in class to post homework.
Fields = ["student number","Deadline","Lecture","Files"]
when students posting their homeworks, I want only use 2 ["student number","files"] fields for the form and I want other fields ["deadline","Lecture"] to be filled automatically from database.
What is the best way do it?
Quoting django model clean method docs:
Model.clean() This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field.
For your scenario:
import datetime
from django.db import models
class Homeworks(models.Model):
...
def clean(self):
self.Deadline = datetime.date.today() + some delta time
self.Lecture = ...
Also, remove this 'self-filled' fields from admin form interface:
class HomeworksAdmin(admin.ModelAdmin):
fields = ["student number","Files"]
Related
Within an app for an online shop I have two simple models for products and deliveries:
class Product(model.models):
delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE)
class Delivery(model.models):
published = models.Datefield()
I am using the build-in Django admin.
class ProductInline(admin.TabularInline):
model = Product
#admin.register(Delivery)
class DeliveryAdmin(admin.ModelAdmin):
inlines = [ProductInline,]
To increase robustness of the app it is very important, that products can't be changed as soon as the related delivery has been published to the customer. So on very attempt to change a product, I need to do some validation to check if the Delivery has been published. Things I have tried:
Create fieldset for InlineAdmin with custom clean()method
Custom clean() method on the model instance
These approaches don't work, though. When implemented, I loose the ability to edit the entire delivery model from the admin panel (I am trying to only limit edits of products). This is because clicking the save Button in the admin Panel will automatically call save() and clean() on the products regardless of weather or not the products were changed.
Has someone encountered a similar problem before?
Maybe, you need to override the form?
class ProductInlineForm(forms.ModelForm):
def clean(self):
# your validation.
# here you can raise ValidationError
return super().clean()
class ProductInline(admin.TabularInline):
form = ProductInlineForm
model = Product
https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#overriding-the-clean-method
in django,i want to extend the auth_user model and adding the 2 fields.one is created_user which will display the date and time when user created something and other is modified_user which will display the date n time when modification is done..
is it possible by migration??
i ve tried dis code..
from django.contrib.auth.models import User, UserManager
class CustomUser(User):
created_user= models.DateTimeField("date and time when created")
modified_user=models.DateTimeField("date and time when modified")
objects= UserManager()
I suggest reading the documentation on creating your own custom user model.
In your particular case, the easiest thing would probably be to subclass AbstractUser and add your fields as above.
If you’re entirely happy with Django’s User model and you just want to add some additional profile information, you can simply subclass django.contrib.auth.models.AbstractUser and add your custom profile fields. This class provides the full implementation of the default User as an abstract model.
Obviously I am new to Django, because I would assume this is relatively simple.
Lets say in my models.py I created a model "User", with two fields, a "username" and a "email" field. In a form called "UserForm", I want to access a list of all the "username"s in the "User" model. This list would then be used to populate a dropdown menu using Select.
I feel like this should be really easy, and I have been looking for some simple way to do it. I can find lots of ways that aren't all inclusive (ie filter(username = "Joe")), but I can't find one that will list all the users.
Any help would be greatly appreciated.
You're looking for a ModelChoiceField. Its queryset property can be populated from an ORM call, getting you all of the Users. Have a look at the section Creating Forms from Models in the docs for more information.
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
class Meta:
model = # Your model here
def __init__(self, *args, **kwargs):
self.fields['user'] = forms.ModelChoiceField(queryset=User.objects.all())
ForeignKey fields will be automatically shown as ModelChoiceFields, but you can always override the choices if you need.
I am having trouble getting my model manager to behave correctly when using the Admin interface. Basically, I have two models:
class Employee(models.Model):
objects = models.EmployeeManager()
username = models.CharField(max_length=45, primary_key=True)
. . .
class Eotm(models.Model): #Employee of the Month
date = models.DateField()
employee = models.ForeignKey(Employee)
. . .
And I have an EmployeeManager class that overrides the get() method, something like this:
class EmployeeManager(models.Manager):
use_for_related_fields = True
def get(self, *arguments, **keywords):
try:
return super(EmployeeManager, self).get(*arguments, **keywords)
except self.model.DoesNotExist:
#If there is no Employee matching query, try an LDAP lookup and create
#a model instance for the result, if there is one.
Basically, the idea is to have Employee objects automatically created from the information in Active Directory if they don't already exist in the database. This works well from my application code, but when I tried to create a Django admin page for the Eotm model, things weren't so nice. I replaced the default widget for ForeignKey fields with a TextInput widget so users could type a username (since username is the primary key). In theory, this should call EmployeeManager.get(username='whatever'), which would either return an Employee just like the default manager or create one and return it if one didn't already exist. The problem is, my manager is not being used.
I can't find anything in the Django documentation about using custom Manager classes and the Admin site, aside from the generic manager documentation. I did find a blog entry that talked about specifying a custom manager for ModelAdmin classes, but that doesn't really help because I don't want to change the model represented by a ModelAdmin class, but one to which it is related.
I may not be understanding what you're trying to do here, but you could use a custom Form for your Eotm model:
#admin.py
from forms import EotmAdminForm
class EotmAdmin(models.ModelAdmin):
form = EotmAdminForm
#forms.py
from django import forms
from models import Eotm, Employee
class EotmAdminForm(forms.ModelForm)
class Meta:
model = Eotm
def clean_employee(self):
username = self.cleaned_data['employee']
return Employee.get(username=username)
That, in theory, should work. I haven't tested it.
I need a model field composed of a numeric string for a Django app I'm working on and since one doesn't exist I need to roll my own. Now I understand how "get_db_prep_value" and such work, and how to extend the Model itself (the django documentation on custom model fields is an invaluable resource.), but for the life of me I can't seem to figure out how to make the admin interface error properly based on input constraints.
How do I make the associated form field in the admin error on incorrect input?
Have a look at the Form and field validation section in the Django documentation, maybe that's what you're looking for?
You would have to make a new type of form field for your custom model field.
All you need to do is define a custom modelform which uses your new field, and then tell the admin to use that form to edit your models.
class MyModelForm(forms.ModelForm):
myfield = MyCustomField()
class Meta:
model = MyModel
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm