Auto fill ForeignKey(User) with current signed in user - django

I have this model called business I want the foreinkey field owner to get the logged in user name automatically without bringing the dropdown button of all users, I have tried some methods, but it doesn't work. How can I autofill the owner field with the logged in user
models.py
class User(AbstractUser):
phone_number = models.CharField(('phone number'), max_length=15,default='+234',
help_text=('Field to save the phone number of the user.'),unique=True)
fullname=models.CharField(max_length=50)
Affidavit=models.ImageField(upload_to='media/')
class Business(models.Model):
owner = models.ForeignKey(User,on_delete=models.CASCADE,default=1)
Phone_Number=models.IntegerField(default='086878432',unique=True)
Figi_ID=models.IntegerField(blank=True)
views.py
def details_business(request):
if request.user.is_authenticated:
business_form=Business()
if request.method=='POST':
business_form=Business_owner_form(request.POST,request.FILES)
if business_form.is_valid():
bform=business_form
bform.owner=request.user
bform.save()
def dashboard(request):
if request.user.is_authenticated:
context = RequestContext(request)
data = Business.objects.all()
current=request.user
print(current)
context={"obj":img}
return render(request,'dashboard.html',context)

You were supposed to call the forms save method.
if business_form.is_valid():
business = business_form.save()
business.owner = request.user
business.save()

Related

i want to see all the users in django admin panel and i can select more than one user

hello i had done some modification in models and get the User.username and inserted them in a user_list and in multiselectfield(choices=user_list)
is was working fine but in the case as i made/create a new user
and i go to the application to select multiple users, my newly made user is not showing there
until i restart the django server
my model is like that:
class Video(models.Model):
listo = []
user = User.objects.all()
for i in user:
a = (str(i), str(i))
listo.append(a)
print("this is listo", listo)
caption = models.CharField(max_length=100)
video = models.FileField(upload_to="video/%y",null=True,blank=True)
show_to = MultiSelectField(choices=User.username)
# show_to = models.ForeignKey(User, on_delete=models.CASCADE)
url_video= models.URLField(blank=True)
def __str__(self):
return self.caption
the thing i want is to instantly show the newly made user in the django application so i could not restart the server again and again.
thanks in advance!
Your defined Model choices are set once when your server start or restart, So your choices not updated after adding users.
You create a ModelForm for your model and set choices for model field in init method of form. When you open form, every time call constructor of your form and set choices.
from django import forms
class VideoForm(forms.ModelForm):
...
...
def __init__(self, *args, **kwargs):
super(VideoForm, self).__init__(*args, **kwargs)
self.fields['show_to'].choices = self.get_dynamic_choices()
def get_dynamic_choices(self):
choices = [(obj.id, obj.username) for obj in User.objects.all()]
return choices

Extending User model with one to one field- how to set user instance in view

I am trying to extend the user model using a one to one relationship to a UserProfile model. I added some boolean fields and in the view I am trying to use those fields as permissions.
Here is my model:
class UserProfile(models.Model):
user = models.OneToOneField(User)
FirstName = models.CharField(max_length=25)
LastName = models.CharField(max_length=25)
ProximityAccess = models.BooleanField(default=True)
NewProxAccess = models.BooleanField(default=False)
def __unicode__(self):
return self.user.username
and here is the view I am trying to use:
#login_required
def NewProx(request):
if UserProfile.NewProxAccess:
if request.method == 'POST':
form = ProxForm(request.POST)
if form.is_valid():
ProxPart_instance = form.save(commit=True)
ProxPart_instance.save()
return HttpResponseRedirect('/proximity')
else:
form = ProxForm()
return render(request, 'app/NewProx.html', {'form': form})
else:
raise PermissionDenied
I don't get any error messages but it does not work as intended. I was hoping that if the user profile had NewProxAccess set to False it would raise the PermissionDenied but it doesn't. I have the admin module wired up and I can select or deselect the checkbox for that field but it has no effect. If I comment out the rest I can get it to show the Permission Denied error so it has to be in the view (I think). I think I am missing a line the establishes the logged in user as the user instance so we can check to see if the user has the permission or not. I know there are a ton of ways to do this and there is probably a better way but for the sake of learning, what is it that I am missing for this to work?
Thanks
Scott
As you want to check access for particular profile but not UserProfile model you need to do:
if request.user.userprofile.NewProxAccess:
# your code
As a note: according to PEP8 best practices you should use camelCase only for naming Classes. For attrs, functions use underscore: my_function

Need success_url to vary depending on user group in CreateView

I have two user groups, 'Owners' and 'Employees'. They can use the same form to enter data, but I want them to be directed to a different list view upon success. I have a working CreateView:
class ServiceAddBlankView(
views.LoginRequiredMixin,
views.FormValidMessageMixin,
views.SetHeadlineMixin,
generic.CreateView
):
form_class = ServiceForm
headline = 'Add Service'
form_valid_message = "Service Entered!"
model = Service
template_name = 'wesapp/service_add.html'
success_url = '/wesapp/service_list/'
But, I want to have the success_url vary by the user group.
I want the success_url to be /wesapp/service_list/ if the user group is 'Owner' and to be /wesapp/services/ if the user group is 'Employee'.
I tried this, but it is not finding any success_url at all:
owner_group = Group.objects.get(name="Owner").user_set.all()
employee_group = Group.objects.get(name="Employee").user_set.all()
class ServiceAddBlankView(
views.LoginRequiredMixin,
views.FormValidMessageMixin,
views.SetHeadlineMixin,
generic.CreateView
):
form_class = ServiceForm
headline = 'Add Service'
form_valid_message = "Service Entered!"
model = Service
template_name = 'wesapp/service_add.html'
if user in owner_group:
success_url = '/wesapp/services/'
if user in employee_group:
success_url = '/wesapp/service_list/'
The error is:
name 'user' is not defined
How do I access the user?
It's not possible to access the user in the class definition as you are doing. Instead, the CreateView has a get_success_url method, which allows you to set the success view dynamically.
In the method, you can access the request with self.request, therefore you can access the logged in user with self.request.user.
class ServiceAddBlankView(generic.CreateView):
def get_success_url(self):
if self.request.user.groups.filter(name="Owner").exists():
return '/wesapp/services/'
elif self.request.user.groups.filter(name="Employee").exists():
return '/wesapp/service_list/'
else:
return '/fallback/url/'
I've changed the query to check whether the user is in the Owner or Employee group. In your original code, you were unnecessarily loading every Owner and Employee. Note that my code is behaves slightly different if the user is an Owner and an Employee - if that's important, you need to change it.
Django's request object has access to the user. Refer to request.user as documented here :
https://docs.djangoproject.com/en/1.8/ref/request-response/#django.http.HttpRequest.user

