How to assign ForeignKey MySQL item in views.py? - mysql

When I save my NoteForm, I want to save my form and the "note" field, then I want to create a "tag" for the Note in the NoteTagModel.
At the moment, I create a new tag but it is not assigned to the note. I know that the following code must be wrong:
notetag.id = new_note_parse.id
If I change to:
notetag.note = new_note_parse.id
I receive the following error:
"NoteTagModel.note" must be a "NoteModel" instance.
The below is my views.py:
def notes(request):
note_form = NoteForm
notetag = NoteTagModel()
note_form=NoteForm(request.POST)
if note_form.is_valid():
new_note = note_form.save(commit=False)
new_note_parse = new_note
new_note.save()
notetag.id = new_note_parse.id
notetag.tag = "Test"
notetag.save()
return HttpResponseRedirect(reverse('notes:notes'))
context = {
'note_form' : note_form,
'notes' : NoteModel.objects.all(),
'notes_tag' : NoteTagModel.objects.all(),
}
return render(request, "notes/notes.html", context)
My models.py is:
class NoteModel(models.Model):
note = models.CharField(
max_length = 5000
)
def __str__(self):
return f"{self.note}"
class NoteTagModel(models.Model):
note = models.ForeignKey(
NoteModel,
on_delete=models.CASCADE,
related_name="notes",
blank= False,
null = True,
)
tag = models.CharField(
max_length = 5000
)
def __str__(self):
return f"Note: {self.note} | Tag: {self.tag}"
I have the following as my forms.py:
class NoteForm(ModelForm):
class Meta:
model = NoteModel
fields = [
'note',
]

Change views.py to reflect the below:
note = NoteModel.objects.get(id=new_note_parse.id)
notetag.note = note

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

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

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.

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

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.