Django Formset - Update Value in Views.py before saving - python

I am trying to set a value on each form in the formset to a single value.
I am not sure how to accomplish this... views.py function below:
Like:
formset.idcst_cnt = id
views.py
def customer_contacts(request, id):
ContactFormSet = modelformset_factory(AppContactCnt, can_delete=True, fields=(
'name_cnt', 'phone_cnt', 'email_cnt', 'note_cnt', 'receives_emails_cnt'), max_num=3, extra=3)
formset = ContactFormSet(queryset=AppContactCnt.objects.filter(idcst_cnt=id), prefix='contact')
if request.method == 'GET':
context = {'formset': formset}
return render(request, 'customer_contacts.html', context=context)
if request.method == 'POST':
formset = ContactFormSet(request.POST, prefix='contact')
if formset.is_valid():
print("we're updating contacts for " + str(id))
# formset.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

Under if request.method == 'POST' you can do for form in formset

Related

UnboundLocalError: local variable 'formset' referenced before assignment in DJANGO

Hey so I have this list of campaigns that have a button to start and stop the process.
'''
from django.shortcuts import render
from .models import Campaign
from .forms import CampaignForm, CampaignStatusFormSet
def home_view(request):
queryset = Campaign.objects.all()
if request.method == 'POST':
form_type = request.POST.get('id')
if form_type == 'campaign_status':
formset = CampaignStatusFormSet(
request.POST, request.FILES,
queryset=queryset,
)
for form in formset.forms:
if form.is_valid():
form.save()
else:
formset = CampaignStatusFormSet(queryset=queryset)
campaigns_and_forms = list(zip(queryset, formset))
context = {
'formset': formset,
'campaigns_and_forms': campaigns_and_forms,
}
return render(request, 'campaigns_in_progress.html', context)
'''
But when I run it and click on the button to change play/pause it shows this error.
UnboundLocalError: local variable 'formset' referenced before assignment
Can anyone help me refactor this code so that it doesn't show this error?
You can remove the else block so that the formset is available even after clicking on the play/pause buttons. When you send a POST request, and campaign_status is as expected, formset variable is not available in the conext and hence the error.
from django.shortcuts import render
from .models import Campaign
from .forms import CampaignForm, CampaignStatusFormSet
def home_view(request):
queryset = Campaign.objects.all()
if request.method == 'POST':
form_type = request.POST.get('id')
if form_type == 'campaign_status':
formset = CampaignStatusFormSet(
request.POST, request.FILES,
queryset=queryset,
)
for form in formset.forms:
if form.is_valid():
form.save()
# Set form with new created campaign
queryset = Campaign.objects.all()
formset = CampaignStatusFormSet(queryset=queryset)
campaigns_and_forms = list(zip(queryset, formset))
context = {
'formset': formset,
'campaigns_and_forms': campaigns_and_forms,
}
else:
formset = CampaignStatusFormSet(queryset=queryset)
campaigns_and_forms = list(zip(queryset, formset))
context = {
'formset': formset,
'campaigns_and_forms': campaigns_and_forms,
}
return render(request, 'campaigns_in_progress.html', context)
I don't know if this is the right solution and if it won't break something else but for now it works perfectly. I just declared the formset before the if statement so it kind of declares 2 times.
If anyone could tell me if this is a good solution I would be greatful
'''
def home_view(request):
queryset = Campaign.objects.all()
formset = CampaignStatusFormSet(
request.POST, request.FILES,
queryset=queryset,
)
if request.method == 'POST':
form_type = request.POST.get('id')
if form_type == 'campaign_status':
formset = CampaignStatusFormSet(
request.POST, request.FILES,
queryset=queryset,
)
for form in formset.forms:
if form.is_valid():
form.save()
else:
formset = CampaignStatusFormSet(queryset=queryset)
campaigns_and_forms = list(zip(queryset, formset))
context = {
'formset': formset,
'campaigns_and_forms': campaigns_and_forms,
}
return render(request, 'campaigns_in_progress.html', context)
'''

How can I get the primary key of the last insered quote?

I have 2 views: display_quote and quote_create.
def display_quote(request, pk):
items_quote = Quote.objects.filter(pk=pk)
items_quote_line = LineQuote.objects.all().filter(num_quote_id=pk)
form = QuoteLineForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.save()
total = 0
for item in items_quote_line:
total = total + item.get_price()
context = {'items_quote': items_quote,
'items_quote_line': items_quote_line,
'form': form,
'total':total
}
return render(request, 'quote/quote_display.html', context)
def quote_create(request):
form = QuoteForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.save()
return render(request, 'quote/quote_create.html', {'form': form})
After creating a quote, I want to redirect to "display_quote" (the quote creted).
Error obtained:
The view quote.views.quote_create didn't return an HttpResponse object. It returned None instead.
def quote_create(request):
form = QuoteForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.save()
return render(request, 'quote/quote_create.html', {'form': form})
return render(request, "...", {})
return something by default. Else conditions are not handled here...

