How to add info to request.POST? - python

When a user creates something using a form, all of the info is submitted through a form which is sent through an AJAX call to the following view:
def goal_create(request):
if request.method == 'POST':
user = request.user
request.POST[user] = user.id
errors = form_validate(request, AddGoalForm, Goal)
I get an error when I try to modify request.POST dict and add a user's id to the model instance. I want to add it, so in the next step (when it goes to form_validate), it will create a new model instance for me.
Here is form_validate, which validates the form according to a ModelForm.
def form_validate(request, form, model):
form = form(request.POST)
if form.is_valid():
new = form.save()
else:
return form.errors.items()
Here is the model I'm working with:
class Goal(models.Model):
goal_name = models.CharField(max_length=200, blank=False)
user = models.ForeignKey(User, null=True, blank=True)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
Another issue is that even though goal_name has attribute blank=False, and I create a new goal with a blank goal_name, it says that the form is_valid() and saves the form.

if request.method == 'POST':
user = request.user
post_values = request.POST.copy()
post_values['user'] = user.id
form = MyForm(post_values)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('success'))
return HttpResponseRedirect(reverse('error'))
p.s This is a quick fix but not a very elegant method to use. Though there are no issues when you would use this

forms.py
class GoalForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(GoalForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
obj = super(GoalForm, self).save(commit=False)
obj.user = self.user
if commit:
obj.save()
return obj
views.py
#login_required
def add_goal(request):
form = GoalForm(user=request.user, data=request.POST)
if form.is_valid():
obj = form.save()
return HttpResponse('ok')
return HttpResponse('errors')

Related

'User' object has no attribute 'staffUser'

I customized the User Model Using Django One To One Field
My models.py
class StaffUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.ForeignKey(Dept, on_delete=models.RESTRICT)
def __str__(self):
return self.user.username
When uploading a form, i want to get the department of the user
'My Views.py'
def FileUploadForm(request, pk):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save(commit=False)
u = User.objects.get(username=request.user)
form.instance.username = u
folder = Folder.objects.get(id=pk)
department = u.staffUser.department
form.save()
messages.success(request, f'File Successfully uploaded to {folder} in {department}!')
return redirect('home')
else:
form = UploadFileForm()
context = {'pk':pk, 'form':form}
return render(request, "pages/fileup_form.html", context)
But it gives error
AttributeError at /file/new/1
'User' object has no attribute 'staffUser'
Please guys i need help
Add related_name on your user field in StaffUser model
class StaffUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=staff_user)
department = models.ForeignKey(Dept, on_delete=models.RESTRICT)
def __str__(self):
return self.user.username
Now you will be able to access StaffUser by staff_user on User object
You need to specify the reverse in lower case, so staffuser instead of staffUser.
Alternatively you can specify the related name to be used for calling the reverse accessor, as per below in place of some_name.
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=some_name)

I have a confusion about creating the user profile when the user is newly registered

