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.
Related
I don't understand the Traceback of the error, but Server is running fine (0 problems), and I get all the data I needed from the view.py. Seems it has to be with the get() method...
DoesNotExist: matching query does not exist
This are the models I used.
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=64, blank=True)
image = models.ImageField(upload_to="portraits", blank=True, default="default.jpg")
def __str__(self):
return f"{self.username}"
class Category(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=64)
description = models.CharField(max_length=255, blank=True)
def __str__(self):
return f"{self.name}"
class Item(models.Model):
id = models.AutoField(primary_key=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="inventory")
name = models.CharField(max_length=64)
description = models.CharField(max_length=255)
image = models.ImageField(blank=True, default="Megamind.jpg")
starting_bid = models.PositiveIntegerField(default=0)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default="1", related_name="stuff")
active = models.BooleanField(default=True)
favorited = models.ManyToManyField(User, blank=True, related_name="favorites")
def __str__(self):
return f"{self.name} of {self.owner}"
and the related view.py file
def index(request):
auctions = Item.objects.filter(active=True)
context = {'auctions':auctions, 'title':'Active Listings'}
return render(request, "auctions/index.html", context)
def category_view(request, category):
category = category.capitalize()
category_obj = Category.objects.get(name=category)
category_id = category_obj.id
items = Item.objects.filter(category=category_id, active=True)
context = {'auctions':items, 'title':category}
return render(request, "auctions/index.html", context)
If it helps:
I'm passing from urls.py to view as str
path("<str:category>", views.category_view, name="category")
As #Sharpek rightly mentioned, the error is caused by a /favicon.ico request, apparently from the browser. The easiest way to fix it is to add this to your base.html template into head tag:
{% load static %} <!-- If it wasn't already used -->
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
Then if you don't have a favicon.ico inside your STATIC_ROOT, you'll have a 404 error. Otherwise, you'll have a 200.
Take a look into traceback, the error is raised on /favicon.ico request. The modern browser automatically asks about favico.
You can do something like that to avoid this error:
url(r'^favicon\.ico$',RedirectView.as_view(url='/static/images/favicon.ico')),
I would really appreciate some help on this because I'm completely stuck. I've started up a simple django app (trying to make an instagram clone). However, when I try to display the post objects (which I created in the django admin page) nothing is displayed in index.html, so I tried printing out the objects in the views.py and it's returning to me an empty query set. I don't quite understand what I'm doing wrong and why I can't access the objects? When I print out the username I am able to get that, but then nothing for both post and stream objects. Please I'm so stuck any advice would be appreciated.
views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.template import loader
from django.http import HttpResponse
# Create your views here.
from post.models import post, stream
#login_required
# we are getting all of the string objects that are created for the user
def index(request):
user = request.user
print(user)
posts = stream.objects.filter(user=user)
print(posts)
group_ids = []
#then looping through and getting post id to a list
for posted in posts:
group_ids.append(posted.post_id)
print(group_ids)
#then filtering them so that you can display it in the index
#selecting a specific post by id
post_items = post.objects.filter(id__in=group_ids).all().order_by('-date')
template = loader.get_template('index.html')
context = {'post_items' : post_items}
return(HttpResponse(template.render(context, request)))
models.py
from django.db import models
from django.contrib.auth.models import User
import uuid
# Create your models here.
from django.db.models.signals import post_save
from django.utils.text import slugify
from django.urls import reverse
def user_directory_path(instance,filename):
# this file is going to be uploaded to the MEDIA_ROOT /user(id)/filename
return('user_{0}/{1}'.format(instance.user.id,filename))
class tag(models.Model):
title = models.CharField(max_length = 80, verbose_name = 'tag')
slug = models.SlugField(null = False, unique = True)
class Meta:
verbose_name = 'tag'
verbose_name_plural = 'tags'
# for when people click on the tags we can give them a url for that
# def get_absolute_url(self):
# return(reverse('tags', args = [self,slug]))
def __str__(self):
return(self.title)
def save(self,*args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
return(super().save(*args, **kwargs))
class post(models.Model):
# will create a long id for each post
id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable = False)
image = models.ImageField(upload_to = user_directory_path, verbose_name= 'image', null = True)
caption = models.TextField(max_length = 2000, verbose_name = 'caption')
date = models.DateTimeField(auto_now_add = True)
tags = models.ManyToManyField(tag, related_name='tags')
user = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.IntegerField()
def get_absolute_url(self):
return reverse('postdetails', args=[str(self.id)])
# def __str__(self):
# return(self.user.username)
class follow(models.Model):
follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower')
following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following')
class stream(models.Model):
following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stream_following')
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(post, on_delete=models.CASCADE)
date = models.DateTimeField()
def add_post(sender, instance,*args, **kwargs):
# here we are filtering all the users that are following you
post = instance
user = post.user
followers = follow.objects.all().filter(following=user)
for follower in followers:
streams = stream(post=post, user=follower.follower, date = post.date, following = user)
streams.save()
post_save.connect(stream.add_post, sender=post)
output from print statements
user
<QuerySet []>
[]
I figured it out. It wasn't an issue with the code, but the way that I was creating posts in the admin panel. So because you can only view posts from users that you are following, the posts that I was creating weren't showing up. So I had to create another user, and follow that user, then have the new user post something. Then the post shows up in the page!
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.
I am new with django framework struggling to compare value from the database.
this are my tables in models.py :
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,)
title = models.CharField(max_length=200)
content = models.TextField()
creationDate = models.DateTimeField(auto_now_add=True)
lastEditDate = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Votes(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,)
post_id = models.ForeignKey(Post, on_delete=models.CASCADE,)
up_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])
down_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])
class Meta:
unique_together = (("user","post_id"),)
I have data in the vote tabe like this:
Now what I want is to check in the above table if 'user_id' and 'post_id' already exists in the Votes tabel's rows if the exist throw a message if not add value on upvote or downvote, i gues everyone understand what i want if not please let me know.
something which i tried was this code:
def chk_table():
user_id = request.user
post_id = id
votes_table = Votes.objects.filter(user_id=user_id, post_id= post_id).exists()
return votes_table
but this function is checking in hole table not just in just in one row...
Assuming that, in your urls.py
from django.urls import path
from .views import add_vote
urlpatterns = [
path('post/<int:post_id>/vote/add/', add_vote, name='add-vote'),
]
In your views.py
from django.shortcuts import redirect, render
def add_vote(request, post_id):
if request.method == 'POST':
# receive your POST data here
user_id = request.user.id
post_id = post_id
if not Votes.objects.filter(user_id=user_id, post_id=post_id).exists():
Votes.objects.create(**your_data)
redirect('your-desired-url')
else:
# your logic here
I see you already defined unique_together in Meta so you can use try except
from django.db import IntegrityError
try:
# your model create or update code here
except IntegrityError as e:
if 'unique constraint' in e.message:
# duplicate detected
Im reviewing a sample DJango code and trying to understand how the urls are resolved?
list.html
Categories
{% for c in active_categories %}
{{c.name}}<br />
{% endfor %}
urls.py
from django.conf.urls import *
urlpatterns = patterns('ecomstore.catalog.views',
(r'^$','index',{'template_name':'catalog/index.html'},'catalog_home'),
(r'^category/(?P<category_slug>[-\w]+)/$','show_category',{'template_name':'catalog/category.html'},'catalog_category'),
(r'^product/(?P<product_slug>[-\w]+)/$','show_product',{'template_name':'catalog/product.html'},'catalog_product'),
)
The above html list all the categories without any problem and its called when I enter the following in the browser..[http:127.0.0.1:8000]
When I hover over - a href="{{p.get_absolute_url}} - I get the url resolved to--[http://127.0.0.1:8000/category/electronics/]
The p.get_absolute_url is resolved only to electronics but Im wondering how "category" is resolved in the url..
models.py
class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50,unique=True,help_text='Unique value for product page URL created from name')
description = models.TextField()
is_active = models.BooleanField(default=True)
meta_keywords = models.CharField("Meta Keywords",max_length=255,help_text="comma-delimited set of SEO Keywords for meta tag")
meta_description = models.CharField("Meta description",max_length=255,help_text="Content for description meta tag")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = 'categories'
ordering = ['-created_at']
verbose_name_plural = 'Categories'
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_category',(),{'category_slug':self.slug})
Hope my question is clear...
get_absolute_url is a function defined inside the model (for example, Category) model like this:
class Category(models.Model):
name = models.CharField(max_length=200)
...
def get_absolute_url(self):
return "/category/%s/" % self.slug
It is also possible to use reverse function to resolve the url using a pattern defined in urls.py:
def get_absolute_url(self):
return reverse('catalog_category', args=[str(self.slug)])
which is almost equal to an old-fashioned form:
#models.permalink
def get_absolute_url(self):
return ('catalog_category', (), {'category_slug': str(self.slug)})
In both ways, calling the get_absolute_url method on a Category object, for example Category(name="electronics"), will result in the string: /category/electronics/.
As you can see in your urls.py, the second url pattern is named catalog_category, which appeard in the reverse function argument. When you call the reverse function, Django will look into urls.py files, looking for a pattern named catalog_category, and the final url will be generated by replacing the url parameter (category_slug) with self.slug.