Django ModelForm exclude data saving - django

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})

Related

Django. Populate user name or ID when user saving a model from web pages

My UserImg Model has a user field that has editable=False.
I want this field to be automatically filled in with the user name when the user is saved from web page.
model.py
def upload_myimg_path(instance, filename):
return 'documents/{0}/{1}'.format(instance.created_by.username, filename)
class UserImg(models.Model):
user = models.ForeignKey(User, verbose_name=_('Created by'), on_delete=models.CASCADE, editable=False, null=True, blank=True)
name = models.CharField(max_length=100, default='')
image = models.ImageField(upload_to=upload_myimg_path, verbose_name=_('File'))
def __str__(self):
return str(self.user)
forms.py
class UserImgForm(forms.ModelForm):
class Meta:
model = UserImg
fields = '__all__'
views.py
def createuserimg(request):
if request.method == 'POST':
form = UserImgForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/accounts/users')
else:
return redirect('/accounts/')
else:
form = UserImgForm
return render(request, 'accounts/user_form.html', {'form': form})
Update your view function to include current logged in user and make use of #login_required decorator to ensure that only logged in users can access this view :
from django.contrib.auth.decorators import login_required
#login_required
def createuserimg(request):
if request.method == 'POST':
form = UserImgForm(request.POST, request.FILES)
if form.is_valid():
obj = form.save(commit=False) # <-- commit=False does not save to database
obj.user = request.user # <-- this allows you to specify the user for your post
obj.save()
return redirect('/accounts/users')
# if the form did not validated, stay on the same page to display errors to your user
else:
form = UserImgForm()
return render(request, 'accounts/user_form.html', {'form': form})
correct answer commit=False allows you to modify the resulting object before it is actually saved to the database. It`s works for me.
Thank you very much for your help
from django.contrib.auth.decorators import login_required
#login_required
def createuserimg(request):
if request.method == 'POST':
form = UserImgForm(request.POST, request.FILES)
if form.is_valid():
link = form.save(commit=False)
link.user = request.user
link.save()
return redirect('/accounts/users')
# if the form did not validated, stay on the same page to display errors to your user
else:
form = UserImgForm()
return render(request, 'accounts/user_form.html', {'form': form})

Django how to assign posts to user

I need to assign posts to user in Django. I created
user = models.ForeignKey('authentication.CustomUser', on_delete=models.CASCADE)
and then if I display this model in my form.html I have to choice one of all users, if I don't display user in my form.html the form's isn't save my views file :
def formularz(request):
form = DodajForm(request.POST)
if form.is_valid():
ogloszenie = form.save(commit=False)
ogloszenie.user = request.user
ogloszenie.save()
return redirect('atrakcje:after')
else:
ogloszenie = DodajForm()
context = {
'form': form,}
return render(request, 'formularz.html', context)
Can i please know how to resolve it?
Rewrite the form to exclude the user field:
class DodajForm(forms.ModelForm):
class Meta:
model = Dodaj
exclude = ['user']
In the view, you better alter the instance, and let the form do the save logic, since a ModelForm can also save many-to-many fields:
def formularz(request):
if request.method == 'POST':
form = DodajForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
return redirect('atrakcje:after')
else:
ogloszenie = DodajForm()
context = {'form': form}
return render(request, 'formularz.html', context)

Django. How can I prevent another user from editing and deleting my listings?

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')

IntegrityError:duplicate key value violates unique constraint "login_account_userprofile_user_id_key"

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()

local variable 'post' referenced before assignment

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