I'm using Django and trying to display the detail of the person who has posted the data. So basically showing the username of the person who has posted the 'thing' defined in models.py
In views.py I'm trying:
def thing_detail_view(request, pk):
thing_detail = Thing.objects.get(pk=pk)
user = User.objects.get(request.user)
return render(request, 'thing_detail.html', {'thing_detail': thing_detail, 'user': user})
Im getting error:
'User' object is not iterable
But I know I should not use request.user because thats basically means the user who is having current session or currently logged in. Any idea how can I get the username of the user who has posted the data of a particular 'pk' and show it in the html?
I think you have to use userId = thing_detail.userId instead of request.user
userId can be your primery key for User Model
Related
I am building a BlogApp App and I have two different sections, One is Blog Section and another is Article Section.
AND i am trying to create two different profiles for them.
When a user register or signup then a Profile is successfully creating for Blog Section ( NOT Article section ). BUT i am trying to do :- When user click on Article section after signup then there will be option of creating another Profile for Article Section and both will be different profile. ( AND there will be no relation between Blog Profile and Article Profile BUT user will same )
Blog Profile is successfully creating BUT I am trying to make Article Profile.
models.py
class ArticleProfile(models.Model):
user = models.ForeignKey(User,default='',null=True,on_delete=models.CASCADE)
full_name = models.CharField(max_length=30,default='')
views.py
def create_profile(request):
if request.method == 'POST':
form = ArticleProfileForm(request.POST,request.FILES,instance=request.user)
if form.is_valid():
custom_form = form.save(False)
custom_form.save()
messages.success(request, "Article Profile is Created")
return redirect('dating:DatingSection')
else:
form = ArticleProfileForm(instance=request.user)
context = {'form':form}
return render(request, 'dating/create_profile.html', context)
BUT when i create profile using this form then it is not saving in Admin.
Any help would be Appreciated.
Thank You in Advance.
I think the problem is here:
form = ArticleProfileForm(request.POST,request.FILES,instance=request.user)
^^^^^^^^^^^^
You are passing User as instance where the ArticleProfileForm creates ArticleProfile instance. So you need to remove that part of the code. And update the code like this:
form = ArticleProfileForm(request.POST,request.FILES)
if form.is_valid():
custom_form = form.save(False)
custom_form.user = request.user # change here
custom_form.save()
If still the problem persists, try renderning the form errors to pin point what is exactly wrong here.
I have a CreateView and inside this CreateView there is a form_valid() function. It gets the user_id and assigns it to the user that's logged in user id. The user is basically creating their own question and user_id is a foreign key.
class QuestionCreate(LoginRequiredMixin, CreateView):
model = Questions
form_class = CreatePost
def form_valid(self, form):
form.instance.user_id = self.request.user.id
return redirect("oauth:profile", username=self.request.user)
When I go to the URL of this view, I can see the view and when I try to submit a question it redirects me to the profile. However, the question is not saved in the database. I've tried inserting form.save() below the first line in form_valid and it does get saved in the table correctly, however, I don't get redirected to the profile, instead I get an error that states connection error what am I doing wrong?
I search Django-way to do some non tipical feature (I think). My env is Django 2.0.2, PostgreSQL 9.6 and Python 3.6.4. So, I have model and form like:
# ./app/models.py
from users.models import User # custom user model
class SubscribeModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=80)
# ./app/forms.py
class SubscribeForm(forms.Form):
phone = forms.EmailField(label='Phone Number', max_length=100)
Also, my view for this model like:
# ./app/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from users.models import User
class SubscribeView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
template_name = 'app/subscribe.html'
form_class = SubscribeForm
def post(self, request):
user = get_object_or_404(User, id=request.user.id)
form = self.form_class(request.POST, instance=user)
if form.is_valid():
form.save()
return redirect('/')
return render(request, self.template_name, {'client': user, 'form': form})
Would be great to understand what to do that logic after save form:
Anonymous user fill the form and click Save;
He is redirecting to login page (because LoginRequiredMixin);
After enter to the site, all data which he filled — saved to his account (automatically).
This feature we can see when online shopping: we choose goods, add to
our cart and only later, site ask us for login to site, if we are not (for save our order).
I think, my question solve saving data to request.session and re-save to DB after logged in, but I have no idea how to do that on my code and is this correctly? I am newbie in Django... yet!
Actually using request.session to store the data without saving it to the database is one approach, you can eighter save it to the localStorage or sessionStorage if you are developing mainly javascript AJAX frontent. But if you render every view with django then is using request.session better for you. Consider storing ids of the objects in the request.session in array and then use it as you want, remember to seralize it to JSON (json.dumps(list of ids)) before assigning it to the request.session.
I just started developing with Django and I'm having a bit of an issue with the use of a form I've created.
Currently I have a model named SignUp which allows users to "sign up" on the site by inputting their first and last names and their email address.
A feature I'm trying to implement deletes a user who is already signed up by the user submitting the email address they signed up with.
I have a form set up that's just a simple email field but I can't seem to figure out how to get my view to match up the form to the user and then successfully delete the user from the database.
Here is the code for the form:
class DeleteUserForm(forms.Form):
email_address = forms.EmailField()
And here is the code for the view:
class DeleteUserView(generic.edit.FormView):
template_name = 'signups/delete_user_form.html'
form_class = DeleteUserForm
success_url = '/users/delete/success/'
def form_valid(self, form):
for user in SignUp.objects.all():
if user.email == form: # The email attribute holds the user's
user.delete() # email address and the form should be
# the address the user submitted to be
# deleted?
return redirect(self.success_url)
return redirect('/users/delete/failure/')
Every time I try to submit an email address, I get no match, no user is deleted, and I just get redirected to my failure directory.
Anybody have an idea of what's going on?
Thanks
Using Kamil's logic, I rewrote the field lookup and this code works:
duplicates = SignUp.objects.filter(email__iexact=form.cleaned_data['email_address'])
if duplicates:
duplicates.delete()
return redirect(self.success_url)
But does anyone know why the code I was using before didn't work?
Simplest solution:
duplicates = SignUp.objects.filter(email=form.cleaned_data['email_address'])
if duplicates:
duplicates.delete()
return redirect(self.success_url)
return redirect('/users/delete/failure/')
Right, fixed the relation lookup.
You can access field values via form.cleaned_data dictionary:
if user.email == form.cleaned_data['email_address']:
I'm using modelforms for getting playlist and its items. It also contains login script. I'm trying to set the currently logged in user to the user model.
You can see this thing I've posted before
How to avoid this dropdown combo box?
class playlistmodel(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
def __unicode__(self):
return self.title
class itemsmodel(models.Model):
playlist = models.ForeignKey(playlistmodel)
item = models.TextField()
def __unicode(self):
return self.item
class playlistform(ModelForm):
class Meta:
model = playlistmodel
exclude = {'user'}
class itemsform(ModelForm):
class Meta:
model = itemsmodel
exclude = {'playlist'}
Here is the playlist view:
def playlistview(request):
if request.method == 'POST':
form = playlistform(request.POST)
if form.is_valid():
data = form.save(commit=False)
data.user = request.user
data.save()
return render_to_response('playlist.html', {'data': data})
else:
form = playlistform()
return render_to_response('playlist.html', {'form': form, 'user': request.user}, context_instance=RequestContext(request))
Playlist.html file:
https://gist.github.com/1576136
Error Page:
https://gist.github.com/1576186
But I'm getting ValueError:
Exception Type: ValueError Exception Value: Cannot assign "<django.utils.functional.SimpleLazyObject object at 0x7f0234028f50>": "playlistmodel.user" must be a "User" instance
Traceback: Local vars --- data.user = request.user
Here is my settings.py
https://gist.github.com/1575856
Thank you.
I know this post is old, but if anyone gets here with the same problem, the answer is that request.user is actually a wrapper for django's auth.user.
So request.user is a SimpleLazyObject, and it's purpose is avoiding unnecessary instantiation, and also implementing a simple user caching mechanism.
To access the actual user (and instantiate it, when accessing the first time), you need to do:
auth.get_user(request)
This will give you an instance of auth.user.
If you need more detail on what's going on inside, see this post.
difficult to tell, but i would try this in your playlistview:
form = playlistform(request, request.POST, instance=playlistmodel)
maybe you can ommit the last parameter (instance=playlistmodel), because this would only be in need if you change an existing object
Hope this helps...
I have the very same problem, but it only arises when no user is logged in (expecting an AnonymousUser instance). At least when my superuser is logged in, I found no problem.
Despite I have not found a solution yet, maybe you'll find a clue in this answer
Well, now I've realised that in my case AnonymousUser should be stored as null in the db, but leave this answer to post the clue link (have no permission yet to leave comments).
Hope it helps!