How to display a current user only in django user form - python

class Book(models.Model):
description = models.CharField(max_length=10)
pdf = models.FileField(upload_to='books/pdfs/')
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.description
def delete(self, *args, **kwargs):
self.pdf.delete()
super().delete(*args, **kwargs)
#forms.py
class BookForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(BookForm, self).__init__(*args, **kwargs)
class Meta:
model = Book
fields = ('description', 'pdf', 'user')
When i run an application it shows all the users, I want to restrict to only current user who is logged in.

Related

How i can add like on product page

I can like my products from admin panel,and i want to add posibility to like them by url products/item/like,i have view of like but i dont know what i should add to there.This is my views.py
class LikeToggleView(AjaxResponseMixin, JSONResponseMixin, FormView):
http_method_names = ('post',)
form_class = LikeForm
product = None
#csrf_exempt
def dispatch(self, request, *args, **kwargs):
product_id = kwargs['product_pk']
try:
self.product = Product.objects.get(id=product_id)
except Product.DoesNotExist:
raise Http404()
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
pass
this is forms.py
class LikeForm(forms.ModelForm):
user = forms.ModelChoiceField(User.objects.all(), required=False)
product = forms.ModelChoiceField(Product.objects.all())
ip = forms.GenericIPAddressField(required=True)
this is models.py
class Like(TimeStampedModel):
product = models.ForeignKey(Product, related_name='likes')
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='likes')
ip = models.GenericIPAddressField(blank=True, null=True)
class Meta:
unique_together = (('product', 'user'), ('product', 'ip'))
def __str__(self):
return '{} from {}'.format(self.product, self.user or self.ip)

UNIQUE constraint failed: groups_groupmember.group_id, groups_groupmember.user_id

I am working on small django project and for that i have created one functionality that allows user to create and then join the group.
Now , here is the problem :
whenever i leave the group and try to rejoin it , it shows error that i mentioned in the the question
"UNIQUE constraint failed: groups_groupmember.group_id, groups_groupmember.user_id"
here is my join class :
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'))
from sqlite3 import IntegrityError
try:
# GroupMember.objects.create(group=group)
GroupMember.objects.create(user=self.request.user, group=group)
except IntegrityError:
messages.warning(self.request, 'already a member!')
else:
messages.success(self.request, 'You are now a member!')
return super().get(request, *args, **kwargs)
Here is my models.py
from django.db import models
from django.utils.text import slugify
from django.urls import reverse
# Create your models here.
# GROUPS MODELS.PY
import markdown
from django.contrib.auth import get_user_model # returns user model that currently active in this project
User = get_user_model()
from django import template
register = template.Library()
class Group(models.Model):
name = models.CharField(max_length=256, unique=True)
slug = models.SlugField(allow_unicode=True, unique=True)
description = models.TextField(blank=True, default='')
description_html = models.TextField(editable=False, default='', blank=True)
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 = markdown.markdown(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')
Can you please help me to solve this problem ? Thank you ! :)
How about use get_or_create
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'))
_, created = GroupMember.objects.create(user=request.user, group=group)
if not created:
messages.warning(request, 'already a member!')
else:
messages.success(request, 'You are now a member!')
return super().get(request, *args, **kwargs)

How to get ChoiceField data based on current user

