'Solution for deleting by "name"
I need solution for deleting Profesor by his 'name':
class Profesor(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
suername = models.CharField(max_length=200, null=True)
Imagine is to ask user on html page to input 'name' of Profesor that he want to delete And then in views.py to delete Profesor by that 'ime' How can i do that?
I try to create form where i get 'name':
class getName(forms.Form):
name = forms.IntegerField()
And then i views.py:
def obrisiProfesora(request):
form = getName()
if request.method=="POST":
form = getName(requst.POST)
form.save()
context = {'form':form}
profesor = Profesor.objects.filter(name=form.name)
return render(request, 'brisanje_profesora.html', context)
But i dont know how to contionue this
Solution 1:[1]
- Class names are idiomatically
PascalCasein Python, sogetNamewould beGetName. However,NameFormmight be more apt, since that's what it is, a form for a name. - Similarly, functions are idiomatically
snake_case. - Why would the name field be an integer field, when the
namefield in the model is aCharField? form.save()isn't a thing for forms that aren't modelforms. That being said, I don't think you've tried that code very hard, since it'd crash atrequstnot being a thing, norcontexthaving been defined.
All in all, with a plain function view you might want something like
class NameForm(forms.Form):
name = forms.CharField(required=True)
def delete_professor(request):
form = NameForm(data=(request.POST if request.method == "POST" else None))
if form.is_bound and form.is_valid():
professor = Profesor.objects.get(name=form.cleaned_data["name"])
professor.delete()
return render(request, 'brisanje_profesora.html', context)
or with a class-based view (so you don't need to do so much work yourself),
class DeleteProfessorView(FormView):
form_class = NameForm
template_name = 'brisanje_profesora.html'
def form_valid(self, form):
professor = Profesor.objects.get(name=form.cleaned_data["name"])
professor.delete()
Some error handling is elided from both solutions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AKX |
