I want that when I try to create a new account, the site_name field is prepopulated with the site that has it
for instance, an account under reddit should have a site_name prepopulated with reddit.com already, instead of having to pick from the list of sites.
Here is my class view for account creating an account:
class AccountCreateView(LoginRequiredMixin, CreateView):
model = Account
template_name = "account_new.html"
fields = (
"site_name",
"username",
"password",
)
The rest of my views:
class HomePageView(ListView):
model = Site
template_name = "home.html"
def get_queryset(self):
try:
return Site.objects.filter(author=self.request.user)
except:
return HttpResponse("Login please!")
class SiteDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):
model = Site
template_name = "site_detail.html"
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
class SiteDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Site
template_name = "site_delete.html"
success_url = reverse_lazy("home")
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
class SiteEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Site
template_name = "site_edit.html"
fields = ("siteName",)
def test_func(self):
obj = self.get_object()
return obj.author == self.request.user
class AccountDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Account
template_name = "account_delete.html"
slug_field = "slug_field"
slug_url_kwarg = "slug_field"
success_url = reverse_lazy("home")
class AccountEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Account
template_name = "account_edit.html"
fields = (
"username",
"password",
)
slug_field = "slug_field"
slug_url_kwarg = "slug_field"
class SiteCreateView(LoginRequiredMixin, CreateView):
model = Site
template_name = "site_new.html"
fields = ("siteName",)
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
models.py:
from django.db import models
from django.urls import reverse
from django.conf import settings
from django.template.defaultfilters import slugify
class Site(models.Model):
siteName = models.CharField(max_length=200)
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
slug = models.SlugField(null=False, unique=True)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.siteName
def get_absolute_url(self):
return reverse("site_detail", kwargs={"slug": self.slug})
def save(self, *args, **kwargs):
if not self.slug:
slug_str = "%s %s" % (self.siteName, self.author)
self.slug = slugify(slug_str)
super(Site, self).save()
class Account(models.Model):
site_name = models.ForeignKey(Site, on_delete=models.CASCADE)
username = models.CharField(max_length=140)
password = models.CharField(max_length=50)
slug_field = models.SlugField(null=False, unique=True)
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse("home")
def save(self, *args, **kwargs):
if not self.slug_field:
self.slug_field = slugify(self.username)
return super().save(*args, **kwargs)
admin.py:
from django.contrib import admin
from .models import Site, Account
class SiteAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("siteName",)}
class AccountAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug_field": ("username",)}
admin.site.register(Site, SiteAdmin)
admin.site.register(Account, AccountAdmin)
A picture of creating a new account under redditcom, still having to specify the site_name:
createaccount picture
Related
I want the Topping model to only be accessible to a current user, and not to other users who could access that page by copying the URL.
models.py
class Pizza(models.Model):
name = models.CharField(max_length=20)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
def get_absolute_url(self):
return "/pizzas"
class Topping(models.Model):
pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("pizza", kwargs={"pizza_id": self.pizza.pk})
views.py
class UpdateTopping(LoginRequiredMixin, UpdateView):
model = Topping
form_class = UpdateToppingForm
template_name = "pizzas/update_topping.html"
Something along these lines (this has worked on the primary model):
class UpdatePizza(LoginRequiredMixin, UpdateView):
model = Pizza
form_class = UpdatePizzaForm
template_name = "pizzas/update_pizza.html"
def get_queryset(self):
base_qs = super(UpdatePizza, self).get_queryset()
return base_qs.filter(owner=self.request.user)
You can do something like this:
from django.core.exceptions import PermissionDenied
class UpdateTopping(LoginRequiredMixin, UpdateView):
model = Topping
form_class = UpdateToppingForm
template_name = "pizzas/update_topping.html"
def form_valid(self, form):
if self.request.user != form.cleaned_data['pizza'].user:
raise PermissionDenied(f"You are not allowed to edit this topping.")
In my project I am trying to show a list of other user's followers and following. Right now it only has the requesting user's. Here are my models and views:
Models
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile',
on_delete=models.CASCADE)
followers = models.ManyToManyField(User, related_name='following', blank=True)
Views
class FollowersPageView(LoginRequiredMixin, ListView):
model = Profile
paginate_by = 20
template_name = 'users/followers.html'
context_object_name = 'users'
def get_queryset(self, **kwargs):
return self.request.user.profile.followers.all()
class FollowingPageView(LoginRequiredMixin, ListView):
model = User
paginate_by = 20
template_name = 'users/following.html'
context_object_name = 'profiles'
def get_queryset(self, **kwargs):
return self.request.user.following.all()
URLS
**(Old url)**
re_path(r'^u/followers$', users_views.FollowersPageView.as_view(),
name='view_all_followers'),
**(New url)**
re_path(r'^u/(?P<username>[\w.#+-]+)/followers$',
users_views.FollowersPageView.as_view(), name='view_all_followers'),
I was trying to change the get_queryset of FollowersPageView to the following but was getting error messages:
def get_queryset(self, **kwargs):
user_username = self.kwargs['username']
user_followers = Profile.objects.filter(followers=user_username)
return user_followers
Thank you
Try this:
from django.shortcuts import get_object_or_404
from django.contrib.auth import get_user_model
User = get_user_model()
def get_queryset(self, **kwargs):
user_username = self.kwargs['username']
user = get_object_or_404(User, username=user_username)
user_followers = user.followers.all()
return user_followers
My models.py
from django.db import models
from django.contrib.auth.models import User
import datetime
from django.utils import timezone
# Create your models here.
class LiveClass(models.Model):
standard = models.IntegerField()
no_of_students_registered = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'Class'
def __str__(self):
return str(self.standard) + ' class'
class User_details(models.Model):
name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30)
standard = models.IntegerField(default=0)
email = models.EmailField()
mobile_number = models.IntegerField()
class Meta:
verbose_name_plural = 'User_details'
def __str__(self):
return str(self.name)
class Mentor(models.Model):
name = models.CharField(max_length=30)
details = models.TextField()
ratings = models.FloatField(default=2.5)
class Meta:
verbose_name_plural = 'Mentors'
def __str__(self):
return self.name
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_name = models.CharField(max_length=30)
chapter_details = models.TextField()
mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
class_time = models.DateTimeField()
end_time = models.DateTimeField(default=timezone.now())
isDoubtClass = models.BooleanField(default=False)
doubtsAddressed = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
def __str__(self):
return self.chapter_name
class SavedClass(models.Model):
class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
is_registered = models.BooleanField(default=False)
is_attended = models.BooleanField(default=False)
class Meta:
verbose_name_plural = 'SavedClasses'
def __str__(self):
return 'SavedClass : ' + str(self.class_details)
my views.py
from django.shortcuts import render
from rest_framework import mixins
from rest_framework import generics
from django.contrib.auth.mixins import LoginRequiredMixin
from rest_framework import status
from django.contrib.auth.models import User
from rest_framework.response import Response
from django.contrib.auth import authenticate
from . import serializers
from . import models
# Create your views here.
class ListLiveClass(mixins.ListModelMixin, LoginRequiredMixin, generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class LiveClassView(mixins.ListModelMixin,
mixins.CreateModelMixin,
LoginRequiredMixin,
generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
if request.user.is_superuser:
return self.create(request, *args, **kwargs)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
class LiveClassViewId(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
LoginRequiredMixin,
generics.GenericAPIView):
queryset = models.LiveClass_details.objects.all()
serializer_class = serializers.LiveClass_details_serializer
lookup_field = 'id'
def get(self, request, id=None, format=None):
if id:
return self.retrieve(request)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
def put(self, request, id, format=None):
if request.user.is_superuser:
return self.update(request, id)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
def delete(self, request, id, format=None):
if request.user.is_superuser:
return self.destroy(request, id)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
class ListMentors(mixins.ListModelMixin, LoginRequiredMixin, generics.GenericAPIView):
queryset = models.Mentor.objects.all()
serializer_class = serializers.Mentor_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
class ListUserDetails(mixins.ListModelMixin, LoginRequiredMixin, generics.GenericAPIView):
queryset = models.User_details.objects.all()
serializer_class = serializers.User_details_serializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
#api endpoints to save and register live classes
class SavedClassView(LoginRequiredMixin, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
serializer_class = serializers.SavedClass_serializer
def get_queryset(self):
user = self.request.user
return models.SavedClass.objects.filter(user=self.request.user.id)
def get(self, request):
return self.list(request)
def post(self, request):
cur_user = self.get_object()
#return self.create(request)
return Response(status=status.HTTP_403_FORBIDDEN)
my serializers.py
from rest_framework import serializers
from . import models
class LiveClass_serializer(serializers.ModelSerializer):
class Meta:
model = models.LiveClass
fields = '__all__'
class SavedClass_serializer(serializers.ModelSerializer):
class Meta:
model = models.SavedClass
fields = '__all__'
class User_details_serializer(serializers.ModelSerializer):
saved_class = SavedClass_serializer()
class Meta:
model = models.User_details
fields = '__all__'
class LiveClass_details_serializer(serializers.ModelSerializer):
class Meta:
model = models.LiveClass_details
fields = '__all__'
class Mentor_serializer(serializers.ModelSerializer):
class Meta:
model = models.Mentor
fields = '__all__'
In savedClass view in GET request i am rendering all the savedClass Model wherever user in the model matches with the current user , now in POST request i want to create the savedclass row only for the current user and forbids the user from creating a view with different user id
I also needs help in my SavedClass model where whether a user is registered or not can only be decided by the admin
I tries different possible things but not able to do it, i am new to Django so needs help
You can get the logged in user from request.user so something like this should work
def post(self, request):
cur_user = request.user
if cur_user.id == request.data.user:
return self.create(request)
return Response(status=status.HTTP_403_FORBIDDEN)
assuming that only logged in users can call this api
I am new on this field and i am currently learning django and i come up with this problem. I am working on a project which is a social clone project and this project you can only post when you are in a group and i've encountered this problem when i post. The first post is working fine but the second post i get this error message called IntegrityError i've tried to delete my migrations and database and migrate and makemigrations again but does not fix the problem and now i am stuck and i hope someone will help me. This is the actual error
Posts Models
##########################
## POSTS MODELS.PY FILE ##
##########################
from django.contrib.auth import get_user_model
from django.db import models
from groups.models import Group
from misaka import html
from django.urls import reverse
from django.conf import settings
User = get_user_model()
class Post(models.Model):
user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
message = models.TextField()
message_html = models.TextField(editable=False)
group = models.ForeignKey(Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.message
def save(self, *args, **kwargs):
self.message_html = html(self.message)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse(
'posts:single',
kwargs={
'username': self.user.username,
'pk': self.pk
}
)
class Meta:
ordering = ['-created_at']
unique_together = ['user', 'group']
Posts Views.py
#########################
## POSTS VIEWS.PY FILE ##
#########################
from django.contrib.auth import get_user_model
from braces.views import SelectRelatedMixin
from django.views import generic
from posts import models, forms
from django.http import Http404
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.contrib import messages
User = get_user_model()
class PostList(SelectRelatedMixin, generic.ListView):
model = models.Post
select_related = ('user', 'group')
class UserPost(generic.ListView):
model = models.Post
template_name = 'posts/user_post_list.html'
def get_queryset(self):
try:
self.post_user = User.objects.prefetch_related('posts').get(
username__iexact=self.kwargs.get('username')
)
except User.DoesNotExist:
raise Http404
else:
return self.post_user.posts.all()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['post_user'] = self.post_user
return context
class PostDetail(SelectRelatedMixin, generic.DetailView):
model = models.Post
select_related = ('user', 'group')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(
user__username__iexact=self.kwargs.get('username')
)
class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView):
model = models.Post
fields = ('message', 'group')
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView):
model = models.Post
select_related = ('user', 'group')
success_url = reverse_lazy('posts:all')
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(user_id=self.request.user.id)
def delete(self, *args, **kwargs):
messages.success(self.request, ('Post Delete'))
return super().delete(*args, **kwargs)
Groups Models.py
##########################
## GROUPS VIEWS.PY FILE ##
##########################
from django.contrib.auth import get_user_model
from django import template
from django.db import models
from django.utils.text import slugify
from misaka import html
from django.urls import reverse
from django.conf import settings
User = get_user_model()
register = template.Library()
class Group(models.Model):
name = models.CharField(max_length=255, unique=True)
slug = models.SlugField(allow_unicode=True, unique=True)
description = models.TextField(blank=True, default='')
description_html = models.TextField(editable=False, blank=True, default='')
members = models.ManyToManyField(User, through='GroupMember')
def __str__(self):
return self.name
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
self.description_html = html(self.description)
super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse('groups:single', kwargs={'slug': self.slug})
class Meta:
ordering = ['name']
class GroupMember(models.Model):
group = models.ForeignKey(Group, related_name='memberships', on_delete=models.CASCADE)
user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class Meta:
unique_together = ('group', 'user')
Groups Views.py
[![##########################
## GROUPS VIEWS.PY FILE ##
##########################
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from groups.models import Group, GroupMember
from django.urls import reverse
from django.shortcuts import get_object_or_404
from django.db import IntegrityError
from django.contrib import messages
from groups import models
class CreateGroup(LoginRequiredMixin, generic.CreateView):
model = Group
fields = ('name', 'description')
class SingleGroup(generic.DetailView):
model = Group
class ListGroups(generic.ListView):
model = Group
class JoinGroup(LoginRequiredMixin, generic.RedirectView):
def get_redirect_url(self, *args, **kwargs):
return reverse('groups:single', kwargs={'slug': self.kwargs.get('slug')})
def get(self, request, *args, **kwargs):
group = get_object_or_404(Group, slug=self.kwargs.get('slug'))
try:
GroupMember.objects.create(user=self.request.user, group=group)
except IntegrityError:
messages.warning(self.request, (f'Warning, Already A Member Of {group.name}.'))
else:
messages.success(self.request, (f'You Are Now A Member Of {group.name} Group.'))
return super().get(request, *args, **kwargs)
class LeaveGroup(LoginRequiredMixin, generic.RedirectView):
def get_redirect_url(self, *args, **kwargs):
return reverse('groups:single', kwargs={'slug': self.kwargs.get('slug')})
def get(self, request, *args, **kwargs):
try:
membership = models.GroupMember.objects.filter(
user=self.request.user,
group__slug=self.kwargs.get('slug')
).get()
except models.GroupMember.DoesNotExist:
messages.warning(self.request, ("You Can't Leave This Group Because You Aren't In It."))
else:
membership.delete()
messages.success(self.request, ('You Have Successfully Left This Group.'))
return super().get(request, *args, **kwargs)
Remove unique_together from your Post model. It means that only one Post object can have that particular user and model combination, that is why you are getting the integrity error.
The error which you are getting is all about the unique constraint.
unique_together = ['user', 'group']
Since you have defined in your model the unique_together attribute, you need to have unique rows of the combination for user and group. One user can post only once in a group and you are trying to post in the same group by the same user, that's why you are getting a unique constraint failed error.
I'm trying to make inline forms with class based views, i followed the instrunctions from here. The only change i've made was to give self.request.user instead of self.object to instance:
models.py
class Client(models.Model):
user = models.OneToOneField(CustomUser)
translate = models.BooleanField(default=False)
class ClientData(models.Model):
client = models.ForeignKey(Client)
language = models.ForeignKey(Language)
forms.py
class ClientForm(ModelForm):
class Meta:
model = Client
fields = '__all__'
exclude = ['user', ]
class ClientDataForm(ModelForm):
class Meta:
model = ClientData
fields = '__all__'
exclude = ['client', ]
ClientFormSet = inlineformset_factory(Client, ClientData, form=ClientDataForm, extra=1)
views.py
class ClientView(LoginRequiredMixin, UpdateView):
model = Client
fields = '__all__'
success_url = reverse_lazy('core:index')
class ClientDataView(LoginRequiredMixin, UpdateView):
template_name = 'core/client_data.html'
model = ClientData
form_class = ClientDataForm
success_url = reverse_lazy('core:index')
def get_object(self, queryset=None):
profile = get_object_or_404(ClientData, client__user=self.request.user)
return profile
def get_context_data(self, **kwargs):
context = super(ClientDataView, self).get_context_data(**kwargs)
if self.request.POST:
context['client_data'] = ClientFormSet(self.request.POST, instance=self.get_object())
else:
context['client_data'] = ClientFormSet(instance=self.get_object())
return context
def form_valid(self, form):
context = self.get_context_data()
client_data = context['client_data']
with transaction.atomic():
self.object = form.save()
if client_data.is_valid():
client_data.instance = self.object
return super(ClientDataView, self).form_valid(form)
Whenever i try to enter the page i get:
ValueError: Cannot query "asd#gmail.com": Must be "Client" instance.
[13/Dec/2017 15:48:36] "GET /client-data/ HTTP/1.1" 500 143759
for this line:
context['client_data'] = ClientFormSet(instance=self.get_object())
Your get_object is returning a ClientData instance.
def get_object(self, queryset=None):
profile = get_object_or_404(ClientData, client__user=self.request.user)
return profile
However, as the error suggests, the instance should be a Client instance, for example:
def get_object(self, queryset=None):
profile = get_object_or_404(Client, user=self.request.user)
return profile
Or you can simply follow the one-to-one relation backwards:
def get_object(self, queryset=None):
return self.request.user.client