Why am I seeing the following error in Django? - django

So, I have a user form in my Django project. After Submitting the form I want to redirect the user to another form (for additional details). But I am seeing the following error
NoReverseMatch at /incubators/add-incuabtor/
Reverse for 'details' with keyword arguments '{'pk': 15}' not found. 1 pattern(s) tried: ['incubators/(?P<incubator_id>[0-9]+)']
Request Method: POST
Request URL: http://127.0.0.1:8000/incubators/add-incuabtor/
I have the following url pattern:
app_name = 'main'
urlpatterns = [
url(r'^home/', views.home, name='home'), # Home page
url(r'incubators/$', views.incubators, name='incubators'), # Incubator list page
url(r'about/', views.about, name='about'), # Websie about page
url(r'results', views.result, name = 'result'), # For search function
url(r'incubators/(?P<incubator_id>[0-9]+)', views.details, name = 'details'), # shows details of incubators
url(r'incubators/add-incuabtor/$', views.AddIncubator.as_view(), name = 'add-incubator'), # Adding Inc
url(r'/add-details/', views.AddDetails.as_view(), name = 'add-details'), #for additional details
]
Following is my models.py
class Incubators(models.Model): # These are our database files for
the Incubator Portal
incubator_name = models.CharField(max_length=30)
owner = models.CharField(max_length=30)
city_location = models.CharField(max_length=30)
description = models.TextField(max_length=100)
logo = models.FileField()
verify = models.BooleanField(default = False)
def get_absolute_url(self):
return reverse('main:details', kwargs={'pk': self.pk})
def __str__(self): # Displays the following stuff when a query is made
return self.incubator_name + '-' + self.owner
class Details(models.Model):
incubator = models.ForeignKey(Incubators, on_delete = models.CASCADE, related_name='banana_pudding')
inc_name = models.CharField(max_length = 30)
inc_img = models.FileField()
inc_contact = models.CharField(max_length = 600, default = "Enter all available means of contacting")
inc_details = models.TextField(max_length= 2500)
inc_address = models.TextField(max_length = 600, default = "Address")
inc_doc = models.FileField()
inc_policy = models.FileField()
def __str__(self):
return self.inc_name
And I have the following views.py
class AddIncubator(CreateView):
model = Incubators
fields = ['incubator_name', 'owner', 'city_location', 'description', 'logo']
class AddDetails(CreateView):
model = Details
field = ['incubator', 'inc_name']

Problem is with you url.
In urls.py, you detail url is
url(r'incubators/(?P<incubator_id>[0-9]+)', views.details, name = 'details'),
Change it to
url(r'incubators/(?P<pk>[0-9]+)', views.details, name = 'details'),
or you can change reverse url in you models as:
def get_absolute_url(self):
return reverse('main:details', kwargs={'incubator_id': self.pk})

Related

Django blog post views count adds two instead of one

