happy new year everyone...I am new to django and i am working on a project a resume page i need help with the contact me section, i want to do something i seen in a video https://www.youtube.com/watch?v=w4ilq6Zk-08. The book i used to learn only uses class to view templates. below is my code
from django.views.generic import TemplateView
from django.shortcuts import render
# Create your views here.
class ProfilePageView(TemplateView):
template_name = 'femi_profile.html'
def contact(request):
if request.method == "POST":
name = request.POST['name']
email = request.POST['email']
subject = request.POST['subject']
message = request.POST['message']
return render(request, 'femi_profile.html', {'contact_name': name})
else:
return render(request, 'femi_profile.html', {})
After reading the django documentation https://docs.djangoproject.com/en/3.1/topics/class-based-views/intro/ once more and trying different lines of code i finally got that run and i am not asking why is it runing? i figured out how to go about this.
find the correct code below
from django.views.generic import TemplateView
from django.shortcuts import render
# Create your views here.
class ProfilePageView(TemplateView):
template_name = 'femi_profile.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name, {})
def post(self, request, *args, **kwargs):
if request.method == "POST":
name = request.POST['name']
email = request.POST['email']
subject = request.POST['subject']
message = request.POST['message']
return render(request, self.template_name, {'contact_name': name})
Related
I am making a to-do app using Django. Currently, the problem I am facing is that no matter which user logs in, the same set of tasks appears, i.e. if a user adds some task for himself, they appear in every other user's to-do list. How can I modify my code so that each user can have a distinct set of tasks?
Here's some of my code:
Models
from django.db import models
# Create your models here.
class TodooModel(models.Model):
fd = models.TextField()
cr_dt = models.DateTimeField(auto_now_add=True)
Views.py
from django.shortcuts import render,redirect
from .models import TodooModel
# Create your views here.
def home(request):
if request.user.is_authenticated:
return render(request,"home.html")
else:
return redirect("user_login")
def create(request):
if request.user.is_authenticated:
if request.method == "POST":
fdk= request.POST.get("task")
data = TodooModel(fd=fdk)
data.save()
return render(request,"create.html",{"msg":"Added Succesfully"})
else:
return render(request,"create.html")
else:
return redirect("user_login")
def views(request):
if request.user.is_authenticated:
data = TodooModel.objects.get()
return render(request,"views.html",{"data":data})
else:
return redirect("user_login")
def delete(request,id):
if request.user.is_authenticated:
de = TodooModel.objects.get(id=id)
de.delete()
return redirect("views")
else:
return redirect("user_login")
You need to add new field to the TodooModel model,
When you create entry in TodooModel add created_by paramater.
And while filtering tasks you need to add created_by=user.
created_by = models.ForiegnKey() # add new field to your model.
data = TodooModel(fd=fdk, created_by=request.user) # in your create method
data = TodooModel.objects.filter(created_by=request.user) # in view method
Edit
Your code should be like,
models,
from django.contrib.auth.models import User
class TodooModel(models.Model):
fd = models.TextField()
cr_dt = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User)
create method,
def create(request):
if request.user.is_authenticated:
if request.method == "POST":
fdk = request.POST.get("task")
data = TodooModel(fd=fdk, created_by=request.user)
data.save()
return render(request, "create.html", {"msg": "Added Succesfully"})
else:
return render(request, "create.html")
else:
return redirect("user_login")
view method,
def views(request):
if request.user.is_authenticated:
data = TodooModel.objects.filter(created_by=request.user)
return render(request, "views.html", {"data": data})
else:
return redirect("user_login")
Hope that helps.
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.
views.py
from paitent.mixini import HttpResponseMixin,SerializeMixin
from paitent.models import Paitent_Details
class PaitentCRUDCBV(View, HttpResponseMixin, SerializeMixin):
def get(self, id, *args, **kwargs):
paitent = Paitent_Details.objects.get(id=id)
json_data = self.render_to_serialize([paitent,])
return self.render_to_http_response(json_data)
urls.py
urlpatterns = [
url(r'^api/json',views.PaitentCRUDCBV.as_view()),
]
My requirement is based on id i have to fetch particular row form data base,from Frontend side i am passing id in url like:(url: "http://127.0.0.1:8000/api/json/?id=2").But i am not finding id inside my class ,don't know where i am doing wrong. please help me.
You can use query_params in view:
def get(self, request):
id = self.request.query_params.get('id')
....
You can get more information from documentation
1)I have edited your following code, you have to pass *request* in your function,
2)Inside the function calling request.query_params.get, you will get parameters value from the url
from paitent.mixini import HttpResponseMixin,SerializeMixin
from paitent.models import Paitent_Details
class PaitentCRUDCBV(View, HttpResponseMixin, SerializeMixin):
def get(self, request, *args, **kwargs):
id=self.request.query_params.get('id')
paitent = Paitent_Details.objects.get(id=id)
json_data = self.render_to_serialize([paitent,])
return self.render_to_http_response(json_data)
currently i pass the parameter 'id' in the url and i call the API by id however i would like to call API by the parameter.here is views.py`
class post_list(APIView):
def get(self,request,format=None):
post_resource=PostResource()
dataset=Dataset()
post = Post.objects.all()
serializer = PostSerializer(post, many=True)
a=[]
for row in post:
a.append(row)
return Response(serializer.data)
def post(self,request,format =None):
serializer = PostSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
class post_detail(APIView):
def get_object(self, pk):
try:
return Post.objects.get(pk=pk)
except Post.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
post = self.get_object(pk)
serializer = PostSerializer(post)
return Response(serializer.data)
def put(self, request, pk, format=None):
snippet = self.get_object(pk)
serializer = PostSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
post = self.get_object(pk)
post.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
this is the result when i pass the id in the url`
when i pass the id in the url it's show only the that particular id result however i need view if i pass the other field instead of the id it's show the result based on that.so my question is what should i have to change in the views.py and Urls.py. this is urls.py file`
from django.conf.urls import url
from api import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^post/$', views.post_list.as_view()),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail.as_view()),
]
urlpatterns=format_suffix_patterns(urlpatterns)
This is my serializer.py file`
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
#fields=('ProductName','Score')
fields ='__all__'
`
You should change your url so that it accepts string:
url(r'^post/(?P<pname>[a-zA-Z0-9]+)/$', views.post_detail.as_view())
and then change your get_object method like this:
def get_object(self, pname):
try:
return Post.objects.get(pname=pname)
except Post.DoesNotExist:
raise Http404
But you will issues if pname is not unique, because it will complain that you have more than one such Post.
Hope it helps!
I am having trouble creating a customizable swagger schema in the Django Rest Framework. I have read pages of documentation, but have not found a clear cut example on how to generate swagger annotations in python.
I am aware that swagger/schema documentation is readily generated when using ViewSets in Django. However, I am solely using APIViews and want to write a customized schema. I have tried creating a CoreAPI schema but am unaware of how to implement it. I am enclosing some of my sample code and some screenshots as well. The screen shots go from what I have to what I want.
Sample code:
urls.py
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from Views import SampleView as sv
from rest_framework_swagger.views import get_swagger_view
from rest_framework.documentation import include_docs_urls
from rest_framework.renderers import CoreJSONRenderer
from rest_framework.schemas import get_schema_view
schema_view enter code here= get_swagger_view(
title='Sample API')
urlpatterns = [
url(r'^sample/$', pv.SampleList.as_view()),
url(r'^sample/(?P<id>[a-f\d]{24})/$', sv.SampleDetail.as_view()),
url('^schema/$', schema_view),
]
urlpatterns = format_suffix_patterns(urlpatterns)
views.py
from rest_framework.views import APIView
from Manager.SampleManager import SampleManager as sm
_sampleManager = sm()
class SampleList(APIView):
"""
get:
Return a list of all the existing samples.
post:
Create a new sample.
"""
def get(self, request, format=None):
return _sampleManager.getAll()
def post(self, request, format=None):
return _sampleManager.create( request)
class SampleDetail(APIView):
"""
get:
Get a sample.
put:
Update a sample.
delete:
Delete a sample.
"""
def get(self, request, id, format =None):
return _sampleManager.getById( id)
def put(self, request, id, format =None):
return _sampleManager.update( request, id)
def delete(self, request, id, format =None):
return _sampleManager.deleteById( id)
Serializers.py
from rest_framework_mongoengine.serializers import DocumentSerializer
from .modles import Sample, SampleInner
from Serializers.SampleInnerSerializer import SampleInnerSerializer
class SampleSerializer(DocumentSerializer):
other = SampleInnerSerializer(many=True)
class Meta:
model = Sample
fields = '__all__'
def create(self, validated_data):
samples = validated_data.pop('other')
created_instance = super(SampleSerializer, self).create(validated_data)
for sample_data in samples:
created_instance.other.append(SampleInner(**sample_data))
created_instance.save()
return created_instance
def update(self, instance, validated_data):
samples = validated_data.pop('other')
updated_instance = super(SampleSerializer, self).update(instance, validated_data)
for sample_data in samples:
updated_instance.other.append(SampleInner(**sample_data))
updated_instance.save()
return updated_instance
Schema.py
import coreapi
from rest_framework.decorators import api_view, renderer_classes
from rest_framework import renderers, response
schema = coreapi.Document(
title='Sample API',
content={
'sample': coreapi.Link(
url='/sample/',
action='post',
fields=[
coreapi.Field(
name='from',
required=True,
location='query',
description='City name or airport code.'
),
coreapi.Field(
name='to',
required=True,
location='query',
description='City name or airport code.'
),
coreapi.Field(
name='date',
required=True,
location='query',
description='Flight date in "YYYY-MM-DD" format.'
)
],
description='Create partner'
)
}
)
#api_view()
#renderer_classes([renderers.CoreJSONRenderer])
def schema_view(request):
return response.Response(schema)
There is two solution for you in this senario, One "go with the GenricApiView" Two "Create Custom row Schema"
let's go with
-- >solution one.
urls.py
schema_view = get_swagger_view(title='Test All API')
urlpatterns = [
path('swagger2/', schema_view),
]
view.py
class LoginAPIView(generics.GenericAPIView):
serializer_class = LoginSerializer
permission_classes = [permissions.AllowAny]
def post(self, request):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.data, status=status.HTTP_200_OK)
Result
--> Solution two:
urls.py
configuration is same as before
views.py
class BlacklistTokenAdding(APIView):
permission_classes = [permissions.AllowAny]
schema = ManualSchema(fields=[
coreapi.Field(
"first_field",
required=True,
location="body",
schema=coreschema.String()
),
coreapi.Field(
"second_field",
required=True,
location="body",
schema=coreschema.String()
),
])
def post(self, request, format='json'):
try:
refresh_token = request.data["refresh_token"]
token = RefreshToken(refresh_token)
token.blacklist()
return Response(status=status.HTTP_200_OK)
except Exception as e:
return Response(status=status.HTTP_400_BAD_REQUEST)
//Note the first_field & second_field is to demonstration you can add here as much field as you want.
Result