how to set a None value with django form - python

i have a form with a google map and when the user does not click on the map i need to send latitude and longitude as None to views.py ,this is views.py :
if request.method == "POST":
if request.user.is_authenticated:
if True:
form = CreatMeetingForm(request.POST,request.FILES)
print(request.POST)
if form.is_valid():
if 'id' in request.POST:
obj= get_object_or_404(Meeting, id=request.POST.get('id'))
form = CreatMeetingForm(request.POST or None,request.FILES or None, instance= obj)
meeting= form.save(commit= False)
members = form.cleaned_data['members_email']
try:
meeting.lat= round(form.cleaned_data['lat'],14)
meeting.lng = round(form.cleaned_data['lng'],14)
except :
meeting.lat= None
meeting.lng = None
meeting.host = request.user
update = True
meeting.save()
else :
meeting=form.save(commit=False)
members = form.cleaned_data['members_email']
try:
meeting.lat= round(form.cleaned_data['lat'],14)
meeting.lng = round(form.cleaned_data['lng'],14)
except :
meeting.lat= None
meeting.lng = None
meeting.host = request.user
update=False
meeting.save()
else:
print('form not valid')
form.errors["code"] = 0
return JsonResponse(form.errors)
else:
return HttpResponse('Unauthorized', status=401)
and this is my model fields:
lat = models.DecimalField(max_digits=19, decimal_places=16,blank=True,null=True)
lng = models.DecimalField(max_digits=19, decimal_places=16,blank=True,null=True)
when i want to create a new form my code works but when in edit mode and i send the id in requet.POST it raises this error:
{"lat": ["Enter a number."], "lng": ["Enter a number."], "code": 0}
it seems i get the error in form.is_valid bcs i can see the print('form not valid')
any suggestion?

It might help to add the default value to the field definitions like so:
lat = models.DecimalField(
max_digits=19,
decimal_places=16,
blank=True,
null=True,
default=None
)
lng = models.DecimalField(
max_digits=19,
decimal_places=16,
blank=True,
null=True,
default=None
)
Edit: If this doesn't help, please share the definition of CreatMeetingForm.

Related

I need to get the value of the field that we enter in the form and immediately take action on it

I need to get the value of the field that we enter in the form (in this case, these are the days of reservation) and immediately calculate the cost of the reservation based on it
And the problem is that I don’t understand how to get the value of these very fields (so this is not QuerySet request, and not accessing the database)
This is my views:
def booking(request):
error = ''
if request.method == 'POST':
form = BookingForm(request.POST)
if form.is_valid():
booking = form.save(commit=False)
booking.user = request.user
booking.sum = #create sum function
form.save()
return redirect('account')
else:
error = 'Форма не корректна'
form = BookingForm()
context = {
'form': form,
'error': error
}
return render(request, 'bookings/booking.html', context)
And this is models:
class Booking(models.Model):
startdate = models.DateField('Startgdate')
finishdate = models.DateField('Finishdate')
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
sum = models.PositiveIntegerField('Sum')
fullname = models.CharField('Full name', max_length=50)
pnumber = models.PositiveBigIntegerField('Phone number')
def __str__(self):
return self.fullname
class Meta:
verbose_name = 'Booking'
verbose_name_plural = 'Bookings'
thanks in advance
This is needs Ajax (which can be done by JQuery or Fetch API) that runs on input onchange and a simple view that receives that value and return a the value of cost reservation.

I trial make Notification for Comment