I built this blog with django and everything is working except the blog post view count. On the page it adds 1 as instructed but adds 2 in django admin. Please let me know what I am doing wrongly
Models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
User = get_user_model()
from ckeditor_uploader.fields import RichTextUploadingField
class Subscribe(models.Model):
email = models.EmailField()
class Comments(models.Model):
name = models.CharField('Name', max_length=120)
post_id = models.IntegerField(null=True)
email = models.EmailField()
website = models.URLField(max_length=200)
comment = models.TextField(blank=True)
date_created = models.DateTimeField(blank=True,null=True)
def publish(self):
self.date_created=timezone.localtime(timezone.now())
self.save()
class Category(models.Model):
name = models.CharField('Name', max_length=120)
slug = models.SlugField(default="", null=False)
def __str__(self):
return self.name
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
about = RichTextUploadingField()
image = models.ImageField(upload_to='images/', null=True)
slug = models.SlugField(default="", null=False)
views = models.IntegerField(default=0)
def __str__(self):
return self.user.username
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
class Post(models.Model):
title = models.CharField('Post Title', max_length=120)
date = models.DateTimeField()
status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default ='draft')
category = models.ForeignKey(Category,on_delete = models.SET_NULL, blank = True, null = True,)
author = models.ForeignKey(User,on_delete = models.SET_NULL, blank = True, null = True,)
details = RichTextUploadingField()
slug = models.SlugField(default="", null=False)
image = models.ImageField(upload_to='images/', null=True)
post_views = models.IntegerField(default=0)
class Meta:
ordering = ['-date']
def __str__(self):
return self.title
def image_url(self):
if self.image and hasattr(self.image, 'url'):
return self.image.url
Views.py
from django.shortcuts import render
from .models import Post
from .models import Comments
from .models import Category
from .models import Author
from .models import Subscribe
from django.http import JsonResponse
from django.utils import timezone
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Count
# DEFINING CONTEXTS DETAILS
posts = Post.objects.filter(status="published")
recentPosts = Post.objects.filter(status="published").order_by("-id")[:3]
sidebarPosts = Post.objects.filter(status="published").order_by("-id")[:5]
morePosts = Post.objects.filter(status="published").order_by("-id")[:2]
popularPosts = Post.objects.order_by("-post_views")[:3]
categoryList = Category.objects.annotate(nblog=Count('post')).values()
# VIEW FOR POST DETAILS PAGE
def details(request, slug):
thisPost = Post.objects.filter(slug=slug).first()
thisPost.post_views+=1
thisPost.save()
id = thisPost.id
author = thisPost.author
category = thisPost.category
postCategory = Category.objects.filter(name = category).first()
authorDetail = Author.objects.filter(user = author).first()
allComments = Comments.objects.filter(post_id = id).order_by("-date_created").values()
commentCount = len(Comments.objects.filter(post_id = id))
context = {
'details' : thisPost,
'postCategory' : postCategory,
'allComments' : allComments,
'count' : commentCount,
'authorDetail' : authorDetail,
'sidebarPosts' : sidebarPosts,
'morePosts' : morePosts,
'recentPosts' : recentPosts,
'popularPosts' : popularPosts,
'categoryList' : categoryList
}
return render(request,'markedia/details.html', context)
Urls
from django.urls import path
from markedia_blog import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name="index"),
path('index', views.index, name="index"),
path('contact', views.contact, name="contact"),
path('details/<slug:slug>', views.details, name="details"),
path('comment', views.comment, name="comment"),
path('subscribe', views.subscribe, name="subscribe"),
path('blog', views.blog, name="blog"),
path('author/<slug:slug>', views.author, name="author"),
path('category/<slug:slug>', views.category, name="category"),
path('search', views.search, name="search"),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
ADMIN PAGE
Default = 0
Admin page
TEMPLATE PAGE
Post views is equal to 1 on template page
Post views is equal to 1 on template page
ADMIN PAGE AFTER VIEWING TEMPLATES PAGE
Post views is equal to 2 instead of 1
Post views is equal to 2 instead of 1
Could you tell me what i'm doing wrong??
Template page post views shows 1 but admin page shows 2

How to create seperate POST request for imagefield in DRF

