I need to create a record with a one-to-one relationship and another field, the model of the one-to-one relationship has a filefield, when I create it, it throws me the error of the title.
This is my code.
Models
class Proyecto(models.Model):
user = models.CharField(max_length=50)
nombre_p = models.CharField(max_length=50)
descripcion_p = models.CharField(max_length=50)
file_arff = models.FileField(upload_to='arff')
def __unicode__(self):
return str(self.file_arff)
class Escenario(models.Model):
proyecto = models.ForeignKey(Proyecto)
file_txt = models.FileField(upload_to='txt/')
View
id_proyecto = Proyecto.objects.get(pk=request.session['proyecto_id'])
escenario = Escenario(proyecto=id_proyecto, file_txt=file_txt)
escenario.save()
throw me this error : AttributeError: 'file' object has no attribute '_committed'
models
class Escenario(models.Model):
proyecto = models.ForeignKey(Proyecto, related_name="xxxxx")
file_txt = models.FileField(upload_to='txt/', null=True, blank=True)
views
id_proyecto = Proyecto.objects.get(pk=request.session['proyecto_id'])
obj = Poyecto.objects.filter(id=id_proyecto)
file_txt = None #Or you can add a file here that you want to attach to the modal.
if file_txt = None:
instance = Escenario.objects.create(proyecto=obj)
else:
instance = Escenario.objects.create(proyecto=obj, file_txt=file_txt)
for x in obj:
instance.xxxxx.add(x)
Related
I am trying to insert some data into MySQL database (model LogsSeparate) through Django and Django Rest Framework but I keep getting an error which I bet is very easy to solve yet I couldn't figure it out myself:
Error:
if obj.pk is None:
AttributeError: 'LogObjTest' object has no attribute 'pk'
Code:
class LogObjTest():
def __init__(self):
self._id = None
self.bits = None
class getLogs(viewsets.ModelViewSet):
arrayTest=[]
for x in Logs.objects.all():
serializer_class = LogsSeparateSerializer
test = Fields.objects.filter(pac_id=x.message_id_decimal)
binaryTest=x.data_binary
for i in test:
obj=LogObjTest()
obj._id=x.message_id_decimal
obj.bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len]
arrayTest.append(obj)
queryset = arrayTest
LogsSeparate.objects.bulk_create(arrayTest)
print("arrayTest",arrayTest)
models.py
class LogsSeparate(models.Model):
_id = models.CharField(max_length=255, primary_key=True, null=False, db_column='_id')
bits = models.CharField(max_length=500, db_column='bits')
def __str__(self):
return self.bits```
Don't use LogObjTest. Import LogsSeparate that you created in the model.py file then use it to create a new object.
class getLogs(viewsets.ModelViewSet):
arrayTest=[]
for x in Logs.objects.all():
serializer_class = LogsSeparateSerializer
test = Fields.objects.filter(pac_id=x.message_id_decimal)
binaryTest=x.data_binary
for i in test:
obj=LogsSeparate(_id=x.message_id_decimal, bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len])
arrayTest.append(obj)
queryset = arrayTest
LogsSeparate.objects.bulk_create(arrayTest)
print("arrayTest",arrayTest)
Losing the will to live here lol - might be fairly obvious that I'm new to Django/Python.
Can't work out what's going wrong here, I'm calling objects from a model that has values in Django Admin but every time I try to fix one thing, it breaks another.
I want to be able to create a new entry from frontend, but I get this error when trying to migrate:
Stack error
File "/usr/local/lib/python3.6/site-packages/django/forms/fields.py", line 784, in __init__
self.choices = choices
File "/usr/local/lib/python3.6/site-packages/django/forms/fields.py", line 801, in _set_choices
value = list(value)
TypeError: 'ModelChoiceField' object is not iterable
Please see my model below:
models.py
# Model
engineer_shifts = [
(0,'Shift 1'),
(1,'Shift 2'),
(2,'Shift 3')
]
class Engineer(models.Model):
engineer = models.CharField(max_length=200,default="John Smith",verbose_name="Engineer")
engineer_shift = models.IntegerField(choices=engineer_shifts,verbose_name="Shift")
def __str__(self):
return f"{self.engineer}"
class Meta:
verbose_name_plural = 'Engineers'
class CreateHandoff(models.Model):
handoff_pk = models.AutoField(primary_key=True)
handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date")
shift1_lead = models.IntegerField(choices=engineer_picker,verbose_name="Shift 1 Lead")
shift1_sec = models.IntegerField(choices=engineer_picker,verbose_name="Shift 1 Secondary")
def __str__(self):
return f"{self.handoff_date}"
class Meta:
verbose_name_plural = 'Handoffs'
# Form
engineer_picker = forms.ModelChoiceField(
queryset=Engineer.objects.all()
)
class CreateHandoffForm(forms.ModelForm):
shift1_lead = forms.ChoiceField(
label = "Select Shift 1 Lead",
choices = engineer_picker,
required = True
)
shift1_sec = forms.ChoiceField(
label = "Select Shift 1 Secondary",
choices = engineer_picker,
required = True
)
class Meta:
model = CreateHandoff
fields = ["shift1_lead","shift1_sec"]
You are looking for a ForeignKey, you can make a ForeignKey to refer to a model record, so:
class CreateHandoff(models.Model):
handoff_pk = models.AutoField(primary_key=True)
handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date")
shift1_lead = models.ForeignKey(Engineer, on_delete=models.CASCADE, related_name='lead_handoffs', verbose_name='Shift 1 Lead')
shift1_sec = models.ForeignKey(Engineer, on_delete=models.CASCADE, related_name='sec_handoffs', verbose_name='Shift 1 Secondary')
def __str__(self):
return f"{self.handoff_date}"
class Meta:
verbose_name_plural = 'Handoffs'
For the ModelForm, you do not need to specify the fields: Django will automatically make ModelChoiceField for these, so:
class CreateHandoffForm(forms.ModelForm):
class Meta:
model = CreateHandoff
fields = ['shift1_lead', 'shift1_sec']
In my serializers.py I have a OrderCreateSerializer:
class OrderCreateSerializer(ModelSerializer):
data_params = serializers.DictField() # 根据产品数据模型不同而异
class Meta:
model = Order
fields = (
"product_describe", # 产品描述 (购买xx产品 + 参数)
"billing_type", # 计费类型 ("包年包月")
"data_params", # 数据
)
def create(self, validated_data):
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
validated_data["order_num"] = generateOrderNum(userid=user.id)
validated_data["order_status"] = "未支付"
validated_data["order_status"] = "未支付"
data_dic = validated_data.pop("data_params") #
# data_dic["data"]["profile"]
validated_data["buytime"] = data_dic["data"]["buytime"]
validated_data["count"] = data_dic["data"]["count"]
validated_data["paytype"] = ""
validated_data["cost"] = ""
validated_data["account"] = user.account
return Order.objects.save(**validated_data) # this is the line 57
When I save the validated_data, it report the bellow error:
Manager object has no attribute 'save'
My Order model is like bellow, there is many fields in it :
class Order(models.Model):
"""
订单
"""
order_num = models.CharField(max_length=128, unique=True) # 订单编号
order_status = models.CharField(max_length=12) # 订单状态 "未支付", "已支付,未完成", "已完成", "已经删除","其他"
product_describe = models.TextField() # 产品描述
billing_type = models.CharField(max_length=16) # 计费类型
buytime = models.CharField(max_length=16) # 比如:1月 永久
count = models.IntegerField() # 购买数量
paytype = models.CharField(max_length=16) # 支付方式(支付包,微信,xxx)
cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) # 费用(需要花费多少钱)
account = models.ForeignKey(to=Account) # 所属账户
ctime = models.DateTimeField(auto_now_add=True) # 创建时间
uptime = models.DateTimeField(auto_now=True) # 更新时间
def __str__(self):
return self.product_describe
def __unicode__(self):
return self.product_describe
I don't know why there is the Manager object here.
You're calling save on the manager (ie, objects)
return Order.objects.save(**validated_data)
You call save on models.
I assume you're trying to create the model, in which case you want create.
return Order.objects.create(**validated_data)
Order.objects is an instance of the Manager class. The save method is a method of the model class.
Try:Order(**validated_data).save()
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.')
I'm getting the error message 'NoneType' object is not callable when trying to save Campaign. In Django does it mean once I have saved my object SingleVoucherReward() I don't have access to it and cannot assign it to my Campaign object?
single_voucher_reward = SingleVoucherReward()
single_voucher_reward.description = "test"
single_voucher_reward.save()
Campaign.participant_reward(single_voucher_reward)
Campaign.save()
Model:
class Campaign(models.Model):
name = models.CharField(max_length=60, help_text="Give your campaign a name i.e Xmas Offer")
participant_reward_content_type = models.ForeignKey(ContentType,
editable=False,
related_name='%(app_label)s_%(class)s_as_participant',
)
participant_reward_object_id = models.PositiveIntegerField()
participant_reward = generic.GenericForeignKey('participant_reward_content_type', 'participant_reward_object_id')
You are trying to assign things to the class, not the instance of the class. Try:
campaign = Campaign()
campaign.participant_reward = single_voucher_reward
campaign.save()
or
campaign = Campaign(participant_reward = single_voucher_reward)
campaign.save()