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. :)
Related
It's showing my in my browser page not found when I am searching in my django API Itried all the methods and the ways but still the same problem please help me
my view.py file
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import BlogPost
from .serilaizer import BlogPostSerializer
#api_view(['GET'])
def getRoutes(request):
routes = [
{
'GET/api',
'GET/api/Blogs',
'GET/api/Blogs/:id',
}
]
return Response(routes)
#api_view(['GET'])
def getBlogs(request):
blogs = BlogPost.objects.all().order_by('-date_created')
Serializers = BlogPostSerializer(blogs, many=True)
return Response(Serializers.data)
#api_view(['GET'])
def getPost(request, pk):
post = BlogPost.objects.get(id=pk)
Serializers = BlogPostSerializer(post, many=False)
return Response(Serializers.data)
#api_view(['GET'])
def Search(request):
q = request.GET.get('q')if request.GET.get('q') != None else''
search = BlogPost.objects.filter(title__icontains=q)
Serializers = BlogPostSerializer(search, many=False)
return Response(Serializers.data)
my serilaizer.py file
from rest_framework import serializers
from .models import BlogPost
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
model = BlogPost
fields = '__all__'
**my urls.py file **
from django.urls import path
from . import views
urlpatterns = [
path('', views.getRoutes, name='Routes'),
path('Blogs', views.getBlogs, name='Blogs'),
path('Blogs/<str:pk>/', views.getPost, name='BlogPost'),
path('search', views.Search, name='Search'),
]
my models.py file
class Categories(models.TextChoices):
WORLD = 'world'
ENVIRONMENT = 'environment'
TECHNOLOGY = 'technology'
DESIGN = 'design'
CULTURE = 'culture'
BUSINESS = 'business'
POLITICS = 'politics'
OPINION = 'opinion'
SCIENCE = 'science'
HEALTH = 'health'
STYLE = 'style'
TRAVEL = 'travel'
class BlogPost(models.Model):
title = models.CharField(max_length=50)
category = models.CharField(
max_length=50, choices=Categories.choices, default=Categories.WORLD)
thumbnail = models.ImageField(upload_to='photos/%Y/%m/%d/')
content = models.TextField()
date_created = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
**the URL in my browser **
http://127.0.0.1:8000/api/search/?q=(the title value)
** showing me Page not found (404) **
I'm working on a project and get the following error: RelatedObjectDoesNotExist at /agents/create/
User has no userprofile.I created a form for the user to submit an Agent but when I create an Agent using the form it gives me the above mentioned error but when I try to submit an already created agent it says User with that name already exists.I have two apps Agents and Leads Here is my code:
agents/views.py
from django.shortcuts import reverse
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from leads.models import Agent
from .forms import CreateAgentForm
class AgentListView(LoginRequiredMixin, generic.ListView):
template_name = 'agents/agent_list.html'
def get_queryset(self):
return Agent.objects.all()
class CreateAgentView(LoginRequiredMixin, generic.CreateView):
template_name = 'agents/agent_create.html'
form_class = CreateAgentForm
def get_success_url(self):
return reverse('agent-list')
def form_valid(self, form):
agent = form.save(commit=False)
agent.userprofile = self.request.user.userprofile
agent.save()
return super(CreateAgentView, self).form_valid(form)
leads/models.py
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Lead(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
age = models.IntegerField(default=0)
agent = models.ForeignKey('Agent', on_delete=models.CASCADE)
def __str__(self):
return f"{self.first_name} {self.last_name}"
class Agent(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
userprofile = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
def __str__(self):
return self.user.first_name
def post_user_profile(instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(post_user_profile, sender=User)
agents/urls.py
from django.urls import path
from .views import AgentListView, CreateAgentView
urlpatterns = [
path('', AgentListView.as_view(), name='agent-list'),
path('create/', CreateAgentView.as_view(), name='agent-create'),
]
agents/forms.py
from django import forms
from leads.models import Agent
class CreateAgentForm(forms.ModelForm):
class Meta:
model = Agent
fields = ('user',)
I'm still learning so any help would be appreciated.
I think the admin user has no user profile created, so you need to manually create one for him in the admin panel since migrations have already been done.
Erase your db and redo a migration.
Create User with the admin panel
I am trying to enable the user to be able to add job and after filling the form i got that error. Here is my code:
models.py
from django.db import models
from django.contrib.auth.models import User
class Job(models.Model):
title = models.CharField(max_length=255)
short_description = models.TextField()
long_description = models.TextField(blank=True, null=True)
created_by = models.ForeignKey(User, related_name='jobs', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
changed_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import AddJobForm
from .models import Job
def job_detail(request, job_id):
job = Job.objects.get(pk=job_id)
return render(request, 'jobs/job_detail.html', {'job': job})
#login_required
def add_job(request):
if request.method == 'POST':
form = AddJobForm(request.POST)
if form.is_valid():
job = form.save(commit=True)
job.created_by = request.user
job.save()
return redirect('dashboard')
else:
form = AddJobForm()
return render(request, 'jobs/add_job.html', {'form': form})
forms.py
from django import forms
from .models import Job
class AddJobForm(forms.ModelForm):
class Meta:
model = Job
fields = ['title','short_description','long_description']
What do i need to do to solve this error? I have try to remove the commit=True, from views.py and I have try to remove sqlite3 and do the migrations again.
You are trying to save the object without a value for created_by (hence the error message), then assign a value for that field and save again. You should change
job = form.save(commit=True)
to
job = form.save(commit=False)
so that the first .save doesn't actually try to commit anything to the database. It is simply used to construct the Job instance so that you can complete any missing values and actually save it using job.save().
Note that if you omit the commit= argument it is assumed to be True.
I'm working on a project from the book 'Django3 by example'. I want to add an image from the URL which the user provided. But when I try to save the page it gives me this error:
IntegrityError at /images/create/
NOT NULL constraint failed: images_image.users_like_id.
I have tried the solutions other posted but it didn't help.
Here is my code:
models.py
from django.db import models
from django.conf import settings
from django.utils.text import slugify
class Image(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='images_created')
users_like = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='images_liked')
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=200, blank=True)
url = models.URLField()
image = models.ImageField(upload_to='images/%Y/%m/%d/')
description = models.TextField()
created = models.DateField(auto_now_add=True, db_index=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import ImageCreateForm
#login_required
def image_create(request):
if request.method == "POST":
form = ImageCreateForm(data=request.POST)
if form.is_valid():
cd = form.cleaned_data
new_item = form.save(commit=False)
new_item.user = request.user
new_item.save()
messages.success(request, 'Image added successfully')
return redirect(new_item.get_absolute_url())
else:
form = ImageCreateForm(data=request.GET)
context = {'section':'images', 'form':form}
return render(request, 'images/image/create.html', context)
forms.py
from django import forms
from urllib import request
from django.core.files.base import ContentFile
from django.utils.text import slugify
from .models import Image
class ImageCreateForm(forms.ModelForm):
class Meta:
model = Image
fields = ('title', 'url', 'description')
widgets = {
'url': forms.HiddenInput,
}
def clean_url(self):
url = self.cleaned_data['url']
valid_extension = ['jpg', 'jpeg']
extension = url.rsplit('.', 1)[1].lower()
if extension not in valid_extension:
raise forms.ValidationError('The given URL does not match valid image extension')
return url
def save(self, force_insert=False, force_update=False, commit=True):
image = super().save(commit=False)
image_url = self.cleaned_data['url']
name = slugify(image.title)
extension = image_url.rsplit('.', 1)[1].lower()
image_name = f'{image}.{extension}'
response = request.urlopen(image_url)
image.image.save(image_name, ContentFile(response.read()), save=False)
if commit:
image.save()
return image
I'm using a ForeignKey on users_like instead of ManyToManyField as a user might
like multiple images and each image can be liked by multiple users.
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".