My CreateView doesn't call the success url, i've also tried using get_success_url function but still gives the same result, it just returns the form sending the request.
It actually creates the objects in the data base and prints out the entered value, but it never goes to the success url.
This is what i've got
MODELS.PY
from django.db import models
from ckeditor.fields import RichTextField
from django_random_id_model import RandomIDModel
DELIVERED_OPTIONS = (
("false", "Not Delivered"),
("true", "Delivered"),
)
# Create your models here.
class Order(models.Model):
name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
address = models.CharField(max_length=200)
phone = models.CharField(max_length=200)
measurements = RichTextField(default='')
delivered = models.CharField(
max_length=200, choices=DELIVERED_OPTIONS, default="false")
FORMS.PY
from django import forms
from ckeditor.widgets import CKEditorWidget
from .models import Order
class DeliveryForm(forms.ModelForm):
class Meta:
model = Order
exclude = ["id"]
fields = ['name', 'email', 'address', 'phone', 'measurements']
name = forms.CharField(label="Enter your full Name", min_length=5, widget=forms.TextInput(
attrs={'placeholder': 'Full name please', 'class': 'form-control'}))
email = forms.CharField(label="Enter your Email address", widget=forms.EmailInput(
attrs={'placeholder': 'Enter a valid email address', 'class': 'form-control'}))
address = forms.CharField(label="Enter Your delivery address", widget=forms.TextInput(
attrs={'placeholder': 'Delivery address', 'class': 'form-control'}))
phone = forms.CharField(label="Enter your phone number", widget=forms.NumberInput(
attrs={'placeholder': 'A valid phone number', 'class': 'form-control'}))
measurements = forms.CharField(widget=CKEditorWidget(
attrs={'class': 'form-control', 'rows': '3'}), required=True)
def send_email(self):
pass
URL.PY
from django.urls import path
from . import views
urlpatterns = [
path('', views.DeliveryFormView.as_view(), name="delivery"),
path('order_completed', views.OrderCompleted, name="order_completed"),
]
VIEWS.PY
from django.shortcuts import render
from django.urls import reverse_lazy, reverse
from delivery.form import DeliveryForm
from django.views.generic import CreateView
# Create your views here.
class DeliveryFormView(CreateView):
# context = {
# "route": "Contact",
# "route_text": "Reach out to us for enquiries and suggestions and complaints"
# }
form_class = DeliveryForm
template_name = 'delivery/delivery_form.html'
success_url = reverse_lazy("order_completed")
def form_valid(self, form):
print(form.cleaned_data)
self.send_mail(form.cleaned_data)
return super(DeliveryFormView, self).form_valid(form)
def send_mail(self, valid_data):
print(valid_data)
def OrderCompleted(request):
print("Order Completed")
# Generate an order number
# save the order number to the database along with
# order name, ordered items, total price
return render(request, "delivery/success.html")
Related
Summarize the problem
<class 'news.admin.NewsAdmin'>: (admin.E035) The value of 'readonly_fields[0]' is not a callable, an attribut
e of 'NewsAdmin', or an attribute of 'news.News'.
This all code error. I learn Django, and write code how in author. But write this error :(
Describe what you`ve tried
I immediately insert problem in search, but not found decision
I read this question, but it not finished
This question elementary, author question not correct write variable
Show some code
admin.py
from django.contrib import admin
from .models import News, Category
class NewsAdmin(admin.ModelAdmin):
list_display = ('id', 'title', 'category', 'create_at', 'updated_at', 'is_published')
list_display_links = ('id', 'title',) # what be links in model
search_fields = ('title', 'content',)
list_editable = ('is_published',) # redact is published in menu
list_filter = ('is_published', 'category',) # create table, what in be setting sorted
fields = ('title', 'category', 'content', 'photo', 'get_photo', 'is_published', 'views',
'create_at', 'updated_at')
readonly_fields = ('get_photo', 'views', 'create_at', 'updated_at')
class CategoryAdmin(admin.ModelAdmin):
list_display = ('id', 'title') # displays
list_display_links = ('id', 'title') # links
search_fields = ('title',)
admin.site.register(News, NewsAdmin)
admin.site.register(Category, CategoryAdmin)
models.py
from django.db import models
from django.urls import reverse
class News(models.Model):
title = models.CharField(max_length=150)
content = models.TextField(blank=True)
create_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
photo = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
is_published = models.BooleanField(default=True)
category = models.ForeignKey('Category', on_delete=models.PROTECT)
views = models.IntegerField(default=0)
def get_absolute_url(self):
return reverse('view_news', kwargs={"news_id": self.pk})
def __str__(self): # return number position model
return self.title
objects = models.Manager()
class Meta:
verbose_name = 'NEWS'
verbose_name_plural = 'NEWS'
ordering = ['-create_at']
class Category(models.Model):
title = models.CharField(max_length=150, db_index=True, verbose_name='Title category')
def get_absolute_url(self):
return reverse('category', kwargs={"category_id": self.pk})
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
ordering = ['title']
def __str__(self): # String views. If not be this parameters, be number vice world
return self.title
Since you've put 'get_photo' in NewsAdmin.read_only_fields and it is not a model field, it's supposed to be a method or a property in either News or NewsAdmin.
You should change it to 'photo' because read_only_fields only meant for fields to be non-editable.
class NewsAdmin(admin.ModelAdmin):
...
readonly_fields = ('photo', 'views', 'create_at', 'updated_at')
Try to add 'views' to list_display.
Probably a field can't be in read_only_fields unless it's shown in list_display.
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 using django DeleteView to delete user account. when i set the user's is_active property to False, it doesn't get saved in the database. it's still set to True
here's my views.py
from django.shortcuts import get_object_or_404
from django.urls import reverse_lazy
from django.http import HttpResponseRedirect
from django.views.generic.edit import DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
class DeleteAccount(LoginRequiredMixin, SuccessMessageMixin, DeleteView):
"""
DeleteAccount: view to delete user account
"""
model = User
template_name = 'registration/delete_account.html'
success_url = reverse_lazy('core:index')
success_message = 'Account Successfully Deleted!'
def form_valid(self, form):
"""
Delete account and logout current user
"""
account = self.get_object()
# verify if user is the rightful owner of this account
if not account.id == self.request.user.id:
return HttpResponseRedirect(reverse_lazy('accounts:index'))
account.is_active = False # DOESN'T GET SAVED
account.save() # EVEN AFTER CALLING MODEL.SAVE() METHOD
logout(self.request)
return super().form_valid(form)
def get_object(self):
return get_object_or_404(User, pk = self.request.user.id)
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
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. :)