What the simplest logic i can add in class HotelDetailView(DetailView) so users can comment on a particular hotel detail page. And it capture user too.
models.py
class Hotel(models.Model):
name = models.CharField(max_length=150)
owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
image = models.ImageField(upload_to=upload_location, null=True, blank=True)
class CommentOnHotel(models.Model):
hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField(max_length=200)
published = models.DateField(auto_now_add=True)
def __str__(self):
return '{} - {}'.format(self.hotel.name, self.user.email)
Forms.py
class CommentOnHotelForm(forms.ModelForm):
class Meta:
model = CommentOnHotel
fields = ['content']
views.py
class HotelDetailView(DetailView):
model = Hotel
........
actually i gave you the better approach for that, but if you want to make all logic and functions at DetailView which is not recommended, here is the solution, you need to override POST function of DetaiView:
class HotelDetailView(DetailView):
model = Hotel
def post(self, request, *args, **kwargs):
# get the hotel object
hotel = self.get_object()
#check for validation of form
form = CommentOnHotelForm({
"hotel": hotel,
"user" :request.user
"comment": request.POST.comment
})
if form.is_valid():
form.save()
#choose where you want to redirect
Related
I am still new to django and have encountered this issue, the situation is like this, I have a profile model, on which I have 2 views ViewProfile and EditProfile inheriting from DetailView and UpdateView respectively. when I edit the profile page, it doesn't get me to the profile page instead it gave the error:
Reverse for 'profile' with keyword arguments '{'id': 9}' not found. 1 pattern(s) tried: ['profile/(?P<pk>[^/]+)/\\Z']
even though I have checked in the python shell, the profile with id:9 is indeed profile with name muham see below
>>> Profile.objects.all()
<QuerySet [<Profile: huzaifa>, <Profile: another1>, <Profile: muham>]>
>>> p1 = Profile.objects.get(name='muham')
>>> p1.id
9
>>>
but still its not showing,
I have overridden the get_success_url to get me to the profile page:
class EditProfile(LoginRequiredMixin, UpdateView):
model = Profile
fields = ('name', 'address', 'phone_no',)
template_name = 'blog_app/edit_profile.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['user'] = self.request.user
return context
def get_success_url(self):
id = self.request.user.profile.id
return reverse_lazy('profile', kwargs={'id': id})
my model is below:
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=60, blank=True, null=True)
address = models.CharField(max_length=400, null=True, blank=True)
# image
phone_no = models.CharField(max_length=40, null=True, blank=True)
def __str__(self):
return str(self.user)
class ViewProfile(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'blog_app/profile.html'
context_object_name = 'profile'
urls.py:
urlpatterns = [
path('', ListBlog.as_view(), name='home'),
path('my-blogs/', MyBlog.as_view(), name='my-blogs'),
path('create-blog/', CreateBlog.as_view(), name='blog-create'),
path('blog-detail/<int:pk>/', BlogDetail.as_view(), name='blog-detail'),
path('edit-blog/<int:pk>/', EditBlog.as_view(), name='blog-edit'),
path('delete-blog/<int:pk>/', DeleteBlog.as_view(), name='blog-delete'),
path('profile/<str:pk>/', ViewProfile.as_view(), name='profile'),
path('edit-profile/<str:pk>/', EditProfile.as_view(), name='edit-profile'),
]
I have found my error, it was because DetailView uses pk or slug, on the urlconf arguments, and before i have added str:id instead of str:pk, and also in the
def get_success_url(self):
id = self.request.user.profile.id
return reverse_lazy('profile', kwargs={'id': id})
i had kwargs={'id':id} instead of {"pk": id}. so that was my issue, and it was resolved after that.
I created a population script for a django website however, after running the script and making migrations, I logged in to the django admin page for my site to access the objects created using the script and could not do it for my Business model. It works fine for my other models.
I get this error when I try to access the registered Businesses in my database from the Django admin page. It does not seem to trace back to any of my code but rather to a template in the admin folder of my python environment. Here's the error message:
error message
Here are my models:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_pic = models.ImageField(upload_to="profile_images", blank=True, default="profile_images/default.png")
description = models.TextField(max_length=1024, default="")
# boolean flag for identifying business owners
is_business_owner = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class Business(models.Model):
owner_fk = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=128)
address = models.CharField(max_length=128)
img = models.ImageField(upload_to="business_images", blank=True)
slug = models.SlugField(unique=True)
class Meta:
verbose_name_plural = 'Businesses'
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Business, self).save(*args, **kwargs)
def __str__(self):
return f"{self.name} owned by {UserProfile.objects.get(pk=self.owner_fk).username}"
Here is how I created the objects through the population script:
def add_user(username, firstname, lastname, password, profile_pic, description,
is_business_owner):
new_user = User.objects.get_or_create(username=username, password=password,
first_name=firstname, last_name=lastname)
if new_user[1]:
new_profile = UserProfile(user=User.objects.get(username=username))
new_profile.profile_pic = profile_pic
new_profile.description = description
new_profile.is_business_owner = is_business_owner
new_profile.save()
def add_business(owner, name, address, img):
new_business = Business(name=name, owner_fk=User.objects.get(username=owner))
new_business.address = address
new_business.img = img
new_business.save()
Any help would be appreciated, thanks.
Your Business class has got __str__ method. You are trying to pass User object to pk (id) key.
class Business(models.Model):
def __str__(self):
return f"{self.name} owned by {UserProfile.objects.get(pk=self.owner_fk).username}"
Instead of searching User object in database Change it to:
return f"{self.name} owned by {self.owner_fk.username}"
because you don't have to search database for related object, just address it directly.
--WHY I CANT TO ACCESS TO ID OF USER AND PRODUCT WITH user__id and product__id?
i have error: (The view store.views.submit_review didn't return an HttpResponse object. It returned None instead).
<pre><code>
i define some code for rating post for any user user
--#views
def submit_review(request, product_id):
url = request.META.get('HTTP_REFERER')
if request.method == 'POST':
try:
reviews = ReviewRating.objects.get(user__id=request.user.id,Product__id=product_id) #my problem is here
form = Reviewform(request.POST, instance=reviews)
form.save()
messages.success(request, 'Thank you!your review has been updated.')
return redirect(url)
except ReviewRating.DoesNotExist:
form = Reviewform(request.POST)
if form.is_valid():
data = ReviewRating()
data.subject = form.cleaned_data['subject']
data.review = form.cleaned_data['review']
data.rating = form.cleaned_data['rating']
data.ip = request.META.get['REMOTE_ADDR']
data.product_id = product_id
data.user_id = request.user.id
data.save()
messages.success(request, 'Thank you! Your review has been submitted')
return redirect(url)
</code></pre>
this section i define model.I checked this part it work correctly
define model for views in my app
#models
class ReviewRating(models.Model):
Product = models.ForeignKey(product, on_delete=models.CASCADE)
user = models.ForeignKey(Account, on_delete=models.CASCADE)
subject = models.CharField(max_length=100, blank=True)
review = models.TextField(max_length=500, blank=True)
rating = models.FloatField()
ip = models.CharField(max_length=20, blank=True)
status = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.subject
this part i define url
#urls
define path for html and views
urlpatterns = [
path('submit_review/int:product_id/',views.submit_review,name='submit_review')
]
your model is not clear. It would be better if you could atleast share your full model.py file
if you provide the objective of your service with models.py, serializers.py, views.py I think I will be able to help more specifically
till now, one issue i've found in the the url section is that you need to add < > on int:product_id.
it should be,
urlpatterns = [
path('submit_review/<int:product_id>/',views.submit_review,name='submit_review')
]
I have two models (customer, movie) and I would like to return (movie_name, customer_name, id) when I hit the URL (api/customer/1) and when I hit the URL (api/customer/1/movies) just wanted the movie names alone. How can we achieve this ?
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True)
class Movie(models.Model):
movie_name = models.CharField(max_length=200, null=True)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
serializers.py
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = Customer
fields = ('id', 'name')
class MovieSerializer(serializers.ModelSerializer):
class Meta:
model = Movie
fields = '__all__'
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^api/customers/$', CustomerSerializer.as_view(), name='customers'),
]
Note:
At the moment, when I hit the URL (api/customers) it returns the id, name of all the customers. Now, I would like to know, when I hit the URL (api/customer/1) how to list the same information along with movie names and when I hit the URL (api/customer/1/movies) how to just return the movie names alone?
You will have to write two urls for this purpose but you can do this with one view and serializer like this
Urls
urlpatterns = [
path('admin/', admin.site.urls),
path('api/customers/<int:id>/', CustomerMovieView.as_view(check=True)),
path('api/customers/<int:id>/movies/', CustomerMovieView.as_view(check=False)),
]
Views and Serializers
from rest_framework import generics, response, serializer
class MovieSerializer(serializers.ModelSerializer):
customer_name = serializers.SerializerMethodField()
def get_customer_name(self, instance):
return instance.customer.name
class Mete:
model = Movie
fields = '__all__'
def to_representation(self, instance):
data = super().to_representation(instance)
if not self.context('check'):
data.pop('customer_name', None)
data.pop('customer', None)
return data
class CustomerMovieView(generics.GenericAPIView):
serializer_class = MovieSerializer
check = True
def get_serializer_context(self):
context = super().get_serializer_context()
context.update({'check': self.check})
return context
def get(self, request, *args, **kwargs):
id = kwargs.get('id')
movie = Movie.objects.get(id=id)
serialized = self.get_serializer(movie)
return response.Respoonse(serialized.data)
I have been learning django and django rest framework since couple of weeks and I want to figure out how can I join two tables and serialize the data of same to return the json response using django rest framework.
I want to return result as json response:
{ 'user_id_id': 1, 'request_msg': 'Hi', 'response_msg': "Hi, Welcome" }
where result is
from django.db import connection
cursor = connection.cursor()
con = cursor.execute("SELECT backend_request_messages.user_id_id, backend_request_messages.request_msg as request_msg,backend_response_messages.response_msg as response_msg FROM backend_request_messages,backend_response_messages Where backend_request_messages.user_id_id=backend_response_messages.user_id_id=1 ")
Here is what I have tried :
#backend/Models.py
class User(models.Model):
username = models.CharField(max_length=50)
name = models.CharField(max_length=50, blank=True, null=True)
uid = models.CharField(max_length=12, blank=True, null=True)
age = models.CharField(max_length=3, blank=True, null=True)
active = models.BooleanField(default=True)
class Meta:
default_related_name = 'users'
def __str__(self):
return self.name
class Request_Messages(models.Model):
request_msg = models.CharField(max_length=100)
request_msg_created_at = models.DateTimeField(auto_now_add=True)
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, null=True)
class Meta:
default_related_name = 'request_messages'
def __str__(self):
return self.request_msg
class Response_Messages(models.Model):
response_msg = response_msg = models.CharField(max_length=400)
response_msg_created_at = models.DateTimeField(auto_now_add=True)
user_id = models.ForeignKey(
User, on_delete=models.CASCADE, null=True)
class Meta:
default_related_name = 'response_messages'
def __str__(self):
return self.response_msg
#backend/serializers.py
class ListSerializer (serializers.Serializer):
user_id_id = serializers.IntegerField()
request_msg = serializers.CharField(max_length=100)
# request_msg_created_at = serializers.DateTimeField(read_only=True)
response_msg = serializers.CharField()
# response_msg_created_at = serializers.DateTimeField(read_only=True)
#backend/views.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Response_Messages, Request_Messages, User
from .serializers import ListSerializer
from django.db import connection
#api_view(['GET', 'POST'])
def chatbot(request):
if request.method == 'GET':
cursor = connection.cursor()
query_set = cursor.execute("SELECT backend_request_messages.user_id_id, backend_request_messages.request_msg as request_msg,backend_response_messages.response_msg as response_msg FROM backend_request_messages,backend_response_messages Where backend_request_messages.user_id_id=backend_response_messages.user_id_id=1 ")
columns = [column[0] for column in query_set.description]
results = []
for row in query_set.fetchall():
results.append(dict(zip(columns, row)))
serializer = ListSerializer(results)
return Response(serializer.data)
About serializers, You should refer to the docs (they're awesome and explain it best).
To give you a direction, I like to create a serializer for every model and if it's related to another model, I refer that in serializer, that way, You can easily customize behavior for each model (although not the only way at all).
So, about serializing I would do the following (notice my comments as well):
from django.contrib.auth.models import User
class User(User):
# Your user class, except, it should inherit Django's User/AbstractUser class.
class RequestMessages(models.Model):
request_msg = models.CharField(max_length=100)
request_msg_created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
User, on_delete=models.CASCADE, null=True, related_name='requests_msg')
# NOTICE THE NEW RELATED NAME, WE'LL USE IT LATER.
class Meta:
default_related_name = 'request_messages'
def __str__(self):
return self.request_msg
class ResponseMessages(models.Model):
response_msg = response_msg = models.CharField(max_length=400)
response_msg_created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='responses_msg')
def __str__(self):
return self.response_msg
class RequestMsgSerializer(serializers.ModelSerializer):
# Specify what ever you like...
class Meta:
model = RequestMessages
fields = # Whatever you like to serialize.
class ResponseMsgSerializer(serializers.ModelSerializer):
class Meta:
model = ResponseMessages
fields = # Whatever you want serialized.
class UserSerializer(serializers.ModelSerializer):
# Using required = False will cause that every time you create a user they don't have to own messages.
requests_msg = RequestMsgSerializer(many=False, required=False)
responses_msg = ResponseMsgSerializer(many=False, required=False)
class Meta:
model = User
field = # Same as above ..
About your query, using raw SQL in Django is rear, usually, in most cases the Django built-in ORM will do the job and usually faster and better than you.
In your case, if you'll call your query like this for exmaple:
query_set = User.objects.filter(user=request.user)
the QuerySet object created will hit the DB one for the user object and X queries for all the associated messages with said user, so expensive.
But no need for a custom query with joins and stuff like that, Django has prefetch_related and select_related.
exmaple:
query_set = User.objects.filter(user=request.user).prefetch_related('requests_msg')
will reduce all the queries made for request messages associated to a user to only one!
Recap:
I wrote a lot because I'm still learning this stuff myself self and if you teach others you got it!
Refer to DRF's docs about serializers (there's even a dedicated section for nested serializers) and API Views, they really great.
Refer to Django's docs about prefetch related, select related and queries in general, again, Amazing docs that cover everything.
Don't just copy my code or anyone else's, there's no problem with that, just make sure you understand it first if not, you're bound to get stuck with it again!