DoesNotExist at /settings : Profile matching query does not exist - django

#login_required(login_url='signin')
def settings(request):
user_profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
if request.FILES.get('image') == None:
image = user_profile.profileimg
bio = request.POST['bio']
location = request.POST['location']
user_profile.profileimg = image
user_profile.bio = bio
user_profile.location = location
user_profile.save()
if request.FILES.get('image') !=None:
image = request.FILES.get('image')
bio = request.POST['bio']
location = request.POST['location']
user_profile.profileimg = image
user_profile.bio = bio
user_profile.location = location
user_profile.save()
return render(request, 'setting.html', {'user_profile' :user_profile})
user_profile = Profile.objects.get(user_profile=request.user)
Hello i am trying to run this code for a social app i am creating and i cant proceed further because i keep getting an error message and i cant proceed.
please i need help with this thank you.

The error is clear: the user which is making the request doesn't have a Profile associated with it.
You should handle the case in which the profile does not exist.
try:
user_profile = Profile.objects.get(user=request.user)
except:
# handle user_profile creation here
user_profile = Profile(user=request.user, ...)
Or use https://docs.djangoproject.com/en/4.1/ref/models/querysets/#get-or-create
Or have a have a post_save signal that automatically creates a Profile for each user, if it doesn't exist already.

Related

how to overide in forms queryset none() attribute and somehow allow to save the field?

