this is views.py
def registerItem(request):
print(request)
try:
print("====111", request.method)
if request.method == 'POST':
print("=========222", request.POST)
form = ItemForm(request.POST)
print("====333", form.is_bound)
print("====444", form)
print("====555", form.cleaned_data['mart_id']())
print("====666", form.is_valid())
if form.is_valid():
mart = MartModel.objects.get(id__exact=form.cleaned_data['mart_id'])
print("====666", mart)
seq = ItemModel.objects.filter(mart_id__exact=mart).values('seq').order_by('-seq')[:1]
if seq:
seq = seq[0]['seq']+1
else:
seq = 1
# form.save()
item = ItemModel(mart_id=mart, seq=seq, name=form.cleaned_data['name'], price=form.cleaned_data['price'], expirationDate=form.cleaned_data['expirationDate'], stockYn=form.cleaned_data['stockYn'])
item.save()
form = ItemForm()
return render(request, 'mobileWeb/admin/register_item.html', {'form':form})
else:
form = ItemForm()
return render(request, 'mobileWeb/admin/register_item.html', {'form':form})
except Exception as ex:
print('====777 : Error occured : ', ex)
request.POST value is correct. you can confirm it by log No.2.
form is bound correctly. you can confirm it by log No.3.
but the form failed to receive values. you can confirm it by log No.4.
this is forms.py
class MartForm(forms.ModelForm):
class Meta:
model = MartModel
fields = ['name', 'address', 'tell', 'phone', 'xPosition', 'yPosition']
class ItemForm(forms.ModelForm):
choicesQueryset = MartModel.objects.all().values('id', 'name')
choicesDic = []
for choice in choicesQueryset:
choicesDic.append((choice['id'], choice['name']))
mart_id = forms.CharField(label='mart', widget=forms.Select(choices=choicesDic))
class Meta:
model = ItemModel
fields = ['mart_id', 'name', 'price', 'expirationDate', 'stockYn']
this is models.py
class MartModel(models.Model):
name = models.CharField(max_length=20, blank=False)
address = models.TextField(blank=False)
tell = models.CharField(blank=True, max_length=12)
phone = models.CharField(blank=True, max_length=11)
imageFileNo = models.CharField(blank=True, max_length=3)
xPosition = models.FloatField(blank=False)
yPosition = models.FloatField(blank=False)
delete_yn = models.CharField(blank=False, default="N", max_length=1)
ins_dttm = models.DateTimeField(blank=False, auto_now_add=True)
ins_user = models.CharField(blank=False, max_length=20, default='ADMIN')
upt_dttm = models.DateTimeField(blank=False, auto_now=True)
upt_user = models.CharField(blank=False, max_length=20, default='ADMIN')
class ItemModel(models.Model):
mart_id = models.ForeignKey('martModel', models.DO_NOTHING)
seq = models.IntegerField(blank=False)
name = models.CharField(blank=False, max_length=20)
price = models.IntegerField(blank=False)
expirationDate = models.DateField(blank=False)
stockYn = models.CharField(blank=False, max_length=1, default='Y')
delete_yn = models.CharField(blank=False, default="N", max_length=1)
ins_dttm = models.DateTimeField(blank=False, auto_now_add=True)
ins_user = models.CharField(blank=False, max_length=20, default='ADMIN')
upt_dttm = models.DateTimeField(blank=False, auto_now=True)
upt_user = models.CharField(blank=False, max_length=20, default='ADMIN')
class Meta:
unique_together = (
('mart_id', 'seq')
)
I know about that it must be a instance not a value when deal with the foreignKey.
but the error occured on binding time.
is this concerend with foreignKey??
================
after advice
no mart name is here.
this is forms.py
class ItemForm(forms.ModelForm):
mart = forms.ModelChoiceField(queryset=MartModel.objects.all(), to_field_name='name')
class Meta:
model = ItemModel
fields = ['mart', 'name', 'price', 'expirationDate', 'stockYn']
this is views.py
from django.shortcuts import render
from .forms import *
# Create your views here.
def index(request):
try:
marts = MartModel.objects.all().values('id', 'name', 'imageFileNo', 'xPosition', 'yPosition')
items = ItemModel.objects.filter(stockYn__exact='Y').values('mart', 'name', 'price', 'expirationDate').order_by('mart_id', 'seq')
return render(request, 'mobileWeb/index/index.html', {'marts':marts, 'items':items})
except Exception as ex:
print('Error occured : ', ex)
def registerMart(request):
try:
if request.method == 'POST' :
form = MartForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'mobileWeb/index/index.html')
else :
form = MartForm()
return render(request, 'mobileWeb/admin/register_mart.html', {'form':form})
except Exception as ex:
print('Error occured : ', ex)
def registerItem(request):
print(request)
try:
print("====111", request.method)
if request.method == 'POST':
print("=========222", request.POST)
form = ItemForm(request.POST)
print("====333", form.is_bound)
print("====444", form)
if form.is_valid():
mart = MartModel.objects.get(id__exact=form.cleaned_data['mart'])
print("====666", mart)
seq = ItemModel.objects.filter(mart__exact=mart).values('seq').order_by('-seq')[:1]
if seq:
seq = seq[0]['seq']+1
else:
seq = 1
# form.save()
item = ItemModel(mart=mart, seq=seq, name=form.cleaned_data['name'], price=form.cleaned_data['price'], expirationDate=form.cleaned_data['expirationDate'], stockYn=form.cleaned_data['stockYn'])
item.save()
form = ItemForm()
return render(request, 'mobileWeb/admin/register_item.html', {'form':form})
else:
form = ItemForm()
return render(request, 'mobileWeb/admin/register_item.html', {'form':form})
except Exception as ex:
print('====777 : Error occured : ', ex)
this is debug variable when make Item Form
this is debug variable about queryset
this is debug variable about 1st member of queryset
ofcourse I did makemigrations, migrate.
I don't know why are you trying to approach like this. ModelForm has very nice way to handle FK, and if you want to show name of the MartModel object, then you can use ModelChoiceField's to_field_name option. For example:
class ItemForm(forms.ModelForm):
mart_id = forms.ModelChoiceField(queryset=MartModel.objects.all(), to_field_name='name')
class Meta:
model = ItemModel
fields = ['mart_id', 'name', 'price', 'expirationDate', 'stockYn']
Also, please change the name of the field mart_id to mart, because underneath django creates a field name mart_id, if you assign the field name to mart.
Finally, in the view, you should not call cleaned_data[...] before calling form.is_valid(). Unless the form is validated, the data won't be available in cleaned_data.
Update
(from comments) Add a __str__ method at the bottom of MartModel class:
class MartModel(models.Model):
...
def __str__(self):
return self.name
Related
I have a specific problem with my forms. I think it would be better to share my codes instead of explaining the problem in detail.
However, to explain in a nutshell; inside my model I have field OneToOneField and model of that field has inlineformset_factory form. My new model also has a form and I want to save both forms.
I get the following error when I want to save the offer update form:
TypeError at /ru/mytarget/offer-update/T2GTTT053E9/
AdminOfferUpdateView.form_invalid() missing 2 required positional arguments: 'request_form' and 'request_item_formset'
Models:
request.py
class RequestModel(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="customer_requests")
id = ShortUUIDField(primary_key=True, length=10, max_length=10, prefix="T", alphabet="ARGET0123456789", unique=True, editable=False)
status = models.BooleanField(default=True)
request_title = models.CharField(max_length=300)
......
updated_on = models.DateTimeField(auto_now=True)
published_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.request_title)
class Meta:
verbose_name_plural = "Requests"
verbose_name = "Request"
def get_absolute_url(self):
return reverse('mytarget:customer_request_details', kwargs={'pk': self.id})
class RequestItem(models.Model):
request_model = models.ForeignKey(RequestModel, on_delete=models.CASCADE, related_name="request_items")
product_name = models.CharField(max_length=300)
......
offer.py
class OfferModel(models.Model):
request_model_name = models.OneToOneField(RequestModel, on_delete=models.CASCADE, primary_key=True)
status = models.BooleanField(default=True)
offer_validity = models.CharField(max_length=50, blank=True)
......
updated_on = models.DateTimeField(auto_now=True)
published_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.request_model_name)
class Meta:
verbose_name_plural = "Offers"
verbose_name = "Offer"
def get_absolute_url(self):
return reverse('mytarget:admin_offer_update', kwargs={'pk': self.request_model_name})
Forms:
request_create_form.py
class CustomerRequestForm(forms.ModelForm):
disabled_fields = ("customer",)
class Meta:
model = RequestModel
fields = ("customer", "request_title", "delivery_time", "shipping_country", "shipping_address",
"preferred_currency", "shipping_term", "delivery_term")
widgets = {
'request_title': TextInput(attrs={'class': 'form-control tableFormInputs',
'placeholder': _('Example: Printers, Toner, and Cartridges')}),
......
}
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('customer')
super(CustomerRequestForm, self).__init__(*args, **kwargs)
self.fields['preferred_currency'].queryset = self.fields['preferred_currency'].queryset.translated().order_by("translations__currency_name")
self.fields['shipping_term'].queryset = self.fields['shipping_term'].queryset.translated().order_by("translations__shipping_term")
for field in self.disabled_fields:
self.fields[field].widget = forms.HiddenInput()
self.fields[field].disabled = True
class CustomerRequestItemForm(forms.ModelForm):
class Meta:
model = RequestItem
fields = ("product_name", "product_info", "target_price", "price", "quantity", "dimensions", "net_weight", "gross_weight",
"hs_or_tn_ved_code", "brand", "manufacturer", "origin_country", "manufacturer_address")
exclude = ()
widgets = {
'product_name': TextInput(attrs={'class': 'form-control tableFormInputs'}),
......
}
RequestItemInlineFormset = inlineformset_factory(RequestModel, RequestItem,
form=CustomerRequestItemForm,
extra=1,
can_delete=True
)
offer_update_form.py
class AdminOfferUpdateForm(forms.ModelForm):
disabled_fields = ()
hidden_fields = ("request_model_name",)
request_title = forms.CharField(required=False, widget=TextInput(attrs={'class': 'form-control tableFormInputs', 'placeholder': _('Example: Printers, Toner, and Cartridges')}))
......
class Meta:
model = OfferModel
fields = ("request_model_name", "offer_validity", ......
)
widgets = {'offer_validity': TextInput(attrs={'class': 'form-control tableFormInputs'}),
......
'is_detailed_offer': CheckboxInput(attrs={'class': 'form-check-input'}),
}
def __init__(self, *args, **kwargs):
super(AdminOfferUpdateForm, self).__init__(*args, **kwargs)
self.fields["preferred_currency"].choices = [(c.id, c.currency_name) for c in Currency.objects.all()]
self.fields["shipping_term"].choices = [(st.id, st.shipping_term) for st in ShippingTerm.objects.all()]
self.fields["delivery_term"].choices = [(dt.id, dt.delivery_term) for dt in DeliveryTerms.objects.all()]
self.fields["request_statuses"].choices = [(r.id, r.status) for r in RequestStatus.objects.all()]
for field in self.disabled_fields:
self.fields[field].disabled = True
for field in self.hidden_fields:
self.fields[field].widget = forms.HiddenInput()
Views:
offer_update_view.py
#method_decorator([login_required(login_url=reverse_lazy("accounts:signin")), user_is_superuser], name='dispatch')
class AdminOfferUpdateView(UpdateView):
model = OfferModel
form_class = AdminOfferUpdateForm
template_name = "mytarget/admin_offer_update.html"
def get_context_data(self, **kwargs):
context = super(AdminOfferUpdateView, self).get_context_data(**kwargs)
if self.request.POST:
context['request_form'] = AdminOfferUpdateForm(self.request.POST, instance=self.object.request_model_name)
context['request_item_formset'] = RequestItemInlineFormset(self.request.POST, instance=self.object.request_model_name)
else:
context['request_form'] = AdminOfferUpdateForm(instance=self.object.request_model_name)
context['request_item_formset'] = RequestItemInlineFormset(instance=self.object.request_model_name)
return context
def form_valid(self, form):
context = self.get_context_data()
request_form = context['request_form']
request_item_formset = context['request_item_formset']
with transaction.atomic():
self.object = form.save()
if request_form.is_valid() and request_item_formset.is_valid():
request_form.instance = self.object.request_model_name
request_form.save()
request_item_formset.instance = self.object.request_model_name
request_item_formset.save(commit=False)
for ri in request_item_formset:
ri.save(commit=False)
request_item_formset.save()
return super(AdminOfferUpdateView, self).form_valid(form)
def form_invalid(self, form, request_form, request_item_formset):
return self.render_to_response(
self.get_context_data(form=form, request_form=request_form, request_item_formset=request_item_formset)
)
def get_initial(self):
self.object = self.get_object()
if self.object:
return {"request_model": self.object.request_model_name, "request_item_formset": self.object.request_model_name}
return super().initial.copy()
def get_success_url(self):
return reverse('mytarget:admin_offer_update', kwargs={'pk': self.object.id})
I solved my problem. I created a button function that creates a new model with inheritance of other model fields. In this way, there is no need to edit the form of the other model inside the form of my current model.
I everyone, I have a problem with a django's view. My goal is to change the 'execute' field into 'True' if newOrder is buy and there is some other sell order with a inferior price. And reverse for sell newOrders. I want to change the 'execute' field for the newOrder and also for the other order (in pairs). That's my code:
views.py
def order(request):
form = OrderForm()
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid():
new_order = form.save()
if new_order.buy is True:
sellOrder = Order.objects.filter(sell=True, execute=False,
price__lte=new_order.price).first().update(execute=True)
new_order.execute = True
sellOrder.save()
else:
buyOrder = Order.objects.filter(buy=True,
execute=False,price__gte=new_order.price).first().update(execute=True)
new_order.execute = True
buyOrder.save()
new_order.profile = request.user
new_order.save()
return redirect('home')
else:
form = OrderForm()
contex = {'form': form}
return render(request, 'app/new_order.html', contex)
models.py
class Profile(models.Model):
_id = ObjectIdField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
wallet = models.FloatField()
class Order(models.Model):
_id = ObjectIdField()
profile = models.ForeignKey(User, on_delete=models.CASCADE)
datetime = models.DateTimeField(auto_now_add=True)
buy = models.BooleanField(blank=True)
sell = models.BooleanField(blank=True)
price = models.FloatField()
quantity = models.FloatField()
execute = models.BooleanField(blank=True)
But something goes wrong. This is the error:
AttributeError at /new_order/
'NoneType' object has no attribute 'update'
sellOrder returns a count of updated rows, not the object updated
sellOrder = Order.objects.filter(sell=True, execute=False,
price__lte=new_order.price).first().update(execute=True)
instead try
sellOrder = Order.objects.filter(sell=True, execute=False,
price__lte=new_order.price).first()
new_order.execute = True
sellOrder.execute = True
sellOrder.save()
I know there are a lot of similar questions here, but none of them seem to be working with my view in Django 1.8 with a ModelForm.
I have a user profile form that works as long as I have each required field in the template context, but I only want each logged in user to fill out their own form.
I'm doing something wrong here, and I'm not sure what the problem is. Can someone correct me? I've spent hours looking at other posts and trying various suggestions from SO. I'm getting "NOT NULL constraint failed: camp_userprofile.user_id"
Here's my models.py:
class UserProfile(models.Model):
user = models.OneToOneField(User)
picture = models.ImageField(upload_to='profile_images', blank=True)
city = models.CharField(max_length = 20)
needs_camp_bike = models.BooleanField(default=False)
diet_lifestyle = models.CharField(max_length = 200, choices=What_are_you, null=True, blank=True)
meal_restrictions = models.CharField(max_length = 200, blank= True)
other_restrictions = models.CharField(max_length=100, blank=True)
arrival_day = models.IntegerField(choices=Days)
departure_day = models.IntegerField(choices=Days)
date = models.DateTimeField(auto_now_add=True, blank=True)
def __str__(self):
return '%s %s %s %s %s %s %s %s %s' %(
self.user, self.picture, self.city,
self.needs_camp_bike,
self.diet_lifestyle, self.meal_restrictions, self.other_restrictions,
self.arrival_day, self.departure_day
)
My forms.py
class UserProfileForm(ModelForm):
class Meta:
Fish = "Fish"
Mammal = "Mammal"
Vegetarian = "Vegetarian"
Omnivore = "Omnivore"
Onions = "Onions"
Cucumber = "Cucumber"
Peppers = "Peppers"
Gluten_free = "Gluten_free"
Vegan = "Vegan"
Shellfish = "Shellfish"
Olives = "Olives"
Pork = "Pork"
Soy = "Soy"
Dairy = "Dairy"
Cilantro = "Cilantro"
Quinoa = "Quinoa"
Nightshades = "Nightshades"
Nuts = "Nuts"
Pescaterian = "Pescaterian"
Restrictions = (
(Mammal, "Mammal"),
(Onions, "Onions"),
(Cilantro, "Cilantro"),
(Soy, "Soy"),
(Dairy, "Dairy"),
(Quinoa, "Quinoa"),
(Pork, "Pork"),
(Olives, "Olives"),
(Dairy, "Dairy"),
(Peppers, "Peppers"),
(Cucumber, "Cucumber"),
(Nightshades, "Nightshades"),
(Nuts, "Nuts")
)
model = UserProfile
fields = ('picture', 'city',
'needs_camp_bike', 'diet_lifestyle',
'other_restrictions', 'arrival_day',
'departure_day', 'meal_restrictions')
widgets = {
'meal_restrictions': forms.widgets.CheckboxSelectMultiple(choices=Restrictions),
}
and my views.py
#login_required
def profile(request):
form = UserProfileForm(request.POST)
print(request.user)
if request.method == 'POST':
if form.is_valid():
form.save(commit=False)
form.user =request.user.username
form.save(commit=True)
else:
print(messages.error(request, "Error"))
return render(request, "profile.html", RequestContext(request, {'form': form, 'profile': profile,}))
You shouldn't do form.user = request.user.username, because form.user won't add the user to the form. You should capture the object that form.save(commit=false) returns, then assign the user to that object and save it.
Also you cannot assign a user field with username, username is only a string not User object. You should do this instead:
if form.is_valid():
userprofile = form.save(commit=False)
userprofile.user = request.user
userprofile.save()
I'm trying to make an editing page for the users to update an object data. However, form.is_valid() keeps failing, I have no idea why.
My model:
class Thread(models.Model):
title = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
creator = models.ForeignKey(User, blank=True, null=True)
body = models.TextField(max_length=10000)
USER_TYPES = (
('INI','Iniciante'),
('INT','Intermediário'),
('AVA','Avançado')
)
user_type = models.CharField(max_length=20, choices = USER_TYPES, default='INI')
category = models.ForeignKey(Category)
orcamento = models.IntegerField(default=0)
slug = models.SlugField(max_length=40, unique=True)
def get_absolute_url(self):
return "/%s/" % self.slug
def __str__(self):
return self.title
def save(self, **kwargs):
slug_str = "%s %s" % (self.category, self.title)
unique_slugify(self, slug_str)
super(Thread, self).save(**kwargs)
My view:
def edit_thread(request, thread_slug):
thread = Thread.objects.get(slug=thread_slug)
if request.method == 'POST':
form = EditThread(request.POST)
if form.is_valid():
thread.title = form.cleaned_data['title']
thread.orcamento = form.cleaned_data['orcamento']
thread.user_type = form.cleaned_data['experiencia']
thread.body = form.cleaned_data['pergunta']
thread.save()
return HttpResponseRedirect('/thread' + thread.get_absolute_url())
else:
data = {'title' : thread.title, 'experiencia':thread.user_type, 'orcamento' : thread.orcamento, 'pergunta': thread.body}
form = EditThread(initial=data)
return render(request, 'edit_thread.html', {
'form': form })
My form:
class EditThread(forms.ModelForm):
title = forms.CharField(label='Título', max_length=200, error_messages=my_default_errors)
orcamento = forms.IntegerField(label='Preço máximo', error_messages=my_default_errors)
experiencia = forms.ChoiceField(label='Você é um usuário...', choices=Thread.USER_TYPES, error_messages=my_default_errors)
pergunta = forms.CharField(label='Pergunta', widget=forms.Textarea, error_messages=my_default_errors)
class Meta:
model = Thread
def __init__(self, *args, **kwargs):
super(EditThread, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Div('title',
'experiencia',
PrependedAppendedText('orcamento', 'R$', ',00', active=True),
'pergunta',
FormActions(
Submit('save', 'Salvar alterações'),
)))
When accessing the page, the form gets pre-populated with the object's data as it should.
Your form should be inherited from the simple forms.Form instead of the forms.ModelForm:
class EditThread(forms.Form):
...
I would suggest you look at django's class based UpdateView. It can generate an update form for you or you could give it a custom ModelForm by overriding the form_class attribute on your view. When using a ModelForm, you also have to specify which model the form is for eg:
class EditThread(forms.ModelForm):
"field definitions ..."
class Meta:
model = Thread
fields = ['my_field_1', 'my_field_2']
Can I get the value of the field which I am not showing in form? I want to pass ref_id in session.
This is my model:
def _createId():
"""
"""
return hexlify(os.urandom(4))
class jobpost(models.Model):
item_types = (
('Full Time','Full Time'),
('Part Time','Part Time'),
('Contract','Contract'),
)
posttype= (
('Job','Job'),
('Classified','Classified'),
('Project/Task','Project/Task'),
('Internship','Internship'),
)
#user = models.ForeignKey(User)
job_id = models.AutoField(primary_key=True)
country= models.ForeignKey(Country,to_field = 'country_name', null=True)
#user = models.ForeignKey(User, editable = False)
post_type = models.CharField(max_length=255,null=True, choices=posttype,default='Job')
job_type = models.CharField(max_length=255,null=True, choices=item_types,default='Full Time')
job_location = models.CharField(max_length=255,null=True)
job_title = models.CharField(max_length=255,null=True)
job_description = models.TextField(null=True)
start_date = models.DateField(null=True, help_text="mm/dd/yyyy")
end_date = models.DateField(null=True, help_text="mm/dd/yyyy")
how_to_apply = models.CharField(max_length=255,null=True)
ref_id = models.CharField(max_length=32, default=_createId)
def __unicode__(self):
return unicode(self.country)
return self.post_type
return self.job_location
return self.job_type
return self.job_title
return self.job_description
return self.start_date
return self.end_date
return self.how_to_apply
return self.ref_id
means i am not displaying it in my form and i want to pass this value in session in next form..
can anyone tell me how can i do this? and how can i pass the primary key of the form in next form ?
forms.py
class JobPostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(JobPostForm, self).__init__(*args, **kwargs)
self.fields['ref_id'].widget = forms.HiddenInput()
class Meta:
model = jobpost
views.py
def your_view(request):
if request.method == 'POST':
form = JobPostForm(request.POST)
if form.is_valid():
request.session['ref_id'] = form.cleaned_data.get('ref_id')
pk = form.save()
request.session['pk'] = pk.id
else:
form = JobPostForm()
return render(request, page.html,{'form': form})