Url not being resolved in, 404 error django - django

I am not able to create an detail and update view using the <pk> and <pk>/update/, this is my url paths.
urlpatterns = [
path('',views.IndexView.as_view(), name='index'),
path('form/',views.CompanyView.as_view(),name='company'),
path('toy/',views.ToyView.as_view(),name='toy'),
path('int:pk>/',views.CompanyDetailView.as_view()),
path('int:pk>/update/',views.CompanyUpdateView.as_view())
]
my views looks like this,
class CompanyUpdateView(generic.UpdateView):
model = Company
fields = '__all__'
success_url = '/company'
class CompanyDetailView(generic.DetailView):
model = Company
fields = '__all__'
class CompanyView(generic.CreateView):
model = Company
template_name = 'company/company.html'
fields = '__all__'
success_url = '/company'
models.py is
class Company(models.Model):
company_name = models.CharField(max_length=50)
location = models.CharField(max_length=50)
email_id = models.EmailField()
def __str__(self):
return self.company_name
class Toys(models.Model):
toy_name = models.CharField(max_length=50)
company = models.ForeignKey(Company,on_delete=models.CASCADE,blank=True,null=True)
price = models.IntegerField()
This is the template used to in the CreateView and UpdateView since I am using a ModelForm
<form method="post">
{% csrf_token %}
<fieldset>
<legend>
<h2> Company Form </h2>
</legend>
{{ form.as_p }}
</fieldset>
<input type="submit" value="Submit" />
</form>
Create view is working. When I got to a url company/1/ or company/1/update I get a 404 error. What would be the reason for it and how to solve this

Related

Django admin filters in custom template

I want to implement django admin filters in my custom template can any body from you help me in resolving this issue i will appreciate. i am getting this error ...... name 'AddFilter' is not defined...
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField()
description = models.TextField()
release_date = models.DateField()
filters.py
import django_filters
class ProductFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='iexact')
class Meta:
model = Product
fields = ['price', 'release_date']
views.py
def filt_page(request):
filter = AddFilter(request.GET, queryset=Add.objects.all())
print (filter)
return render_to_response('filt_page.html',{'filter':filter})
template
<form action="" method="get"> {% csrf_token %}
{{ filter.form.as_p }}
<input type="submit" />
</form>
{% for obj in filter %}
{{ obj.name }}<br />
{% endfor %}
You've called an undefined class in your views.py
class name in filters.py is 'ProductFilter' but you've called 'AddFilter' in views.py
Also the model name in your filter is undefined, you've used 'Add' instead of 'Product'
Try
filter = ProductFilter(request.GET, queryset=Product.objects.all())

Using my own template beside django rest framework one to upload a file

I did the upload of an image with some information using a form with Django Rest Framework, it works but displayed using DRF default template, I want to use my own template so that i can add more button and link.
When i looked at that, it's about creating my template "api.html" in a folder rest_framework in my folder of templates but i don't know what i can put in the template content that i want to create.
My views :
class ImageViewSet(viewsets.ModelViewSet):
queryset = Video.objects.all()
serializer_class = ImageWatermarkSerializer
filter_backends = (filters.DjangoFilterBackend,filters.OrderingFilter,)
filter_fields = ('completed',)
ordering = ('-date_created',)
For the serializer :
class ImageWatermarkSerializer(serializers.ModelSerializer):
image = serializers.FileField(max_length=None,use_url=True)
class Meta:
model = Image
fields = ('id', 'image_name', 'image_desc', 'date_created', 'image', 'completed', 'size')
My models :
class Video(models.Model):
image_name = models.CharField(max_length=50)
image_desc = models.TextField(max_length=200)
completed = models.BooleanField(default=False)
date_created = models.DateTimeField(auto_now=True)
image = models.FileField(upload_to='imgs', default='/home/None/No-image.mp4')
size = models.IntegerField(default=10)
def __str__(self):
return "%s" % self.image_name
In my urls.py:
router = routers.DefaultRouter()
router.register(r'upl', views.ImageViewSet)
urlpatterns = [
url(r'^upload/', include(router.urls)), ]
As you already created your api.html file, you need to define template_name in your api view.
renderer_classes = [TemplateHTMLRenderer]
template_name = 'api.html'
And in your api.html
{% load rest_framework %}
<form class="form-horizontal" action="{% url 'upload' %}" method="post" novalidate enctype="multipart/form-data">
{% csrf_token %}
# this will include your serializer fields
{% render_form serializer %}
# Here you can customize your buttons
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</div>
</form>
If you need to change the image field styles DRF gives you style attribute,
image = serializers.FileField(
style={'template': 'app/image.html'}
)
Find more details at docs

