I have three models.
#Peronal_info Models:
class Personal_info(models.Model):
pinfo_id = models.AutoField(primary_key=True)
userid = models.OneToOneField(User, on_delete=models.CASCADE)
nfullname = models.CharField(validators=[max_len_check], max_length=128)
efullname = models.CharField(validators=[max_len_check], max_length=128)
dob_ad = models.DateField()
dob_bs = models.DateField()
gender = models.CharField(max_length=6)
citizen_no = models.CharField(max_length=56)
cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE)
cissue_date = models.DateField()
language = models.CharField(max_length=56)
p_district = models.CharField(max_length=56)
p_vdc = models.CharField(max_length=56)
p_ward = models.CharField(max_length=2)
telephone = models.BigIntegerField(null=True, blank=True)
mobile = models.BigIntegerField()
mother_name = models.CharField(validators=[max_len_check], max_length=128)
mother_cit = models.CharField(max_length=10, null=True)
father_name = models.CharField(validators=[max_len_check], max_length=128)
father_cit = models.CharField(max_length=10, null=True)
image = models.FileField(upload_to="photos/", null=True, blank=True)
cit_image = models.FileField(upload_to="citizens/")
inclu_image = models.FileField(upload_to="inclusions/", null=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.efullname)
Education Models:
class Education(models.Model):
edu_id = models.AutoField(primary_key=True)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
institute = models.CharField(max_length=255, validators=[max_len_check])
board = models.CharField(max_length=128, validators=[max_len_check1])
pexam = models.CharField(max_length=16)
faculty = models.CharField(max_length=16)
division = models.CharField(max_length=16, validators=[max_len_check2])
tmarks = models.IntegerField()
percent = models.FloatField(null=True, blank=True)
mainsub = models.CharField(max_length=16, validators=[max_len_check2])
image = models.FileField(upload_to="educations/", null=True, blank=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.userid)
V_applied Models:
class V_applied(models.Model):
appNo = models.IntegerField(null=True, blank=True, default=add_one)
p_srlno = models.IntegerField(blank=True, null=0, default=0)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Vacancy,on_delete=models.CASCADE)
inclusive = models.ManyToManyField(Inclusive)
bank = models.CharField(max_length=128,choices=bank_choice)
v_no = models.CharField(max_length=32, validators=[max_len_check1])
dep_date = models.DateField()
ser_fee = models.IntegerField()
image = models.FileField(upload_to="vouchers/")
personal_info = models.ForeignKey(Personal_info, on_delete=models.CASCADE, blank=True)
education = models.ManyToManyField(Education, blank=True, default=0)
active = models.BooleanField(default=True)
status = models.CharField(max_length=10, validators=[max_len_check], default="Pending")
remarks = models.CharField(max_length=56, validators=[max_len_check1], default="Pending")
comment = models.CharField(max_length=128, validators=[max_len_check2], blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
#To save data automatically in ManyToMany Field i.e. in perosnal_info & education fields, there is a function form_valid() in CreateView Class in views.py
#method_decorator(login_required(login_url='login'), name='dispatch')
class v_appliedadd(CreateView):
form_class = V_appliedForm
template_name = 'v_applied/v_applied_form.html'
success_url = '/v_applied/vapp_details/'
def form_valid(self, form):
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
instance_from = form.save()
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
instance_edu = Education.objects.get(pk=edu.pk)
instance_from.education.add(instance_edu)
instance_from.save()
instance_from.save_m2m()
return super().form_valid(form)
Problem is here that while executing this function Error display but while checking table Data is inserted, How to make error free? Error is:
AttributeError at /v_applied/v_appliedadd/
'V_applied' object has no attribute 'save_m2m'
Request Method: POST
Request URL: http://localhost:8000/v_applied/v_appliedadd/
Django Version: 3.0.8
Exception Type: AttributeError
Exception Value:
'V_applied' object has no attribute 'save_m2m'
Exception Location: D:\DjangoProject\app_epf\v_applied\views.py in form_valid, line 50
Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.1
Python Path:
['D:\\DjangoProject\\app_epf',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\User\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Sun, 20 Sep 2020 22:42:21 +05
It is not being solve, Please help for solution.
You need to use form.save_m2m() rather than instance.save_m2m()
If you need to bypass that error you can use exceptions, but I will not suggest you that:
try:
//smth
except AttributeError :
// smth
The save_m2m() method is only added to a saved ModelForm object if you passed commit=false as an argument to the .save method. In your code, you never did this, therefore you are calling .save_m2m needlessly. You get the error because the save_m2m method doesn't exist in your saved ModelForm.
To solve your error, simply remove the call to save_m2m altogether; there is no need for it, and it's throwing an error because the method was never created on the object. (It's worth noting that you also happen to be calling .save_m2m on the wrong object: it should be called on the ModelForm instance, not the new Model class object, as already noted in the comments to your post; but you still get the error after changing it to the form, because the .save_m2m method does not exist in your form).
instance_from.save_m2m() # remove this entire line
If you had previously saved your form with commit=False passed as an argument -- perhaps because you needed to do some additional modification to the newly created object before saving it the database -- and your object contained Many2Many connections, then it would be necessary to manually save the new object followed by a call to save_m2m on the ModelForm instance. In your code, however, there is no usage of commit=False, and this step is not necessary, and doing so leads to the error you are receiving.
Related
I came across an error message within the model.py. I would appreciate if you guys could give me some assistance on this; the following are parts of the model.py:
class WorkJob(models.Model):
id = models.AutoField(primary_key=True)
share = models.ForeignKey(FShare, on_delete=models.PROTECT)
aftId = models.ForeignKey(AftId, null=True, blank=True, on_delete=models.PROTECT)
history = HistoricalRecords()
def __str__(self):
if self.aftId:
return self.aftId.aft
else:
return str('AFT-NA')
class Image(models.Model):
id = models.AutoField(primary_key=True)
imagingJob = models.OneToOneField(WorkJob, on_delete=models.PROTECT)
md5 = models.CharField(max_length=32, null=True, blank=True)
originalCopy = models.ForeignKey(Disc, related_name='originalCopy', null=True, blank=True, on_delete=models.PROTECT)
workingCopy = models.ForeignKey(Disc, related_name='workingCopy', null=True, blank=True, on_delete=models.PROTECT)
history = HistoricalRecords()
def __str__(self):
return self.imagingJob.fileShare.identifier
class Copy(models.Model):
id = models.AutoField(primary_key=True)
image = models.ForeignKey(Image, on_delete=models.PROTECT)
disc = models.ForeignKey(Disc, on_delete=models.PROTECT, related_name='copy')
history = HistoricalRecords()
def aftId(self):
return self.image.imagingJob.aftId.aft
the next class is the one that I have problems.
class TFI(models.Model):
id = models.AutoField(primary_key=True)
createDate = models.DateTimeField(auto_now_add=True, null=True)
status = models.IntegerField(choices=STATUS_OPTIONS, default=0)
history = HistoricalRecords()
def check_third(self):
if self.status == 5:
im = 0
third_imajob = WorkJob.objects.filter(share=self.share)
for ima in third_imajob:
if Copy.objects.filter(image__exact=ima.aftId).exists():
# some code blablabla
else:
break
The line that the error message says that it is problematic is:
if Copy.objects.filter(image__exact=ima.aftId).exists():
I am not certain why is it saying that the instance must be with Image. The line clearly is extracting from class Copy and WorkJob. I did see that that the Copy.image has a foreignkey reference to class Image but I am not certain how to troubleshoot this. Thanks in advance!
EDIT: following is also a part of the code and the above code has also been added.
class AftId(models.Model):
id = models.AutoField(unique=True, primary_key=True)
aft = models.CharField(unique=True, max_length=30)
assignedTo = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.PROTECT)
history = HistoricalRecords()
def __str__(self):
return self.aft
You are trying to compare some aftID instances and Image.
I can't see your aftId model but I guess it has an image foreign key field, so your query should be Copy.objects.filter(image__exact=ima.aftId.image).exists()
I created a form with the model form manager. Before saving my TransactionProfile ModelForm, I want to connect it with an order model. When I print session_order_id it is the correct id, however self.order_set.get is always empty when I print it in the console. Anyone can help me with that? Would you in general solve it the way I did it here, or ist there a more clean method?
In my views.py I have the following:
t = transaction_profile.save(commit=False)
t.update_order_with_transaction_profile(session_order_id)
t.save()
transactions/models.py
class TransactionProfile(models.Model):
email = models.EmailField()
address_line_1 = models.CharField(max_length=120)
address_line_2 = models.CharField(max_length=120, null=True, blank=True)
city = models.CharField(max_length=120)
country = models.CharField(max_length=120)
state = models.CharField(max_length=120)
postal_code = models.CharField(max_length=120)
update = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
customer_id = models.CharField(max_length=120, null=True, blank=True)
def update_order_with_transaction_profile(self, session_order_id):
# In ModelManager or just in class TransactionProfile
o = self.order_set.get(order_id=session_order_id)
o.transaction_profile = self
o.save()
orders/models.py
class Order(models.Model):
order_id = models.CharField(max_length=10, unique=True)
customer_key = models.CharField(max_length=10, unique=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
transaction_profile = models.ForeignKey(TransactionProfile, blank=True, null=True, on_delete=models.CASCADE)
You need to save object to DB before using it as foreign key. Since in your code t is not saved in DB, update_order_with_transaction_profile will not work.
Instead of self.order_set, which gives you only orders related to specific profile(empty list for new object), you can directly query on Order model, note you need to save transaction_profile firts:
t = transaction_profile.save()
t.update_order_with_transaction_profile(session_order_id)
def update_order_with_transaction_profile(self, session_order_id):
# In ModelManager or just in class TransactionProfile
o = Order.objects.get(order_id=session_order_id)
o.transaction_profile = self
o.save()
I am having an interesting problem. I am using the ForeignKey call in the relations mananger. I.e. if I want all the objects from a related model known as hamsters the call would be hamsters_set
now here is a working model attached to a serializer everything is working in this implementation.
class SearchCity(models.Model):
city = models.CharField(max_length=200)
class SearchNeighborhood(models.Model):
city = models.ForeignKey(SearchCity, on_delete=models.CASCADE)
neighborhood = models.CharField(max_length=200)
class CityNeighborhoodReadOnlySerializer(serializers.ModelSerializer):
searchneighborhood_set = SearchNeighborhoodSerializer(many=True, read_only=True)
class Meta:
model = SearchCity
fields = ('pk','city','searchneighborhood_set')
read_only_fields =('pk','city', 'searchneighborhood_set')
but with this new model in which I am trying to do the same thing, I am getting an attribute error
class Room(models.Model):
venue = models.ForeignKey(Venue, on_delete=models.CASCADE)
name = models.CharField(max_length=100, null=True, blank=True)
online = models.BooleanField(default=False)
description = models.CharField(max_length=1000, blank=True, null=True)
privateroom = models.BooleanField(default=False)
semiprivateroom = models.BooleanField(default=False)
seatedcapacity = models.CharField(max_length=10, null=True, blank=True)
standingcapacity = models.CharField(max_length=10, null=True, blank=True)
minimumspend = models.PositiveSmallIntegerField(blank=True, null=True)
surroundsoundamenity = models.BooleanField(default=False)
outdoorseatingamenity = models.BooleanField(default=False)
stageamenity = models.BooleanField(default=False)
televisionamenity = models.BooleanField(default=False)
screenprojectoramenity = models.BooleanField(default=False)
naturallightamenity = models.BooleanField(default=False)
wifiamenity = models.BooleanField(default=False)
wheelchairaccessibleamenity = models.BooleanField(default=False)
cocktailseatingseatingoption = models.BooleanField(default=False)
classroomseatingoption = models.BooleanField(default=False)
ushapeseatingoption = models.BooleanField(default=False)
sixtyroundseatingoption = models.BooleanField(default=False)
boardroomseatingoption = models.BooleanField(default=False)
theaterseatingoption = models.BooleanField(default=False)
hallowsquareseatingoption = models.BooleanField(default=False)
class RoomImage(models.Model):
room = models.ForeignKey(Room, on_delete=models.CASCADE)
order = models.PositiveSmallIntegerField(blank=True, null=True)
imageurl = models.CharField(max_length=200, blank=True, null=True)
class RoomAndImageSerializer(serializers.ModelSerializer):
roomimage_set = RoomImageSerializer(many=True)
class Meta:
model = Room
fields = ('name', 'online', 'description','privateroom','semiprivateroom', 'seatedcapacity', 'standingcapacity','minimumspend','surroundsoundamenity','outdoorseatingamenity','stageamenity','televisionamenity','screenprojectoramenity','naturallightamenity','wifiamenity','wheelchairaccessibleamenity','cocktailseatingseatingoption', 'classroomseatingoption','ushapeseatingoption','sixtyroundseatingoption','boardroomseatingoption','theaterseatingoption','hallowsquareseatingoption','roomimage_set')
AttributeError: Got AttributeError when attempting to get a value for
field roomimage_set on serializer RoomAndImageSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance.
Original exception text was: 'QuerySet' object has no attribute 'roomimage_set'.
rather interesting as the two implementations seem to be the same.
Can anyone catch what I am doing wrong?
You need to set your serializer to readonly
class RoomAndImageSerializer(serializers.ModelSerializer):
roomimage_set = RoomImageSerializer(many=True,read_only=True)
class Meta:
model = Room
fields = ('name', 'online', 'description','privateroom','semiprivateroom', 'seatedcapacity', 'standingcapacity','minimumspend','surroundsoundamenity','outdoorseatingamenity','stageamenity','televisionamenity','screenprojectoramenity','naturallightamenity','wifiamenity','wheelchairaccessibleamenity','cocktailseatingseatingoption', 'classroomseatingoption','ushapeseatingoption','sixtyroundseatingoption','boardroomseatingoption','theaterseatingoption','hallowsquareseatingoption','roomimage_set')
I have a model and I am trying to save the user to the models database when the user submits the form. I had a site that did this but now my editor says "Use of super on an old style class"
I am using django 1.8 and i get
IntegrityError at /auction/createview/ NOT NULL constraint failed:
auction_auction.user_id
which is the nicest error I have been able to get. with all the tinkering i have done
class AuctionCreateView(LoginRequiredMixin,CreateView):
model = Auction
action = "created"
form_class = AuctionForm
auction_form = AuctionForm(initial={'user':request.user})
class AuctionForm(forms.ModelForm):
class Meta:
model = Auction
fields = (
"user",
"item_name",
"reserve",
"start_date",
"end_date",
"description",
"tags",
)
class Auction(models.Model):
user = models.ForeignKey(User)
item_id = models.CharField(max_length=255, blank=True, null=True)
item_name = models.CharField(max_length=255, blank=True, null=True)
winner = models.ForeignKey(User, related_name='Auction_Winner', blank=True, null=True)
reserve = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')
created = models.DateTimeField(editable=False, null=True)
slug = AutoSlugField(('slug'), max_length=128, unique=True, populate_from=('item_name',))
start_date = models.DateTimeField(verbose_name="Start date")
end_date = models.DateTimeField(verbose_name="End date")
active = models.BooleanField(default=False, verbose_name='Active')
total_bids = models.IntegerField(default=0, verbose_name='Total bids')
date_added = models.DateTimeField(auto_now_add=True, verbose_name='Date added')
last_modified = models.DateTimeField(auto_now=True, verbose_name='Last modified')
description = models.TextField(max_length=3000)
tags = tagging.fields.TagField()
# bid_set = models.IntegerField(default= 0, verbose_name = "Bid set")
starting_amount = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')
def __unicode__(self):
return '%s selling %s' % (self.user, self.item_name)
def _get_increment(self):
""" add some logic to base incrementing amount on starting price """
def get_absolute_url(self):
return reverse('auction_detail',
kwargs={'slug': self.slug})
when i saw this post I thought i'd be able to figure it out. thanks ★ ✩
You need insert user_id before form save.
AuctionForm - need update request.user value. Added this fields from form initial.
You have to include 'user' on the fields of the Auction form class to solve that error and just put an initial parameter on the form instance in the views.py like
auction_form = AuctionForm(initial={'user':request.user})
because request.user on the form_valid method will not work at all
I am writing a method for my model which returns entries (translations) for a specific service.
I am having a problem with request in model, it does not return any data.
Why? How to fix this?
class Services(models.Model):
global_title = models.CharField(max_length=32, null=True, blank=True)
service_color = models.CharField(max_length=32)
service_order = models.PositiveIntegerField(default=0, null=True,blank=True)
date_added = models.DateTimeField(auto_now_add=True)
date_edited = models.DateTimeField(auto_now=True)
def get_language(self, request):
return self.servicetranslation_set.filter(language=request.LANGUAGE_CODE)