I have a view with model form, the ModelForm doesn't really contain all fields in the model. other fields I've used the methods of form.field = value before form.save(), but all of this fields being saved as default. none take the value am trying to give. here are the code :
def PostAd(request):
ad_post_form = AdPostForm()
if request.user.is_authenticated:
obj = Account.objects.get(user=request.user)
if request.method == "POST":
ad_post_form = AdPostForm(request.POST, request.FILES)
if ad_post_form.is_valid():
ad_post_form.created_by = request.user
if obj.role == 'admin':
ad_post_form.is_active = True
ad_post_form.save()
return redirect('home')
else:
ad_post_form = AdPostForm(request.POST, request.FILES)
else:
if request.method == "POST":
ad_post_form = AdPostForm(request.POST, request.FILES)
if ad_post_form.is_valid():
otp_number = random.randint(100000, 999999)
ad_post_form.otp = otp_number
ad_post_form.is_activated = False
ad_post_form.save()
current_id = ad_post_form.id
current_contact_email = request.POST.get('contact_email')
email_url_active = str(settings.URL_LOCAL) + 'new_ad/adidnumberis' + str(
current_id) + '/needactivate/activate/' + str(otp_number) + '/'
email_msg = "Please Confirm adding the Ad to Jehlum. Click link " + email_url_active
email = EmailMessage('Active Email', email_msg, to=[current_contact_email])
email.send()
return redirect('home')
else:
ad_post_form = AdPostForm()
context = {
'ad_post_form': ad_post_form,
}
return render(request, 'pages/post-ad.html', context)
the problem is ad_post_form.is_active = True is being saved as False(default)
also ad_post_form.otp = otp_number is being saved as 0 (default) and i need to give the spicific values i assigned here .
You need to get the model instance and set the attributes there. You so this by calling save with commit=False.
if ad_post_form.is_valid():
ad_post = ad_post_form.save(commit=False)
ad_post.created_by = request.user
...
ad_post.save()
Related
I have a form with counterparty, object and sections i connected them to each other with django-forms-dynamic package but object not connected to sections
Counterparty connected to object form but sections are not connected to object how can i fix that?
I guess that im wrong with 2 functions in forms.py: section_choices and initial_sections and they`re not connected to objects but dont know how to fix that
forms.py
class WorkLogForm(DynamicFormMixin, forms.ModelForm):
def object_choices(form):
contractor_counter = form['contractor_counter'].value()
object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter])
return object_query
def initial_object(form):
contractor_counter = form['contractor_counter'].value()
object_query = ObjectList.objects.filter(contractor_guid__in=[contractor_counter])
return object_query.first()
def section_choices(form):
contractor_object = form['contractor_object'].value()
section_query = SectionList.objects.filter(object=contractor_object)
return section_query
def initial_sections(form):
contractor_object = form['contractor_object'].value()
section_query = SectionList.objects.filter(object=contractor_object)
return section_query.first()
contractor_counter = forms.ModelChoiceField(
label='Контрагент',
queryset=CounterParty.objects.none(),
initial=CounterParty.objects.first(),
empty_label='',
)
contractor_object = DynamicField(
forms.ModelChoiceField,
label='Объект',
queryset=object_choices,
initial=initial_object,
)
contractor_section = DynamicField(
forms.ModelMultipleChoiceField,
label='Раздел',
queryset=section_choices,
initial=initial_sections,
)
views.py
#login_required
def create_work_log(request):
if request.method == 'POST':
form = WorkLogForm(request.POST, user=request.user)
if form.is_valid():
work_log = form.save(commit=False)
work_log.author = request.user
work_log = form.save()
messages.success(request, 'Данные занесены успешно', {'work_log': work_log})
return redirect('create_worklog')
else:
messages.error(request, 'Ошибка валидации')
return redirect('create_worklog')
form = WorkLogForm(user=request.user, initial=initial)
return render(request, 'contractor/create_work_log.html', {'form': form})
def contractor_object(request):
form = WorkLogForm(request.GET, user=request.user)
return HttpResponse(form['contractor_object'])
def contractor_section(request):
form = WorkLogForm(request.GET, user=request.user)
return HttpResponse(form['contractor_section'])
This may not be an answer you want but I use HTMX for these things. Here is a link to their example for this.
https://htmx.org/examples/value-select/
There is also a package plugin called Django-htmx.
You may need to learn HTMX but it is a mature technology, rather simple and reliable. I am unfamiliar with Django-forms-dynamic
I want to get value of j in test function, but it returns None, How i get value of this session variable.
This is index function where session variable is created and passing it.
def index(request):
j = ''
if request.method == "POST":
form = InputForm(request.POST)
if form.is_valid():
form.save()
try:
ids = form.cleaned_data['git_Id']
print(ids)
obj = sql()
query = f""" SELECT request_id FROM request_form_db.request_form_mymodel
where git_Id= '{ids}' ;
"""
print(query)
p = obj.fetch_query(query)
print("Query Result", p)
for i in p:
print("Result[0] : ", i[0])
print("Result : ", p)
i = i[0]
j = i
approve_url = f"http://127.0.0.1:8000/form/test?request_id={i}"
print("Url : ", approve_url)
form = InputForm()
else:
form = InputForm()
print('J : ', j)
request.session['j'] = j
print('Request ID Sent : ', j)
return render(request, 'home.html', {'form': form})
This is test function where i want to getting value of j, but here it returns None.
def test(request):
pro = request.session.get('j')
print("Request ID from Index View : ", pro)
if request.method == "POST":
form = TestForm(request.POST)
if form.is_valid():
print("Form is Valid")
selected = form.cleaned_data.get('myfield')
print(selected)
else:
rq = request_id["request_id"]
s = sql()
query = f"""update request_form_db.request_form_mymodel
set is_approved=1
where request_id = '{rq}' """
print(query)
s.update_query(query)
print("Updated Successfully")
form = TestForm()
else:
form = TestForm()
return render(request, 'test.html', {'form': form})
The code is working fine and no error when running the script, but i want to use value of j in test function as well. index and test both are view functionin django.
I just wanna get profile with full form or empty form.
def local_cabinet(request):
user_id = request.user.id
caruser = Checkout.objects.filter(user=request.user)
# form = CheckoutForms()
orders = request.user.orderitem_set.all()
total_orders = orders.count()
ready_order = request.user.order_set.all()
customer = Customer.objects.filter(user=request.user)
customer_form = CustomerForm()
Maybe here's problem I don't know:
if request.method == 'POST':
if customer.exists():
form = CustomerForm(request.POST, request.FILES, instance=customer)
else:
form = CustomerForm(request.POST)
if form.is_valid():
form.save()
context = {
'caruser': caruser,
'orders': orders,
'total_orders': total_orders,
'ready_order': ready_order,
'cat_selected': 0,
'customer_form': customer_form,
'customer': customer,
}
return render(request, 'localcabinet.html', context=context)
I don't know why I get this, maybe because I'm not right at saving the form.
You are missing User instance in form, that you probably need to pass it after form creation and before saving it.
You didn't provide model nor forms, but I guess it will look like this:
if request.method == 'POST':
...
else:
form = CustomerForm(request.POST)
form.user = request.user
if form.is_valid():
form.save()
...
Another thing is that you assign queryset instead of single object with filter method:
customer = Customer.objects.filter(user=request.user) # gives queryset with probably one object
customer = Customer.objects.get(user=request.user) # gives an object - but gives Error if there is None or more than one
Probably the best approach to get single object is with try and except:
try:
customer = Customer.objects.get(user=request.user)
except Customer.DoesNotExists:
customer = None
then later instead of if customer.exists() you can use simple if customer.
Here's my code
#login_required
def upload(request):
form_type = ''
transcript = Transcript()
transcript.file_path = ''
if request.method == 'POST':
if 'file_form' in request.POST:
file_form = FileForm(request.POST, request.FILES)
if file_form.is_valid():
path = handle_uploaded_file(request.FILES['file'], request.user)
transcript.file_path = path
transcript.user = request.user
export_form = InfoForm()
form_type = 'info_form'
elif 'info_form' in request.POST:
if transcript.file_path:
info_form = InfoForm(request.POST)
if info_form.is_valid():
transcript.user = request.user
transcript.title = info_form.cleaned_data.get('title')
transcript.instructions = info_form.cleaned_data.get('instructions')
transcript.save()
return HttpResponseRedirect('thanks')
else:
raise ValueError('Transcript object has no file path attribute')
else:
export_form = FileForm()
form_type = 'file_form'
return render(request, 'transcription/upload.html', {'form': export_form, 'form_type': form_type})
always, the file-form is called before the info-form, so the code in the if statement
if transcript.file_path:
#...
should always execute. But the ValueError always gets raised, meaning transcript.file_path is reset. How does this happen, and how can it be fixed?
file_form and info_form in POST are names of the different submit buttons, so I know which form I am dealing with.
def handle_uploaded_file(file, user):
id = randint(0, 10000)
user_dir = settings.MEDIA_ROOT + '/' + str(user.id).replace(".", "") + '/'
path = user_dir + file.name.replace(".mp3", str(id) + ".mp3")
if not os.path.exists(user_dir):
os.makedirs(user_dir)
with open(path, 'wb+') as destination:
for chunk in file.chunks():
destination.write(chunk)
file = File(destination)
info = {'path': path, 'file': file}
return path
So it was a rookie mistake.
I didn't know that during each post request the whole view gets called again.
So I just initialized my variables
form_type = ''
transcript = Transcript()
transcript.file_path = ''
outside the view and voila!
When i have this view, It only change username a password from first Form, but it would save any data from second form. Why?
if request.method == 'POST': # If the form has been submitted...
username_a_heslo = UserCreationForm(request.POST, prefix = "začátek")
přidat_údaje = UcitelZmenaForm(request.POST, prefix = "konec")
if username_a_heslo.is_valid() and přidat_údaje.is_valid(): # All validation rules pass
změnajména = request.user
změnajména.username = username_a_heslo.cleaned_data["username"]
změnajména.save()
zmenahesla=request.user.set_password(username_a_heslo.cleaned_data["password1"])
# primary = username_a_heslo.save()
cast_form = Ucitel.objects.all().filter(user=request.user)
form = UcitelZmenaForm(přidat_údaje.cleaned_data, instance=cast_form[0])
form.save
#b = přidat_údaje.save()
return HttpResponseRedirect('/hlavni_stranka/')
else:
username_a_heslo = UserCreationForm(prefix = "začátek")
přidat_údaje = UcitelZmenaForm(prefix = "konec")
return render(request, 'registration/prihlasen.html', {'prvni_prihlaseni':prvni_prihlaseni,'první_form': username_a_heslo,'druhý_form':přidat_údaje})
You did not call the function on the second one, you only have form.save when you need form.save().