I tried how to save this code. it shows the form in the template but when the form filled and submit the data isn't saving to the database here is my views.py
def create_tables(request):
restaurant = Restaurant.objects.get(user=request.user)
print(restaurant)
form = TablesForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
user.refresh_from_db()
user.restaurant = restaurant
user.name = form.cleaned_data.get('name')
user.time = form.cleaned_data.get('time')
user.save()
return redirect('/')
args = {
'table': restaurant,
'form': form
}
return render(request, 'main/tt.html', args)
and also here is my forms.py
class TablesForm(forms.ModelForm):
name = forms.CharField(max_length=250, label="Table Name")
time = forms.ModelChoiceField(queryset=Time.objects.all())
class Meta:
model = Table
fields = [
'name',
'time',
]
so help me please.
In the views.py remove the instance and user.refresh_from_db and change to this
form = TablesForm(request.POST or None)
if form.is_valid():
user = form.save(commit=False)
user.restaurant = restaurant
user.name = form.cleaned_data.get('name')
user.time = form.cleaned_data.get('time')
user.save()
I hope this will help.
Related
I've a category and I've added a form for user in each category.
So I've two fields to fill and after filling them correctly I submit but the page reload, and nothing appears in my DB... only one error on Image field: This field required. I don't really know what's wrong here.
class Picture(models.Model):
catego = models.ForeignKey(Catego,on_delete=models.CASCADE,related_name="catego_pictures")
user = models.ForeignKey(User, blank=True, null=True,on_delete=models.CASCADE,related_name='user_pictures')
image = models.ImageField(upload_to='nutriscore/')
pictureoption = models.CharField(max_length=20,choices=Pictureoption.choices,default=Pictureoption.HOME,)
publishing_date = models.DateField(auto_now_add=True)
class CreatePictureForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(CreatePictureForm, self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_method="post"
self.helper.layout = Layout(
Field("image",css_class="single-input"),
Field("pictureoption",css_class="single-input"),
)
self.helper.add_input(Submit('submit','Upload a pic',css_class="single-input textinput textInput form-control"))
class Meta:
model = Picture
fields = [
'image',
'pictureoption',
]
def __str__(self):
return self.catego.name
views.py
#login_required(login_url='/cooker/login')
def catego(request, slug):
catego = Catego.objects.get(slug=slug)
context = {
'catego': catego
}
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CreatePictureForm(request.POST)
# check whether it's valid:
if form.is_valid():
form.instance.catego = self.object
form.instance.user = self.request.user
form.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
else:
form = CreatePictureForm()
context['form'] = form # add `form` to the context
return render(request, 'post_catego.html', context)
here is the answer
#login_required(login_url='/cooker/login')
def catego(request, slug):
catego = Catego.objects.get(slug=slug)
context = {
'catego': catego
}
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = CreatePictureForm(request.POST, request.FILES)
# check whether it's valid:
if form.is_valid():
form.instance.catego = catego
form.instance.user = request.user
form.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
else:
form = CreatePictureForm()
context['form'] = form # add `form` to the context
return render(request, 'post_catego.html', context)
I need to assign posts to user in Django. I created
user = models.ForeignKey('authentication.CustomUser', on_delete=models.CASCADE)
and then if I display this model in my form.html I have to choice one of all users, if I don't display user in my form.html the form's isn't save my views file :
def formularz(request):
form = DodajForm(request.POST)
if form.is_valid():
ogloszenie = form.save(commit=False)
ogloszenie.user = request.user
ogloszenie.save()
return redirect('atrakcje:after')
else:
ogloszenie = DodajForm()
context = {
'form': form,}
return render(request, 'formularz.html', context)
Can i please know how to resolve it?
Rewrite the form to exclude the user field:
class DodajForm(forms.ModelForm):
class Meta:
model = Dodaj
exclude = ['user']
In the view, you better alter the instance, and let the form do the save logic, since a ModelForm can also save many-to-many fields:
def formularz(request):
if request.method == 'POST':
form = DodajForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('atrakcje:after')
else:
ogloszenie = DodajForm()
context = {'form': form}
return render(request, 'formularz.html', context)
This question already has answers here:
Saving Many To Many data via a modelform in Django
(2 answers)
Closed 4 years ago.
There's form with many fields (Date, Char, Text, Image, URL...) and they works fine. I mean values are submitted to DB as they must. But when I added ManyToManyField, it didn't save the value of this MultipleChoice form to DB. Any ideas why?
models.py:
class EventTag(models.Model):
tags = models.CharField(max_length=300)
def __str__(self):
return self.tags
class Article(models.Model):
source = models.CharField(max_length=100)
source_img = models.ImageField(default='default.png', blank=True)
#other fields
event_tags = models.ManyToManyField(EventTag, blank=True)
forms.py:
class CreateArticle(forms.ModelForm):
class Meta:
model = models.Article
fields = ['source', 'source_img', 'event_tags', ]
views.py:
def article_create(request):
if request.method == 'POST':
form = forms.CreateArticle(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return redirect('articles:list')
else:
form = forms.CreateArticle()
return render(request, 'articles/article_create.html', { 'form': form })
after save your form you must call form.save_m2m(). your view must be like this:
def article_create(request):
if request.method == 'POST':
form = forms.CreateArticle(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.author = request.user
instance.save()
form.save_m2m()
return redirect('articles:list')
else:
form = forms.CreateArticle()
return render(request, 'articles/article_create.html', { 'form': form })
Consider this simple user profile:
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
onboarding_step = models.SmallIntegerField(default='1')
What is the simplest method it increment the onboarding_step within UserProfile each time a separate form from a different model is submitted? For example:
Here's the ModelForm (from a separate model, Site) I am submitting:
class OnBoardingProgressForm(forms.ModelForm):
class Meta:
model = Site
fields = ( 'abc', 'xyz', )
And here is the view.py for the form:
if request.method == "POST":
form = OnBoardingProgressForm( request.POST )
if form.is_valid():
....
THIS CODE DOES NOT WORK BUT IS MY BEST GUESS:
last = request.user.profile
last.onboarding_step = 2
....
obj = form.save(commit=False)
obj.user = current_user
obj.save()
return render(request, "nextpage.html", {'form': form })
How can I increment the user.onboarding_step by 1?
if request.method == "POST":
form = OnBoardingProgress( request.POST )
if form.is_valid():
....
// Can I increment the code here? //
....
obj = form.save(commit=False)
obj.user = current_user
obj.save()
user_obj = UserProfile.objects.get(user=request.user)
user_obj.onboarding_step = user_obj.onboarding_step + 1
user_obj.save()
return render(request, "nextpage.html", {'form': form })
or you can make autoincrement field also.
Get the UserProfile object for the current user and then increment the value of the attribute of onboarding_step.
Try this:
if request.method == "POST":
form = OnBoardingProgress(request.POST)
current_user = request.user
if form.is_valid():
user_profile = UserProfile.objects.filter(user=current_user)[0] # get the user profile object for the current user
user_profile.onboarding_step += 1 # increment the value
user_profile.save() # save the object
obj = form.save(commit=False)
obj.user = current_user
obj.save()
return render(request, "nextpage.html", {'form': form })
How to validate the unique_together error and how to return the custom error message to the html through the view.py. Please help.
model.py:
class Pcq(models.Model):
product = models.ForeignKey(Product, null=False)
component = models.ForeignKey(Component, null=False)
quantity = models.IntegerField('Quantity', null=False)
class Meta:
unique_together = ("product", "component")
def __unicode__(self):
return self.product.productname
Form.py
class PcqForm(ModelForm):
class Meta:
model = Pcq
fields = ['component', 'quantity']
exclude = ['product']
Views.py
def pcq_add(request, product_id):
if request.method == 'POST':
form = PcqForm(request.POST or None)
if form.is_valid():
pcq = form.save(commit=False)
pcq.product_id = product_id
pcq.save()
form = PcqForm()
successmsg = "Component added successfully! Add another Component..."
return render(request, 'maps/pcq/pcq_add.html', {'form': form, 'product_id': product_id, 'successmsg': successmsg})
form = PcqForm()
return render(request, 'maps/pcq/pcq_add.html', {'form': form, 'product_id': product_id})
You need a custom clean function for the form
class PcqForm(ModelForm):
class Meta:
model = Pcq
fields = ['component', 'quantity']
exclude = ['product']
def clean(self):
cleaned_data = super(PcqForm, self).clean()
component = cleaned_data.get('component')
quantity = cleaned_data.get('quantity')
if component and quantity:
try:
Pcq.objects.get(
component=component,
quantity=quantity,
)
except Pcq.DoesNotExist:
# Yay
pass
else
raise forms.ValidationError(_("Error message goes here"))
UPDATE
Same concept as above but in the view.
def pcq_add(request, product_id):
if request.method == 'POST':
form = PcqForm(request.POST or None)
data = {
'form': form,
'product_id': product_id
}
if form.is_valid():
pcq = form.save(commit=False)
pcq.product_id = product_id
try:
pcq.save()
except IntegrityError:
# You'll need to check the exception that is raised
# Handle failed unique_together
pass
else:
form = PcqForm()
data['successmsg'] = (
"Component added successfully! Add another Component.")
else:
form = PcqForm()
data = {'form': form, 'product_id': product_id}
return render(request, 'maps/pcq/pcq_add.html', data)
Alternatively:
remove the exclude = ['product']
on GET pass product_id to the form form = PcqForm(initial_data={'product': product_id})
Use the form to validate unique_together (Not sure you even need a custom clean then)