I am unable to set default value for a dropdown while loading forms.
Here is the code
state = forms.TypedChoiceField(choices = formfields.State)
State = (
('QC_APPROVED','QC_APPROVED'),
('REVERT','REVERT'),
('FIXED','FIXED'),
)
If I want to make the default state as FIXED. I am writing this code
state = forms.TypedChoiceField(choices = formfields.State, default = 'FIXED')
If I execute the above code I am getting the below error.
Exception Value: __init__() got an unexpected keyword argument 'default'
Can some one help on this?
state = forms.TypedChoiceField(choices=formfields.State, initial='FIXED')
As shown in documentation: http://docs.djangoproject.com/en/dev/ref/forms/fields/#initial
I came across this thread while looking for how to set the initial "selected" state of a Django form for a foreign key field, so I just wanted to add that you do this as follows:
models.py:
class Thread(NamedModel):
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
title = models.CharField(max_length=70, blank=False)
forms.py:
class ThreadForm(forms.ModelForm):
class Meta:
model = Thread
fields = ['topic', 'title']
views.py:
def createThread(request, topic_title):
topic = Topic.getTopic(topic_title)
threadForm = ThreadForm(initial={'topic': topic.id})
...
The key is setting initial={'topic': topic.id} which is not well documented in my opinion.
fields take initial values
state = forms.TypedChoiceField(choices=formfields.State, initial='FIXED')
title = forms.CharField(widget=forms.Select(choices=formfields.State) , initial='FIXED')
toppings = forms.ChoiceField(
widget=forms.Select(attrs={'class':"hhhhhhhh"}),
choices = formfields.State,
initial='FIXED'
)
If the other solutions dont work for you,Try this:
It turns out that ModelChoiceField has an attribute called empty_label.With empty _label you can enter a default value for the user to see.
Example: In forms.py
Class CreateForm(forms.ModelForm):
category = forms.ModelChoiceField(empty_label="Choose Category")
Try the number:
state = forms.TypedChoiceField(choices = formfields.State, default = 2 )
Related
So I have a user model with the following columns:
username = models.CharField(db_column='Username',max_length=32,unique=True)
email = models.CharField(db_column='Email',max_length=255)
password = models.CharField(db_column='Password',max_length=128)
prosthodontist = models.ForeignKey('Prosthodontist',on_delete=models.SET_NULL,null=True)
I'm trying to make a dropdown that allows the user to change their Prosthodontist value through django forms. It can't be a static list cause it has to always have every available Prosthodontist as they get added.
Just for show this is what I have so far along the lines of the form:
class ChangeProsthodontistForm(forms.ModelForm):
class Meta:
model = User
fields = ('prosthodontist',)
prosthodontist = forms.ChoiceField(
label = "Prosthodontist",
widget = forms.Select(
attrs={
'id':'prosthodontist',
},
),
choices=()
)
Please help me with this cause I'm really confused I feel like I could be able to iterate through the entries with a for loop but I feel like there has to be a better way through Django.
You answer is ModelChoiceField.
prosthodontist = forms.ModelChoiceField(
# ...
queryset = Prosthodontist.objects.all(),
# ...
)
My goal is to be able to select a location and Input part numbers without seeing this quote field. I dont even completely understand what this select box is looking for. I have Quote objects saved and yet these are not coming up as selectable options. Not that I want them to, Im just saying. My thinking regarding the seelctable options is that this would be auto-populated? You can probably tell my confusion even in my explanation. Ultimately, I dont want to see a select box at all as Im not really interested in whatever this pointing to, but just for kicks would like to know what it is trying to point to.
quote/Models.py
class Quote(models.Model):
QUOTE_ENVIRONMENTS = (
('testing', 'Test'),
('production', 'Production')
)
SALES_SOURCE=((1, 'Marketplace'),
(2, 'Webstore'),
(3, 'Physical Store'),
(4, 'Phone')
)
environment = models.CharField(max_length=20, choices=QUOTE_ENVIRONMENTS, default="testing")
sales_source = models.IntegerField(choices=SALES_SOURCE, null=True)
order_notes = models.TextField(blank=True)
locations = models.ManyToManyField('products.ProductSelection')
products/models.py
class Product(models.Model):
pass
class Warehouse(models.Model):
pass
class ProductSelection(models.Model):
location = models.ForeignKey('Warehouse', on_delete = models.CASCADE)
product = models.ManyToManyField('Product')
Admin.py
class ProductOrderForm(forms.ModelForm):
locations = forms.ModelChoiceField(queryset= Warehouse.objects.all())
part_number = forms.IntegerField()
def clean_product_id(self):
cd = self.cleaned_data
logger.info(cd)
value = cd['part_number']
if value not in Products.objects.list_part_numbers():
raise forms.ValidationError("Not a valid partnumber")
class ProductSelectionTabularInline(admin.TabularInline):
form = ProductOrderForm
model = Quote.locations.through
class QuoteAdmin(admin.ModelAdmin):
list_display=['id', 'environment', 'order_notes','sales_source']
list_editable = ['environment', 'sales_source', 'order_notes']
inlines = [ProductSelectionTabularInline]
exclude=['quote']
Error when using exclude attr.
ERRORS:
<class 'orders.admin.ProductSelectionTabularInline'>: (admin.E201) Cannot exclude the field 'quote', because it is the foreign key to the parent model 'orders.Quote'.
I dont want the left most box. Thanks for your help
I figure out that the field to the left is the ProductSelection instance. I confused myself by adding the other 2 form widgets. So this does not allow me to do what I want which is to edit the parts to the locations and add it to the form for creating a quote.
I'm having difficulty assigning a title to the UserService model, which is a foreign key to another model.
models.py
class IndustryService(models.Model):
industryname = models.ForeignKey(Industry, on_delete=models.CASCADE)
title = models.CharField(max_length=120)
class UserService(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
title = models.ForeignKey(IndustryService, on_delete=models.CASCADE)
Here is the portion of code within the view that is failing:
industryservices = IndustryService.objects.filter(industryname=industry)
for service in industryservices:
try:
qs = UserService.objects.get(user=user, title=service.title)
except:
userserv = UserService.objects.create(user=request.user)
userserv.title = service
userserv.save()
The error that I'm getting is as follows:
NOT NULL constraint failed: accounts_userservice.title_id
Based on my testing, the way in which I'm assigning the value to the 'title' foreign key field is wrong (i.e. these 2 lines of code).
service2 = IndustryService.objects.get(title=service.title)
userserv.title = service2
Any thoughts on how I can fix this? Thanks!
You're doing two updates, unnecessarily. Either create the item in one go:
userserv = UserService.objects.create(user=request.user, title=service)
or instantiate without saving and then save at the end:
userserv = UserService(user=request.user)
userserv.title = service
userserv.save()
I have trouble to get my data from DB.
Basically one teacher can create more no of class_room each class_room contains a title and it has more number of students.
models.py
class class_room(models.model):
user = models.ForeignKey(User,related_name = 'classroom')
title = models.charField(max_length=50)
students = models.ManyToManyField(User,related_name= 'commits',symmetrical=FAlSE)
views.py
def index(request):
user = request.user
Total_class = class_room.objects.get(user = user)
students_list = Total_class.students.all()
class_name = Total_class.title.all()
return render(request,'trial/index.html,{'Total':Total_class ,'no':students_list, 'class_name ':class_name )
When i try to execute this code. i get this error get() returned more than one
Then i removed get() bcoz the user has more number of class_room so i put filter() After that i get 'QuerySet'object has no attribute 'students'
Any help appreciated :(
You have multiple objects for model class_room in the database, with the same user. Either you need to enforce the uniqueness to the user attribute in the models.
Or, you can get the students attribute of the first object in the query like,
Total_class = class_room.objects.filter(user = user).first()
students_list = Total_class.students.all()
or using index,
Total_class = class_room.objects.filter(user = user)[2]
#any element.
EDIT
As per the request of OP, I think the required queryset would be,
student_list = User.objects.filter(class_room__user=request.user)
I apologize in advance if my question has already been there, but I have not found.
there is a model:
class Artikul_cabinets(models.Model):
artikul_cabinets = models.CharField(verbose_name="Артикул шкафа", max_length=20)
title_cabinets = models.CharField(verbose_name="Описание шкафа", max_length=200)
width_cabinets = models.ManyToManyField(Width_cabinets)
depth_cabinets = models.ManyToManyField(Depth_cabinets)
unit_cabinets = models.ManyToManyField(Unit_cabinets)
weight_cabinets = models.ManyToManyField(Weight_cabinets)
type_cabinets = models.ForeignKey(Type_cabinets, default=1)
color_cabinets = models.ForeignKey(Color_cabinets)
glass_cabinets = models.ManyToManyField(Glass_cabinets)
class Meta:
verbose_name_plural = "Артикул шкафа"
def __str__(self):
return self.artikul_cabinets
It is necessary to make the selection on the field
glass_cabinets = models.ManyToManyField(Glass_cabinets)
The selection is done as follows
data = Artikul_cabinets.objects.filter(Q(glass_cabinets=perf) &
Q(glass_cabinets=glass)
perf and glass the variables with different values.
And I returned to my empty QuerySet, although the database element with the parameters 'perf' and 'glass' are present in the record.
Tell me what I'm doing wrong.
also tried:
data = Artikul_cabinets.objects.filter(Q(glass_cabinets=perf),
Q(glass_cabinets=glass)
and also did not work, though if you put the operator '|' the conditions or work out correctly.
So I think you should do Artikul_cabinets.objects.filter(glass_cabinets=perf).filter(glass_cabinets=glass)
check How to filter model results for multiple values for a many to many field in django