django updateview return blank template

here is in my models.py:
class Segment(models.Model):
email_segment_name = models.CharField(max_length=200)
email_segment_status = models.BooleanField()
user = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True,null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.email_segment_name
and forms.py:
class SegmentForm(forms.ModelForm):
class Meta:
model = Segment
fields = ['email_segment_name']
labels = {
'email_server_name':('Server Name'),
}
and views:
#method_decorator(login_required, name='dispatch')
class SegmentUpdate(UpdateView):
model = Segment
form_class = SegmentForm
template_name_suffix = '_update_form'
success_url = '/emails/segment'
segment_update_form.html:
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update" />
</form>
the FormView and DeleteView just works fine, but when I update the form, it response with 200 OK and the page is blank, any ideas?
change:
method='post'
to:
method='get'
in segment_update_form.html

django-autocomplete-light with crispy forms

I am trying to implement an autocomplete search on a foreignkey field in my form. I have been through the docs but not sure what I need to do to get it working. I just get the normal dropdown box on the foreignkey field.
Here is my attempt:
settings.py
INSTALLED_APPS = (
'crispy_forms',
'autocomplete_light',
)
urls.py
url(r'^autocomplete/', include('autocomplete_light.urls')),
models.py
class Client(models.Model):
...
class Branch(models.Model):
client = models.ForeignKey(Client, related_name='clients')
...
forms.py
import autocomplete_light
class BranchForm(autocomplete_light.ModelForm):
class Meta:
model = Branch
autocomplete_fields = ('client')
exclude = ('creation', 'last_modified')
form.html
<form method="POST" action="">{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-primary" type="submit" value="Submit" />
<button type="button" class="btn btn-danger">Cancel</button>
</form>
Figured it out in the end. Needed to register it.
autocomplete_light.register(Branch,
name = 'ClientAutocomplete',
choices = Client.objects.all()
)
class ClientForm(forms.ModelForm):
class Meta:
model = Client
exclude = ('creation', 'last_modified')
class BranchForm(autocomplete_light.ModelForm):
class Meta:
model = Branch
autocomplete_names = {'client':'ClientAutocomplete'}
exclude = ('creation', 'last_modified')

How to show ManyToMany fields using CreateView in Django 1.8

I'm doing a basic application in Django 1.8 and I'm using Create-View, I don't know why the create form doesn't have manyTOmany fields neither foreign-key field previously defined in my model. This is my code:
My Model:
class Autor(models.Model):
nombre = models.CharField(max_length=30)
....
class Editor(models.Model):
nombre = models.CharField(max_length=30)
...
class Libro(models.Model):
titulo = models.CharField(max_length=100)
autores = models.ManyToManyField(Autor) #MANY2MANY FIELD
editor = models.ForeignKey(Editor) #FOREIGN KEY FIELD
fecha_publicacion = models.DateField()
portada = models.ImageField(upload_to = 'portadas/')
def __unicode__(self):
return self.titulo
My View:
class LibroCreateView(CreateView):
model = Libro
template_name = 'biblioteca/crear.html'
fields = ['titulo', 'autores', 'editor', 'fecha_publicacion', 'portada']
My template:
{% block main %}
<form action="" enctype="multipart/form-data" method="POST">{% csrf_token %}
<table>
{{form.as_table}}
</table>
<input type="submit" name="crear" value="Crear">
</form> <br>
{% endblock main %}
My result
Why isn't my fields "Autores"(many2many) and "Editor"(foreign-key) correctly shown?. Thanks.
Try giving form to the view that is CreateView. Make a ModelForm using your model
There you can do query for you foreign key and many to many field.
You can present them as you like