Django AttributeError 'float' object has no attribute 'split' - mysql

I installed the module Django Import / Export link
the installation went smoothly. Now when I want to import a file with the extension .xls it shows me the following error:
AttributeError at /admin/xxxx/xxxx/process_import/
'float' Has No object attribute 'split'
Exception Location:
C:\Python34\lib\site-packages\import_export\widgets.py in clean, line 321
When I edit the file here widgets.py source code
def clean(self, value):
if not value:
return self.model.objects.none()
if isinstance(value, float):
ids = [int(value)]
else:
ids = value.split(self.separator)
ids = filter(None, value.split(self.separator))
return self.model.objects.filter(**{
'%s__in' % self.field: ids
})
Here are the lines 321 ids = filter(None, value.split(self.separator))
Django models
class Vehicule(models.Model):
matricule = models.CharField(max_length=200)
modele = models.CharField(max_length=200)
annee = models.IntegerField()
def __str__(self):
return self.matricule
class Ligne(models.Model):
nom = models.CharField(max_length=200)
vehicule = models.ManyToManyField(Vehicule, through='Affecter_Vehicule_Ligne')
def __str__(self):
return str(self.nom)
class Affecter_Vehicule_Ligne(models.Model):
vehicule = models.ForeignKey(Vehicule, on_delete=models.CASCADE)
ligne = models.ForeignKey(Ligne, on_delete=models.CASCADE)
actif = models.BooleanField(default=False)
dateAffectation = models.DateTimeField(null=True)
def __str__(self):
return str(self.dateAffectation)
class Arret(models.Model):
nom = models.CharField(max_length=200, null=True)
latitude = models.CharField(max_length=200, null=True)
longitude = models.CharField(max_length=200, null=True)
lignes = models.ManyToManyField(Ligne, through='Ligne_Arret')
def __str__(self):
return str(self.nom)
class Ligne_Arret(models.Model):
sens = models.CharField(max_length=200)
section = models.BooleanField(default=False)
ligne = models.ForeignKey(Ligne, on_delete=models.CASCADE)
arret = models.ForeignKey(Arret, on_delete=models.CASCADE)
def __str__(self):
return str(self.arret)
Django admin
class VehiculeAdmin(admin.ModelAdmin):
list_display = ('matricule', 'modele', 'annee')
search_fields = ('matricule', 'modele')
class Affecter_Vehicule_LigneAdmin(admin.ModelAdmin):
list_display = ('vehicule', 'dateAffectation', 'ligne')
class ArretAdmin(ImportExportModelAdmin):
pass
class Ligne_ArretAdmin(admin.ModelAdmin):
list_display = ('ligne', 'arret', 'section', 'sens')
admin.site.register(Vehicule, VehiculeAdmin)
admin.site.register(Ligne)
admin.site.register(Affecter_Vehicule_Ligne, Affecter_Vehicule_LigneAdmin)
admin.site.register(Arret, ArretAdmin)
admin.site.register(Ligne_Arret, Ligne_ArretAdmin)
Help me please to solve this problem ???

You are trying to split a float value in this line ids = filter(None, value.split(self.separator))
I think you can just remove this line. As you handle the None case and split before.

Related

Django complete form as signed up user

After you sign up, you are prompted to a page that contains a form used for gathering additional information about the new user and after that it redirects you to the login page. The problem is that the form doesn't submit if i don't specify the {{form.user}} instance in the html file. Probably because the user_id is not recognized by default. When i specify it, the form let me chooses from already existing users, and i would like it to go with the logged in user by default.
views.py
class CreateInfoView(CreateView):
model = AdditionalInfoModel
form_class = AdditionallnfoModelForm
template_name = "user_ski_experience/additional_info.html"
def get_form_kwargs(self):
variable_to_send = super(CreateInfoView, self).get_form_kwargs()
variable_to_send.update({'pk': None})
variable_to_send.update({'pk_user': self.request.user.pk})
return variable_to_send
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
def get_success_url(self):
return reverse('login')
forms.py
class AdditionallnfoModelForm(forms.ModelForm):
class Meta:
model = AdditionalInfoModel
fields = '__all__'
def __init__(self, pk, *args, **kwargs):
pk_user = kwargs.pop('pk_user')
super(AdditionallnfoModelForm, self).__init__(*args, **kwargs)
self.pk = pk
self.fields['user'].disabled = True
self.fields['user'].initial = pk_user
for el in self.fields:
self.fields[el].label = False
def clean(self):
return self.cleaned_data
How can i solve this ?
class AdditionalInfoModel(models.Model):
objects = None
skill_choices = (('Beginner', 'BEGINNER'),
('Intermediate', 'INTERMEDIATE'),
('Expert', 'EXPERT'))
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = models.CharField(max_length=30, blank=True)
city = models.CharField(max_length=30, blank=True)
assumed_technical_ski_level = models.CharField(max_length=30,
choices=skill_choices)
years_of_experience = models.PositiveIntegerField(blank=True)
money_to_spend = models.PositiveIntegerField(blank=True)
resort_choice = models.ForeignKey(Resorts, on_delete=models.CASCADE,
blank = True, null = True)
def __str__(self):
return self.user.username

