def createProject(request):
form = ProjectForm()
initial_data = {
'responsible':request.user.username
}
yonetici = Project(host=request.user)
if request.method == 'POST':
form = ProjectForm(request.POST, instance=yonetici,initial=initial_data)
if form.is_valid():
form.save()
return redirect('home')
context = {'form': form}
return render(request, 'base/project_form.html', context)
i tried many solutions but i couldnt make it work where am i doing wrong?
Related
how do I not save the form data until the transaction is done which is in a different URL, if the shipping form and the payment options were to be in the same URL then there wouldn't be this problem but it's not so how do I go about this? thx!
views.py
def checkout(request):
if request.method == 'POST':
form = ShippingForm(request.POST)
if form.is_valid():
new_shipping = form.save(commit=False)
new_shipping.customer = customer
new_shipping.order = order
#how do I not save the data until the transaction is successful
new_shipping.save()
return redirect('store:checkout_shipping')
else:
form = ShippingForm()
else:
form = ShippingForm()
context = {"form": form}
return render(request, 'shop/checkout.html', context)
def checkout_payment(request):
return render(request, 'shop/checkout_payment.html', context)
urls.py
path('checkout', views.checkout, name="checkout"),
path('checkout_payment', views.checkout_payment, name="checkout_payment"),
forms.py
class ShippingForm(forms.ModelForm):
address_one = forms.CharField(max_length=200)
address_two = forms.CharField(max_length=200)
I think what might help is to use sessions. Django will store this temporary data using session cookies. Here's the idea:
from django.forms.models import model_to_dict
def checkout(request):
form = ShippingForm(request.POST or None)
if form.is_valid():
new_shipping = form.save(commit=False)
new_shipping.customer = customer
new_shipping.order = order
request.session['partial-data'] = model_to_dict(new_shipping)
return redirect('store:checkout_shipping')
context = {"form": form}
return render(request, 'shop/checkout.html', context)
def checkout_payment(request):
# I'm guessing here is where the rest of the data
# is to be filled in. The data of the previous view
# is already here stored in the cookie
full-form-data = request.session['partial-data']
full-form-data['extra-field-1'] = 'something'
full-form-data['extra-field-2'} = 'something else'
form = ShippingForm(full-form-data or None)
if form.is_valid():
form.save()
context = {
'form': form
}
return render(request, 'shop/checkout_payment.html', context)
I have this TemplateView:
class DamageEntry(TemplateView):
template_name = "damage/damageadd.html"
def get(self, request):
general = General.objects.get(pk=1)
form = DamageEntryForm()
args = {'form': form,
'general': general,
}
return render(request, self.template_name, args)
def post(self, request):
general = General.objects.get(pk=1)
form = DamageEntryForm(request.POST)
form.non_field_errors()
if form.is_valid():
post = form.save(commit=False)
if self.request.user.is_authenticated():
post.user = request.user
post.userip = get_client_ip(request) # το IP του χρήστη
location = get_cocation(post.lat, post.lng)
post.location = location
post.formatted_address= location.formatted_address
post.entry_date = datetime.datetime.now(tz=timezone.utc)
post.save()
form = DamageEntryForm()
args = {'form': form,
'general': general
}
return http.HttpResponseRedirect('damage/add/')
else:
print('form is not valid')
print(form.errors)
# form = DamageEntryForm()
args = {'form': form,
'general': general
}
return render(request, self.template_name, args)
It works fine for create new record.
I want to use thw same view for update, because of the extra code on Post section.
I use this URL for update:
# /damage/damage/list/1
url(r'damage/list/(?P<pk>[0-9]+)/$', views.DamageEntry.as_view(), name="damage-by-id"),
Can I do this? How can I pass pk for create and update record?
how to add an error message to be displayed if the user tried to add an entry that is already on the table
forms.py
class AddCatForm(ModelForm):
class Meta:
model = Categories
fields = ['category_name']
labels = {
'category_name': ('إسم الفئة الجديدة')
}
error_messages = {
'category_name': {
'unique': ('الفئة موجودة بالفعل')
}
}
views.py
def add_cat(request):
if request.method == "POST":
form = AddCatForm(request.POST)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.save()
return redirect('/')
else:
form = AddCatForm()
return render(request, "add_cat.html", {'form': form})
When i add an entry that is already there , it just does nothing , i want it to view an error
You might be getting an error which you will not see because of your indentation. Amend it to:
def add_cat(request):
if request.method == "POST":
form = AddCatForm(request.POST)
if form.is_valid():
model_instance = form.save(commit=False)
model_instance.save()
return redirect('/')
else:
form = AddCatForm()
return render(request, "add_cat.html", {'form': form})
The data is not showing in fields when i update data in updateview
def dis_update(request, pk, template_name='sales/distributor_form.html'):
alldistributor = get_object_or_404(Distributor, pk=pk)
if request.method=='POST':
form = DistributorForm(request.POST, instance=alldistributor)
if form.is_valid():
form.save()
return redirect('index.html')
else:
form=DistributorForm()
return render(request, template_name, {'form':form})
def dis_update(request, pk, template_name='sales/distributor_form.html'):
alldistributor = get_object_or_404(Distributor, pk=pk)
if request.method=='POST':
form = DistributorForm(request.POST, instance=alldistributor)
if form.is_valid():
form.save()
return redirect('index.html')
else:
form=DistributorForm(instance=alldistributor)
return render(request, template_name, {'form':form})
else:
form = DistributorForm(instance=alldistributor)
return render(request, template_name, {'form': form})
def new_topic(request):
"""add new topic"""
if request.method != 'POST':
form = TopicForm()
else:
form = TopicForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('learning_logs:topics'))
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
The error I got:
The view learning_logs.views.new_topic didn't return an HttpResponse object. It returned None instead.
And I have searched many related problems as well as tested them, yet they did not work.Could you please give me some help,thanks.
def new_topic(request):
"""add new topic"""
if request.method == 'POST':
form = TopicForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('learning_logs:topics'))
else:
form = TopicForm()
return render(request, 'learning_logs/new_topic.html', {'form': form})