I am adding fields to the signup, the user is created and saved but the data aren't reaching the db. There is no custom User model. The additional fields go to a different table, it is a different model.
settings.py
SOCIALACCOUNT_AUTO_SIGNUP = False
ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.UserDataForm'
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
'SCOPE': ['email'],
'METHOD': 'js_sdk' # instead of 'oauth2'
}
}
models.py
from django.contrib.auth.models import User
from django.db import models
from django import forms
class UserData(models.Model):
user = models.OneToOneField(User)
year = models.CharField(max_length=4)
month = models.CharField(max_length=2)
day = models.CharField(max_length=2)
hour = models.CharField(max_length=2)
minute = models.CharField(max_length=2)
sec = models.CharField(max_length=2)
latdeg = models.CharField(max_length=2)
latmin= models.CharField(max_length=2)
londeg = models.CharField(max_length=2)
lonmin= models.CharField(max_length=2)
def __unicode__(self):
return self.user.username
forms.py
from myapp.models import UserData
from django.contrib.auth.models import User
from django import forms
from django.forms.widgets import HiddenInput
class UserDataForm(forms.ModelForm):
class Meta:
model = UserData
fields = ('year','month','day','hour','minute','sec','latdeg','latmin','londeg','lonmin')
def signup(self,request, user):
user.username = user.username
user.year = self.cleaned_data['year']
user.month = self.cleaned_data['month']
user.day = self.cleaned_data['day']
user.hour = self.cleaned_data['hour']
user.minute = self.cleaned_data['minute']
user.sec = self.cleaned_data['sec']
user.latdeg = self.cleaned_data['latdeg']
user.latmin = self.cleaned_data['latmin']
user.londeg = self.cleaned_data['londeg']
user.lonmin = self.cleaned_data['lonmin']
user.save()
Ok, solved by myself afte a while I did this with the form signup def:
def signup(self,request,user):
user=User.objects.get(email=request.email)
year = request.POST.get('year', '')
month = request.POST.get('month', '')
day = request.POST.get('day', '')
hour = request.POST.get('hour', '')
minute = request.POST.get('minute', '')
sec = request.POST.get('sec', '')
latdeg = request.POST.get('latdeg', '')
latmin = request.POST.get('latmin', '')
londeg = request.POST.get('londeg', '')
lonmin = request.POST.get('lonmin', '')
userdata_obj = UserData(user=user,year=year, month=month, day=day, hour=hour,minute=minute, sec=sec,latdeg=latdeg,latmin=latmin,londeg=londeg,lonmin=lonmin)
userdata_obj.save()
Related
I have been trying to make a relationship between two table and have a QuerySelectFiled to select a field from the other table, I have managed to do so, but the problem came when I wanted to submit the field I keep getting :
InterfaceError: <unprintable InterfaceError object>
after debugging the issue I found out that when the form is submitted the value of the field is being submitted not the id, I have solved that by saying in my model
self.firstAuthor = firstAuthor.id
solved the issue but if I choose the empty value it will break because the empty field does not have property id.
so can someone suggest how to do that?
here is my form:
from wtforms_alchemy import QuerySelectField, QuerySelectMultipleField
from ....module1.authors.author.authorModel import Author
from flask_wtf import FlaskForm
from wtforms import SubmitField, HiddenField, BooleanField, SelectField, StringField, FileField, IntegerField, DateTimeField
from datetime import datetime
from wtforms.validators import DataRequired
def getAuthor():
return Author.query
class PublicationsForm(FlaskForm):
id = HiddenField()
title = StringField('Title', validators=[DataRequired()])
category = SelectField('Category', choices=[('', ''),('Journal', 'Journal'), ('Conference', 'Conference'), ('Talk', 'Talk'),('Talk2', 'Talk2'),('Talk3', 'Talk3')])
year = DateTimeField('Year', format='%Y')
publisher = BooleanField('Publisher')
volume = IntegerField('Volume')
issue = IntegerField('Issue')
pages = StringField('Pages')
location = StringField('Location')
note = StringField('Note')
fullCitation = FileField('FullCitation')
fullSource = FileField('FullSource')
finalVersion = FileField('FinalVersion')
firstAuthor = QuerySelectField("FirstAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
secondAuthor = QuerySelectField("SecondAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
thirdAuthor = QuerySelectField("ThirdAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
fourthAuthor = QuerySelectField("FourthAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
fifthAuthor = QuerySelectField("FifthAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
sixthAuthor = QuerySelectField("SixthAuthor", query_factory=getAuthor, get_label="lastName", allow_blank=True, blank_text='')
submit = SubmitField("Save")
here is my model:
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from app import db
class Publications(db.Model):
id = db.Column(Integer, primary_key=True)
title = db.Column(String, nullable=False)
category = db.Column(String, nullable=False)
year = db.Column(db.DateTime)
publisher = db.Column(Boolean)
volume = db.Column(Integer)
issue = db.Column(String)
pages = db.Column(String)
location = db.Column(String)
note = db.Column(String)
fullCitation = db.Column(String)
fullSource = db.Column(String)
finalVersion = db.Column(String)
issue = db.Column(db.Text)
firstAuthor = db.Column(db.Integer, db.ForeignKey('author.id'))
secondAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
thirdAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
fourthAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
fifthAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
sixthAuthor = db.Column(db.Integer, db.ForeignKey("author.id"),nullable=True )
def __init__(self, title, category, year, publisher, volume, issue, pages, location, note, fullCitation, fullSource, finalVersion, firstAuthor, secondAuthor, thirdAuthor, fourthAuthor, fifthAuthor, sixthAuthor):
self.title = title
self.category = category
self.year = year
self.publisher = publisher
self.volume = volume
self.issue = issue
self.pages = pages
self.location = location
self.note = note
self.fullCitation = fullCitation
self.fullSource = fullSource
self.finalVersion = finalVersion
self.firstAuthor = firstAuthor
self.secondAuthor = secondAuthor
self.thirdAuthor = thirdAuthor
self.fourthAuthor = fourthAuthor
self.fifthAuthor = fifthAuthor
self.sixthAuthor = sixthAuthor
def __repr__(self):
return self.title
here is my view:
from flask import render_template, request, flash, redirect, url_for
from . import publications_blueprint
from .publicationsForm import PublicationsForm
from .publicationsModel import Publications
from app import db
#publications_blueprint.route("/publications", methods=["GET", "POST"])
def createPublications():
form = PublicationsForm(request.form)
publicationss = Publications.query.all()
if request.method == "POST" and form.validate_on_submit():
publications = Publications(form.title.data, form.category.data, form.year.data, form.publisher.data, form.volume.data, form.issue.data, form.pages.data, form.location.data, form.note.data, form.fullCitation.data, form.fullSource.data, form.finalVersion.data, form.firstAuthor.data, form.secondAuthor.data, form.thirdAuthor.data, form.fourthAuthor.data, form.fifthAuthor.data, form.sixthAuthor.data)
db.session.add(publications)
db.session.commit()
flash("Added Publications Successfully")
return redirect(url_for("publications.createPublications"))
return render_template("publications/publications.html", title="Publicationss", form=form, publicationss=publicationss)
#publications_blueprint.route("/updatePublications/<int:publications_id>", methods=["GET", "POST"])
def updatePublications(publications_id):
publications = Publications.query.get(publications_id)
form = PublicationsForm(request.form, obj=publications)
if request.method == "POST" and form.validate_on_submit():
publications.title = form.title.data
publications.category = form.category.data
publications.year = form.year.data
publications.publisher = form.publisher.data
publications.volume = form.volume.data
publications.issue = form.issue.data
publications.pages = form.pages.data
publications.location = form.location.data
publications.note = form.note.data
publications.fullCitation = form.fullCitation.data
publications.fullSource = form.fullSource.data
publications.finalVersion = form.finalVersion.data
publications.firstAuthor = form.firstAuthor.data
publications.secondAuthor = form.secondAuthor.data
publications.thirdAuthor = form.thirdAuthor.data
publications.fourthAuthor = form.fourthAuthor.data
publications.fifthAuthor = form.fifthAuthor.data
publications.sixthAuthor = form.sixthAuthor.data
db.session.commit()
flash("Updated Publications Successfully")
return redirect(url_for("publications.createPublications"))
publicationss = Publications.query.all()
return render_template("publications/publications.html", title="Publications", form=form, publicationss=publicationss)
#publications_blueprint.route("/deletePublications/<int:publications_id>", methods=["GET", "POST"])
def deletePublications(publications_id):
publications = Publications.query.get(publications_id)
db.session.delete(publications)
db.session.commit()
return redirect(url_for("publications.createPublications"))
In a similar case, I also use allow_blank=True in the model for a QuerySelectField search_target. I check manually if there was something selected in the view:
if formfilter.search_target.data:
search_target = formfilter.search_target.data.id
else:
....
I am building a parking app, and my issue is that i used 4 different constraints.
My issue: if on 25th of Oct i have a P1 location booked from 9-17, i want it to be free for booking from 18-24.
My models:
from django.db import models
from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from datetime import datetime, timedelta, time
from django.core.exceptions import NON_FIELD_ERRORS
today = datetime.now().date()
tomorrow = today + timedelta(1)
now = datetime.now()
l = now.hour
m=int(now.strftime("%H"))
class ParcareManager(models.Manager):
def active(self, *args, **kwargs):
return super(ParcareManager, self).filter(draft=False).filter(parking_on__lte=datetime.now())
class Parcare(models.Model):
PARKING_PLOT = (('P1', 'Parking #1'), ('P2', 'Parking #2'),('P3', 'Parking #3'))
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,null=True, default=1, on_delete=True)
email=models.EmailField(blank=True, null=True)
parking_on = models.DateField(auto_now=False, auto_now_add=False,blank=True, null=True,
help_text='Alege data cand doresti sa vii in office',)
parking_off = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True,
help_text='Alege Data Plecarii')
numar_masina = models.CharField(max_length=8, default="IF77WXV",blank=True, null=True,
help_text='Introdu Numarul Masinii')
location = models.CharField(max_length=3, blank=True, default="P1",null=True, choices=PARKING_PLOT,
help_text='Alege Locul de Parcare Dorit')
updated = models.DateTimeField(auto_now=True, auto_now_add=False,blank=True, null=True)
timestamp=models.DateTimeField(auto_now=False, auto_now_add=True,blank=True, null=True)
venire = models.TimeField(default=time(9, 00), auto_now=False,auto_now_add=False, help_text='Alege Ora Venirii')
plecare = models.TimeField(default=time(18, 00), auto_now=False, auto_now_add=False, help_text='Alege Ora Plecarii')
objects = ParcareManager()
def __str__(self):
return self.location + " | " + str(self.parking_on) + " | " + str(self.parking_off)
def validate_unique(self, exclude=None):
try:
super(Parcare, self).validate_unique()
except ValidationError as e:
raise ValidationError("Dear " + str(self.user) +
" seems that the parking places "+ str(self.location) +
" you want to book, is already taken on "+ str(self.parking_on) + " at"+ str(self.venire)+" !"+
" Please select another date! ")
class Meta:
verbose_name_plural = "parcare"
ordering = ["-parking_on"]
unique_together = ("parking_on", "location", "venire", "plecare")
The error:
IntegrityError at /admin/parcare/parcare/add/
UNIQUE constraint failed: parcare_parcare.parking_on, parcare_parcare.location, parcare_parcare.venire, parcare_parcare.plecare
It works like a charm if the user selects to book on 25th from 9-17, but gives me this error from 18-24.
Admin:
from django.contrib import admin
from .models import Parcare
from django.core.exceptions import NON_FIELD_ERRORS
class ParcareModelAdmin(admin.ModelAdmin):
list_display = ["user", "location",
"parking_on", "parking_off", "venire", "plecare", "timestamp"]
list_display_links = ["user" , "location"]
list_editable = [ "parking_off", "parking_on","venire", "plecare"]
list_filter = ["parking_on","location", "email"]
search_fields = ["location", "parking_on"]
date_hierarchy='parking_on'
class Meta:
model = Parcare
def get_form(self, request, obj=None, **kwargs):
form = super().get_form(request, obj, **kwargs)
if not obj:
user = request.user
form.base_fields['user'].initial = user
form.base_fields['email'].initial = user.email
return form
admin.site.register(Parcare, ParcareModelAdmin)
works ok only with unique_together = ("parking_on", "location"), but i need some sort of validation for the hour when they want to come and leave.
def save(self, *args, **kwargs):
delta = self.parking_off.date() - self.parking_on.date()
if delta.days == 0:
super().save(*args, **kwargs)
else:
day = self.parking_on
booking_days = []
for i in range(delta.days+1):
print('day variable is', day.date())
print('parking_off date is', self.parking_off.date())
if day.date() == self.parking_on.date():
booking_days.append(
Parcare(
user=self.user,
email=self.email,
parking_on=self.parking_on,
parking_off=self.parking_on.replace(hour=18, minute=0, second=0),
location=self.location
)
)
day = day + datetime.timedelta(days=1)
continue
elif day.date() == self.parking_off.date():
booking_days.append(
Parcare(
user=self.user,
email=self.email,
parking_on=self.parking_off.replace(hour=9, minute=0, second=0),
parking_off=self.parking_off,
location=self.location
)
)
else:
booking_days.append(
Parcare(
user=self.user,
email=self.email,
parking_on=self.parking_on.replace(hour=9, minute=0, second=0) + datetime.timedelta(days=i),
parking_off=self.parking_off.replace(hour=18,
minute=0,
second=0) - datetime.timedelta(days=delta.days-i),
location=self.location
)
)
day = day + datetime.timedelta(days=1)
Parcare.objects.bulk_create(booking_days)
I am facing a strange problem while implementing ChoiceField and UpdateView in django. I have made a small clip showing the problem that I am facing. Please watch it with subtitles/cc enabled. It will give an idea about the problem I am facing. https://youtu.be/M36TnlJvrZs. The problem goes like this.....
During CreateView, I set the 'gender' ChoiceField as 'Female'. But in UpdateView it pre-populates the 'gender' ChoiceField as Male.
However, The ListView renders the 'gender' field properly as 'Female'.
And strangely, the django admin panel, displays no value at all for the 'gender' field.
Here are all the codes:
models.py:
from django.db import models
from django.core.urlresolvers import reverse
gender_choices = (('Male', 'Male'), ('Female', 'Female'))
class Birth(models.Model):
full_name = models.CharField(max_length = 100)
gender = models.CharField(max_length=6, choices=gender_choices)
date_of_birth = models.DateField()
place_of_birth = models.CharField(max_length = 50)
mother_name = models.CharField(max_length = 50)
father_name = models.CharField(max_length = 50)
address_at_time_of_birth = models.TextField(max_length = 500)
permanent_address = models.TextField(max_length = 500)
registration_no = models.CharField(max_length = 50)
remarks = models.CharField(max_length = 200)
registration_date = models.DateField()
issue_date = models.DateField()
def get_absolute_url(self):
return reverse('birth:birth_update', kwargs={'pk':self.pk})
#return reverse('birth:birth_home')
def __str__(self):
return self.full_name
forms.py:
from django import forms
from .models import *
class BirthForm(forms.ModelForm):
full_name = forms.CharField()
gender = forms.ChoiceField(choices = gender_choices, widget=forms.Select())
date_of_birth = forms.DateField(widget = forms.DateInput(attrs = {'placeholder':'DD/MM/YYYY'}))
place_of_birth = forms.CharField()
mother_name = forms.CharField()
father_name = forms.CharField()
address_at_time_of_birth = forms.CharField(widget = forms.Textarea())
permanent_address = forms.CharField(widget = forms.Textarea())
registration_no = forms.CharField(required = False)
registration_date = forms.DateField(required = False, widget = forms.DateInput(attrs = {'placeholder':'DD/MM/YYYY'}))
remarks = forms.CharField(required = False)
issue_date = forms.DateField(required = False, widget = forms.DateInput(attrs = {'placeholder':'DD/MM/YYYY'}))
class Meta:
model = Birth
fields = '__all__'
views.py:
from django.views.generic import ListView, CreateView, UpdateView
from .models import *
from .forms import *
from datetime import date
class BirthHome(ListView):
template_name = 'birth/birth_home.html'
model = Birth
context_object_name = 'birth_objects'
paginate_by = 20
def get_queryset(self):
return Birth.objects.all().order_by('-id')
class NewBirth(CreateView):
model = Birth
form_class = BirthForm
#fields = '__all__'
template_name = 'birth/birth_add.html'
def form_valid(self, form):
obj = form.save(commit = False)
if not obj.registration_date:
obj.registration_date = date.today()
if not obj.issue_date:
obj.issue_date = date.today()
if not (date(1900, 1, 1) <= obj.date_of_birth <= date.today()):
form.add_error('date_of_birth', 'Please enter a valid date')
return super(NewBirth, self).form_invalid(form)
obj.full_name = obj.full_name.upper()
obj.gender = obj.gender.upper()
obj.place_of_birth = obj.place_of_birth.upper()
obj.mother_name = obj.mother_name.upper()
obj.father_name = obj.father_name.upper()
obj.address_at_time_of_birth = obj.address_at_time_of_birth.upper()
obj.permanent_address = obj.permanent_address.upper()
if obj.remarks:
obj.remarks = obj.remarks.upper()
self.object = form.save()
return super(NewBirth, self).form_valid(form)
class BirthUpdate(UpdateView):
model = Birth
form_class = BirthForm
template_name = 'birth/birth_update.html'
def form_valid(self, form):
obj = form.save(commit = False)
if not obj.registration_date:
obj.registration_date = date.today()
if not obj.issue_date:
obj.issue_date = date.today()
if not (date(1900, 1, 1) <= obj.date_of_birth <= date.today()):
form.add_error('date_of_birth', 'Please enter a valid date')
return super(BirthUpdate, self).form_invalid(form)
obj.full_name = obj.full_name.upper()
obj.gender = obj.gender.upper()
obj.place_of_birth = obj.place_of_birth.upper()
obj.mother_name = obj.mother_name.upper()
obj.father_name = obj.father_name.upper()
obj.address_at_time_of_birth = obj.address_at_time_of_birth.upper()
obj.permanent_address = obj.permanent_address.upper()
if obj.remarks:
obj.remarks = obj.remarks.upper()
self.object = form.save()
return super(BirthUpdate, self).form_valid(form)
I searched a lot and experimented a lot as well, but to no avail. Seriously need help. Also if this approach is not correct, what should be the correct working approach??
Solved!
So after lots of experimenting, I realized what the problem was!! It was in models.py file:
Since, I was converting all my inputs to uppercase, the 'choices' tuple also needed to have the values in uppercase. Initially the gender_choices tuple read like this:
gender_choices = (('Male', 'Male'), ('Female', 'Female'))
And in my views, I was making the gender as uppercase, thus causing mis-match in the declared tuple data and form data.
So, I changed the tuple to this:
gender_choices = (('MALE', 'MALE'), ('FEMALE', 'FEMALE'))
Works like a Charm!! Cheers.... And thanx for all the help and suggestions. Any feedback is always welcome :)
I have been working on a project in which I have to point out the expenses that the workers of a company have.
For this I have created two models, workers and expenses, in which expenses has a foreign key to workers, in the field: "nomTreballador".
When I try to save it in the db I get the error: "Cannot assign "u'Joan Manel'": "despesa.nomTreballador" must be a "treballador" instance."
My models.py:
from __future__ import unicode_literals
from django.db import models
from django.core.validators import RegexValidator
KILOMETRATGE = 'KM'
DINAR = 'DIN'
AUTOPISTA = 'AP'
MANTENIMENTPC = 'PC'
GASTOS = (
(KILOMETRATGE, 'Kilometres'),
(DINAR, 'Dinar'),
(AUTOPISTA, 'Autopista peatge'),
(MANTENIMENTPC, 'Manteniment de pc')
)
NIF = 'NIF'
NIE = 'NIE'
DNI = 'DNI'
TIPUSDOC = (
(DNI, 'DNI'),
(NIF, 'NIF'),
(NIE, 'NIE')
)
class treballador(models.Model):
nom = models.CharField(max_length=150, null=False, unique=True)
cognom = models.CharField(max_length=150, null=False)
tipusDocID = models.CharField(max_length=3, choices=TIPUSDOC, null=False)
docId = models.CharField(max_length=9, null=False)
tlf_regex = RegexValidator(regex=r'^\d{9,9}$',message="Phone number must be entered in the format: '+999999999'. Up to 9 digits allowed.")
tlf = models.CharField(validators=[tlf_regex], blank=True, max_length=9) # validators should be a list
correu = models.EmailField(max_length=254)
ciutat = models.CharField(max_length=150)
dataDAlta = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return unicode(self.nom) or 'u'
class despesa(models.Model):
nomTreballador = models.ForeignKey(treballador, to_field='nom')
tipusDeGast = models.CharField(max_length=3, choices=GASTOS)
quantia = models.DecimalField(max_digits=5, decimal_places=2)
data = models.DateTimeField()
def __unicode__(self):
return unicode(self.nomTreballador) or 'u'
My forms.py:
from django import forms
from functools import partial
from .models import despesa, treballador
DateInput = partial(forms.DateInput, {'class':'datepicker'})
class desModelForm(forms.ModelForm):
data = forms.DateField(widget=DateInput(format='%d/%m/%Y'), label="Data de la despesa", input_formats=['%d/%m/%Y'])
iquery = treballador.objects.values_list('nom', flat=True).distinct()
iquery_choices = [('','None')] + [(treballador,treballador) for treballador in iquery]
nomTreballador = forms.ChoiceField(choices=iquery_choices)
class Meta:
model= despesa
fields= ["nomTreballador","tipusDeGast","quantia","data"]
def clean_despesa(self):
despeses = self.cleaned_data.get("tipusDeGast")
return despeses
def clean_date(self):
date = self.cleaned_data.get("data")
return date
def clean_quantia(self):
quantia = self.cleaned_data.get("quantia")
return quantia
def clean_nom(self):
nomTreballador = self.cleaned_data.get("nomTreballador")
return nomTreballador
My views.py:
from django.shortcuts import render
from .forms import desModelForm, treballadorForm
from .models import treballador, despesa
def home(request):
form = desModelForm(request.POST or None)
context = {
"gast_form": form
}
if form.is_valid():
desp = form.save(commit=False)
desp.save()
return render(request, "imputacioDespeses.html", context)
I've tried solutions of similar questions but I have not managed to solve it
Thank you!!
You are getting this error because you are passing a text string to be used as the nomTreballador foreign key, while you should be passing a treballador instance.
It looks like you're trying to restrict the available choices to a set of distinct trebelladors by using a forms.ChoiceField, but a better way to do this with a ModelForm is to change the queryset attribute of the nomTreballador field. You do this in the form's init method:
self.fields['nomTreballador'].queryset = treballador.objects.all().distinct()
Also you should check the clean methods you've implemented because not all of them map to an existing field.
I am creating a custom UserViewCreateForm (using wtforms) in my flask-admin as follows:-
from app.vendors.models import Vendor
class UserViewCreateForm(form.Form):
username = fields.TextField('Username')
first_name = fields.TextField('First Name')
last_name = fields.TextField('Last Name')
email = fields.TextField('Email')
contact_number = fields.TextField('Contact Number')
password = fields.PasswordField('Password')
is_admin = fields.BooleanField('Is Admin')
is_active = fields.BooleanField('Is Active')
is_verified = fields.BooleanField('Is Verified')
vendor = fields.SelectField('Vendor', coerce=int)
class UserView(ModelView):
form_overrides = dict(title=SelectField)
form_args = dict(
# Pass the choices to the `SelectField`
title=dict(
choices=TITLE_TYPE
))
def __init__(self, session, **kwargs):
super(UserView, self).__init__(User, session, **kwargs)
def is_accessible(self):
return login.current_user.is_authenticated()
def create_form(self):
form = UserViewCreateForm()
form.vendor.choices = [(0, '')] + [(v.id, v.name) for v in Vendor.query.all()]
return form
The vendor select field is giving me a Not a valid choice validation error.
What am I doing wrongly?
Possibly because you have no choices?
CA_STATES = [
('', 'Province'),
('AB', 'Alberta'),
('BC', 'British Columbia'),
('MB', 'Manitoba'),
('NB', 'New Brunswick'),
('NL', 'Newfoundland and Labrador'),
('NS', 'Nova Scotia'),
('ON', 'Ontario'),
('PE', 'Prince Edward Island'),
('QC', 'Quebec'),
('SK', 'Saskatchewan'),
('NT', 'Northwest Territories'),
('NU', 'Nunavut'),
('YT', 'Yukon'),
]
state_ca = SelectField('Province', choices=CA_STATES)
If you want to pull your choices from your vendor table, then you want a QuerySelectField from wtforms.ext.sqlalchemy (prior to WTForms 3.0 - after 3.0, it's now a seperate WTForms-SQLAlchemy package.)
from app.vendors.models import Vendor
from wtforms.ext.sqlalchemy import QuerySelectField
class UserViewCreateForm(form.Form):
username = fields.TextField('Username')
first_name = fields.TextField('First Name')
last_name = fields.TextField('Last Name')
email = fields.TextField('Email')
contact_number = fields.TextField('Contact Number')
password = fields.PasswordField('Password')
is_admin = fields.BooleanField('Is Admin')
is_active = fields.BooleanField('Is Active')
is_verified = fields.BooleanField('Is Verified')
vendor = QuerySelectField('Vendor')
class UserView(ModelView):
def create_form(self):
form = UserViewCreateForm()
form.vendor.query = Vendor.query.all()
return form