views.py
def register_view(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user = form.save()
## login(request,user)
messages.success(request,'Account created succcessfully')
return redirect('login')
else:
messages.error(request,'Invalid information! Please retry!')
else:
form = UserForm()
context = {'form':form}
return render(request,'register.html',context)
def login_view(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
if user is not None:
login(request,user)
return redirect('homepage')
else:
messages.error(request,'No current user!')
else:
form = AuthenticationForm()
context = {'form':form}
return render(request,'login.html',context)
def logout_view(request):
logout(request)
return redirect('login')
#login_required
def profile(request):
Profile.objects.get_or_create(user=request.user)
if request.method == 'POST':
u_form = UserUpdateForm(request.POST,instance=request.user)
p_form = ProfileForm(request.POST,request.FILES,instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request,'Profile updated successfully!')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileForm(instance=request.user.profile)
context = {
## 'user':request.user,
'u_form':u_form,
'p_form':p_form,
}
return render(request,'profile.html',context)
signals.py
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
models.py
class Profile(models.Model):
name = models.OneToOneField(User,on_delete=models.CASCADE)
mobile = models.IntegerField(null=True)
address = models.CharField(max_length=350,null=True)
image = models.ImageField(upload_to='profile_pics', default='default.png',null=True)
def __str__(self):
return str(self.name.username)+'\'s Profile'
forms.py
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['mobile', 'address', 'image']
Error msg:
RelatedObjectDoesNotExist at /login/
User has no profile.
I am facing an issue that the user profile could not get created or updated although I used the signals for the profile model. When I login a registered user, the error message told me that User has no profile. However if I login a user that has created a profile it could show the related information so for newly registered user how to automatically create a profile for that user?
because you have a existing which does not have any profile because didn't load signal then wile creating that user if it is superuser create the new superuser from terminal delete the existing one who doesn't have profile after login in admin panel by the way i am also using signal for my web here is the code how i use it
my models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User ,on_delete=models.CASCADE,)
profile_pic = models.ImageField(upload_to='profile_pics', default='default.png',)
first_name = models.CharField(max_length=50, blank=True)
last_name = models.CharField(max_length=75, blank=True)
dob = models.DateField(blank=True, null=True)
joined_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, *args, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
tell me if you still got error

Using a primary key within a form view (Django)

I have a form that is associated with a model, and want to specify the form data using the model's PK to log the response.
However, when I do this, I get the error: QuestionRecordSubmitView() got an unexpected keyword argument 'pk'
urls.py
path('survey/<int:pk>/record_submit_question/', views.QuestionRecordSubmitView, name='survey-question-submit-record')
views.py
def QuestionRecordSubmitView(request):
model = Question
if request.method == 'POST':
form = PostAudio(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('survey-share', kwargs={"pk": form.question}))
else:
form = PostAudio()
return render(request, 'survey/question_audio_submit.html')
models.py
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
response_file = models.FileField(blank=True, upload_to='audio_responses')
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
forms.py
class PostAudio(forms.ModelForm):
class Meta:
model = Choice
fields = ('response_file',)
The view should accept a pk parameter, the primary key that is captured from the path. Furthermore, you should specify the question_id of the instance:
from django.shortcuts import redirect
def QuestionRecordSubmitView(request, pk):
if request.method == 'POST':
form = PostAudio(request.POST, request.FILES)
if form.is_valid():
form.instance.question_id = pk
form.save()
return redirect('survey-share', pk=pk)
else:
form = PostAudio()
return render(request, 'survey/question_audio_submit.html')

django wont store authUser referenced as foreign key in my model

I created my model that have authUser referenced as foreign key, then using django Form API i am trying to store data into my DB but my user field remains null.
I have used build-in FORM API to receive an uploaded file and before storing my file, i also store filename. I tried to do the same for userField but django throw ValueError.
Models.py
class sample(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True ,default=1)
submit_time = models.DateTimeField(auto_now=True)
file_name = models.CharField(max_length=1024)
score = models.FloatField(default=0.0)
is_pending = models.BooleanField(default=True)
is_complete = models.BooleanField(default=False)
json_URL = models.FilePathField()
sample = models.FileField(upload_to='samples/')
Views.py
#login_required
def upload(request):
if request.method == 'POST':
file = request.FILES['sample']
form = SampleForm(request.POST, request.FILES)
if form.is_valid():
new_sample = form.save(commit=False)
new_sample.file_name = file.name
new_sample.user = User.id #throws ValueError Cannot assign "sample.user" must be a "User" instance.
form.save()
return redirect('reports')
else:
print("form is invalid")
else:
form = SampleForm()
if request.method == 'GET':
return render(request, 'upload2.html', {'form': form})
forms.py
class SampleForm(forms.ModelForm):
class Meta:
model =sample
fields=('sample',)
my goal is to save the user id in my db so i know who uploaded the file.
You should use request.user to the new_sample.user object, or request.user.id (or request.user.pk) to the request.user_id attribute, like:
# …
new_sample = form.save(commit=False)
new_sample.file_name = file.name
new_sample.user = request.user
form.save()
return redirect('reports')
# …
By using User.id, you get a reference to the field of the User model, not an object.

Get the currently logged in Django user in a models.py file?

I'm trying to make a model that's stores basic information about an Article also store the name of the currently logged in user, is this possible? or is it something that needs to be done in the views.py file.
Here's my code:
from django.db import models
from time import time
from django.contrib.auth.models import User
def get_upload_file_name(instance, filename):
return "uploaded_files/%s_%s" % (str(time()).replace('.','_'), filename)
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(User.get_username()) #AUTOMATICALLY STORE USERNAME
body = models.TextField()
pub_date = models.DateTimeField(auto_now=True)
likes = models.IntegerField(default=0)
thumbnail = models.FileField(upload_to=get_upload_file_name)
def __unicode__(self):
return self.title
Here's the function that handles the Article model located in views.py:
def create(request):
if request.POST:
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('/articles/all')
else:
form = ArticleForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
How can I make it so that when a new article is created, the username should be stored as the "author" the same way the "pub_date" automatically stores the current date?
You'll need to take care of this in the view:
# views.py
def create(request):
if request.POST:
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return HttpResponseRedirect('/articles/all')
else:
form = ArticleForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
# models.py
class Article(models.Model):
author = models.ForeignKey('auth.User')
You'll need to do it in the view, as the model has no idea where it is being created from. Pass commit=False to the form.save() method so it doesn't commit the data to the database, set the author from the request, and then save manually:
if form.is_valid():
article = form.save(commit=False)
article.author = request.user
article.save()
return HttpResponseRedirect('/articles/all')

Categories