__init__() got an unexpected keyword argument 'use_required_attribute'

I don't know why in some pages give me this error, and in others dosen't show me the error
I try to add a requiered attrbute but dosen't work, I don't how to add it
Model
class Vehicle(models.Model):
registration = models.CharField(max_length=200, default='')
vehicle_type = models.ForeignKey(VehicleType, on_delete=models.CASCADE)
def __str__(self):
return self.registration
class Meta:
verbose_name_plural = "Vehicles"
Form
class VehicleForm(ModelForm):
class Meta:
model = Vehicle
fields = ['registration', 'vehicle_type']
View
def vehicles(request):
vehicles = Vehicle.objects.all()
context = {
'title' : 'Vehicles',
'generic_objects' : vehicles
}
return render(request, 'vehicle/index.html',context)
def vehicle(request, id):
VehicleFormSet = modelformset_factory(Vehicle, exclude=(), extra=0)
#Add a vehicle
if request.method == 'POST':
formset = VehicleFormSet(request.POST, request.FILES)
if formset.is_valid():
formset.save()
return HttpResponseRedirect('/favorita/vehicles')
#Edit the vehicle
else:
vehicles_search = Vehicle.objects.filter(id = id)
if vehicles_search:
formset = VehicleFormSet(queryset=vehicles_search)
else:
formset = formset_factory(VehicleForm)
return render(request, 'vehicle/details.html', {'formset': formset, 'id':id, 'title':"Vehicle"})
def delete_vehicle(request, id):
Vehicle.objects.filter(id=id).delete()
return HttpResponseRedirect('/favorita/vehicles')
The error image

In Django Rest Framework, how do I serialize values to an arraylist?

In Django Rest Framework 3.0+,I want get this value:
{
image:[img1,img2,img3]
}
and my code like:
models.py
class UserDynamic(models.Model):
"""User dynamic"""
user = models.ForeignKey(settings.AUTH_USER_MODEL)
content = models.TextField(max_length=200)
createtime = models.DateTimeField(auto_now_add=True)
class UserDynamicImage(models.Model):
"""User dynamic images"""
userdynamic = models.ForeignKey(UserDynamic)
image = models.ImageField(upload_to='UserDynamicImage/')
serializers.py
class UserDynamicImageSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
return obj.image
class UserDynamicSerializer(serializers.ModelSerializer):
user = UserProfileSerializer()
imgs = serializers.SerializerMethodField('GetImage')
# imgs = serializers.ListField(img = serializers.ImageField())
# imgs = UserDynamicImageSerializer(many=True, read_only=True)
class Meta:
model = UserDynamic
fields = ('id', 'user', 'content', 'imgs', 'createtime')
def GetImage(self,UserDynamic):
entity = UserDynamicImage.objects.filter(userdynamic = UserDynamic)
return UserDynamicImageSerializer(entity,many=True,context={"request": self.context['request']}).data
Right now,it return a error:
is not JSON serializable
In your UserDynamicImageSerializer instead of returning obj.image return obj.image.url
you can do like:
class UserDynamicImageSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
if obj.image:
return obj.image.url
Another way to do this without using UserDynamicImageSerializer:
class UserDynamicSerializer(serializers.ModelSerializer):
user = UserProfileSerializer()
imgs = serializers.SerializerMethodField('GetImage')
class Meta:
model = UserDynamic
fields = ('id', 'user', 'content', 'imgs', 'createtime')
def GetImage(self,UserDynamic):
entity = UserDynamicImage.objects.filter(userdynamic=UserDynamic).values_list('image',flat=True)
return entity

Parent formset with childrens inline formsets