I trial make Notification for Comment
by Many-to-many relationships
how fix it
raise TypeError(
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use NotfFaId.set() instead.
[17/Apr/2021 03:37:31] "POST /forum/addcomment/ HTTP/1.1" 500 73061
class CommentT(MPTTModel):
Topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='author')
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
NotfFaId = models.ManyToManyField( User, related_name='NotfFaVId', default=None, blank=True)
content = models.TextField()
publish = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)
class MPTTMeta:
order_insertion_by = ['publish']
def addcomment(request):
if request.method == 'POST':
if request.POST.get('action') == 'delete':
id = request.POST.get('nodeid')
c = CommentT.objects.get(id=id)
c.delete()
return JsonResponse({'remove': id})
else:
comment_form = NewCommentTForm(request.POST)
# print(comment_form)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
result = comment_form.cleaned_data.get('content')
user = request.user.username
user_comment.author = request.user
user_comment.NotfFaId = request.user
user_comment.save()
Topic.objects.get(id = request.POST.get('Topic') ).NotfFaV.add(request.user)
# CommentT.objects.get(id=user_comment.id).NotfFaId.add(request.user)
return JsonResponse({'result': result, 'user': user,'id': user_comment.id })
don't work ,
raise ValueError('"%r" needs to have a value for field "%s" before '
ValueError: "<CommentT: CommentT object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used.
def addcomment(request):
if request.method == 'POST':
if request.POST.get('action') == 'delete':
id = request.POST.get('nodeid')
c = CommentT.objects.get(id=id)
c.delete()
return JsonResponse({'remove': id})
else:
comment_form = NewCommentTForm(request.POST)
# print(comment_form)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
result = comment_form.cleaned_data.get('content')
user = request.user.username
user_comment.author = request.user
user_comment.NotfFaId.set( request.user )
user_comment.save()
Topic.objects.get(id = request.POST.get('Topic') ).NotfFaV.add(request.user)
return JsonResponse({'result': result, 'user': user,'id': user_comment.id })
thank Iain Shelvington,
it is word
I Called CommentT.objects.get(id=user_comment.id).NotfFaId.add(request.user) after user_comment.save(). You can't add many to many entries before you have saved both sides of the relationship – Iain Shelvington 2 hours ago
def addcomment(request):
if request.method == 'POST':
if request.POST.get('action') == 'delete':
id = request.POST.get('nodeid')
c = CommentT.objects.get(id=id)
c.delete()
return JsonResponse({'remove': id})
else:
comment_form = NewCommentTForm(request.POST)
# print(comment_form)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
result = comment_form.cleaned_data.get('content')
user = request.user.username
user_comment.author = request.user
# user_comment.NotfFaId.set( request.user )
user_comment.save()
Topic.objects.get(id = request.POST.get('Topic') ).NotfFaV.add(request.user)
CommentT.objects.get(id=user_comment.id).NotfFaId.add(request.user)
return JsonResponse({'result': result, 'user': user,'id': user_comment.id })

Editing Django formset data creating new records instead of updating

Please Help!
I am trying to update a group of formsets that are related the main form (Project Information) by the main forms pk. The create form works fine, but I am finding it extremely difficult to implement the update version.
It's the save as an update part that I can't figure out for the formsets. The main form updates the database correctly. The formsets just create new records instead of updating the existing ones. I do not know how to instance the formsets.
Here the code.
view.py
#login_required
def edit_project(request):
SampleInformationFormSet = formset_factory(SampleInformationForm, extra=1)
DissolutionMethodsFormSet = formset_factory(DissolutionMethodsForm, extra=1)
form = ProjectInformationForm(request.POST or None)
si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
d_formset = DissolutionMethodsFormSet(request.POST or None, prefix='d')
if request.method == 'POST':
form = ProjectInformationForm(request.POST or None)
si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
d_formset = DissolutionMethodsFormSet(request.POST or None, prefix='d')
pi_pk = ''
p = ''
if form.is_valid():
pi_pk = form.cleaned_data['hd']
p = ProjectInformation.objects.get(pk=pi_pk)
form = ProjectInformationForm(request.POST, instance=p)
form.save() # This form saves correctly
for si_form in si_formset:
si_form.save() # I do not know how to attach an instance to these formsets
for d_form in d_formset:
d_form.save()
messages.success(request, 'Your project has been updated!')
return redirect('edit_project')
else:
pass
form = ProjectInformationForm(request.POST or None)
si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
messages.warning(request, 'There was an error saving your form.')
study_id_select = list(
ProjectInformation.objects.values('dissolution_study_id', 'id').filter())
context = {'form': form, 'si_formset': si_formset, 'd_formset': d_formset, 'study_id_select': study_id_select}
return render(request, 'main/edit_project.html', context)
models.py I'm just going to include part of three of the seven models to keep this a little shorter.
class ProjectInformation(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE)
compound_code = models.CharField(max_length=60)
product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE)
main_component = models.CharField(max_length=100)
class SampleInformation(models.Model):
sample_index = models.CharField(max_length=30)
sample_type_purpose = models.ForeignKey(SampleTypePurpose, on_delete=models.CASCADE)
specification_number = models.CharField(max_length=20, blank=True, null=True)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE, blank=True, null=True)
class DissolutionMethods(models.Model):
number_of_methods = models.IntegerField(default=1,
validators=[MaxValueValidator(10), MinValueValidator(1)],
blank=True, null=True)
dissolution_method_index = models.CharField(max_length=10)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE, blank=True, null=True)
forms.py
class ProjectInformationForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['hd'] = forms.CharField(widget=forms.HiddenInput, required=False)
class Meta:
model = ProjectInformation
fields = '__all__'
class SampleInformationForm(forms.ModelForm):
class Meta:
model = SampleInformation
fields = '__all__'
Please help if you can. This project has been a trial by fire and the flames are hot!
Finally solved it myself.
#login_required
def edit_project(request):
SampleInformationFormSet = formset_factory(SampleInformationForm, extra=1)
DissolutionMethodsFormSet = formset_factory(DissolutionMethodsForm, extra=1)
form = ProjectInformationForm(request.POST or None)
si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
d_formset = DissolutionMethodsFormSet(request.POST or None, prefix='d')
if request.method == 'POST':
form = ProjectInformationForm(request.POST or None)
si_formset = SampleInformationFormSet(request.POST or None, prefix='si')
d_formset = DissolutionMethodsFormSet(request.POST or None, prefix='d')
pi_pk = ''
p = ''
if form.is_valid():
pi_pk = form.cleaned_data['hd']
p = ProjectInformation.objects.get(pk=pi_pk)
form = ProjectInformationForm(request.POST, instance=p)
form.save()
si = p.sampleinformation_set.all() # All the Methods related to the instance
d = p.dissolutionmethods_set.all()
si_cnt = 0
for si_form in si_formset:
if si_form.is_valid():
update = si_form.save(commit=False)
update.pk = si[si_cnt].pk
update.save()
si_cnt += 1
d_cnt = 0
for d_form in d_formset:
if d_form.is_valid():
update = d_form.save(commit=False)
update.pk = d[d_cnt].pk
update.save()
d_cnt += 1

