So in this formset the first field saves & updates just fine... but when I want to add a new object, it doesn't work out so well.
#Views.py
def edit_auto(request):
car = Auto.objects.filter(user=request.user)
CarFormSet = modelformset_factory(Auto, form=AutoForm, max_num=3)
if request.method == 'POST':
formset = CarFormSet(request.POST, request.FILES, queryset=car)
if formset.is_valid():
formset.save(commit=False)
formset.user = request.user
formset.save()
return render_to_response('manage_users.html', {'message':'Success! The user has been updated!'}, context_instance=RequestContext(request))
else:
formset = CarFormSet(queryset=car)
return render_to_response('mycar.html', locals(), context_instance=RequestContext(request))
#forms.py
class AutoForm(forms.ModelForm):
class Meta:
model = Auto
user = Auto.user
exclude = ('user',)
Is it something in the template? If it was a single instance of the form, form.user = request.user normally saves but this doesn't. Any suggestions? Thank you for your help.
For the user-assigning step, just iterate over the formset.
...
if request.method == 'POST':
formset = CarFormSet(request.POST, request.FILES, queryset=car)
if formset.is_valid():
formset.save(commit=False)
for form in formset:
form.user = request.user
formset.save()
...
Related
I'm learning how to use django rest API for my project. I created a stored_procedure on my postgresql and I want to incorporate it to my project
I did make one but without serializers or any related to the rest API, just plain django
here's my views.py without the rest_framework
def add(request):
if request.method == "POST":
if request.POST.get('office_id') and request.POST.get('sem') and request.POST.get('sy') and request.POST.get('incident_details') and request.POST.get('resolution') and request.POST.get('studid'):
saverec = Clearanceinsert()
saverec.office_id = request.POST.get('office_id')
saverec.sem = request.POST.get('sem')
saverec.sy = request.POST.get('sy')
saverec.remarks = request.POST.get('incident_details')
saverec.resolution = request.POST.get('resolution')
saverec.studid = request.POST.get('studid')
cursor = connection.cursor()
email = request.user.userid
cursor.execute("select add_clearance_item('"+saverec.office_id+"','"+saverec.sem+"','"+saverec.sy+"','"+saverec.remarks+"','"+saverec.resolution+"','"+email+"','"+saverec.studid+"')")
return render(request, 'clearance/index.html')
else:
return render(request, 'clearance/add.html')
views.py using rest_framework
#api_view(['POST'])
def saveitem(request):
if request.method == 'POST':
saveserialize = Insertserialize(data=request.data)
if saveserialize.is_valid():
cursor = connection.cursor()
cursor.execute("select add_clearance_item('"+saveserialize.office_id+"','"+saveserialize.sem+"','"+saveserialize.sy+"','"+saveserialize.remarks+"','"+saveserialize.resolution+"','"+saveserialize.studid+"')")
return Response(saveserialize.data, status=status.HTTP_201_CREATED)
return Response(saveserialize.data, status=status.HTTP_400_BAD_REQUEST)
When using rest_framework code, It's throwing an error 'Insertserialize' object has no attribute 'office_id'
serializer.py
class Insertserialize(serializers.ModelSerializer):
class Meta:
model = ClearanceItem
fields = [
'office_id',
'sem',
'sy',
'remarks',
'resolution',
'studid'
]
hope someone can help me with this
I am trying to create a form where user can create a team. I did the view, the model and the form, But, somehow the template return with only a submit button and I don't know how to solve it. Any help is of great help, thanks.
Here is the view:
def team_create_view(request):
title = 'Create'
form = TeamCreateForm(request.POST or None, request.FILES or None)
coach = get_coach(request.user)
if request.method == 'POST':
if form.is_valid():
form.instance.coach = coach
form.save()
return redirect(reverse("club", kwargs={ 'id': form.instance.id }))
context = {
'title': title,
'form': form
}
return render(request, "team_create.html", context)
Now the form:
class TeamCreateForm(forms.Form):
form = forms.CharField(widget=forms.Textarea)
class Meta:
model = Team
fields = ('form', 'name', 'logo', 'birth', 'coach', 'players')
The model:
class Team(models.Model):
name = models.CharField(max_length=200)
logo = models.ImageField(default="", blank=True, null=True)
birth = models.DateField(default="", blank=True, null=True)
coach = models.ForeignKey(User, on_delete=models.CASCADE, default="", blank=True, null=True)
players = models.ManyToManyField(User, related_name='players')
def __str__(self):
return self.name
And finally the form:
You form render is written in inside the POST method condition. So in GET method does not render.Please try this.
First Method
Here we just change render code to outside of POST method checking if condition.
def team_create_view(request):
title = 'Create'
form = TeamCreateForm(request.POST or None, request.FILES or None)
coach = get_coach(request.user)
if request.method == 'POST':
if form.is_valid():
form.instance.coach = coach
form.save()
return redirect(reverse("club", kwargs={'id': form.instance.id }))
context = {'title': title,'form': form}
return render(request, "team_create.html", context)
Second Method
Here we check if GET method.
def team_create_view(request):
title = 'Create'
form = TeamCreateForm(request.POST or None, request.FILES or None)
coach = get_coach(request.user)
if request.method == 'POST':
if form.is_valid():
form.instance.coach = coach
form.save()
return redirect(reverse("club", kwargs={'id': form.instance.id }))
elif request.method == "GET":
context = {'title': title,'form': form}
return render(request, "team_create.html", context)
I'm trying to add a checkbox to a form, if true, I want it to add a row to a through model for a manytomanyfield, but I can't access the checkbox variable. Here is the form that I have added it to, and it appears as expected, so half there:
class ProjectUpdateForm(forms.ModelForm):
completed = forms.BooleanField(). # this variable here
class Meta:
model = Update
fields = [
'category',
'update'
]
Here is my view that I was hoping to deal with it:
def project_update_view(request, slug):
obj = Project.objects.get(slug=slug)
if request.method == 'POST':
form = ProjectUpdateForm(request.POST)
form.instance.project = obj
if form.is_valid():
print(f"================{form.completed}") # attempt to find variable
form.save()
return redirect('project-list')
else:
form = ProjectUpdateForm()
context = {
"form": form,
"object": obj
}
return render(request, 'project_portal/project_update.html', context)
This gives me the error in the title. So I now don't understand what an attribute is, I thought it was an aspect of the class represented by a variable. How can I access this checkbox variable so I can work with it please?
This is in the cleaned_data of the form:
def project_update_view(request, slug):
obj = Project.objects.get(slug=slug)
if request.method == 'POST':
form = ProjectUpdateForm(request.POST)
form.instance.project = obj
if form.is_valid():
print(form.cleaned_data['completed'])
form.save()
return redirect('project-list')
I am trying to update the record with PUT method, Getting AttributeError: 'QuerySet' object has no attribute '_meta'.
My models.py:
class TableInfo(models.Model):
table_name = models.CharField(max_length=10)
columns = JSONField(null=False)
serializer.py:
class TableInfoSerializer(serializers.ModelSerializer):
class Meta:
model = TableInfo
fields = '__all__'
views.py :
#api_view(['GET','PUT'])
def table_info(request):
try:
queryset = TableInfo.objects.all()
print("1")
except TableInfo.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
print("2")
serializer_class = TableInfoSerializer(queryset, many=True)
return Response(serializer_class.data)
elif request.method == 'PUT':
print(request.data)
serializer = TableInfoSerializer(queryset, data=request.data)
if serializer.is_valid():
serializer.save()
print("4")
return HttpResponse(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
code is breaking at if serializer.is_valid():
On "GET" I am getting the result. Please help me with "PUT" method.
This error happens with PUT because the serializer tries to access the Meta class on the model instance it is updating, but fails because you are not passing a model instance - you're passing a queryset as indicated in the comments.
So you need to pass an instance, and to specify which instance you would normally pass the instance id via the URL. For that you would be best to separate out your views, and create a table_detail view for retrieving and updating a specific instance.
#api_view(['GET','PUT'])
def table_detail(request, pk):
try:
table_info = TableInfo.objects.get(pk=pk) # Lookup a specific object
except TableInfo.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer_class = TableInfoSerializer(table_info)
return Response(serializer_class.data)
elif request.method == 'PUT':
serializer = TableInfoSerializer(table_info, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Your table_info view can then just handle the list operation.
#api_view(['GET'])
def table_info(request):
if request.method == 'GET':
queryset = TableInfo.objects.all()
serializer_class = TableInfoSerializer(queryset, many=True)
return Response(serializer_class.data)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
get request data in Django form
There's part of my Guest Model:
class Guest(models.Model):
event = models.ForeignKey(Event, related_name='guests')
user = models.ForeignKey(User, unique=True, related_name='guests')
...
Form to get the response from the Guest:
class RSVPForm(forms.Form):
attending_d= forms.ChoiceField(choices=VISIBLE_ATTENDING_CHOICES, initial='yes', widget=forms.RadioSelect)
attending_b = forms.ChoiceField(choices=VISIBLE_ATTENDING_CHOICES, initial='yes', widget=forms.RadioSelect)
number_of_guests = forms.IntegerField(initial=0)
comment = forms.CharField(max_length=255, required=False, widget=forms.Textarea)
....
def save(self):
guest = self.guest_class.objects.get(user=1)
guest.attending_status_d = self.cleaned_data['attending_d']
guest.attending_status_b = self.cleaned_data['attending_b']
guest.number_of_guests = self.cleaned_data['number_of_guests']
guest.comment = self.cleaned_data['comment']
guest.save()
return guest
The problem is in save method. How can I associate guest with the currently logged in user?
guest = self.Guest.objects.get(user=1)
Instead of user=1 I need to have id of the currently logged in user.
Thank you!
I found the way :)
Write a __init__ method on the form :
def __init__(self, user, *args, **kwargs):
self.user = user
super(RSVPForm, self).__init__(*args, **kwargs)
Change view function, and pass request.user to the form
def event_view(request, slug, model_class=Event, form_class=RSVPForm,
template_name='rsvp/event_view.html'):
event = get_object_or_404(model_class, slug=slug)
if request.POST:
form = form_class(request.user, request.POST)
if form.is_valid():
guest = form.save()
return HttpResponseRedirect(reverse('rsvp_event_thanks',
kwargs={'slug': slug, 'guest_id': guest.id}))
else:
form = form_class(request.user)
return render_to_response(template_name, {
'event': event,
'form': form,
}, context_instance=RequestContext(request))
the line of the save() method would look like this now:
guest = self.guest_class.objects.get(user=self.user)