I am trying to implement a CSV Import in Django Admin and save bulk data corresponding to the CSV file's rows.
This is my Admin class:
class EmployeeAdmin(admin.ModelAdmin):
list_display = ('user', 'company', 'department', 'designation', 'is_hod', 'is_director')
search_fields = ['user__email', 'user__first_name', 'user__last_name']
form = EmployeeForm
This is my Form class:
class EmployeeForm(forms.ModelForm):
company = forms.ModelChoiceField(queryset=Companies.objects.all())
file_to_import = forms.FileField()
class Meta:
model = Employee
fields = ("company", "file_to_import")
def save(self, commit=True, *args, **kwargs):
try:
company = self.cleaned_data['company']
records = csv.reader(self.cleaned_data['file_to_import'])
for line in records:
# Get CSV Data.
# Create new employee.
employee = CreateEmployee(...)
except Exception as e:
raise forms.ValidationError('Something went wrong.')
My Employee class is:
class Employee(models.Model):
user = models.OneToOneField(User, primary_key=True)
company = models.ForeignKey(Companies)
department = models.ForeignKey(Departments)
mobile = models.CharField(max_length=16, default="0", blank=True)
gender = models.CharField(max_length=1, default="m", choices=GENDERS)
image = models.ImageField(upload_to=getImageUploadPath, null=True, blank=True)
designation = models.CharField(max_length=64)
is_hod = models.BooleanField(default=False)
is_director = models.BooleanField(default=False)
When I upload my file and click save, it shows me this error:
'NoneType' object has no attribute 'save'
with exception location at:
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py in save_model, line 1045
EDIT I understand I need to put a call to super.save, but I am unable to figure out where to put the call, because the doc says that the save method saves and returns the instance. But in my case, there is no single instance that the superclass can save and return. Wham am I missing here?
TIA.
You should just add the super().save() to the the end of the function:
def save(self, *args, commit=True, **kwargs):
try:
company = self.cleaned_data['company']
records = csv.reader(self.cleaned_data['file_to_import'])
for line in records:
# Get CSV Data.
# Create new employee.
employee = CreateEmployee(...)
super().save(*args, **kwargs)
except Exception as e:
raise forms.ValidationError('Something went wrong.')
Related
I can't find the mistake here. I saw some similar questions but still can't fix it.
here is my models.py
class Department(models.Model):
name = models.CharField(max_length=100)
class CustomUser(AbstractUser):
department = models.ManyToManyField(Department, blank=True)
class Student(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True)
department = models.ManyToManyField(Department, blank=True)
forms.py
class StudentRegisterForm(UserCreationForm):
class Meta(UserCreationForm):
model = CustomUser
fields = ['department', ..]
widgets = {'department': forms.CheckboxSelectMultiple()}
def __init__(self, *args, **kwargs):
super(StudentRegisterForm, self).__init__(*args, **kwargs)
self.fields['department'].required = True
def clean_department(self):
value = self.cleaned_data.get('department')
if len(value) > 1:
raise forms.ValidationError("You can't select more than one department!")
return value
def save(self, commit=True):
user = super().save(commit=False)
user.save()
student = Student.objects.create(user=user)
student.department.add(self.cleaned_data.get('department')) <-- got error on this line
return (user, student)
When the CustomUser object is created, the Student object will also be created within save method. But for some reasons it gave me an error
TypeError: Field 'id' expected a number but got <QuerySet [<Department: GEE>]>.
Noticed that the Department objects were created within admin panel and also the department field within the Student model works just fine if I create it inside admin panel.
I fixed it by adding * into the add method like this
student.department.add(*self.cleaned_data.get('department'))
i have a model, like this:
name = models.CharField(max_length=255)
modify_time = models.DateTimeField(auto_now=True)
chasha = models.CharField(max_length=255)
stat = models.CharField(max_length=255)
Usually, 'modify_time' will be updated when i update 'name', 'chasha', 'stat' field. But, I just did not want the 'modify_time' been updated when i update 'stat'. how can i do that?
thanks.
Use a custom save method to update the field by looking at a previous instance.
from django.db import models
from django.utils import timezone as tz
class MyModel(models.Model):
name = models.CharField(max_length=255)
modify_time = models.DateTimeField(null=True, blank=True)
chasha = models.CharField(max_length=255)
stat = models.CharField(max_length=255)
def save(self, *args, **kwargs):
if self.pk: # object already exists in db
old_model = MyModel.objects.get(pk=self.pk)
for i in ('name', 'chasha'): # check for name or chasha changes
if getattr(old_model, i, None) != getattr(self, i, None):
self.modify_time = tz.now() # assign modify_time
else:
self.modify_time = tz.now() # if new save, write modify_time
super(MyModel, self).save(*args, **kwargs) # call the inherited save method
Edit: remove auto_now from modify_time like above, otherwise it will be set at the save method.
I'm trying to write a "def create" method to perform nested serialization for multiple objects.
def create(self, validated_data):
suggested_songs_data = validated_data.pop('suggested_songs')
suggest_song_list = list()
for song_data in suggested_songs_data:
song = Song.objects.create(**song_data)
suggest_song_list.append(song)
message = Messages.objects.create(suggested_songs=suggest_song_list, **validated_data)
return message
Here is my schema:
class MessagesSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(source='pk', read_only=True)
suggested_songs = SongSerializer(many=True)
class Meta:
model = Messages
fields = ('id','owner','url','suggested_songs',)
#fields = ('id','url','suggested_songs',)
class SongSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Song
fields =('id','title','artist','album','albumId','num_votes','cleared')
read_only_fields = ('song_id')
But I am getting this error
Cannot assign "[<Song: Song object>, <Song: Song object>]": "Messages.suggested_songs" must be a "Song" instance.
Any advice?
EDIT:
Here is the model.
class Messages(models.Model):
owner = models.OneToOneField(User, primary_key=True, related_name='user_messages', editable=False) #TODO, change owner to 'To'
#suggested_songs = models.ForeignKey(Song, null=True, blank=True)
suggested_songs = models.ManyToManyField(Song, related_name='suggested_songs')
You can't create manyToMany relations without the objects already created. You must first create the objects and then make the relation.
Something like:
def create(self, validated_data):
suggested_songs_data = validated_data.pop('suggested_songs')
message = Messages.objects.create(**validated_data)
for song_data in suggested_songs_data:
song = Song.objects.create(**song_data)
message.suggested_songs.add(song)
return message
How to create an object for a Django model with a many to many field?
From above question i come to know we can save Many to Many field later only.
models.py
class Store(models.Model):
name = models.CharField(max_length=100)
class Foo(models.Model):
file = models.FileField(upload_to='')
store = models.ManyToManyField(Store, null=True, blank=True)
views.py
new_track.file = request.FILES['file']
new_track.save()
And file uploading working fine then later i modify my code to add store then i am here...
Now i am sure db return id's here. Then i tried with my below code but that's given me error only
x = new_track.id
new = Foo.objects.filter(id=x)
new.store.id = request.POST['store']
new.save()
ok so the error here is 'QuerySet' object has no attribute 'store'
And also i tried with add that's now working either.
So the question is how to save()
the right way of saving objects with manytomany relations would be:
...
new_track.file = request.FILES['file']
new_track.save()
new_store = Store.objects.get(id=int(request.POST['store']))
new_track.store.add(new_store)
As of 2020, here's my approach to saving ManyToMany Field to a given object.
Short Answer
class HostingRequestView(View):
def post(self, request, *args, **kwargs):
form = VideoGameForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.updated_by = request.user
obj.save()
selected_categories = form.cleaned_data.get('category') #returns list of all selected categories e.g. ['Sports','Adventure']
#Now saving the ManyToManyField, can only work after saving the form
for title in selected_categories:
category_obj = Category.objects.get(title=title) #get object by title i.e I declared unique for title under Category model
obj.category.add(category_obj) #now add each category object to the saved form object
return redirect('confirmation', id=obj.pk)
Full Answer
models.py
class Category(models.Model):
title = models.CharField(max_length=100, null=True, unique=True)
class VideoGame(models.Model):
game_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50, blank=False, null=False)
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, on_delete=models.CASCADE)
category = models.ManyToManyField(Category) #ManyToMany Category field
date_added = models.DateTimeField(auto_now_add=True, verbose_name="date added")
forms.py ModelForm
class VideoGameForm(forms.ModelForm):
CATEGORIES = (
('Detective', 'Detective'),
('Sports', 'Sports'),
('Action', 'Action'),
('Adventure', 'Adventure'),
)
category = forms.MultipleChoiceField(choices=CATEGORIES, widget=forms.SelectMultiple())
class Meta:
model = VideoGame
fields = ['name', 'category', 'date_added']
views.py on POST
class HostingRequestView(View):
def post(self, request, *args, **kwargs):
form = VideoGameForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.updated_by = request.user
obj.save()
selected_categories = form.cleaned_data.get('category') #returns list of all selected categories e.g. ['Sports','Adventure']
#Now saving the ManyToManyField, can only work after saving the form
for title in selected_categories:
category_obj = Category.objects.get(title=title) #get object by title i.e I declared unique for title under Category model
obj.category.add(category_obj) #now add each category object to the saved form object
return redirect('confirmation', id=obj.pk)
URL path for redirect
urlpatterns = [
path('confirmation/<int:id>/', Confirmation.as_view(), name='confirmation'),
]
I hope this can be helpful. Regards
new.stores.all()
returns all stores linked to the object.
Maybe:
Change Foo to Tracks
Tracks.objects.filter(id=x) to Tracks.objects.get(id=x)
Let me know how it goes
why this confusion so much.. you are getting the id there then, call the store like
new_track.save()
new_track.store.add(request.POST['store'])
I have the following models:
class Product(models.Model):
active = models.BooleanField(default=True)
name = models.CharField(max_length=40, unique=True)
acronym = models.CharField(max_length=3, unique=True)
bool1_name = models.CharField(max_length=60, blank=True, null=True)
bool1_default = models.BooleanField(default=False)
int1_name = models.CharField(max_length=60, blank=True, null=True)
int1_default = models.IntegerField(blank=True, null=True)
float1_name = models.CharField(max_length=60, blank=True, null=True)
float1_default = models.FloatField(blank=True, null=True)
date1_name = models.CharField(max_length=60, blank=True, null=True)
class ProductData(models.Model):
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User)
item = models.ManyToManyField(Item)
bool1_val = models.BooleanField(default=False)
int1_val = models.IntegerField(blank=True, null=True)
float1_val = models.FloatField(blank=True, null=True)
date1_val = models.DateField(blank=True, null=True)
class Item(models.Model):
product = models.ForeignKey(Product)
business = models.ForeignKey(Business)
And I have put in the following data into the database:
# pseudo code
Product(1,'Toothpaste','TP','Is the toothpaste white?',1,,,'Weight',1,)
Product(1,'Milk','MLK',,,,,'Litres',2,'Best Before')
I want to be able to build a form for ProductData based on the variables defined in Product (create-a-form-based-on-the-values-from-another-table). I want something like this:
class ProductDataForm(ModelForm):
def __init__(self,p,*args,**kwargs):
super(ProductDataForm, self).__init__(*args, **kwargs)
# if the values isn't set in the product
if p.bool1_name is None:
# hide the input
self.fields['bool1_val'].widget = forms.CharField(required=False)
else:
# else make sure the name the field name is the product name
self.fields['bool1_val'].widget = forms.BooleanField(label=p.bool1_name)
...
But I'm having a problem passing an instance of Product to ProductDataForm. Others have said I could use a BaseModelFormSet but literature on this is sketchy and I'm not to sure how to apply it.
EDIT
If I create an array of all the fields I DON'T want to show in ProductDataForm's init how can I pass these to the Meta class's exclude. Like so:
class ProductDataForm(ModelForm):
def __init__(self,p,*args,**kwargs):
super(ProductDataForm, self).__init__(*args, **kwargs)
tempExclude = []
if not p.bool1_name:
tempExclude.append('bool1_val')
else:
self.fields['bool1_val'].label = p.bool1_name
self.Meta.exclude = tempExclude
class Meta:
model = ProductData
exclude = []
EDIT
I'm now trying to store the fields I want to exclude in the setting.py file like so:
# settings.py
SUBITEM_EXCLUDE_FIELDS = ['dave']
# views.py
def new_product_data_view(request,product='0'):
try:
i_fpKEY = int(product)
except ValueError:
raise Http404()
if not i_fpKEY:
t_fp = Product.objects.filter(active=1).order_by('id')[0]
else:
t_fp = Product.objects.get(id=i_fpKEY)
FieldsToExcludeFromProductDataForm(t_fp)
print "views.py > PRODUCTDATA_EXCLUDE_FIELDS = "+str(PRODUCTDATA_EXCLUDE_FIELDS)
siForm = ProductDataForm(t_fp, request.POST, auto_id='si_%s')
return render_to_response(...)
# middleware.py
def FieldsToExcludeFromProductDataForm(tempFP):
excludedFields = ['created','created_by','item']
if not tempFP.bool1_name:
excludedFields.append('bool1_val')
if not tempFP.int1_name:
excludedFields.append('int1_val')
...
for val in excludedFields:
PRODUCTDATA_EXCLUDE_FIELDS.append(val)
print "middleware.py > PRODUCTDATA_EXCLUDE_FIELDS = "+str(PRODUCTDATA_EXCLUDE_FIELDS)
# forms.py
class ProductDataForm(ModelForm):
# Only renames the fields based on whether the product has a name
# for the field. The exclusion list is made in middleware
def __init__(self,fp,*args,**kwargs):
super(ProductDataForm, self).__init__(*args, **kwargs)
if fp.bool1_name:
self.fields['bool1_val'].label = fp.bool1_name
if fp.int1_name:
self.fields['int1_val'].label = fp.int1_name
class Meta:
def __init__(self,*args,**kwargs):
super(Meta, self).__init__(*args, **kwargs)
print 'Meta > __init__ > PRODUCTDATA_EXCLUDE_FIELDS = '+str(PRODUCTDATA_EXCLUDE_FIELDS)
model = ProductData
print 'Meta > PRODUCTDATA_EXCLUDE_FIELDS = '+str(PRODUCTDATA_EXCLUDE_FIELDS)
#exclude = PRODUCTDATA_EXCLUDE_FIELDS
But terminal shows that the Meta class gets processed very early on and therefore can't get the newly amended PRODUCTDATA_EXCLUDE_FIELDS :
Meta > PRODUCTDATA_EXCLUDE_FIELDS = ['dave']
[11/Jul/2011 15:51:31] "GET /page/profile/1/ HTTP/1.1" 200 11410
middleware.py > PRODUCTDATA_EXCLUDE_FIELDS = ['dave', 'created', 'created_by', 'item', 'bool1_val', 'int1_val']
views.py > PRODUCTDATA_EXCLUDE_FIELDS = ['dave', 'created', 'created_by', 'item', 'bool1_val', 'int1_val']
[11/Jul/2011 15:51:32] "GET /item/new/ HTTP/1.1" 200 5028
[11/Jul/2011 15:51:32] "GET /client/1/ HTTP/1.1" 200 5445
[11/Jul/2011 15:51:32] "GET /client/view/1/ HTTP/1.1" 200 3082
Why bother with exclude, and metaclasses - just delete fields you want to exclude:
class ProductDataForm(ModelForm):
__init__():
...
for field_name in PRODUCTDATA_EXCLUDE_FIELDS:
del self.fields[field_name]
...
Maybe it's not quite right, but it's simple, and it works.
Your idea was spot on but then you tried to implement it in a very roundabout way.
Python lets you create classes dynamically at runtime using the three argument form of the type() function.
The common way to make use of this is with a factory function and Django provides just that in the form of django.forms.models.modelform_factory.
This function isn't documented but that seem to be in progress. It's from the same family of functions as modelformset_factory and inlineformset_factory which are documented so I'd say it's safe to use.
The signature is
modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None)
model, exclude and fields are equivalent to what you would normally declare in the form's inner Meta class (and that's how it's implemented).
Now, to use this in your example you'll want to change your approach a bit. First import the factory function.
from django.forms.models import modelformset_factory
Then use your view function or class to:
Get the product instance.
Generate a list of excluded fields based on the product instance (I'll call this excludedFields).
Create a form class:
formClass = modelform_factory(ProductData, excludes=excludedFields)
Initialise your form as usual, but using formClass instead of a predefined form (ProductDataForm)
form = formClass() or form = formClass(request.POST) etc...