Django Delete Objects - python

I'm receiving this error "TemplateDoesNotExist at /bookmarks/list/1/delete_link/" when attempting to delete an object in Django.
In forms.py I have:
class DeleteForm(forms.ModelForm):
class Meta:
model = Link
fields = []
In views.py:
def delete_link(request, link_id):
link_to_delete = get_object_or_404(Link, id=link_id)
context_dict = {'link_id': link_id}
if request.method == 'POST':
form = DeleteForm(request.POST, instance=link_to_delete)
if form.is_valid():
link_to_delete.delete()
return HttpResponseRedirect('bookmarks/list')
else:
form = DeleteForm(instance = link_to_delete)
template_vars = {'form': form}
return render_to_response(request, 'bookmarks/delete_link.html', template_vars)
urls.py:
url(r'^list/(?P<link_id>\w+)/delete_link/$', views.delete_link, name='delete_link'),
embedded in list.html (template for displaying a list of links, I want delete options next to each):
<a href='/bookmarks/list/{{ link.pk }}/delete_link/'> Delete</a>

Here:
return render_to_response(request, 'bookmarks/delete_link.html', template_vars)
Django can't find your template. do you have it in your TEMPLATES_DIRS?

Related

Django model from create a new record instead of updating old one

I am beginner in Django. My issue is that I updating my record but it's adding a new record instead of updating old one.
Where did I go wrong?
views.py
class EditProduct(TemplateView):
template_name = 'stock/editproduct.html'
def get(self, request, product_id):
productedit = get_object_or_404(Product, pk=product_id)
data=Product.objects.get(id=product_id)
form = EditProductForm(instance=data)
args = {'form':form, 'productedit':productedit}
return render(request, self.template_name, args)
def post(self, request, product_id):
form = EditProductForm(request.POST, request.FILES)
if form.is_valid():
productadded = form.save(commit=False)
productadded.saler = request.user
productadded.pub_date = timezone.datetime.now()
productadded.save()
return redirect('stock')
else:
args = {'form': form}
return render(request, self.template_name, args)
I'm assuming stock is the name of the app/folder that contains views.py, models.py, url.py.
views.py see here for documentation of UpdateViews.
from django.views.generic import UpdateView
from django.utils import timezone
from stock.models import Product
from stock.forms import EditProductForm
Class ProductUpdateView(UpdateView):
model = Product
form_class = EditProductForm
success_url = reverse_lazy('stock:product_list')
template_name = 'stock/editproduct.html'
def form_valid(self, form):
form.instance.saler = self.request.user
form.instance.pub_date = timezone.now()
return super().form_valid(form)
urls.py
from stock import views
app_name = 'stock'
urlpatterns = [
path('product/update/<int:pk>', views.ProductUpdateView.as_view(), name='product_update'),
path('product/list', views.ProductListView.as_view(), name='product_list'
]
The below snippet can be added to the html of the product page you want to update, this is generally the product details page generated by the details views class or function.
On that page add a button to take you to the update page passing in the id of the product you want to update.
<a class="btn btn-outline-warning waves-effect" href="{% url 'stock:product_update' pk=product.pk %}"> Update product</a>

Convert Function Based View to Class Based View

I have a Django 2.1 views.py that I wanted to convert to Class Based View, I am NOT Django advanced user, and I know that I did translate the Functions the wrong way. The code was ment to serve a Bootstrap Modal Ajax form, and don't ask me to go see some solution already built out there, I tried everything, even the ones that worked fine in standalone, they are not compatible/conflict with my template (Maybe jquery or ..). I did convert List View and so far Create View, but I keep getting this Error :
UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.
"A {% csrf_token %} was used in a template, but the context "
Here's my views.py that I want to convert to CBV :
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from django.template.loader import render_to_string
from .models import Book
from .forms import BookForm
from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView
#The Old function List view
#def book_list(request):
# books = Book.objects.all()
# return render(request, 'books/book_list.html', {'books': books})
#The New Class List view
class Book_list(ListView):
template_name = 'books/book_list.html'
model = Book
def save_book_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def book_create(request):
if request.method == 'POST':
form = BookForm(request.POST)
else:
form = BookForm()
return save_book_form(request, form, 'books/includes/partial_book_create.html')
def book_update(request, pk):
book = get_object_or_404(Book, pk=pk)
if request.method == 'POST':
form = BookForm(request.POST, instance=book)
else:
form = BookForm(instance=book)
return save_book_form(request, form, 'books/includes/partial_book_update.html')
def book_delete(request, pk):
book = get_object_or_404(Book, pk=pk)
data = dict()
if request.method == 'POST':
book.delete()
data['form_is_valid'] = True
books = Book.objects.all()
data['html_book_list'] = render_to_string('books/includes/partial_book_list.html', {
'books': books
})
else:
context = {'book': book}
data['html_form'] = render_to_string('books/includes/partial_book_delete.html', context, request=request)
return JsonResponse(data)
I've been strugling since 9 days now. asking around, asked even the developper of that code ... no answer..
I really appreciate it, thank you guys
You can try this to change you view's to class based view's
class BookList(ListView):
template_name = 'books/book_list.html'
model = Book
class BookCreate(CreateView):
template_name = "books/includes/partial_book_list.html"
model = Book
form_class = BookForm
success_url = 'success' #name of url you want to redirect to
class BookUpdate(UpdateView):
model = Book
form_class = BookForm
fields = ['name',] #field's you want to update
template_name = 'books/includes/partial_book_update.html'
success_url = 'success' #name of url you want to redirect to
class BookDelete(DeleteView):
model = Book
template_name = 'books/includes/partial_book_delete.html'
success_url = 'success'

NOT NULL constraint failed: issue_tracker_label.project_id

I am trying to create a 'Label'. Basically, you click on 'label' button, and it will show title and content under. I am using POST method. But when I click on 'submit', it gave me this error:
IntegrityError at /project/1/issue/2/label/
NOT NULL constraint failed: issue_tracker_label.project_id
Btw, I am using crispy form and I did do makemigrations and migrate after I modified my model.py. Not sure why I still get this error.
view.py
#csrf_exempt
def label_create(request, project_id,issue_id):
issue = get_object_or_404(Issue, id=issue_id)
project = Project.objects.get(id=project_id)
if request.method == 'POST':
form = LabelForm(request.POST)
if form.is_valid():
label = form.save(commit=False)
label.issue = issue
label.save()
return redirect('project:issue_tracker:issue_detail', project_id=project.id, issue_id=issue.id)
else:
form = LabelForm()
template = 'issue_tracker/issue/label.html'
context = {'form': form, 'project': project}
return render(request, template, context)
model.py
class Label(models.Model):
issue = models.ForeignKey(Issue, related_name='issue_label', on_delete=models.CASCADE)
project = models.ForeignKey(Project, related_name='project_label', on_delete=models.CASCADE)
title=models.CharField(max_length=20,default='Debug')
color=models.CharField(max_length=20,default='red')
def __str__(self):
return self.title
form.py
class LabelForm(forms.ModelForm):
class Meta:
model = Label
fields = ('title','color',)
Try adding the project in your object save:
views.py
#csrf_exempt
def label_create(request, project_id,issue_id):
issue = get_object_or_404(Issue, id=issue_id)
project = Project.objects.get(id=project_id)
if request.method == 'POST':
form = LabelForm(request.POST)
if form.is_valid():
label = form.save(commit=False)
label.issue = issue
label.project = project
label.save()
return redirect('project:issue_tracker:issue_detail', project_id=project.id, issue_id=issue.id)
else:
form = LabelForm()
template = 'issue_tracker/issue/label.html'
context = {'form': form, 'project': project}
return render(request, template, context)
Notice the label.project = project

Django form passing key to next form

I want to pass a pk from one form to another so that it can be used as the foreign key for the second form. Here are the model:
models.py
class CompanyDetails(models.Model):
name = models.CharField(max_length=100)
class CompanyDetailsForm(forms.ModelForm):
class Meta:
model = CompanyDetails
class DataRequest(models.Model):
company = models.ForeignKey(CompanyDetails, default="0")
agency_name = models.CharField(max_length=100)
class DataRequestForm(forms.ModelForm):
class Meta:
model = DataRequest
exclude = ['company']
And here is the view for the first form:
views.py
def index(request):
if request.method == 'POST':
form = CompanyDetailsForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.save()
return HttpResponseRedirect(reverse('canareeform:datarequest', data.id))
else:
form = CompanyDetailsForm()
return render(request, 'canareeform/index.html', {'form': form})
How should I set up my second view so that the form will save an object that has the foreign key for the object created by the first form in it?
I got it to work by passing the primary key of the first object through the url. It goes abc.com/form -> abc.com/form/16/datarequest. Not super ideal since by changing the number in the url the second object will use some other foreign key.
views.py
def index(request):
if request.method == 'POST':
form = CompanyDetailsForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.save()
return HttpResponseRedirect(reverse('canareeform:datarequest', args=(data.id,)))
else:
form = CompanyDetailsForm()
return render(request, 'canareeform/index.html', {'form': form})
def datarequest(request, company_id):
if request.method == 'POST':
form = DataRequestForm(request.POST or None)
if form.is_valid():
data = form.save(commit=False)
data.company = CompanyDetails.objects.get(pk=company_id)
data.save()
return HttpResponse("Thanks")
else:
form = DataRequestForm()
return render(request, 'canareeform/datarequest.html', {'form': form})
If anyone has a better solution I'd love to hear it.

How update models modelforms and django

i have a problem when i try update the data for model usuario
this is my model
class Usuario(models.Model):
user = models.ForeignKey(User)
nombres = models.CharField(max_length = 50)
correo = models.EmailField()
class Meta:
db_table = u'utp_users'
def __str__(self):
return str(self.nombres.encode('utf-8') )
this is mi form. py
class UsuarioForm(forms.ModelForm):
class Meta:
model = Usuario
fields = ['nombres','correo']
my url
url(r'^menu/update/(?P<usuario_id>\d+)$', 'utpapp.views.update'),
this my view update
#login_required(login_url='/')
def update(request,usuario_id):
form = UsuarioForm(request.POST)
if form.is_valid():
user = Usuario.objects.get(pk=usuario_id)
form = UsuarioForm(request.POST, instance = user)
form.save()
return redirect('/menu/')
else:
user = Usuario.objects.get(pk = usuario_id)
form = UsuarioForm(instance=user)
return render_to_response('form.html',{ 'form':form }, context_instance=RequestContext(request))
and the template i am do this
<a title="Editar informacion" href="/menu/update/{{usuario.id}}"><img src="/media/imagenes/usuario.png" class=" col-xs-3 col-md-7 quitar-float" alt="Editar informacion" ></a>
the problem is when i select the option update i get the this msj "Page not found (404)"
but i change in template href {{usuario.id}} for {{user.id}} is work but with user different what is the problem ??
Try this, you need to pass usuario as context to the template, and you can much simplify the code (especially the form for GET/POST, they are basically the same form, so don't repeat it) as like:
from django.shortcuts import get_object_or_404
#login_required(login_url='/')
def update(request,usuario_id):
user = get_object_or_404(Usuario, pk=usuario_id)
form = UsuarioForm(request.POST or None, instance=user)
if request.method == 'POST' and form.is_valid():
form.save()
return redirect('/menu/')
# you need to pass `usuario` as part of the context to template
# so you can access usuario.id in template
return render_to_response('form.html',{ 'form':form, 'usuario': user }, context_instance=RequestContext(request))
Also make sure you have a url route for /menu/, or else redirect will get you 404.
You forget to pass the usuario variable to the template.

Categories

Resources