Saving FieldIn Django Via API Call

I'm trying to create a new CustomerDetail object whenever an api is called.But the issue is, Whenever I try to create something for the favorite meal multi-selectfield, I get this error:
MultiValueDictKeyError at /api/customer/favorite_meal/
"'favorite_meal'"
This is the api:
#csrf_exempt
def favorite_meal(request):
if request.method == "POST":
access_token = AccessToken.objects.get(token = request.GET.get("access_token"),
expires__gt = timezone.now())
customer = access_token.user.customer
details = CustomerDetailSerializer(
CustomerDetails.objects.create(
customer = customer,
favorite_mean = request.POST["favorite_meal"]
))
return JsonResponse({"status" : "success"})
Here are my models:
class CustomerDetails(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer')
TYPE = (
('Time', (
('Breakfast', 'Breakfast'),
('Lunch', 'Lunch'),
('Dinner', 'Dinner'),
)),
)
favorite_meal = MultiSelectField(choices=TYPE)
interested_in = MultiSelectField(choices=CATEGORIES)
likes = models.ManyToManyField('Product')
completed_orders = models.IntegerField(default = "0", blank=True)
shares = models.IntegerField(default = "0", blank=True)
average_order = models.FloatField(default = "0.0", blank=True)
def __str__(self):
return self.customer.user.get_full_name()
In the request, I'm trying to select breakfast and lunch via the api. How would I do this?
Sending Params:
The status says success but, there is no Customer data in details
The MultiValueDictKeyError error raises when you are trying to access favorite_meal from request.POST, but the favorite_meal doesn't exist in request.POST
Try this
#csrf_exempt
def favorite_meal(request):
if request.method == "POST":
if not 'access_token' in request.POST:
return JsonResponse({"status": "'access_token' missing in POST payload"})
access_token = AccessToken.objects.get(token=request.POST.get("access_token"),
expires__gt=timezone.now())
customer = access_token.user.customer
if not 'favorite_meal' in request.POST and not request.POST["favorite_meal"]:
return JsonResponse({"status": "'favorite_meal' missing in POST payload"})
details = CustomerDetailSerializer(
CustomerDetails.objects.create(
customer=customer,
favorite_mean=request.POST["favorite_meal"]
))
return JsonResponse({"status": "success"})
Screenshot
UPDATE
#csrf_exempt
def favorite_meal(request):
if request.method == "POST":
if not 'access_token' in request.POST:
return JsonResponse({"status": "'access_token' missing in POST payload"})
access_token = AccessToken.objects.get(token=request.POST.get("access_token"),
expires__gt=timezone.now())
customer = access_token.user.customer
if not 'favorite_meal' in request.POST and not request.POST["favorite_meal"]:
return JsonResponse({"status": "'favorite_meal' missing in POST payload"})
for favorite_meal in request.POST["favorite_meal"]:
details = CustomerDetailSerializer(
CustomerDetails.objects.create(
customer=customer,
favorite_mean=favorite_meal
))
return JsonResponse({"status": "success"})

Error when inserting into database Django

I have a new problem, it is when I insert in the database the news, it adds but without the region. How can I insert the comment with the correct region?
Here is my view :
def index_region(request,region):
try:
actuCommentaire = Actu.objects.get(region=region)
except ObjectDoesNotExist:
actuTempo = Actu(region=region)
actuCommentaire = actuTempo.commentaire
form = UpdateActu(request.POST or None, instance=actuCommentaire)
if form.is_valid():
form.save()
return redirect('index.html')
Here is my model "Actu" :
class Actu(models.Model):
commentaire = models.TextField(max_length=200, null=True)
region = models.CharField(max_length=30, null=True)
def __str__(self):
return self.region
Here is my form :
class UpdateActu(forms.ModelForm):
class Meta:
model = models.Actu
fields = ['commentaire']
widgets = {
'commentaire': forms.Textarea(attrs={'class': 'form-control', 'id': 'exampleTextarea', 'rows': '2'})
}
Here is the result when inserting into the database :
enter image description here
I found how to solve the problem.
Here is my new view :
try:
actuCommentaire = Actu.objects.get(region=region)
except ObjectDoesNotExist:
actuTempo = Actu(region=region)
actuCommentaire = actuTempo.commentaire
form = UpdateActu(request.POST or None, instance=actuCommentaire)
if form.is_valid():
if Actu.objects.filter(region=region).count() == 0:
formActu = Actu(commentaire=request.POST['commentaire'], region=region)
formActu.save()
else:
form.save()
return redirect('index.html')

Categories