**views.py code**(views.py function id not call urls.py)
def SendMail(request,id):
post=get_object_or_404(Post,slug=slug,status='published')
form=EmailSendForm()
return render(request,'mail.html',{'form':form,'post':post})
**models.py**(models.py not accept the id number in views.py)
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils import timezone
class CustomManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES=(('draft','Draft'),('published','Published'))
id=models.IntegerField(primary_key=True)
title=models.CharField(max_length=300)
slug=models.SlugField(max_length=300,unique_for_date='publish')
author=models.ForeignKey(User,related_name='post',on_delete=models.CASCADE)
body=models.TextField()
publish=models.DateTimeField(default=timezone.now)
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
status=models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
objects=CustomManager()
class Meta:
ordering=('-publish', )
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post',args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
urls.py(urls show page not found 404 error)
path('/(?P\d+)share/$',views.SendMail),
**views.py**
from django.core.mail import send_mail
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render,get_object_or_404
from app.models import Post
from app.forms import EmailSendForm
def post_list_view(request):
post_list=Post.objects.all()
paginator=Paginator(post_list,3)
page_number=request.GET.get('page')
try:
post_list=paginator.page(page_number)
except PageNotAnInteger:
post_list=paginator.page(1)
except EmptyPage:
post_list=paginator.page(paginator.num_pages)
return render(request, 'post_list.html', {'post_list':post_list})
def post_detail_view(request,year,month,day,slug):
post=get_object_or_404(Post,slug=slug,
status='published',
publish__year=year,
publish__month=month,
publish__day=day,
)
return render(request, 'post_detail.html', {'post':post})
def SendMail(request,post_id):
post = get_object_or_404(Post,id=post_id,status='published')
sent=False
if request.method=='POST':
form=EmailSendForm(request.POST)
if form.is_valid():
cd=form.cleaned_data
subject='{}({})Please read message"{}"'.format(cd['name'],cd['email'],post.title)
post_url=request.build_absolute_uri(post.get_absolute_url())
message="Read Post at:\n {}\n\n{}\'s Comments:\n{}".format(post_url,cd['name'],cd['comments'])
send_mail(subject,message,'vpnraut#gmail.com',[cd['to']])
sent=True
else:
form = EmailSendForm()
return render(request, 'mail.html', {'sent':sent,'form':form, 'post':post})
**models.py**
from django.contrib.auth.models import User
from django.db import models
from Django.urls import reverse
from Django.utils import timezone
class CustomManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES=(('draft','Draft'),('published','Published'))
id=models.IntegerField(primary_key=True)
title=models.CharField(max_length=300)
slug=models.SlugField(max_length=300,unique_for_date='publish')
author=models.ForeignKey(User,related_name='post',on_delete=models.CASCADE)
body=models.TextField()
publish=models.DateTimeField(default=timezone.now)
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
status=models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
objects=CustomManager()
class Meta:
ordering=('-publish', )
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post',args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
class Comment(models.Model):
post=models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE)
name=models.CharField(max_length=30)
email=models.EmailField()
body=models.TextField()
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
active=models.BooleanField(default=True)
class Meta:
ordering=('-created', )
def __str__(self):
return 'Commnted by {} on {}'.format(self.name,self.post)
**urls.py**
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.post_list_view),
path('<int:year>/<int:month>/<int:day>/<slug:slug>/',views.post_detail_view,name='post'),
path('(<int:post_id>\d+)/share/',views.SendMail, name='post_share'),]
Related
I'm extending my current model to have some common properties from other base classes.
Before extending the model, everything was working fine. But after extending, I'm getting the assertion error while performing put and post Operation. I tried my best to resolve it by my own. But not getting where it is going wrong. Can anyone help me on this?
Please find my model and serializers below.
basemodel.py
from django.db import models
class BaseModel(models.Model):
created_at=models.DateTimeField(auto_now=True)
updated_at=models.DateTimeField(auto_now=True)
class Meta:
abstract = True
softdelete.py
from django.db import models
class SoftDeleteModel(models.Model):
is_deleted = models.BooleanField(default=False)
def delete(self):
self.is_deleted = True
self.save()
def restore(self):
self.is_deleted = False
self.save()
class Meta:
abstract = True
movies.py
from django.db import models
from cinimateApp.models.comman.softdelete import SoftDeleteModel
from cinimateApp.models.comman.basemodel import BaseModel
# Create your models here.
class Movies(SoftDeleteModel,BaseModel):
name=models.CharField(max_length=250)
description=models.CharField(max_length=250)
active=models.BooleanField(default=False)
def __str__(self):
return self.name
movieSerializer.py
#Model Serializer
from rest_framework import serializers
from cinimateApp.models.movies import Movies
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movies
fields = '__all__'
# fields=['id', 'name', 'description', 'active']
# exclude=['name']
# field Level Validation
def validate_name(self,value):
if(len(value)<3):
raise serializers.ValidationError('name is too short')
return value
#Objectlevel validation
def validate(self,data):
if(data['name']==data['description']):
raise serializers.ValidationError('name and description should be different')
return
#custome serializer field
name_length=serializers.SerializerMethodField()
def get_name_length(self,object):
return len(object.name)
views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from cinimateApp.serializers.movieSerializer import MovieSerializer
from cinimateApp.models.movies import Movies
# Create your views here.
class MovieList(APIView):
def get(self,request):
movies=Movies.objects.all()
serializer=MovieSerializer(movies,many=True)
return Response(serializer.data,status=status.HTTP_200_OK)
def post(self,request):
serialiser=MovieSerializer(data=request.data)
if(serialiser.is_valid()):
serialiser.save()
return Response(serialiser.data,status=status.HTTP_201_CREATED)
else:
return Response(serialiser.errors,status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class MovieDetailsAV(APIView):
def get(self,request,id):
try:
movie=Movies.objects.get(pk=id)
serializer=MovieSerializer(movie)
return Response(serializer.data,status=status.HTTP_200_OK)
except Movies.DoesNotExist:
return Response({'Error':'Movie not found'},status=status.HTTP_404_NOT_FOUND)
def put(self,request,id):
try:
movie=Movies.objects.get(pk=id)
serializer=MovieSerializer(movie,data=request.data)
if(serializer.is_valid()):
serializer.save()
return Response(serializer.data,status=status.HTTP_200_OK)
return Response(serializer.errors,status=status.HTTP_500_INTERNAL_SERVER_ERROR)
except Movies.DoesNotExist:
return Response({'Error':'Movie not found'},status=status.HTTP_404_NOT_FOUND)
def delete(self,request,id):
try:
movie=Movies.objects.get(pk=id)
movie.delete()
return Response({'message' : 'Content deleted successfully'},status=status.HTTP_204_NO_CONTENT)
except Movies.DoesNotExist:
return Response({'Error':'Movie not found'},status=status.HTTP_404_NOT_FOUND)
def patch(self,request,id):
try:
movie=Movies.objects.get(pk=id)
serializer=MovieSerializer(movie,data=request.data,partial=True)
if(serializer.is_valid()):
serializer.save()
return Response(serializer.data,status=status.HTTP_200_OK)
return Response(serializer.errors,status=status.HTTP_500_INTERNAL_SERVER_ERROR)
except Movies.DoesNotExist:
return Response({'Error':'Movie not found'},status=status.HTTP_404_NOT_FOUND)
I'm getting following errors for put and post requests.
assert value is not None, '.validate() should return the validated data'
AssertionError: .validate() should return the validated data
validate() function should return data so:
def validate(self,data):
if(data['name']==data['description']):
raise serializers.ValidationError('name and description should be different')
return data
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from rest_framework import serializers
from rest_framework import parsers
from rest_framework.parsers import JSONParser
from .models import Article
from .serializer import Articleserializer
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
# Create your views here.
def artical_list(request):
if request.method=='GET':
article= Article.objects.all()
serializer=Articleserializer(article,many=True)
return JsonResponse(serializer.data,safe=False)
elif request.method=='POST':
data=JSONParser.parse(request)
serializer=Articleserializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data,status=201)
return JsonResponse(serializer.errors, status=400)
this is my serializer class
from django.db.models import fields
from rest_framework import serializers
from .models import Article
class Articleserializer(serializers.ModelSerializer):
class Meta:
model=Article
fields= ['id','title','author']
this is my model class
from django.db import models
# Create your models here.
class Article(models.Model):
title=models.CharField(max_length=50)
author=models.CharField(max_length=100)
email=models.EmailField(max_length=100)
date=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
when I post the data using postman giving this error please help me django rest freamwork is
The JSONParser should be instantiated. The parse method is a normal method, not a classmethod. So you need a instance for it to work:
JSONParser().parse(request) # Instead of JSONParser.parse(request)
I've tried everything but I cannot figure out why my images for an Avatar won't save to the media folder in Django.
I am happy the front end is passing form data to the AvatarAPIView and I get the following when I print out the data being passed to the view.
<QueryDict: {'myFile': [<InMemoryUploadedFile: 1965.jpg (image/jpeg)>]}>
[07/Feb/2021 10:48:54] "PUT /api/profile/avatar/ HTTP/1.1" 200 31
view.py
from profiles.api.serializers import (UserDisplaySerializer,
SubscriptionSerializer,
AvatarSerializer)
from profiles.models import CustomUser
from rest_framework import status, viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import UpdateAPIView, GenericAPIView
from rest_framework import mixins
from rest_framework.parsers import MultiPartParser, FileUploadParser, FormParser
from django.http import HttpResponse
class CurrentUserAPIView(APIView):
def get(self, request):
serializer = UserDisplaySerializer(request.user)
return Response(serializer.data)
def patch(self, request):
serializer = UserDisplaySerializer(request.user, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserUpdateAPIView(UpdateAPIView):
queryset = CustomUser.objects.all()
serializer_class = UserDisplaySerializer
class AvatarAPIView(APIView):
parser_classes = (MultiPartParser, FormParser)
def get(self, request):
serializer = AvatarSerializer(request.user)
return Response(serializer.data)
def put(self, request, format=None):
serializer = AvatarSerializer(
request.user, data=request.data)
print(request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializer.py
from rest_framework import serializers
from profiles.models import CustomUser, Subscription
class SubscriptionSerializer(serializers.ModelSerializer):
class Meta:
model = Subscription
exclude = ('id', 'user', )
class UserDisplaySerializer(serializers.ModelSerializer):
subscription = SubscriptionSerializer(read_only=True, many=False)
class Meta:
model = CustomUser
exclude = ('password',)
class AvatarSerializer(serializers.ModelSerializer):
class Meta:
model = CustomUser
fields = ('avatar',)
urls.py
from django.urls import path
from django.conf.urls import include
from profiles.api.views import (CurrentUserAPIView,
UserUpdateAPIView,
AvatarAPIView,
)
from rest_framework import routers
urlpatterns = [
path("user/", CurrentUserAPIView.as_view(), name="current-user"),
path("user/update/<int:pk>", UserUpdateAPIView.as_view()),
path("avatar/", AvatarAPIView.as_view(), name='user-avatar'),
]
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
bio = models.CharField(max_length=240, blank=True)
city = models.CharField(max_length=30, blank=True)
avatar = models.ImageField(null=True, blank=True)
I can upload files from the Django admin no problems. It's just when running through the serializer I have issues. Particularly because the data passes is_valid() and a code 200 is issued.
I'm half a day deep and I've got nothing.
not sure if your user is logged in or not;
as your formdata shows:
<QueryDict: {'myFile': [<InMemoryUploadedFile: 1965.jpg (image/jpeg)>]}> [07/Feb/2021 10:48:54] "PUT /api/profile/avatar/ HTTP/1.1" 200 31
In your form data, the "input name" of image is "myFile" while the name of imagefield in your Model and Serializer is "avatar".
Good day, I have got a Django project where I want to link to order_detail but I get this error: django.urls.exceptions.NoReverseMatch: Reverse for 'orderdetail' with arguments '('',)' not found. 1 pattern(s) tried: ['orders/myorder/detail/(?P<order_id>[0-9]+)$']
models.py
from datetime import timezone
from django.contrib.auth.models import User
# Create your models here.
from django.db import models
from django.forms import ModelForm
from django.urls import reverse
from shop.models import Product
from decimal import Decimal
from django.core.validators import MinValueValidator, MaxValueValidator
from coupons.models import Coupon
class Order(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
phone_number = models.CharField(max_length=20)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
braintree_id = models.CharField(max_length=150, blank=True)
reference_id = models.DateTimeField(auto_now_add=True, blank=True)
coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL)
discount = models.IntegerField(default=0, validators=[
MinValueValidator(0),
MaxValueValidator(100)
])
class Meta:
ordering = ('-created',)
def __str__(self):
return self.first_name
def get_absolute_url(self):
return reverse('orders:orderdetail', args=[self.id])
def get_total_cost(self):
total_cost = sum(item.get_cost() for item in self.items.all())
return total_cost - total_cost * (self.discount / Decimal(100))
def delivery_fee(self):
fee = 500
return fee
def get_total_after_delivery(self):
total = self.get_total_cost() + self.delivery_fee()
return total
class OrderItem(models.Model):
order = models.ForeignKey(Order,
related_name='items',
on_delete=models.CASCADE)
product = models.ForeignKey(Product,
related_name='order_items',
on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
def __str__(self):
return str(self.id)
def get_cost(self):
return self.price * self.quantity
class ShopCart(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
quantity = models.PositiveIntegerField()
def __str__(self):
return str(self.product)
#property
def price(self):
return self.product.price
#property
def cost(self):
return self.quantity * self.price #self.product.price
class ShopCartForm(ModelForm):
class Meta:
model = ShopCart
fields = ['quantity']
views.py
from django.contrib import messages
from django.urls import reverse
from django.shortcuts import render, redirect
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from django.template.loader import render_to_string
import weasyprint
from cart.cart import Cart
from .models import OrderItem, Order, ShopCartForm, ShopCart
from .forms import OrderCreateForm
from .tasks import order_created
def order_list(request):
current_user = request.user
success = Order.objects.filter(user=current_user.id).filter(paid=True)
fail = Order.objects.filter(user=current_user.id).filter(paid=False)
return render(request, 'orders/order/order_list.html', {
'success': success,
'fail': fail,
'current_user': current_user,
})
def order_detail(request, order_id):
order = get_object_or_404(Order, id=order_id)
return render(request, 'orders/order/order_detail.html', {'order': order})
order/urls.py
from django.urls import path
from . import views
app_name = 'orders'
urlpatterns = [
path('create/', views.order_create, name='order_create'),
path('admin/order/<int:order_id>/', views.admin_order_detail, name='admin_order_detail'),
path('admin/order/<int:order_id>/pdf/', views.admin_order_pdf, name='admin_order_pdf'),
path('order/', views.order, name='order'),
path('addtocart/<int:id>', views.addtocart, name='addtocart'),
path('myorder/', views.order_list, name='orderlist'),
path('myorder/detail/<int:order_id>', views.order_detail, name='orderdetail'),
]
project/urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('cart/', include('cart.urls', namespace='cart')),
path('orders/', include('orders.urls', namespace='orders')),
path('payment/', include('payment.urls', namespace='payment')),
path('coupons/', include('coupons.urls', namespace='coupons')),
path('members/', include('members.urls', namespace='members')),
path('social-auth/', include('social_django.urls', namespace='social')),
path('verification/', include('verify_email.urls')),
path('', include('shop.urls', namespace='shop')),
path('members/', include('django.contrib.auth.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
order_list.html
View Details
But when I try this View Details, the link doesn't seem functional as it directs to no where.
Also, when I try the link manually, like this: https://buyerschoice.com:8000/orders/myorder/detail/69 I get the desired result.
Pls, how can i fix this?
Thanks
Well, after some brainstorming, I realized I missed out on some code.
I only updated my views.py
Update
views.py
def order_list(request):
orders = Order.objects.all()
current_user = request.user
success = Order.objects.filter(user=current_user.id).filter(paid=True)
fail = Order.objects.filter(user=current_user.id).filter(paid=False)
return render(request, 'orders/order/order_list.html', {
'success': success,
'fail': fail,
'current_user': current_user,
'orders':orders,
})
order_list.html
{% for order in orders%}
View Details
{% endfor %}
And it works. :)
from myapp import views
File "C:\Users\User\job\mysite\myvenv\myproject\myapp\views.py", line 151
class MarketingBusinessDetailView(generic.DetailView):
SyntaxError: invalid syntax
At models.py,
class MarketingBusiness(models.Model):
title = models.CharField(max_length=128)
description = models.TextField(max_length=200, help_text="Enter a brief description of the Marketing business.")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('myapp:marketingbusiness-detail', args=[str(self.id)])
And it's working perfectly in my admin.
At myapp urls.py,
from myapp import views
app_name = 'myapp'
urlpatterns = [
path('marketingbusinesses/', views.MarketingBusinessListView.as_view(), name='marketingbusiness'),
path('marketingbusiness/<int:pk>/', views.MarketingBusinessDetailView.as_view(), name='marketingbusiness-detail'),
At views.py,
from django.shortcuts import render
from django.views import View
from django.views import generic
from myapp.models import MarketingBusiness
class MarketingBusinessDetailView(generic.DetailView):
model = MarketingBusiness
def marketingbusiness_detail(request, pk):
marketingbusiness_id = get_object_or_404(MarketingBusiness, pk=pk)
return render(
request,
'myapp/marketingbusiness-detail.html', context={'marketingbusiness_id':marketingbusiness}
)
How could I resolve this error, please?...