Using Value From One View in Another View Django

In View 1's form their is a field called 'reference'. I need to access whatever value is submitted in that field in View 2 and set a variable equal to it. Right now I am just getting an error "orders matching query does not exist".
This is what I'm trying (I've commented the code in view2 to indicate where im getting the error).
views.py
def view1(request, pk):
item = get_object_or_404(Manifests, pk=pk)
if request.method == "POST":
form = CreateManifestForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('view2')
else:
form = CreateManifestForm(instance=item)
return render(request, 'edit_manifest_frombrowse.html', {'form': form})
def view2(request):
form = CreateManifestForm(request.POST)
if request.method == "POST":
if form.is_valid():
form.save()
...
reference_id = request.POST.get('reference') #this is how Im trying to get reference from the previos view
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist"
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)
forms.py
class CreateManifestForm(forms.ModelForm):
class Meta:
model = Manifests
fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB')
I just want to be able to use whatever value is submitted in the 'reference' field in view1 in view2 and assign it equal to reference_id
Something like this:
from django.urls import reverse
def view1(request, pk):
item = get_object_or_404(Manifests, pk=pk)
if request.method == "POST":
form = CreateManifestForm(request.POST, instance=item)
if form.is_valid():
obj = form.save()
reference_id = request.POST.get('reference') or obj.reference.id
return redirect(reverse('view2')+f'?reference={reference_id}')
else:
form = CreateManifestForm(instance=item)
return render(request, 'edit_manifest_frombrowse.html', {'form': form})
def view2(request):
if request.method == "POST":
form = CreateManifestForm(request.POST)
if form.is_valid():
form.save()
...
data = getattr(request, 'POST', None) or getattr(request, 'GET', {})
reference_id = data.get('reference') #this is how Im trying to get reference from the previos view
data = Manifests.objects.all().filter(reference__reference=reference_id)
form = CreateManifestForm(initial={
'reference': Orders.objects.get(reference=reference_id), #this is where im getting "does not exist"
})
total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases'))
context = {
'reference_id': reference_id,
'form': form,
'data': data,
'total_cases': total_cases['cases__sum'],
}
return render(request, 'manifest_readonly.html', context)

How to save to a database on click

In my previous question, I recently asked how to make forms.py in Django 1.9 show in HTML. now that this is done im trying to make a button which when the selection has been made (in this case it's radiobuttons) it will post to the database and move on with the questionaire.
Currently im attempting to make it post in my views.py but im having no luck in making it send the data.
def question1(request):
question_form = QuestionForm()
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
return render(request, 'music.questions2,html')
return render(request, 'music/question1.html', locals())
Would really appreciate the help in making this happen.
def question1(request):
question_form = QuestionForm()
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
form.save() # save to db!
return render(request, 'music.questions2,html')
return render(request, 'music/question1.html', locals())
# models.py
class Question(models.Model):
# Q_CHOICES is the previous declared one
question = models.CharField(max_length=20, choices=Q_CHOICES)
# forms.py
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
fields = ['question']
widgets = {
'question': forms.RadioSelect()
}
Use: form.save()
def question1(request):
if request.method == 'POST':
form = QuestionForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'music.questions2,html')
else:
form = QuestionForm()
return render(request, 'music/question1.html', locals())

Form validation failing in Django

Im trying to get a form to validate with a Charfield but using the Select widget.
Here is my view.py code:
def mpld3plot(request):
form = PlotlyPlotForm()
form.fields['plot_file'].widget.choices = own_funcs.uploaded_files(string=False)
if request.method == 'POST':
print(form.is_valid())
if form.is_valid():
return HttpResponseRedirect('/mpld3')
else:
pass
else:
pass
return render(request, 'evert/plot.html', {'plottype': 'MPLD3',
'form': form})
Below is my forms.py code:
class Mpld3PlotForm(forms.Form):
plot_file = forms.CharField(widget=forms.Select(choices=[('', 'a'), ('', 'b')]))
The form does not validate on submit. I update the choices dynamically based on uploaded files. Any help would be appreciated.
Turns out I did not pass the request object to the form.
The view.py file should look like the following:
def mpld3plot(request):
form = PlotlyPlotForm(request.POST)
form.fields['plot_file'].widget.choices = own_funcs.uploaded_files(string=False)
if request.method == 'POST':
print(form.is_valid())
if form.is_valid():
return HttpResponseRedirect('/mpld3')
else:
pass
else:
pass
return render(request, 'evert/plot.html', {'plottype': 'MPLD3',
'form': form})

Categories