I know similar question asked, but in my case am getting RelatedObjectDoesNotExist after deployment to pythonanywhere.com.
"RelatedObjectDoesNotExist: User has no eisfiles."
However same codes works fine in local machine.
Model.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class gwDashboard(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
htmlname = models.CharField(max_length=100)
def __str__(self): # __unicode__ on Python 2
return self.htmlname
class userInformation(models.Model):
user = models.ForeignKey(User)
DbName = models.CharField(max_length=200)
DbTable = models.CharField(max_length=200)
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(max_length=100)
class eisfiles(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
htmlname = models.CharField(max_length=100)
meterId = models.CharField(max_length=100)
esiid = models.CharField(max_length=100)
metermultiplier = models.CharField(max_length=100)
DbName = models.CharField(max_length=100,default='800WILCREST')
DbTable = models.CharField(max_length=100)
def __str__(self):
return self.htmlname
def __str__(self):
return self.DbName
class Member(models.Model):
ID = models.AutoField(primary_key=True)
FIRST_NAME = models.CharField('First name', max_length=50)
LAST_NAME = models.CharField('Last name', max_length=50)
# Using multi table inheritance - automaticly creates one to one field
class MemberDetail(Member):
DATE_OF_BIRTH = models.DateField('Date of birth')
EMAIL = models.EmailField('E-mail')
PHONE = models.CharField('Phone', max_length=15)
Views.py
def home(request):
userName = request.user
u = User.objects.get(username=userName);
DbName=u.eisfiles //THIS LINE OF CODE THROWS ERROR
try:
DbName=u.eisfiles //THIS LINE OF CODE THROWS ERROR
DbName=u.eisfiles.DbName
direct=''
return render_to_response(
'registration/result.html',
{ 'kWhHeatMap': kWhHeatMap, 'temHeatMap':temHeatMap,"histKwhChart":histKwhChart,'officeBuilding':officeBuilding},
)
except User.eisfiles.RelatedObjectDoesNotExist:
pass
return render_to_response(
'registration/result.html',
{ 'kWhHeatMap': "", 'temHeatMap':"","histKwhChart":"",'officeBuilding':""},
)
# except User.AttributeError:
# return HttpResponse('something went wrong!! try again')
finally:
pass
You may want to check if the user you're attempting to retrieve actually exists.
userName = request.user # ??? This is the user object not the username
u = User.objects.get(username=userName)
There appears to be a problem with your query.Try this instead:
user = request.user
u = User.objects.get(id=user.id)
DbName = u.eisfiles.DbName
Related
I have two model classes as follows that are related to each other with User class.
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
...
first_name = models.CharField(max_length=30, null=False, blank=False)
last_name = models.CharField(max_length=30, null=False, blank=False)
father_name = models.CharField(max_length=30, null=False, blank=False)
class Company(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
...
code = models.CharField(max_length=15, null=True, blank=True)
And now a request comes as follows:
http://localhost:8000/api/v1/search/users/?first_name=john&&last_name=dev&&code=25
How can I search if one of the input parameters is in one of the tables (person or company)?
The effort I have made but no result found:
class SearchUserAPI(APIView):
def get(self, request, format=None):
try:
from django.db.models import Q
q = request.query_params
search_models = [Person, Company]
search_results = []
for model in search_models:
fields = [x for x in model._meta.fields if isinstance(x, django.db.models.CharField)]
search_queries = [Q({x.name + "__icontains": q.get(x.name)}) for x in fields]
print(search_queries)
q_object = Q()
for query in search_queries:
q_object = q_object | query
results = model.objects.filter(q_object)
search_results.append(results)
data = [search_results]
return Response(data, status=status.HTTP_200_OK)
except Exception as e:
return Response({"error": e}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
thats will better and will work i hope )
class SearchUserAPI(APIView):
def get(self, request, format=None):
try:
q = request.query_params
first_name = q.get('first_name')
last_name = q.get('last_name')
code = q.get('code')
data = Person.objects.filter(first_name=first_name, last_name=last_name, company_code=code)
data = [search_results]
return Response(data, status=status.HTTP_200_OK)
except Exception as e:
return Response({"error": e}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
also you can easy add another fields to filter
you can use filterset in drf
I assume your user is somehow linked with person or company in Foreign key or One to one
from django_filters import rest_framework as filters, BaseInFilter
class SearchFilter(filters.FilterSet):
first_name = filters.CharFilter(
field_name="person__first_name",
label='person name'
)
last_name = filters.CharFilter(
field_name="person__first_name",
label='person name'
)
code = = filters.NumberFilter(
field_name="company__code",
label='code'
)
class Meta:
model = User
fields = ['first_name','last_name','code']
You can simply call your searchfilter set in views now It will do your work
I tried to compare password and confirmpassword. If i enter different password it does not raise error and redirects to loginpage.
models.py
class reg1(models.Model):
name=models.CharField(max_length=100)
city=models.CharField(max_length=100)
email=models.CharField(max_length=100)
username=models.CharField(max_length=100)
password=models.CharField(max_length=100)
cpassword=models.CharField(max_length=100)
class Meta:
db_table='reg1'
forms.py
class regform(forms.Form):
name = forms.CharField(max_length=100)
city = forms.CharField(max_length=100)
email = forms.CharField(max_length=100)
username = forms.CharField(max_length=100)
password = forms.CharField(max_length=100)
cpassword=forms.CharField(max_length=100)
def clean_password(self):
if self.data['password'] != self.data['cpassword']:
raise forms.Error('Passwords are not the same')
return self.data['password']
views.py
if myregform.is_valid():
name1 = myregform.cleaned_data['name']
city1 = myregform.cleaned_data['city']
email = myregform.cleaned_data['email']
username1 = myregform.cleaned_data['username']
password1 = myregform.cleaned_data['password']
password2=myregform.cleaned_data['cpassword']
a=reg1(name=name1,city=city1,email=email,
username=username1,password=password1,cpassword=password2)
a.save()
I expect the output as i enter a different password it will show password not matching error
I am using pycharm software and django framework with sqlite3 database.
Use a ModelForm to save yourself a bunch of typing.
You need to use clean() to validate data that relates to other fields.
You need to raise ValidationErrors.
class reg1(models.Model):
name = models.CharField(max_length=100)
city = models.CharField(max_length=100)
email = models.CharField(max_length=100)
username = models.CharField(max_length=100)
password = models.CharField(max_length=100)
cpassword = models.CharField(max_length=100)
class Meta:
db_table = "reg1"
class regform(forms.ModelForm):
class Meta:
model = reg1
exclude = ()
def clean(self, cleaned_data):
if cleaned_data["password"] != cleaned_data["cpassword"]:
raise forms.ValidationError("Passwords are not the same")
return cleaned_data
# ...
if myregform.is_valid():
a = myregform.save()
I'm trying to add an "event" in the admin and get this error:
TypeError at /admin/sms/event/add/
'Contact' object is not subscriptable
models.py:
class Contact(models.Model):
users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="contact")
name = models.CharField(_("Recipient"), max_length=40)
phone = models.IntegerField(_("Phone"), max_length=10)
def __unicode__(self):
return "%s: %d" % (self.name, self.phone)
class Event(models.Model):
calendar = models.ForeignKey(Calendar, verbose_name=_("Calendar"), related_name="event_calendar")
message = models.ForeignKey(Message, verbose_name=_("Message"), related_name="event_message")
recipient = models.ForeignKey(Contact, verbose_name=_("Recipient"), related_name="event1")
event_date = models.DateField(_("Date"))
start_time = models.TimeField(_("Start time"))
end_time = models.TimeField(_("End time"), blank=True, null=True)
location = models.CharField(_("Location of meeting"), blank=True, null=True, max_length=100)
reminder_options = models.IntegerField(choices=ReminderOptions.CHOICES, verbose_name=_("Reminder time"))
content = models.CharField(_("Event Notes"), max_length=160)
# recurring_options = models.IntegerField(choices=RecurringOptions.CHOICES, verbose_name=_("Recurring time"))
def __unicode__(self):
return self.recipient
def get_absolute_url(self):
return u'/create-event/'
First guess is that your phone field gets a string from your admin form. Use a charField for phone in your model and make a custom form in your admin.py.
In models.py change your phone Integerfield to a CharField:
class Contact(models.Model):
...
phone = models.CharField(_("Phone"), max_length=200)
def __unicode__(self):
return "%s: %s" % (self.name, self.phone) # %d becomes %s
In Admin.py create a form:
from models import Contact
from django import forms
from django_localflavor_fr.forms import FRPhoneNumberField
class ContactForm(forms.ModelForm):
phone = FRPhoneNumberField()
class Meta:
model = Contact
https://docs.djangoproject.com/en/1.5/ref/contrib/localflavor/
In Admin.py create a ModelAdmin:
class ContactAdmin(admin.ModelAdmin):
form = ContactForm
I have a problem getting my django ordering to work. When I define a function in a model definition which returns a QuerySet with order_by() called on it I get the correct order. However, when I call order_by() outside of the definition I do not get the correct order.
working code:
The following orders the 'parts' correctly by name:
# models.py
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, default=0)
...
def get_parts_as_owner(self):
user=self.user
return Part.objects.filter(Q(owner=user)).order_by('name')
class Part(models.Model):
name = models.CharField(max_length=45,unique=True)
last_modified = models.DateTimeField(auto_now=True)
owner = models.ForeignKey(User)
# views.py
def view_parts(request):
user = request.user
owned = user.get_profile().get_parts_as_owner()
return render_to_response('parts/view_parts.html', {'owned': owned}, RequestContext(request))
not working code:
the following does not order as I would expect (by name):
# models.py
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, default=0)
...
def get_parts_as_owner(self):
user=self.user
return Part.objects.filter(Q(owner=user))
class Part(models.Model):
name = models.CharField(max_length=45,unique=True)
last_modified = models.DateTimeField(auto_now=True)
owner = models.ForeignKey(User)
# views.py
def view_parts(request):
user = request.user
owned = user.get_profile().get_parts_as_owner().order_by('name')
return render_to_response('parts/view_parts.html', {'owned': owned}, RequestContext(request))
also not working
The following orders by name and not by last_modified, which I would expect
# models.py
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, default=0)
...
def get_parts_as_owner(self,order='name'):
user=self.user
return Part.objects.filter(Q(owner=user)).order_by(order)
class Part(models.Model):
name = models.CharField(max_length=45,unique=True)
last_modified = models.DateTimeField(auto_now=True)
owner = models.ForeignKey(User)
# views.py
def view_parts(request):
user = request.user
owned = user.get_profile().get_parts_as_owner(order='last_modified')
return render_to_response('parts/view_parts.html', {'owned': owned}, RequestContext(request))
Why are these not ordering as I would expect? What is the difference in when I call order_by?
You should be using the related managers instead of creating methods on the model to return an entirely new queryset. For example, to get the user's parts, you need only do:
request.user.get_profile().part_set.order_by('name')
This is built-in for you. There's no need to do anything else.
Is it possible to have a field in a Django model which does not get stored in the database.
For example:
class Book(models.Model):
title = models.CharField(max_length=75)
description models.CharField(max_length=255, blank=True)
pages = models.IntegerField()
none_db_field = ????
I could then do
book = Book.objects.get(pk=1)
book.none_db_field = 'some text...'
print book.none_db_field
Thanks
As long as you do not want the property to persist, I don't see why you can't create a property like you described. I actually do the same thing on certain models to determine which are editable.
class Email(EntryObj):
ts = models.DateTimeField(auto_now_add=True)
body = models.TextField(blank=True)
user = models.ForeignKey(User, blank=True, null=True)
editable = False
...
class Note(EntryObj):
ts = models.DateTimeField(auto_now_add=True)
note = models.TextField(blank=True)
user = models.ForeignKey(User, blank=True, null=True)
editable = True
Creating a property on the model will do this, but you won't be able to query on it.
Example:
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def _get_full_name(self):
return "%s %s" % (self.first_name, self.last_name)
def _set_full_name(self, combined_name):
self.first_name, self.last_name = combined_name.split(' ', 1)
full_name = property(_get_full_name)
full_name_2 = property(_get_full_name, _set_full_name)
Usage:
from mysite.models import Person
a = Person(first_name='John', last_name='Lennon')
a.save()
a.full_name
'John Lennon'
# The "full_name" property hasn't provided a "set" method.
a.full_name = 'Paul McCartney'
Traceback (most recent call last):
...
AttributeError: can't set attribute
# But "full_name_2" has, and it can be used to initialise the class.
a2 = Person(full_name_2 = 'Paul McCartney')
a2.save()
a2.first_name
'Paul'
To make it an instance variable (so each instance gets its own copy), you'll want to do this
class Book(models.Model):
title = models.CharField(max_length=75)
#etc
def __init__(self, *args, **kwargs):
super(Foo, self).__init__(*args, **kwargs)
self.editable = False
Each Book will now have an editable that wont be persisted to the database
If you want i18n support:
# Created by BaiJiFeiLong#gmail.com at 2022/5/2
from typing import Optional
from django.db import models
from django.utils.translation import gettext_lazy as _
class Blog(models.Model):
title = models.CharField(max_length=128, unique=True, verbose_name=_("Title"))
content = models.TextField(verbose_name=_("Content"))
_visitors: Optional[int] = None
#property
def visitors(self):
return self._visitors
#visitors.setter
def visitors(self, value):
self._visitors = value
visitors.fget.short_description = _("Visitors")