How to save MultipleChoiceField to db - django

I want to create a settings page where a user can select multiple values of skills they have. It will have a main category and then subcategories. I need to save those into my database, so I can query them and show their selected skillset again.
I know how to create the MultipleChoiceField but not how to save them to the database. How would I go on about that?
Forms.py
from django import forms
class skills(forms.Form):
jobs = [
('Håndværker', (
('Gulv', 'Gulv'),
('Væg', 'Væg'),
)
),
('Murer', (
('Mur', 'Mur'),
('blabla', 'blabla'),
)
),
]
job = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,
choices=jobs)
Views.py
from .forms import skills
def index(request):
if request.method == 'POST':
form = skills(request.POST)
if form.is_valid():
picked = form.cleaned_data.get('job')
# do something with your results
else:
form = skills
return render(request, 'settings/index.html', {"form":form})
It currently looks like this when the page loads which is good. Next step is just how I would save it to the database, so I can display this again with their previous chosen values.

Since you don't have any models setup yet, you can look into django-multiselectfield, which would store the selected choices "as a CharField of comma-separated values". Then you'd just need to pass those values from your form.
Alternatively you can look into PostgreSQL's Array field.

I would recommend you have a Jobs model and a Skills Model. Then have a skills field on the job model which will be a ManyToManyField to the Skills model. The form for this can then be autogenerated for you by Django as a ModelForm.
# Create your models here.
class Skill(models.Model):
name = models.CharField(max_length=20, null=False, blank=False)
def __str__(self):
return self.name
class Job(models.Model):
name = models.CharField(max_length=20, null=False, blank=False)
skills = models.ManyToManyField(Skill)
def __str__(self):
return self.name
class Person(models.Model):
name = models.CharField(max_length=20, null=False, blank=False)
skills = models.ManyToManyField(Skill)
def __str__(self):
return self.name
You can then add them to the db as
skill1 = Skill.objects.create(name="Skill One")
skill2 = Skill.objects.create(name="Skill Two")
skill3 = Skill.objects.create(name="Skill Three")
skill4 = Skill.objects.create(name="Skill Four")
job1 = Job.objects.create(name="Job One")
job1.skills.add(skill1)
job1.skills.add(skill2)
job2 = Job.objects.create(name="Job Two")
job2.skills.add(skill3)
job2.skills.add(skill4)
Have a form to display
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ["name", "skills"]
You can cutomize the form or the template to your linking

in models.py just create the field with CharField
from django.db import models
class UserProfileInfo(models.Model):
Gender = models.CharField(max_length=10,default='')
in forms.py just create CHOICE like below
class UserProfileInfoForm(forms.ModelForm):
YESNO_CHOICES = (('male', 'male'), ('female', 'female'))
Gender = forms.ChoiceField(choices=YESNO_CHOICES)
class Meta():
model = UserProfileInfo
fields = ('Gender',)
in views.py import this form and display it.
or you can definitely go with
https://pypi.org/project/django-multiselectfield/

Related

how to insert foreign key data through Django Model form

How to insert foreign key data through form. Please help . what am I doing wrong. So I have two models as follows :
class Genre(models.Model):
"""Model representing a book genre."""
name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)')
def __str__(self):
"""String for representing the Model object."""
return self.name
ass UserItem(models.Model):
name= models.CharField(max_length = 50, null=True)
genre = models.ForeignKey(Genre, on_delete=models.SET_NULL, null=True)
Forms.py : I want to create form to store Item data. Not able to reference Genre and enter value through form.
class ItemForm(forms.ModelForm):
name = forms.CharField()
genre = forms.CharField()
class Meta:
model = UserItem
fields = ['name', 'genre' ]
Views.py
def item(request):
if request.method == 'POST':
genre_obj = Genre.objects.get(name=request.POST.get('name'))
print("Inside post")
item_form = ItemForm(request.POST)
if item_form.is_valid():
print("valid form")
item_form_obj = ItemForm.save(commit=False)
item_form_obj.genre = genre_obj
item_form_obj.save()
return HttpResponseRedirect(reverse('file_upload') )
else:
print("invalid form")
return HttpResponseRedirect(reverse('file_list') )
genre_obj is a queryset you can not assign queryset to foreignkey field. You can assign objects which is inside the queryset so try this way
item_form_obj.genre = genre_obj[0]
and instead of using HttpResponseRedirect use redirect in both places
from django.shortcuts import redirect
return redirect(reverse('file_upload'))

Add multiple fields to django form