I have models.py
class Visit(Model):
reference_visit = models.ForeignKey('self',
help_text="Visit needs a refrence to Prior Visits",
null=True, blank=True)
show_prior_responses = models.BooleanField(default=False,
help_text="Show PriorResponses")
# has many field but i am making it short.
def __unicode__(self):
result = """Visit id:%s pt:%s""" % (self.id, self.patient.id)
return result
forms.py
class VisitSetupForm(Form):
list_visit_ids = ModelChoiceField(
queryset=Visit.objects.none(),
empty_label='Select Revisit ID',required=False)
show_prior_visit = ModelChoiceField(
queryset=User.objects.all(),
empty_label="Select User for Revisit",required = False)
has many but question is on list_visit_ids.
views.py
def setup(request):
"""
Allow an Admin user the ability to setup a patient & visit all at once.
"""
if request.user.is_superuser:
form_class = AdminVisitSetupForm
all_topics = True
else:
form_class = VisitSetupForm
all_topics = False
f = form_class()
# Get a list of topics for each report.
report_topics = {}
for r in Interview.objects.all():
report_topics[r.id] = [t['ad'] for t in r.topics.values('ad')]
data = {
'superuser':request.user.is_superuser,
'report_topics':simplejson.dumps(report_topics)
}
try:
request.user.reviewer
data['reviewer'] = True
except:
pass
if request.method == "POST":
f = form_class(request.POST)
if f.is_valid():
# Create the patient, generate a password, and send them on their way.
cd = f.cleaned_data
patient = None
if cd['revisit']:
# Check for an existing user first.
try:
patient = Patient.objects.get(username=cd['username'])
except Patient.DoesNotExist, e:
data['form'] = f
data['msg'] = 'There is no user with this username.'
return render_to_response('visit/setup.html', data, context_instance=RequestContext(request))
admin_user = get_user(request)
organization = None
if admin_user:
organization = admin_user.organization
if patient and not request.user.is_superuser:
# Make sure the patient they've selected is one of their own.
if patient.organization != organization:
return HttpResponseForbidden('You are not allowed to see this page.')
if not patient:
password = generate_password()
user = User.objects.create_user(cd['username'], cd['contact_email'], password)
user.first_name = cd['first_name']
user.last_name = cd['last_name']
user.save()
patient = Patient(
user=user,
username=user.username,
contact_phone=cd['contact_phone'],
date_of_birth=cd['date_of_birth'],
email=user.email,
first_name=user.first_name,
gender=cd['gender'],
last_name=user.last_name,
maiden_name=cd['maiden_name'],
organization=organization,
patient_type=cd['patient_type'],
security_answer=cd['security_answer'],
security_question=cd['security_question'],
)
patient.save()
# Send them an email.
t = loader.get_template('www/new_account.txt')
c = Context({
'password':'%s-%s-%s' % (password[:3], password[3:5], password[5:]),
'patient':patient
})
msg = t.render(c)
try:
send_mail(
'A request by your physician to do an online medical history before your appointment.',
msg,
'support#careprep.com',
[user.email]
)
except Exception, e:
log.error('Could not send email for new account %s because: [%s]' % (user.username, e))
request.session['password'] = password
# Create the Visit, too.
interview = cd['interview']
list_visit_ids = cd['list_visit_ids']
print list_visit_ids
visit = Visit(
reference_visit = cd['list_visit_ids'],
show_prior_responses = cd['show_prior_responses'],
patient=patient
)
if request.user.is_superuser:
topics = cd['topics']
else:
topics = set(list(interview.topics.all()) + list(cd['topics']))
reviewer_mode = cd.get('reviewer_mode') or patient.patient_type == 'Reviewer'
url, visit = initialize_visit(
request,
patient=patient,
starting_section=interview.starting_section,
visit_title='%s %s' % (patient, interview.title),
topics=topics,
reviewer_mode=reviewer_mode,
chief_complaint=cd['chief_complaint'],
location=cd['interview_site'],
reference_visit = cd['list_visit_ids'],
show_prior_responses = cd['show_prior_responses'],
)
next_url = "/visit/confirmation/%s/%s/?next=%s" % (patient.user.id, interview.id, url)
else:
v = Visit.objects.get(pk=request.POST['list_visit_ids'])
print v
return HttpResponseRedirect(next_url)
# all the fields that are not given pls ignore.
The template is fine.
Now watch forms.py when i do list_visit_ids = ModelChoiceField(queryset=Visit.objects.all(), empty_label='Select Revisit ID',required=False) It works perfectly fine on my local machine.But on my server it has around 6000 visit objects so this page hangs or i should say keep on loading.
So initially i changed it to list_visit_ids = ModelChoiceField(queryset=Visit.objects.none(), empty_label='Select Revisit ID',required=False)
Now i know that by this the form becomes invalid and should go to the else part Now my question how do i make reference_visit=cd['list_visit_ids'] in else (form is invalid)
case save().How do i override the none() attribute.
Thanks in advance i will really appreciate.
If your goal is to save your html page load by removing the 6000 choices (which I've done too: 10000+ <option> fields wrapped by misc html will absolutely choke a page), you shouldn't be using a ChoiceField at all. By setting queryset=Visit.objects.none() you're allowing zero choices and nothing passed in will validate.
You either show 6000 select item drop downs, radio boxes, etc., or find a way to /not/ have a giant select drop down (such as a hidden input or charfield), not fake around a ModelChoiceField who's main purpose is to populate that select drop down and validate.
In short: don't use a ModelChoiceField if you're not going to be using the html choices generated by it. Use something else and do the validation / model pulling yourself via the clean_FOO methods.
class MyForm(forms.Form):
my_input = forms.CharField()
def clean_my_input(self):
input = self.cleaned_data.get('my_input')
try:
return MyModel.objects.get(pk=input) # add a filter here if you want
# (whatever filters you were using in the queryset argument)
except MyModel.DoesNotExist:
raise forms.ValidationError("Doesn't exist / is invalid")
return input

Problem with pymongo and django unique value

I am writing django app that as a beckend is using mongodb. I am curently writing register part. Here is how I connecto to database in settings.py
if socket.gethostname() == "Production server":
CON = Connection()
DB = CON.fish
else:
CON = Connection()
DB = CON.test
DB.user.ensure_index([("username", ASCENDING),("email",ASCENDING)],unique = True)#,drop_dups=True
Here is mye register view:
def register(request):
"""
handle user registration
code variable is for testing purposes
"""
if request.method== 'GET':
form = RegisterForm(auto_id=False)
code = 1
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
elif request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
password = form.cleaned_data['password']
password_confirmation = form.cleaned_data['password_confirmation']
if password == password_confirmation:
login = form.cleaned_data['login']
email = form.cleaned_data['email']
newsletter = form.cleaned_data['newsletter']
key = register_user(login,email,password,newsletter)
if key:
#send email
send_mail("Dziękujemy za rejestrację"," Klucz aktywacyjny to " + key,settings.EMAIL_HOST_USER,[email])
request.session['email'] = email
return redirect(register_success)
else:
code = 4
error = "Login/email taken"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 3
error = "invalid password"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 2
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
Here is my function I use to register user:
def register_user(login,email,password,newsletter):
"""
This function will return activation key for this user if user was added successfully or none otherwise
"""
key = generate_activation_key()
user = {
"username":login,
"email":email,
"password":crypt_password(password),
"date_join": datetime.now(),
"key": key
}
if newsletter:
user['newsletter'] = True
try:
settings.DB.user.insert(user,safe = True)
except DuplicateKeyError, error:
logging.debug("error raise during saving user")
return None
except OperationFailure, error:
logging.critical("Cannot save to database")
logging.critical(error)
else:
#we have no errors users is registred
return key
And when I test it in the browser it seems to be working. But I write test for it and it isn't working anymore. Here is code for test:
def test_valid_credentials(self):
#now try to register valid user
data = {'login':'test','password':'zaq12wsx','password_confirmation':'zaq12wsx','terms':True,'newsletter':True,'email':'test#test.com'}
response = self.c.post(reverse('register'),data)
#our user should be registred
self.assertEquals(302, response.status_code,'We dont have benn redirected')
self.assertEqual(len(mail.outbox), 1,'No activation email was sent')
#clen email box
mail.outbox = []
#now try to add another user with the same data
response = self.c.post(reverse('register'),data)
#template should be rendered with error message about used login and email
self.assertEquals(200, response.status_code)#this fails
And here is error that i get.
self.assertEquals(200, response.status_code)
AssertionError: 200 != 302
So user was registred with the same username and email which shoudn't happen. Any sugestions? Thanks in advance
Why don't you use https://github.com/django-mongodb-engine/mongodb-engine it works almost perfect with Django ORM. Works like a charm for me.

Django-forms validation problem at initialization

I have a problem about validation of form fields in Django.
I have a profile_edit form it has a set of clean functions. Also, in order to control the current password, I need to pass current user's password to the form.
email = forms.EmailField(label=_("member_Email"),required = True)
currentPassword = forms.CharField(label=_("member_currentPassword"),widget=forms.PasswordInput,required=False)
newPassword = forms.CharField(label=_("member_newPassword"),widget=forms.PasswordInput,required=False)
newPasswordRe = forms.CharField(label=_("member_newPasswordRe"),widget=forms.PasswordInput,required=False)
emailPreference = forms.ChoiceField(label=_("member_email_preference"), widget=forms.RadioSelect(renderer=HorizRadioRenderer),choices = UserMailPreference.USER_MAIL_PREF,required = True)
gender = forms.ChoiceField(label=_("member_gender"), widget=forms.RadioSelect(renderer=HorizRadioRenderer),choices = UserGender.USER_GENDER ,required = False)
birthYear = forms.ChoiceField(label=_("member_birthyear"),required = False)
education = forms.ChoiceField(label=_("member_education"),choices = UserEducation.USER_EDU, required = False)
def __init__(self,*args, **kwargs):
super(MemberSettings,self).__init__(*args, **kwargs)
now = datetime.datetime.now()
self.fields["birthYear"].choices = birthYearList
def set_user(self, user):
self.user = user
def clean_email(self):
field_data = self.cleaned_data['email']
if not field_data:
return ''
try:
u = User.objects.get(email=field_data)
if not u.id == self.user.id:
raise forms.ValidationError(_('err_already_registered'))
except ObjectDoesNotExist:
pass
return field_data
By using the set_user method I can pass the current user to form however, when I write
form = MemberSettings(default_data)
form.set_user(u)
in my view, form tries to validate all the fields although I just try to initialize the form.
But if I do not set the user, form works normal.
What is the problem that I can't notice ?
Thanks
See my answer on: Django form edit problem at intiliazation
It's the same issue. You need to use the initial argument when passing data to the form.

send data to a ForeignKey manually?

i want to save data in two table mysql, that was nice, but now i change a field form Interget to FK.. the problem is that now i cant send the data to the field FK....
im new with Django, but im working in this way:
#login_required
def agregar_diligencia(request):
if request.method =='POST':
form = DiligenciaForm(request.POST)
#trac = Tracking()
tracknum = 'ABCD458LK'
if form.is_valid():
from django.contrib.auth.models import User
User = User.objects.get(pk=request.user.id)
obj = form.save(commit=False)
obj.socio = User
obj.status = 0
obj.secuencia = 1
obj.save()
t = Tracking()
t.track = tracknum
t.diligencia = obj.id
t.save()
return HttpResponseRedirect('/accounts/diligencias/activas')
else:
form = DiligenciaForm()
return render_to_response('account/agregar_diligencia_form.html',
{ 'formulario':form },context_instance = RequestContext(request))
Where t.diligencia = obj.id (t.diligencia) is my FK and obj.id is the data that i want to save in the FK
Sorry with my English and thanks.
You haven't at all stated what the problem is.
However one thing that I can see is that you're overwriting User in this line:
User = User.objects.get(pk=request.user.id)
You should be assigning to user with a lower-case u - but I doubt that's the source of your problem, whatever it is.
just do
obj.socio = request.user

Handling Image Uploads in Django

I have this view for my form:
if request.method == 'POST':
vehicle = VehicleForm(request.POST or None)
photos = PhotosFormSet(request.POST or None)
if vehicle.is_valid() and photos.is_valid():
new = vehicle.save()
photos = PhotosFormSet(request.POST, instance=new)
photos.save()
return HttpResponseRedirect('/vehicles/')
else:
prefix = "09-"
queryset = Vehicle.objects.all().order_by("stock_number")
if queryset == None:
last_rec = queryset.reverse()[0]
a = str(last_rec.stock_number)
b = int(a[-3:])+1
next = prefix+str(b)
else:
next = prefix+"001"
vehicle = VehicleForm(initial={'stock_number': next})
photos = PhotosFormSet(instance=Vehicle())
However when I try to save the record, the image field in PhotosFormset gives an error saying This field is required.
PhotosFormset is declared as PhotosFormSet = generic_inlineformset_factory(Photo, extra=5)
What am I missing here?
You don't appear to be binding uploaded files to your formset. You need to pass in request.FILES as well as request.POST:
photos = PhotosFormSet(request.POST, request.FILES, instance=new)
More info in the Django docs