Slugfield URL implementation in Django

So, I am having some difficulty trying to slugify a title field in my model and still have it return the proper information.
Currently, a user can follow the url, if the list in their account exists under this regular expression:
url(r'^user/(?P<username>\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'),
The issue I face is that the user can have a list containing spaces, but the regex bases their url off their list name. I am wanting to implement a slug url, but still have it retrieve the correct model/object information.
I am trying to have a slug field and then pre-populate it based on the list name, but I am lost at how this implementation is supposed to work. Much appreciation in advance from any insight.
Model
class newlist(models.Model):
user = models.ForeignKey(User)
list_name = models.CharField(max_length = 100,)
picture = models.ImageField(upload_to='profiles/', default = "/media/profiles/default.jpg")
slugurl = models.SlugField(default = slugurl(self))
def __str__(self):
return self.list_name
def slugurl(self):
return slugify(self.list_name)
Views
def mylistpage(request, username, listname):
context = RequestContext(request)
#make sure that the user is authenticated
if username == request.user.username:
#If the user is authenticated, then perform the following functions to the page
if request.user.is_authenticated():
#Store the current user request object into a variable
user = User.objects.get(username=username)
#Store the list name to the item that starts with the url input
listname = request.user.newlist_set.filter(list_name__iexact=listname)
listitems = request.user.newlist_set.all()
if not listname:
return redirect('/notfound')
else:
return redirect('/notfound')
return render_to_response('listview.html', {'lista': listname}, context)
I have used django-autoslug to great success. You can find a live example here.
SlugField is just a char field with a little syntactic sugar.
You will want to name your slug just slug so django can find it automatically in the URL resolution and passes the right parameter to views.
Your amended code would look like:
from autoslug import AutoSlugField
from django.db import models
class Newlist(models.Model): # Classes start with uppercase names by default
user = models.ForeignKey(User)
list_name = models.CharField(max_length = 100,)
picture = models.ImageField(upload_to='profiles/', default = "/media/profiles/default.jpg")
slug = AutoSlugField(populate_from='list_name')
def __str__(self):
return self.list_name
Your View:
def mylistpage(request,username, slug):
context = RequestContext(request)
#make sure that the user is authenticated
if username == request.user.username:
#If the user is authenticated, then perform the following functions to the page
if request.user.is_authenticated():
#Store the current user request object into a variable
user = User.objects.get(username=username)
#Store the list name to the item that starts with the url input
listname = request.user.newlist_set.filter(slug=slug)
listitems = request.user.newlist_set.all()
if not listname:
return redirect('/notfound')
else:
return redirect('/notfound')
return render_to_response('listview.html', {'lista': listname}, context)
urls.py
url(r'^user/(?P<username>\w+)/list/(?P<slug>[\w-]+)/$', mylistpage, name='lists'),

django form use excluded field

with django 1.5.1 I try to use the django form for one of my models.
I dont want to add the "user" field (Foreignkey) somewhere in the code instead of letting the user deceide whoes new character it is.
My Code:
Model:
class Character(models.Model):
user = models.ForeignKey(User)
creation = models.DateTimeField(auto_now_add=True, verbose_name='Creation Date')
name = models.CharField(max_length=32)
portrait = models.ForeignKey(Portrait)
faction = models.ForeignKey(Faction)
origin = models.ForeignKey(Origin)
The form:
class CreateCharacterForm(forms.ModelForm):
class Meta:
model = Character
fields = ['name', 'portrait', 'faction', 'origin']
The view:
def create_character(request, user_id):
user = User.objects.get(id=user_id)
if request.POST:
new_char_form = CreateCharacterForm(request.POST)
if new_char_form.is_valid():
new_char_form.save()
return HttpResponseRedirect('%s/characters/' % user_id)
else:
return render_to_response('create.html',
{'user': user, 'create_char':new_char_form},
context_instance=RequestContext(request))
else:
create_char = CreateCharacterForm
return render_to_response('create.html',
{'user': user, 'create_char': create_char},
context_instance=RequestContext(request))
I have tried to use a instance to incluse the userid already. i've tried to save the userid to the form before saving it, or changing the save() from my form.
I keep getting the error that character.user cant be null
I have to tell that im pretty new to django and im sure one way or another it should be possible
Can someone please help me out?
Its explained well in document model form selecting fields to use
You have to do something like this in your view
...
if request.POST:
new_char_form = CreateCharacterForm(request.POST)
if new_char_form.is_valid():
#save form with commit=False
new_char_obj = new_char_form.save(commit=False)
#set user and save
new_char_obj.user = user
new_char_obj.save()
return HttpResponseRedirect('%s/characters/' % user_id)
else:
...