I am new to django and I'm making food recipe app. I want the users to be able to add their own recipe.
models.py
from django.db import models
from django.core.urlresolvers import reverse
class Recipe(models.Model):
def __unicode__(self):
return self.recipe_name
recipe_name = models.CharField(max_length=250)
category = models.CharField(max_length=50)
description = models.CharField(max_length=1000)
image = models.CharField(max_length=1000)
prep_time = models.CharField(max_length=250)
difficulty = models.CharField(max_length=50)
instructions_url = models.CharField(max_length=1000)
def get_absolute_url(self):
return reverse('detail', kwargs={'pk': self.pk})
class Ingredients(models.Model):
def __unicode__(self):
return self.ingredients
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredients = models.CharField(max_length=1000)
views.py
class RecipeCreate(CreateView):
model = Recipe
fields = ['recipe_name', 'category', 'image', 'prep_time', 'difficulty', 'instructions_url']
At the moment my form display the fields only from my "class Recipe", but what i want is to have Ingredient field with option to add additional fields. Do you have any suggestions how to do this? Thanks!
It's going to be difficult to do that with the generic CreateView which is meant to create just one instance of a model.
What you want is a view (you could use the generic Django View) with a form (ModelForm) for your Recipe and a formset (see Django formsets) for multiple Ingredients forms. In your View's post method you then validate all the forms and save the data.
In your HTML, you'll need to create additional fields dynamically using javascript and update the number of formsets accordingly (in the formset's management form)

Django : Excluded fields are saved

I have a model :
from django.db import models
from tinymce.models import HTMLField
class Team(models.Model):
name = models.CharField(max_length=100, verbose_name='Team name')
city = models.CharField(max_length=100, verbose_name='Team city')
biography = HTMLField(verbose_name='Team biography')
country = models.ForeignKey('Country')
slug = models.SlugField(max_length=100)
def __str__(self):
return self.name
class Country(models.Model):
name = models.CharField(max_length=100, verbose_name='Country name')
code = models.CharField(max_length=5, verbose_name='Country code')
def __str__(self):
return self.code
And a form for this model:
from django import forms
from teams.models import Team
class TeamForm(forms.ModelForm):
class Meta:
model = Team
fields = (
'biography',
'city',
'country'
)
And this is my view:
def add(request):
if request.method == 'POST':
form = TeamForm(request.POST)
if form.is_valid():
send = True
form.save()
else:
form = TeamForm()
return render(request, 'teams/add.html', locals())
As you can see, all my model fields are required because I don't add argument 'null' to True in my model attributes.
In my ModelForm, for testing, I just specify fields biography, city and country.
But when I fill the form and send-it, data are saved in database, however is missing name and slug....
Why dont i have a django exception ?
Thanks for youre help
Neither of those fields are saved as Null, though. They are both character fields (SlugField is a subclass of CharField), and an empty charfield is saved as an empty string - which is perfectly valid from the database point of view.

Django forms(not ModelForms): pre-populate checkbox data from model onto forms

I am trying using django forms and not model forms. While trying to populate data for edit I keep getting keyError (u 'manager'). This does not appear if I remove assignment of a field 'choices'. Choice is a many to many field on my model. to make it less confusing I will paste my model, forms and view.
#model.py
class Choices(models.Model):
choices = models.CharField(max_length=70)
def __unicode__(self):
return self.choices
class UserProfile(models.Model):
user = models.OneToOneField(MyUser)
about_me = models.TextField(max_length=2000, null=True, blank=True)
country = models.CharField(max_length=100,null=True, blank=True)
choices = models.ManyToManyField(Choices, blank=True)
#forms.py
class UserProfileForm(forms.Form):
CHOICES = (
('like to cook', 'like to cook'),
('like only to eat', 'like only to eat')
)
about_me = forms.CharField(widget=forms.Textarea, required=False)
country = forms.CharField(max_length=60,required=False)
choices =forms.MultipleChoiceField(choices=CHOICES,widget=forms.CheckboxSelectMultiple(),required=False)
#views.py
#login_required
def update_profile(request):
userprofile = UserProfile.objects.get(user=request.user)
form = UserProfileForm(initial={'about_me':userprofile.about_me,
'country':userprofile.country,
'choices': userprofile.choices})
return render(request, 'u_profiles/edit_pro.html', {'form':form})
now when I assign the initial value of selected choices I get the keyerror. I would like to know the correct way of doing this.
Thanks.

how I can load a model to multipleChoiceField

please y have been trying to show the table in the form, but I have not been able to do.
please clone and create database and run the project on github.
is too much code to paste here.
github: https://github.com/mattisbmx/django-multipleChoiceField
Model:
from django.db import models
from multiselect.fields import ManyToManyField
class Choice(models.Model):
choice = models.CharField(max_length=15)
def __unicode__(self):
return self.choice
class SampleModel(models.Model):
name = models.CharField(max_length=15)
funciones = ManyToManyField(Choice)
passwd = models.TextField()
def __unicode__(self):
return unicode(self.pk)
View:
def index(request):
data = {'form': forms.SelectForm()}
return render_to_response("multiselect/index.html", data,
context_instance=RequestContext(request
Form:
class SelectForm(forms.Form):
data = (('1', 'One'), ('2', 'Two'), ('3', 'Three'), ('4', 'Four')) #<--I think here I load the data model
choices = MultipleChoiceField(choices=data)
Thanks
You can use ModelMultipleChoiceField
class SelectForm(forms.Form):
choices = forms.ModelMultipleChoiceField(queryset=Choice.objects.all()) #Replace the queryset with the queryset of your choice.
If you wish to change the default widget
You can use widget=CheckboxSelectMultiple() or whichever you wish.