class MarketingBusinessDetailView(generic.DetailView): syntaxError: invalid syntax - python-3.x

from myapp import views
File "C:\Users\User\job\mysite\myvenv\myproject\myapp\views.py", line 151
class MarketingBusinessDetailView(generic.DetailView):
SyntaxError: invalid syntax
At models.py,
class MarketingBusiness(models.Model):
title = models.CharField(max_length=128)
description = models.TextField(max_length=200, help_text="Enter a brief description of the Marketing business.")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('myapp:marketingbusiness-detail', args=[str(self.id)])
And it's working perfectly in my admin.
At myapp urls.py,
from myapp import views
app_name = 'myapp'
urlpatterns = [
path('marketingbusinesses/', views.MarketingBusinessListView.as_view(), name='marketingbusiness'),
path('marketingbusiness/<int:pk>/', views.MarketingBusinessDetailView.as_view(), name='marketingbusiness-detail'),
At views.py,
from django.shortcuts import render
from django.views import View
from django.views import generic
from myapp.models import MarketingBusiness
class MarketingBusinessDetailView(generic.DetailView):
model = MarketingBusiness
def marketingbusiness_detail(request, pk):
marketingbusiness_id = get_object_or_404(MarketingBusiness, pk=pk)
return render(
request,
'myapp/marketingbusiness-detail.html', context={'marketingbusiness_id':marketingbusiness}
)
How could I resolve this error, please?...

Related

why it's giving me Page not found (404) when I am searching and filtering in my django api

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) **

Showing same template for all url of an Django app

Here are the two views :
from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
class sectionOfficer_home(View):
def get(self, request, *args, **kwargs):
return render(request, 'sectionofficer/UI/index.html', {})
class sectionOfficer_main(View):
def get(self, request, *args, **kwargs):
return render(request, 'sectionofficer/UI/404.html', {})
Here is my urls.py of the app sectionOfficer:
from django.urls import path
from .views import (sectionOfficer_home, sectionOfficer_main)
app_name= 'sectionofficer'
urlpatterns = [
path('', sectionOfficer_home.as_view(), name = "sectionofc"),
path('secmain', sectionOfficer_main.as_view(), name = "secmain")
]
And here is the global urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('sectionoffc', include('sectionofficer.urls')),
path('secmain', include('sectionofficer.urls')),
]
But it showing always the first view template for any different url. What is wrong here ? Help please.

IntegrityError at /images/create/ NOT NULL constraint failed: images_image.users_like_id

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.

Image Upload serializer not working but is valid and saving

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".

Django mail not sending mail to def in views error

**views.py code**(views.py function id not call urls.py)
def SendMail(request,id):
post=get_object_or_404(Post,slug=slug,status='published')
form=EmailSendForm()
return render(request,'mail.html',{'form':form,'post':post})
**models.py**(models.py not accept the id number in views.py)
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils import timezone
class CustomManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES=(('draft','Draft'),('published','Published'))
id=models.IntegerField(primary_key=True)
title=models.CharField(max_length=300)
slug=models.SlugField(max_length=300,unique_for_date='publish')
author=models.ForeignKey(User,related_name='post',on_delete=models.CASCADE)
body=models.TextField()
publish=models.DateTimeField(default=timezone.now)
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
status=models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
objects=CustomManager()
class Meta:
ordering=('-publish', )
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post',args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
urls.py(urls show page not found 404 error)
path('/(?P\d+)share/$',views.SendMail),
**views.py**
from django.core.mail import send_mail
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render,get_object_or_404
from app.models import Post
from app.forms import EmailSendForm
def post_list_view(request):
post_list=Post.objects.all()
paginator=Paginator(post_list,3)
page_number=request.GET.get('page')
try:
post_list=paginator.page(page_number)
except PageNotAnInteger:
post_list=paginator.page(1)
except EmptyPage:
post_list=paginator.page(paginator.num_pages)
return render(request, 'post_list.html', {'post_list':post_list})
def post_detail_view(request,year,month,day,slug):
post=get_object_or_404(Post,slug=slug,
status='published',
publish__year=year,
publish__month=month,
publish__day=day,
)
return render(request, 'post_detail.html', {'post':post})
def SendMail(request,post_id):
post = get_object_or_404(Post,id=post_id,status='published')
sent=False
if request.method=='POST':
form=EmailSendForm(request.POST)
if form.is_valid():
cd=form.cleaned_data
subject='{}({})Please read message"{}"'.format(cd['name'],cd['email'],post.title)
post_url=request.build_absolute_uri(post.get_absolute_url())
message="Read Post at:\n {}\n\n{}\'s Comments:\n{}".format(post_url,cd['name'],cd['comments'])
send_mail(subject,message,'vpnraut#gmail.com',[cd['to']])
sent=True
else:
form = EmailSendForm()
return render(request, 'mail.html', {'sent':sent,'form':form, 'post':post})
**models.py**
from django.contrib.auth.models import User
from django.db import models
from Django.urls import reverse
from Django.utils import timezone
class CustomManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES=(('draft','Draft'),('published','Published'))
id=models.IntegerField(primary_key=True)
title=models.CharField(max_length=300)
slug=models.SlugField(max_length=300,unique_for_date='publish')
author=models.ForeignKey(User,related_name='post',on_delete=models.CASCADE)
body=models.TextField()
publish=models.DateTimeField(default=timezone.now)
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
status=models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
objects=CustomManager()
class Meta:
ordering=('-publish', )
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post',args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
class Comment(models.Model):
post=models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE)
name=models.CharField(max_length=30)
email=models.EmailField()
body=models.TextField()
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now=True)
active=models.BooleanField(default=True)
class Meta:
ordering=('-created', )
def __str__(self):
return 'Commnted by {} on {}'.format(self.name,self.post)
**urls.py**
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.post_list_view),
path('<int:year>/<int:month>/<int:day>/<slug:slug>/',views.post_detail_view,name='post'),
path('(<int:post_id>\d+)/share/',views.SendMail, name='post_share'),]

Resources