I have a model StaffProfile.while creating a form for Visiti want to get staff_user data(Based on current user) to that ChoiceField (to_meet).
models.py
class StaffProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
related_name="user_profile")
staff_user = models.ManyToManyField(User, null=True, blank=True,
related_name="staff_user")
class Visit(models.Model):
name = models.CharField(max_length=200, name="name")
gender = models.CharField(choices=GENDER_CHOICE, max_length=1, name="gender")
mobile = models.CharField(max_length=18, default="", name="mobile")
to_meet = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py
class VisitForm(forms.ModelForm):
to_meet = forms.ChoiceField(choices=[], required=False, label="Select Staff")
class Meta:
model = Visit
fields = ("__all__")
def __init__(self, *args, **kwargs):
super(VisitForm, self).__init__(*args, **kwargs)
self.fields['to_meet'].choices = StaffProfile.objects.filter(user=request.user).values_list("staff_user")
Initially override the __init__() method of your view
class VisitForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(VisitForm, self).__init__(*args, **kwargs)
self.fields['to_meet'].choices = [self.request.user]
to_meet = forms.ChoiceField(choices=[], required=False, label="Select Staff")
class Meta:
model = Visit
fields = "__all__" # small typo here
Then, in your view,
def foo_view(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = VisitForm(request.POST,request=request)
# check whether it's valid:
if form.is_valid():
# do somrthing
.....
You need to pass the request from view to form. For example:
def some_view(request):
form = VisitForm(request=request)
# rest of the code
and use it in the form:
def __init__(self, *args, **kwargs):
request = kwargs.pop('request')
super(VisitForm, self).__init__(*args, **kwargs)
self.fields['to_meet'].choices = StaffProfile.objects.filter(user=request.user).values_list("staff_user")

Pass kwargs from CreateView to ModelForm?

I am trying to pass a kwarg from CreateView to a ModelForm so I can dynamically adjust the fields based on values in the related Parent object. Other answers have indicated that passing a kwarg by overriding get_form_kwargs in the view and catching it with kwarg.pop in the form should work, but I get an AttributeError: 'ChildForm' has no attribute 'get' when I try. Passing the kwarg into the view context works, but doesn't give me access to the value inside the form instance.
models.py:
class Parent(models.Model):
name = models.CharField(max_length=255)
details = models.CharField(max_length=255)
detailstwo = models.CharField(max_length=255, null=True)
child_mod = models.BooleanField(default=False)
slug = models.SlugField()
creator = models.ForeignKey(User)
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.name)
super(Parent, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Child(models.Model):
parent = models.ForeignKey(Parent)
parent_mod = models.CharField(max_length=255)
child_name = models.CharField(max_length=255)
def __unicode__(self):
return self.child_name
views.py:
class ChildCreateView(CreateView):
model = Child
form_class = ChildForm
template_name = 'testapp/child_form.html'
def dispatch(self, *args, **kwargs):
return super(ChildCreateView, self).dispatch(*args, **kwargs)
def get_form_kwargs(self, **kwargs):
kwargs = super(ChildCreateView, self).get_form_kwargs()
parent = get_object_or_404(Parent, slug=self.kwargs['parent_slug'])
kwargs['parent'] = parent
return kwargs
def get_context_data(self, **kwargs):
context = super(ChildCreateView, self).get_context_data(**kwargs)
parent = get_object_or_404(Parent, slug=self.kwargs['parent_slug'])
context['parent'] = parent
return context
def form_valid(self, form):
child = form.save(commit=False)
parent_slug = form.data['parent_slug']
parent = get_object_or_404(Parent, slug=parent_slug)
child.parent = parent
return super(ChildCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('testapp:parent_view', kwargs={'slug': self.object.parent.slug})
forms.py:
class ChildForm(forms.ModelForm):
class Meta:
model = Child
fields = ['parent', 'parent_mod', 'child_name']
def __init__(self, *args, **kwargs):
self.parent_object = kwargs.pop('parent')
assert isinstance(self.parent_object, Parent)
super(ChildForm, self).__init__(self, *args, **kwargs)
self.fields["parent_slug"] = forms.CharField(widget=forms.HiddenInput())
if not self.parent_object.child_mod:
del self.fields['parent_mod']
Full Traceback is here: http://dpaste.com/2QBMRJX

Django Userprofile form extension

Im extending the django User model with User profile like this :
class UserProfile(BaseModel):
user = models.ForeignKey(User, unique=True, related_name="profile")
city = models.CharField(_("City"), max_length=200)
tel = models.CharField(_("Phone Number"), max_length=50,
help_text=_("(+ Country Code) (Area Code) (Your phone number)"))
description = models.TextField(null=True, blank=True,
help_text = _("Small description about yourself."))
photo = models.ImageField(max_length=255, upload_to="profiles/")
def __unicode__(self):
return "%s %s" % (self.user.first_name, self.user.last_name)
def profile_image(self):
return settings.DEFAULT_PROFILE_IMAGE
and this is the form Im using on the front end in order to edit the profile from there:
class UserProfileForm(forms.ModelForm):
# uniForm Helper
helper = FormHelper()
helper.form_id = "edit_profile_form"
helper.form_class = 'mlForm'
layout = Layout(
Fieldset('',
'country', 'city',
'tel', 'photo', 'description',
)
)
helper.add_layout(layout)
# Submit button(s)
submit = Submit('submit','Submit')
helper.add_input(submit)
cancel = Submit('cancel','Cancel')
helper.add_input(cancel)
class Meta:
model = UserProfile
fields = ['city',
'tel', 'photo', 'description',]
def __init__(self, request, *args, **kw):
super(UserProfileForm, self).__init__(*args, **kw)
self.request = request
def save(self, *args, **kw):
edit_profile_form = super(UserProfileForm, self).save(*args, **kw)
return edit_profile_form, "User successfully modified."
What I want to do is add the User email field in the form so that the user can also edit this field from the frontend.
How would I do that?
Hope, this will help
class UserProfileForm(forms.ModelForm):
email = forms.EmailField(label=u'Email address',required=True)
class Meta:
model = UserProfile
exclude = ['user',]
def __init__(self, *args, **kw):
super(UserProfileForm, self).__init__(*args, **kw)
self.fields['email'].initial = self.instance.user.email
self.fields.keyOrder = ['your','fields','you','want','to','display','including','email']
def save(self, *args, **kw):
super(UserProfileForm, self).save(*args, **kw)
self.instance.user.email = self.cleaned_data.get('email')
self.instance.user.save()
this recipe works for me (django 1.3).
in views.py must be something like this:
def profile(request,id):
if request.method == 'POST':
user = get_object_or_404(User,pk=id)
profile = user.profile
form = UserProfileForm(data = request.POST,instance = profile)
if form.is_valid():
form.save()
Send the two objects-forms (UserEditForm and UserProfileForm) into the template form and submit them together.

Categories