FieldError: Cannot resolve keyword 'published_date' into field - django

i am creating a new blog django apllication but when run it i got error
here is my code
#model.py
class Post(models.Model):
author=models.ForeignKey('auth.user',on_delete=models.CASCADE)
title=models.CharField(max_length=200)
text=models.TextField()
create_date=models.DateTimeField(default=timezone.now())
pubished_date=models.DateTimeField(blank=True,null=True)
def publish(self):
self.published_date=timezone.now()
self.save()
def approve_comments(self):
return self.comments.filter(approved_comments=True)
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
def __str__(self):
return self.title
class Comment(models.Model):
post=models.ForeignKey('blog.Post',related_name='comments')
author=models.CharField(max_length=200)
test=models.TextField()
create_date=models.DateTimeField(default=timezone.now())
approved_comment=models.BooleanField(default=False)
def approve(self):
self.approved_comment=True
self.save()
def get_absolute_url(self):
return reverse('post_list')
def __str__(self):
return self.text
whenerver i run server i got this field error message. i m new to django

In your Post model you have a typo in pubished_date, it's may be published_date

Related

Django get_absolute_url() doesn't seem to work in comment section

I'm trying to get my users to the article page after comments, but something is missing.
class Comment(models.Model):
post = models.ForeignKey(Post, related_name="comments" ,on_delete=models.CASCADE)
name = models.CharField(max_length=30)
body = RichTextUploadingField(extra_plugins=
['youtube', 'codesnippet'], external_plugin_resources= [('youtube','/static/ckeditor/youtube/','plugin.js'), ('codesnippet','/static/ckeditor/codesnippet/','plugin.js')])
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
class Meta:
verbose_name = "comentario"
verbose_name_plural = "comentarios"
ordering = ['date_added']
def get_absolute_url(self):
return reverse('article-detail', kwargs={'pk': self.pk})
urls.py
path('article/<int:pk>/comment/', AddCommentView.as_view(), name='add_comment'),
path('article/<int:pk>', ArticleDetailView.as_view(), name="article-detail"),
path('article/edit/<int:pk>', UpdatePostView.as_view(), name='update_post'),
path('article/<int:pk>/remove', DeletePostView.as_view(), name='delete_post'),
For the update_post the get_absolute_url() works. Thanks in advance.
You would need to pass a parameter which belongs to the ArticleDetailView model. For example if the model for the ArticleDetailView is Post:
class ArticleDetailView(DetailView):
model = Post
The get_absolute_url should use a post.pk:
class Comment(models.Model):
....
....
def get_absolute_url(self):
return reverse('article-detail', kwargs={'pk': self.post.pk})
In your case it is not working as it is using the Comment pk with the Article(Post) view
Ok the thing is I was using this class for comment, had to delete the function of success_url and now works.
class AddCommentView(CreateView):
model = Comment
form_class = CommentForm
#form_class = PostForm
template_name = 'add_comment.html'
success_url = reverse_lazy('home')
def form_valid(self,form):
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)

RecursionError:maximum recursion depth exceeded

i'm building an e-commerece and when i try to add more than one orderitems to the order but i get this error enter image description here .
Any help is appreciated .
def Cart(request):
`enter code here` customer=request.user.customer
if request.user.is_authenticated:
order,status=Order.objects.get_or_create(customer=customer,complete=False)
items=order.orderitem_set.all()
else:
items=[]
context={"items":items}
return render(request,'store/Cart.html',context)
and this the tree models
class Customer(models.Model):
user=models.OneToOneField(User,null=True,on_delete=models.CASCADE,blank=True)
name=models.CharField(max_length=200,null=True)
email=models.EmailField(null=True,help_text='A valid email address,please.')
objects = models.Manager()
def __str__(self):
return self.name
class Order(models.Model):
customer=models.ForeignKey(Customer,on_delete=models.SET_NULL,null=True)
date_orderd=models.DateField(auto_now_add=True)
complete=models.BooleanField(default=True,null=True,blank=False)
transaction_id=models.CharField(max_length=200,null=True)
objects = models.Manager()
def __str__(self):
return str(self.pk)
class OrderItem(models.Model):
product=models.ForeignKey(Product,on_delete=models.CASCADE,null=True)
order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True)
quantity=models.IntegerField(default=1,null=True,blank=True)
date_added=models.DateField(auto_now_add=True)
objects = models.Manager()
def __str__(self):
return self.product.name
#property
def get_total(self):
total=self.product.price*self.quantity
return self.get_total
This error usually occurs when you add an app's urls in itself.
check your app's url.py you mayhave included itself in it.

How can I make Django slug and id work together?

