Here is my html link from where I want to use <int:pk>
<a href= "/main/profile/edit/{{ user.myprofile.id }}" >Edit Profile</a>
When I click on the link I get a url mapping error
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/main/profile/edit/
Using the URLconf defined in lunarcodes.urls, Django tried these URL patterns, in this order:
main/ home/
main/ profile/
main/ feed/
main/ profile/edit/<int:pk>
here is my urls.py,
urlpatterns = [
path('profile/edit/<int:pk>', views.MyProfileUpdateView.as_view(success_url="/main/profile")),
]
this is my views.py,
#method_decorator(login_required, name="dispatch")
class MyProfileUpdateView(UpdateView):
model = MyProfile
fields = ["name", "description", "pic"]
this is my models.py,
class MyProfile(models.Model):
name = models.CharField(max_length = 100)
user = models.OneToOneField(to=User, on_delete=CASCADE)
description = models.TextField(null=True, blank=True)
pic= models.ImageField(upload_to = "images\\", null=True)
def __str__(self):
return "%s" % self.user
I myself couldn't understand the problem properly as I am beginner.
Related
I have created models.py, views.py, and urls.py and later on accordingly updated data.html file but when I click on the delete button it gives me an error. so the error file also attached for reference. Help appreciated and waiting for resolution.
error file
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/delete/
Using the URLconf defined in student.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
export/ [name='export']
export-pdf [name='export-pdf']
register/ [name='register']
login/ [name='login']
home/ [name='home']
logout/ [name='logout']
upload/ [name='upload']
result/ [name='result']
dashbord/ [name='dashbord']
data/ [name='data']
delete/<int:id>
^static/(?P<path>.*)$
The current path, delete/, didn’t match any of these.
You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
urls.py
path('data/', views.data, name='data'),
path('delete/<int:id>', views.delete),
data.html
<a href="/edit/{{ student.id }}" class="btn btn-success"><span>Edit</span></a
Delete
views.py
def data(request):
data1 = Contact.objects.all()
# myFilter = OrderFilter()
dict = {
"data1":data1
}
return render(request, 'data.html', context=dict)
# Delete Data
def delete(request):
data1 = Contact.objects.all(id=id)
data1.delete()
return redirect("/data")
model.py
from django.db import models
from django.db.models.fields import CharField
from django.contrib import admin
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=50, default="")
contact = models.CharField(max_length=50, default='')
address = models.TextField(max_length=50, default='')
program = models.CharField(max_length=50, default='')
email = models.CharField(max_length=50, primary_key=True, null=False, unique=True)
w3review = models.TextField(max_length=60, default="")
def __str__(self):
return self.name
class Cv(models.Model):
filename = models.CharField(max_length=20)
upload = models.FileField(upload_to='cv')
def __str__(self):
return self.filename
I think you didnt specify the id number after
http://127.0.0.1/delete:8000/--id-here--
I think you need to use get() method instead of all() method. You code should be something like this:
def delete(self, request, id):
data1 = Contact.objects.get(id=id)
data1.delete()
return redirect("/data")
And you must specify the id number according to #Ariel's Answer.
I am having a big confusion right now and can't any good answers online about my issue.
What I am trying to do is, to let the users click on an image. I have 52 different images on my page and by clicking on the image i want to pass an int between 1-53 (52 is missing) in order to get a filtered view.
models.py
class CentroidCount(models.Model):
id_centroid_count = models.AutoField(primary_key=True)
id_observation = models.ForeignKey('Observation', models.DO_NOTHING, db_column='id_observation', blank=True, null=True)
step = models.SmallIntegerField(blank=True, null=True)
centroid = models.SmallIntegerField(blank=True, null=True)
count = models.SmallIntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'centroid_count'
ordering = ['id_observation', 'step', 'centroid']
def get_absolute_url(self):
return reverse('centroid-detail', args=[str(self.id_centroid_count)])
def __str__(self):
return 'Observation: %s' % (self.id_observation)
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('observations/', views.ObservationListView.as_view(), name='observations'),
]
views.py
class ObservationListView(generic.ListView):
model = CentroidCount
context_object_name = 'observation_list'
queryset = CentroidCount.objects.filter(centroid__in=[]).order_by('id_observation').values_list('id_observation', flat=True).distinct()
template_name = 'centroid_webapp/observation_list.html'
def get_queryset(self):
return CentroidCount.objects.filter(centroid__in=[2]).order_by('id_observation').values_list('id_observation', flat=True).distinct()
and the image part of the html
<div class="col-sm">
<img src="{% static 'images/1.png'%}" class='img-fluid' alt='Responsive image'>
</div>
What I still don't understand that is how can this be done dynamically. What I do have now is a static page that is filterint out all "id_observations" with the number 2. But I would like to pass the with the image via the url to the view.
Hope I was able to give a good enough picture of the situation
You can try this:
Create a hyperlinked image in the template:
<div class="col-sm">
<a href="\myview\[id]"> <!-- pass the image id -->
<img src="{% static 'images/1.png'%}" class='img-fluid' alt='Responsive image'>
</a>
</div>
Also create the url in the urls.py:
urlpatterns = [
path('', views.index, name='index'),
path('observations/', views.ObservationListView.as_view(), name='observations'),
path('myview/<int:img_id>', views.MyView(), name='myview'), #call the view
]
And create the view where you want the image id:
def MyView(request, img_id):
"""your code"""
return HttpResponse('Hello World!') #return the response you want to
I am getting this error:
TypeError at /product/177042279214449276022367789942330057699/
product() got an unexpected keyword argument 'id'
I am trying to generate detail page of product (book is product).
urls.py
app_name = 'bookrepo'
urlpatterns = [
path('',views.home,name='home'),
path('product/',views.product,name='product'),
path('product/<id>/', views.product, name='product_detail'),
]
template where I am using get_absoulte_url
<a href="{{ item.get_absolute_url }}" class="btn btn-sm my-btn detail-btn">
<span><i class="fa fa-info-circle"></i></span> View Details
</a>
views.py
def product(request):
return render(request, 'bookrepo/product.html')
models.py
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField('Title', max_length=255)
authors = models.ManyToManyField(Author, related_name='books_written')
publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published')
price = models.DecimalField('Price', decimal_places=2, max_digits=10)
description = models.TextField('Description')
upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True)
categories = models.ManyToManyField(Category, related_name='book_category')
def get_absolute_url(self):
return "/product/%i/" % self.id
I might be completely wrong with respect to my view and urls. I want to display book details after button in template gets clicked.
Change views.py
def product(request, id=None):
return render(request, 'bookrepo/product.html')
I'm trying to figure out how url matching works in django template.
What i'm trying to achieve is when clicking on a link it would bring up a specific objects.
Models.py
class PostManager(models.Manager):
def get_queryset(self):
return super(PostManager,self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (('published','Published'),
('draft','Draft '))
FIELD_CHOICES = (('1','1 Title and body field'),
('2','2 Title and body fields'),
('3','3 Title and body fields'),
('4', '4 Title and body fields'),
('5', '5 Title and body fields'))
author = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='blog_post')
title = models.CharField(max_length=100)
sub_title = models.TextField(max_length=50,default="")
title_1 = models.CharField(max_length=100,null=True,blank=True)
title_1_body = models.TextField(null=True,blank=True)
title_2 = models.CharField(max_length=100,null=True,blank=True)
title_2_body = models.TextField(null=True,blank=True)
title_3 = models.CharField(max_length=100,null=True,blank=True)
title_3_body = models.TextField(null=True,blank=True)
title_4 = models.CharField(max_length=100,null=True,blank=True)
title_4_body = models.TextField(null=True,blank=True)
title_5 = models.CharField(max_length=100,null=True,blank=True)
title_5_body = models.TextField(null=True,blank=True)
created = models.DateField()
publish = models.DateTimeField(default=timezone.now)
slug = models.SlugField(max_length=250,
unique_for_date='created')
status = models.CharField(max_length=250,
choices=STATUS_CHOICES,
default='draft')
object = models.Manager()
postManager = PostManager()
class Meta():
ordering = ('publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail',
args=[self.slug])
def get_image_filename(instance, filename):
title = Post.title
slug = slugify(title)
return "media/%s-%s" % (slug, filename)
class Image(models.Model):
post = models.ForeignKey(Post,
on_delete=models.CASCADE,
related_name='images')
image_1 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True)
image_2 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True)
image_3 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True)
image_4 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True)
image_5 = models.ImageField(upload_to=get_image_filename,default='123.jpg',verbose_name="Image",null=True)
views.py
def post_detail(request):
post = get_object_or_404(Post)
return render(request, 'blog_application/templates/single.html',
{'post':post})
index.html
{% for elem in posts %}
<p class="mb-md-5">A small river named Duden flows by their place and supplies it with the necessary regelialia</p>
<p>Read More <span class="icon-arrow_forward ml-lg-4"></span></p>
{% endfor %}
urls.py
path('post_detail/<slug:slug>',views.post_detail,name='single'),
path('', views.show_index, name='index'),
I don't quite understand how url matching and linking works for templates. Could some one be kind enough to explain based on my example.
There's two issues in your view:
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
return render(request, 'blog_application/templates/single.html',
{'post':post})
on a more general note, you receive the slug value from the url and pass it to your view with the argument.
Also, you need to pass the argument to get_object_or_404 see this.
before I dive, Let's agree that a slug is just a fancy name, It's just a string nothing else.
Ok so you want to understand how django urls work. back off plz
Let's first understand how URLs work, let's say I'll open this website www.example.com & just open it as is, The website just opens right? You expect the home page to be there
Now, let's open it as www.example.com?text=welcome
Press F12 in chrome & switch to networks tab, Essentially what happens is that you added a parameter which appears in chrome as 'query string parameter' at the very bottom of the networks tab, This says you wanted to visit this website with a parameter called text that contains the string hello
Ok, now what's the relation between this & the question? bear with me please
Imagine I have a social website with posts & I want to create a code "slug" for each post so that when It's typed as a parameter in the URL, It gets that specific post
now, this is your urlpatterns.py
path('post_detail/<slug:slug>', views.post_detail, name='single'),
path('', views.show_index, name='index'),
I'll assume that this is the project level urls.py for simplicity.
The user visits the website without any url params or subpages, it just calls your views.show_index
now the user visits your website/post_detail/, What happens is sees if there's any urlpattern in urlpatterns that matches this, but it doesn't, so it's just a 404
now the user visits your website/post_detail/ANY_RANDOM_TEXT
What happens is that there's actually a urlpattern that matches website/post_detail/ANY_RANDOM_TEXT
which path('post_detail/<slug:slug>', views.post_detail, name='single')
therefore, the "ANY_RANDOM_TEXT" must be the slug, Let's take it as the slug then!
now we have the slug, and the urlpattern will call views.post_detail (function or view) and pass the slug to it, so we must accept it right?
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
return render(request, 'blog_application/templates/single.html',
{'post':post})
now you have access to the 'slug' which is just "ANY_RANDOM_TEXT" because we matched it, now get the post with slug that's the same as the slug in the url & just render it!
Btw don't forget the slash at the end of any urlpattern or otherwise the world is gonna explode
So, I have a user form in my Django project. After Submitting the form I want to redirect the user to another form (for additional details). But I am seeing the following error
NoReverseMatch at /incubators/add-incuabtor/
Reverse for 'details' with keyword arguments '{'pk': 15}' not found. 1 pattern(s) tried: ['incubators/(?P<incubator_id>[0-9]+)']
Request Method: POST
Request URL: http://127.0.0.1:8000/incubators/add-incuabtor/
I have the following url pattern:
app_name = 'main'
urlpatterns = [
url(r'^home/', views.home, name='home'), # Home page
url(r'incubators/$', views.incubators, name='incubators'), # Incubator list page
url(r'about/', views.about, name='about'), # Websie about page
url(r'results', views.result, name = 'result'), # For search function
url(r'incubators/(?P<incubator_id>[0-9]+)', views.details, name = 'details'), # shows details of incubators
url(r'incubators/add-incuabtor/$', views.AddIncubator.as_view(), name = 'add-incubator'), # Adding Inc
url(r'/add-details/', views.AddDetails.as_view(), name = 'add-details'), #for additional details
]
Following is my models.py
class Incubators(models.Model): # These are our database files for
the Incubator Portal
incubator_name = models.CharField(max_length=30)
owner = models.CharField(max_length=30)
city_location = models.CharField(max_length=30)
description = models.TextField(max_length=100)
logo = models.FileField()
verify = models.BooleanField(default = False)
def get_absolute_url(self):
return reverse('main:details', kwargs={'pk': self.pk})
def __str__(self): # Displays the following stuff when a query is made
return self.incubator_name + '-' + self.owner
class Details(models.Model):
incubator = models.ForeignKey(Incubators, on_delete = models.CASCADE, related_name='banana_pudding')
inc_name = models.CharField(max_length = 30)
inc_img = models.FileField()
inc_contact = models.CharField(max_length = 600, default = "Enter all available means of contacting")
inc_details = models.TextField(max_length= 2500)
inc_address = models.TextField(max_length = 600, default = "Address")
inc_doc = models.FileField()
inc_policy = models.FileField()
def __str__(self):
return self.inc_name
And I have the following views.py
class AddIncubator(CreateView):
model = Incubators
fields = ['incubator_name', 'owner', 'city_location', 'description', 'logo']
class AddDetails(CreateView):
model = Details
field = ['incubator', 'inc_name']
Problem is with you url.
In urls.py, you detail url is
url(r'incubators/(?P<incubator_id>[0-9]+)', views.details, name = 'details'),
Change it to
url(r'incubators/(?P<pk>[0-9]+)', views.details, name = 'details'),
or you can change reverse url in you models as:
def get_absolute_url(self):
return reverse('main:details', kwargs={'incubator_id': self.pk})