I need to make a separate API for the image file. How can I achieve this?
models.py
class Organization(models.Model):
code = models.CharField(max_length=25, null=False, unique=True)
name = models.CharField(max_length=100, null=False)
location = models.ForeignKey(Location, on_delete=models.RESTRICT)
description = models.TextField()
total_of_visas = models.IntegerField(null=False, default=0)
base_currency = models.ForeignKey(Currency, on_delete=models.RESTRICT)
logo_filename = models.ImageField(upload_to='uploads/')
serializers.py
class OrganizationSerializer(serializers.ModelSerializer):
location = serializers.CharField(read_only=True, source="location.name")
base_currency = serializers.CharField(read_only=True, source="base_currency.currency_master")
location_id = serializers.IntegerField(write_only=True, source="location.id")
base_currency_id = serializers.IntegerField(write_only=True, source="base_currency.id")
class Meta:
model = Organization
fields = ["id", "name", "location", "mol_number", "corporate_id", "corporate_name",
"routing_code", "iban", "description", "total_of_visas", "base_currency", "logo_filename",
"location_id", "base_currency_id"]
def validate(self, data):
content = data.get("content", None)
request = self.context['request']
if not request.FILES and not content:
raise serializers.ValidationError("Content or an Image must be provided")
return data
def create(self, validated_data):
....
def update(self, instance, validated_data):
....
views.py
class OrganizationViewSet(viewsets.ModelViewSet):
queryset = Organization.objects.all()
serializer_class = OrganizationSerializer
lookup_field = 'id'
urls.py
router = routers.DefaultRouter()
router.register('organization', OrganizationViewSet, basename='organization')
urlpatterns = [
path('', include(router.urls)),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I don't have idea how to make POST request for image field from postman. I've been stuck here for a long time. Any help is appreciated.
if you want to update the image field separately you just have to create a separate serializer for it
class OrganizationImageSerializer(serializers.ModelSerializer):
logo_filename = serializers.ImageField()
class Meta:
model = Organization
fields = ["logo_filename"]
view.py
class OrganizationImageView(generics.UpdateAPIView):# or `generics.RetrieveUpdateAPIView` if you also want to retriev the current one before updating it
serializer_class = OrganizationImageSerializer
permission_classes = [IsAuthenticated, ]
def get_queryset(self):
queryset = Organization.objects.filter(id=self.kwargs['pk'])
return queryset
urls.py
from .views import OrganizationImageView
urlpatterns = [
...
path('update_org/<int:pk>', OrganizationImageView.as_view(), name='OrganizationImageUpdater'),
]

django-autocomplete-light dependant filter over 3 models

I have 3 models.
class FilterDefaultValues(BaseModel):
value = models.CharField(max_length=255, null=True, blank=True)
display_value = models.CharField(max_length=255, null=True, blank=True)
class Filter(BaseModel):
name = models.CharField(max_length=255)
default_value = models.ManyToManyField(FilterDefaultValues, blank=True)
class ProductFilter(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='filters')
filter = models.ForeignKey(Filter, on_delete=models.CASCADE)
value = models.ForeignKey(FilterDefaultValues, blank=True, on_delete=models.RESTRICT)
urls.py
class LinkedDataView(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = super(LinkedDataView, self).get_queryset()
filter = self.forwarded.get('filter', None)
if filter:
qs = qs.filter(filter_id=filter)
return qs
urlpatterns = [
url(
'^linked_data/$',
LinkedDataView.as_view(model=ProductFilter),
name='linked_data'
),
]
forms.py
class ProductFilterForm(forms.ModelForm):
def clean_test(self):
filter = self.cleaned_data.get('filter', None)
value = self.cleaned_data.get('value', None)
if value and filter and value.filter != filter:
raise forms.ValidationError('Wrong owner for test')
return value
class Meta:
model = ProductFilter
fields = ('product', 'filter', 'value', 'value_type', 'product_images', 'is_variation')
widgets = {
'value': autocomplete.ModelSelect2(url='linked_data',
forward=('filter',))
}
class Media:
js = (
'linked_data.js',
)
What I want to is in the admin panel when the user selects a filter, then the value field must be populated with appropriate default values.
But now what I get is: When user selects filter then only productfilter items are populated here.
What I am missing here?
This is because your LinkedDataView.get_queryset() method is using the model ProductFilter, when it should be using the FilterDefaultValues model instead.
If you look in your urls.py file, the LinkedDataView is initialized with model=ProductFilter. This means that the LinkedDataView.get_queryset() method will only return ProductFilter instances.
Instead, you want to be able to show suggestions for FilterDefaultValues instances that are referenced (many-to-many) by Filter instances through the Filter.default_value attribute.
To do this, you'll need to create a new autocomplete view that operates on FilterDefaultValues:
urls.py
class FilterDefaultValuesAutocompleteView(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = super().get_queryset()
filter_id = self.forwarded.get("filter", None)
if filter_id:
qs = qs.filter(filter__id=filter_id)
return qs
urlpatterns = [
url(
"^filter_default_values_autocomplete/$",
FilterDefaultValuesAutocompleteView.as_view(model=FilterDefaultValues),
name="filter_default_values_autocomplete",
),
]
And then update your form class:
forms.py
class ProductFilterForm(forms.ModelForm):
class Meta:
model = ProductFilter
fields = ...
widgets = {
"value": autocomplete.ModelSelect2(
url="filter_default_values_autocomplete",
forward=["filter"],
)
}

Django rest_framework oAuth2 APIView error

I am making a Django application API, where an authorized user can post a messages, and other users can browse the message and like/dislike/comment on the messages (twitter style).
I have implemented oAuth2 already and tested it.
The API works fine from the admin panel, but when I access it through url, it is giving error:
enter image description here
My models.py class is:
class Posts(models.Model):
def expirationTimeCalculation(self):
EXPIRATION_DURATION = 86400 #time in seconds
expirationTime = self.creationTimestamp + timedelta(seconds = EXPIRATION_DURATION)
return expirationTime
def postLiveStatus(self):
return (self.expirationTimestamp > timezone.now)
def postLiveTimeRemaining(self):
if (self.expirationTimestamp > timezone.now):
return (self.expirationTimestamp - timezone.now).total_seconds()
else:
return 0
postIdentifier = models.IntegerField()
title = models.CharField(max_length=100)
message = models.TextField()
topic = models.ManyToManyField('Topics')
creationTimestamp = models.DateTimeField(default=timezone.now)
expirationTimestamp = property(expirationTimeCalculation)
post_owner = models.ForeignKey(AppUser, related_name='post_owner', on_delete=models.CASCADE)
isLive = property(postLiveStatus)
post_likes = models.ForeignKey('Likes', related_name="post_likes", on_delete=models.CASCADE)
post_dislikes = models.ForeignKey('Dislikes', related_name="post_dislikes", on_delete=models.CASCADE)
post_comments = models.ForeignKey('Comments', related_name="post_comments", on_delete=models.CASCADE)
def __str__(self):
return self.title
class Topics(models.Model):
TOPICS = [('P','Politics'),('H','Health'),('S','Sports'),('T','Tech')]
topicName = models.CharField(max_length=2, choices=TOPICS, blank=False)
class Likes(models.Model):
isLiked = models.BooleanField(null=True)
likes_owner = models.ForeignKey(AppUser, related_name='likes_owner', on_delete=models.CASCADE)
post = models.ForeignKey(Posts, related_name='likes', on_delete = models.CASCADE)
class Dislikes(models.Model):
isDisliked = models.BooleanField(null=True)
dislikes_owner = models.ForeignKey(AppUser, related_name='dislikes_owner', on_delete=models.CASCADE)
post = models.ForeignKey(Posts, related_name='dislikes', on_delete = models.CASCADE)
class Comments(models.Model):
comment = models.TextField(null=True)
comments_owner = models.ForeignKey(AppUser, related_name='comments_owner', on_delete=models.CASCADE)
post = models.ForeignKey(Posts, related_name='comments', on_delete = models.CASCADE)
The serializer class is:
class CommentsSerializer(serializers.ModelSerializer):
comments_owner = CreateUserSerializer()
class Meta:
model = Comments
fields = ('comment', 'comments_owner')
class DislikesSerializer(serializers.ModelSerializer):
dislikes_owner = CreateUserSerializer()
class Meta:
model = Dislikes
fields = ('isDisliked', 'dislikes_owner')
class LikesSerializer(serializers.ModelSerializer):
likes_owner = CreateUserSerializer()
class Meta:
model = Likes
fields = ('isLiked', 'likes_owner')
class TopicsSerializer(serializers.ModelSerializer):
class Meta:
model = Topics
fields = ('topicName')
class PostsSerializer(serializers.ModelSerializer):
class Meta:
model = Posts
fields = ('postIdentifier', 'title', 'message', 'topic', 'creationTimestamp', 'expirationTimestamp', 'isLive', 'post_owner', 'post_likes', 'post_dislikes', 'post_comments')
Views class is:
from rest_framework.generics import ListAPIView
from .models import Posts
from .serializers import PostsSerializer
class PostsView(ListAPIView):
queryset = Posts.objects.all()
serilaizer_class = PostsSerializer
And the main URLS class is:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
import posts_backend.views
urlpatterns = [
path('admin/', admin.site.urls),
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), #Adding oAuth2 privider URLS to the url path
path('authentication/', include('accounts.urls')), #Creating authentication endpoints http://10.61.64.150:8000/authentication/ for performing authentication
path('v1/posts/', posts_backend.views.PostsView.as_view(),), # Version 1 of the API
]
Can anyone kindly let me know why I am getting this error and how to resolve this?
try renaming the attribute from serilaizer_class to serializer_class

django models imagefield upload_to method not working

I am using create view to create a model instance (product).
Evey thing is working fine bt after doing some new migrations
i can't get the uploaded image, instead getting default image.
I think upload_to method of models isn't working.
i also used this in my urls
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is my settigs vars:
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
This is my models.py:
class Product(models.Model):
TYPE = [
('Sell','Sell'),
('Rent','Rent'),
('Sell or Rent','Sell or Rent'),
]
owner = models.ForeignKey(Owner, on_delete=models.CASCADE)
title = models.CharField(max_length = 25)
type = models.CharField(max_length = 12, choices = TYPE, default = 'Sell')
price = models.IntegerField()
description = models.TextField(default="No Description Given")
image = models.ImageField(default='default.jpeg', upload_to='product')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('store')
and this is my views.py:
class ProductCreateView(LoginRequiredMixin, CreateView):
model = Product
fields = ['title','type', 'price','description', 'image']
def form_valid(self, form):
print(self.request.POST)
owner , created = Owner.objects.get_or_create(user=self.request.user)
form.instance.owner = self.request.user.owner
return super().form_valid(form)
I am getting default image for every new product created.
Thanks
P.S. when i am adding product from admin panel then every thing is working fine.