I'm trying to come up with the best approach for this problem. I have 2 models with 2 forms and 1 formset:
#models
class ModbusDevice(models.Model):
ixModbusDevice = models.AutoField(primary_key=True)
sModbusName = models.CharField(verbose_name='Device Name',max_length=100)
iPort = models.IntegerField(verbose_name='Port')
iSlave = models.IntegerField(verbose_name='Slave ID')
sIP = models.GenericIPAddressField(verbose_name='IP Address')
class Meta:
db_table = 'TModbusDevice'
class Register(models.Model):
ixRegister = models.AutoField(primary_key=True)
sRegisterName = models.CharField(max_length=100)
iStartingAddr = models.IntegerField()
bRange = models.BooleanField(default=False)
ixIOType = models.ForeignKey(IOType)
ixModbusDevice = models.ForeignKey(ModbusDevice)
iOffset = models.IntegerField(blank=True, null=True)
class Meta:
db_table = 'TRegister'
#forms
class InitialRegisterFormset(BaseModelFormSet):
def __init__(self, *args, **kwargs):
super(InitialRegisterFormset, self).__init__(*args, **kwargs)
self.queryset = Register.objects.all()
class ModbusRegistersForm(ModelForm):
ixIOType = ModelChoiceField(queryset=IOType.objects.all()),
bRange = BooleanField(required=False)
bRange.widget.attrs['data-form'] = 0
class Meta:
model = Register
fields = ['sRegisterName','iStartingAddr','bRange','ixIOType','iOffset']
widgets = {
'sRegisterName': TextInput(attrs={'placeholder': 'Register Name','class': 'form-control', 'data-form': '0'}),
'iStartingAddr': TextInput(attrs={'placeholder': 'Starting address','class': 'form-control','data-form': '0'}),
'iOffset': TextInput(attrs={'placeholder': 'Address offset','class': 'form-control','data-form': '0'}),
}
class CreateModbusForm(ModelForm):
class Meta:
model = ModbusDevice
fields = ['sModbusName','iPort', 'iSlave', 'sIP']
widgets = {
'sModbusName': TextInput(attrs={'placeholder': 'Device Name','class': 'form-control','data-form': '0',}),
'iPort': TextInput(attrs={'placeholder': 'Port','class': 'form-control','data-form': '0',}),
'iSlave': TextInput(attrs={'placeholder': 'Slave id','class': 'form-control','data-form': '0',}),
'sIP': TextInput(attrs={'placeholder': 'Modbus IP address','class': 'form-control','data-form': '0',})
}
What I'm trying to do is create a formset of ModbusDevices along with their belonging registers(inline formset).
So far this is what I've managed to get:
I'm returning all existing modbus devices(in this example I only have 1 in my db) and 1 extra if the user wants to add a new device. In my registers is where I have a problem. Right now I'm returning all registers in my table and displaying them instead of displaying only the related registers. I'm not sure how I can go about iterating my device formset and accessing it's children belonging to the device.
Here is my view:
ModbusFormset = modelformset_factory(ModbusDevice, form=CreateModbusForm)
register_qset = Register.objects.all()
InlineRegisterFormset = None
if not register_qset:
InlineRegisterFormset = inlineformset_factory(ModbusDevice, Register, form=ModbusRegistersForm, extra=1)
else:
InlineRegisterFormset = inlineformset_factory(ModbusDevice, Register, form=ModbusRegistersForm, formset=InitialRegisterFormset, extra=len(register_qset))
modbus_qset = ModbusDevice.objects.all()
devices = ModbusFormset(queryset=modbus_qset, prefix="modbus")
registers = InlineRegisterFormset(prefix="register")

Column 'user_id' cannot be null django

I seek to create a post with a form where a registered user creates and inserts the primary key id in the db but this does not give me the following error Column 'user_id' can not be null
This is my models.py
class posts(models.Model):
titulo = models.CharField(max_length=180, unique=True)
slug = models.SlugField(max_length=180, editable=False)
contenido = models.TextField()
categoria = models.ForeignKey(categorias)
user = models.ForeignKey(User)
tags = models.CharField(max_length=200)
creado = models.DateTimeField(auto_now_add=True)
modificado = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.titulo)
super(posts, self).save(*args, **kwargs)
def __str__(self):
return self.titulo
This is my view.py
def addPosts(request):
if request.method == "POST":
form = addPostForm(request.POST)
if form.is_valid():
add = form.save(commit=False)
#add.user = User.objects.get(id=request.user)
add.save()
form.save_m2m()
return HttpResponseRedirect('/')
else:
form = addPostForm ()
ctx = {'form': form}
return render_to_response('posts/add.html', ctx, context_instance=RequestContext(request))
This is forms.py
class addPostForm(forms.ModelForm):
class Meta:
model = posts
exclude = {'slug','user', 'creado'}
some solution to this problem?
Request.user returns the current user object. No need to do a lookup.
add.user = request.user
in your view
If tying to the Django built-in user, you're going to want to do it differently from your model:
user = models.ForeignKey(User)
Consider defining this in your settings and instead, use:
user = models.ForeignKey(settings.AUTH_USER_MODEL)
See the documentation here: https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#referencing-the-user-model
This will also future-proof you if you decide to extend the Django base user model in the future.