I want my URL to contain both id and slug like StackOverflow, but the slug is not working properly. Instead of being like this:
www.example.com/games/155/far-cry-5
the URL is like this:
www.example.com/games/155/<bound%20method%20Game.slug%20of%20<Game:%20Far%20Cry%205>>
My models.py :
class Game(models.Model):
name = models.CharField(max_length=140)
def slug(self):
return slugify(self.name)
def get_absolute_url(self):
return reverse('core:gamedetail', kwargs={'pk': self.id, 'slug': self.slug})
My views.py :
class GameDetail(DetailView):
model = Game
template_name = 'core/game_detail.html'
context_object_name = 'game_detail'
My urls.py :
path('<int:pk>/<slug>', views.GameDetail.as_view(), name='gamedetail')
Call the slug() method to get the value.
return reverse('core:gamedetail', kwargs={'pk': self.id, 'slug': self.slug()})
Or define it as a propery of the class
#property
def slug(self):
...

Redirection issue using PK

I Have a very strange phenomenon
In my app the user Create a project and is redirected to that project detail using its pk. On that project detail page he is asked to create a team and when the team is created he is redirected again to the project detail page but to the wrong pk
for example: I just created a project and I got redirected to .../project/24. I was asked to create a team, I created it but got redirected to ../project/17 any idea why and how to redirect my page to the right URL ?
model.py:
class Team(models.Model):
team_name = models.CharField(max_length=100, default = '')
team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
def get_absolute_url(self):
return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk})
def __str__(self):
return self.team_name
class TeamMember(models.Model):
user = models.ForeignKey(MyUser)
team = models.ForeignKey(Team)
def __str__(self):
return self.user.first_name
class Project(models.Model):
name = models.CharField(max_length=250)
team_id = models.ForeignKey(Team, blank=True, null=True)
project_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
def get_absolute_url(self):
return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk})
def __str__(self):
return self.name
views.py
class TeamCreate(CreateView):
model = Team
fields = ['team_name']
template_name = 'team_form.html'
def form_valid(self, form):
valid = super(TeamCreate, self).form_valid(form)
form.instance.team_hr_admin = self.request.user
obj = form.save()
#SELECT * FROM project WHERE user = 'current_user' AND team_id = NULL
obj2 = Project.objects.get(project_hr_admin=self.request.user, team_id=None)
obj2.team_id = obj
obj2.save()
return valid
return super(TeamCreate, self).form_valid(form)
def get_success_url(self):
project = Project.objects.get(team_id=self.obj, project_hr_admin=self.request.user)
return project.get_absolute_url()
The problem here is your CreateView is refering to a TeamObject and not project.
You should override the get_success_url method:
def get_success_url(self):
project = Porject.objects.get(team_id=self.object, project_hr_admin=self.request.user)
return project.get_absolute_url()
The function called was the get_absolute_url of your Team model. So you're calling the project detail view but with the team pk => you get a random project assuming there's a project with a pk which has the same value as your project or, the pk you're sending doesn't exist and you'll have a 404 error (pk doesn't exist).
def get_absolute_url(self):
return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk})
That's the one in your Team model, but you call ProjectDetails. So here, self.pk is Teaminstance.pk.
What I do in the code i gave you is to call the get_absolute_url of the project instance.
But as told in the other answer, you should remove or change your get_absolute_url of your team model.
class Team(models.Model):
# ...
def get_absolute_url(self):
return reverse('website:ProjectDetails', kwargs = {'pk' : self.pk})
^^^^^^^
Here, the wrong pk will be delived. Thx to #Bestasttung for clarification

Class meta got invalid attributes

Please help to fix this Meta class value as I gave up after detailed research.
I am getting back error while trying to handle template urls with "get_absolute_url" as it responds with following error.
TypeError: 'class Meta' got invalid attribute(s): sale_price,get_absolute_url.
Below is my code.
class Meta:
db_table = 'products'
ordering = ['-created_at']
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_product', (), {'product_slug': self.slug})
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
Thanks.
You are misunderstanding how models are defined. You add your methods and attributes to the actual Model class and use the Meta class to specify options upon the class:
class MyModel(models.Model):
old_price = ...
price = ...
slug = ...
created_at = ...
...
def __unicode__(self):
return self.name
#models.permalink
def get_absolute_url(self):
return ('catalog_product', (), {'product_slug': self.slug})
def sale_price(self):
if self.old_price > self.price:
return self.price
else:
return None
class Meta:
db_table = 'products'
ordering = ['-created_at']
Have a read of the Model documentation and pay attention to the section on Meta options
EDIT
Also, don't use the permalink decorator as it's no longer recommended:
https://docs.djangoproject.com/en/1.6/ref/models/instances/#the-permalink-decorator
The permalink decorator is no longer recommended. You should use reverse() in the body of your get_absolute_url method instead.