Im trying to assign the current logged in username to the existing model through a form. But facing a problem while saving the form
#views.py
def create(request):
if request.method == "POST":
form=NotForm(request.POST)
if form.is_valid():
post.user = request.user.get_username()
post = form.save(commit=False)
post.save()
return redirect('base')
else:
form=NotForm()
return render(request, 'create.html',{'form':form})
forms.py
class NotForm(forms.ModelForm):
class Meta:
model=Note
fields = ('title', 'desc',)
models.py
class Note(models.Model):
title=models.CharField(max_length=50)
desc=models.TextField(max_length=200)
user=models.ForeignKey('auth.User')
if request.method == "POST":
form=NotForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.user = request.user.get_username()
post.save()
return redirect('base')
try this in the view
Related
This is my code for my view:
def edit(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
else:
if form.is_valid():
user = form.save()
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'social/edit.html', args)
And here is the code for the form:
class EditProfileForm(UserChangeForm):
edit ='social/edit.html'
class Meta:
model = UserProfile
fields = ('description', 'image')
Here is the model:
class UserProfile(models.Model):
description = models.CharField(max_length=300, default=' ', blank=True)
image = models.ImageField(upload_to='profile_image', blank=True)
if you need any more information to help I would be more than gladly to give it to you
The problem is with the view function.
Every View must return some sort of response (HTTP Response in General)
you have an if else statement in your view if its a post it will just execute
form = EditProfileForm(request.POST, instance=request.user)
and then it doesn't return anything.
I think you have to do is,
For GET Request (when you visit the url, it has to render the form)
if request.method == 'GET':
form = EditProfileForm(instance=request.user)
args = {'form': form}
return render(request, 'social/edit.html', args)
For POST request (when you send POST to this view or different one)
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
user = form.save()
# use render/redirect as needed. make sure it returns an HTTP Response
# note that render method also return HTTP Response
return HttpResponse('Done')
Make sure Form class is simply this
class EditProfileForm(UserChangeForm):
class Meta:
model = UserProfile
fields = ('description', 'image')
Please help me implement these features so that another user cannot delete or edit my ads. So far, only unregistered users can not edit and delete.
#login_required
def listing_delete(request, listing_id):
listing = Listing.objects.get(id=listing_id)
listing.delete()
return redirect('index')
#login_required
def listing_edit(request, listing_id):
form = ListingForm(instance = Listing.objects.get(id = listing_id))
if request.method == "POST":
form = ListingForm(request.POST, request.FILES, instance = Listing.objects.get(id = listing_id))
if form.is_valid():
listing = form.save()
return redirect('listing', listing_id)
return render(request, 'listings/listing_edit.html', {'form': form})
#login_required
def listing_add(request):
form = ListingForm()
if request.method == "POST":
form = ListingForm(request.POST, request.FILES)
if form.is_valid():
listing = form.save(commit=False)
listing.realtor = request.user.realtor
listing.save()
return redirect('dashboard')
return render(request, 'listings/listing_add.html', {'form': form})
class Listing(models.Model):
realtor = models.ForeignKey(Realtor, on_delete=models.CASCADE, verbose_name='Риэлтор')
...
class Realtor(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь', related_name='realtor')
You just need to check that the user making the POST request is the author (realtor) of the listing:
#login_required
def listing_edit(request, listing_id):
listing = Listing.objects.get(id=listing_id) # avoid multiple database calls
form = ListingForm(instance=listing)
if request.method == "POST" and request.user == listing.realtor.user:
form = ListingForm(request.POST, request.FILES, instance=listing)
if form.is_valid():
listing = form.save()
return redirect('listing', listing_id)
return render(request, 'listings/listing_edit.html', {'form': form})
The same applies for the delete view.
#login_required
def listing_delete(request, listing_id):
listing = Listing.objects.get(id=listing_id)
if request.user == listing.realtor.user:
listing.delete()
return redirect('index')
Trying to save data with login user. Tried as below.
models.py
class MyModel(TimeStamped):
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
title = models.CharField(max_length=250)
forms.py
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
exclude = ['user']
views.py
def add(request):
if request.method == 'GET':
form = MyForm()
else:
form = MyForm(request.POST, request.FILES)
if form.is_valid():
form.save(commit=False)
form.save()
messages.success(request, 'Message Sent Successfully')
redirect('home')
return render(request, "add.html", {'form': form})
It saved data. But problem is user is not setting to login user. Tried adding in view form.user = request.user. still is not saving.
Try this.
def add(request):
if request.method == 'GET':
form = MyForm()
else:
form = MyForm(request.POST, request.FILES)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
messages.success(request, 'Message Sent Successfully')
redirect('home')
return render(request, "add.html", {'form': form})
IntegrityError comes when user uploading the profile pic, on form.save() it gives error, here is the code (" ` " it is uses for formality at last of line)
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)`
image = models.FileField(upload_to ="profile_image")`
def __str__(self):
return self.user.username`
forms.py
class ProfilePicForm(ModelForm):
class Meta:
model = UserProfile
fields = ("image",)`
view.py
def profile_pic(request):
if request.method =="POST":
form = ProfilePicForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user =request.user
form.save()
return redirect('/login/profile')
else:
args = {'form': ProfilePicForm()}
return render(request, 'login_account/profile_pic.html',args)`
You should probably try the following:
user = UserProfile(user=request.user)
form = ProfilePicForm(request.POST, request.FILES, instance=user)
if form.is_valid():
form.save()
Consider this simple user profile:
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User)
onboarding_step = models.SmallIntegerField(default='1')
What is the simplest method it increment the onboarding_step within UserProfile each time a separate form from a different model is submitted? For example:
Here's the ModelForm (from a separate model, Site) I am submitting:
class OnBoardingProgressForm(forms.ModelForm):
class Meta:
model = Site
fields = ( 'abc', 'xyz', )
And here is the view.py for the form:
if request.method == "POST":
form = OnBoardingProgressForm( request.POST )
if form.is_valid():
....
THIS CODE DOES NOT WORK BUT IS MY BEST GUESS:
last = request.user.profile
last.onboarding_step = 2
....
obj = form.save(commit=False)
obj.user = current_user
obj.save()
return render(request, "nextpage.html", {'form': form })
How can I increment the user.onboarding_step by 1?
if request.method == "POST":
form = OnBoardingProgress( request.POST )
if form.is_valid():
....
// Can I increment the code here? //
....
obj = form.save(commit=False)
obj.user = current_user
obj.save()
user_obj = UserProfile.objects.get(user=request.user)
user_obj.onboarding_step = user_obj.onboarding_step + 1
user_obj.save()
return render(request, "nextpage.html", {'form': form })
or you can make autoincrement field also.
Get the UserProfile object for the current user and then increment the value of the attribute of onboarding_step.
Try this:
if request.method == "POST":
form = OnBoardingProgress(request.POST)
current_user = request.user
if form.is_valid():
user_profile = UserProfile.objects.filter(user=current_user)[0] # get the user profile object for the current user
user_profile.onboarding_step += 1 # increment the value
user_profile.save() # save the object
obj = form.save(commit=False)
obj.user = current_user
obj.save()
return render(request, "nextpage.html", {'form': form })