Django project, data deleted from the database - python

I am new in web development with Django and MySQL database, I got to develop a web application with Django framework, after deployment of my project in the server.
after 2 months, I noticed that data from my order table was deleted as well as the data of one user is displayed in the profile of another,
I want to know what I must do as a test to know the PR eventual error and to stop the deletion of data in my database.
data often deleted in the order and customer table.
the ORDER model bind with a foreign key to other Model:
class Order(models.Model):
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
created = models.DateTimeField( auto_now_add=True, verbose_name=_('Creation Date'))
payed = models.DateTimeField( verbose_name=_('Payment Date'), default=datetime.now, null=True, blank=True)
reference = models.IntegerField( verbose_name=_('Order Reference'), default=0, null=True, blank=True )
customer = models.ForeignKey( Customers, verbose_name=_('Customer'), null=True, blank=True, on_delete=models.CASCADE )
company = models.ForeignKey( Compagnie, verbose_name=_('Company'), null=True, blank=True, on_delete=models.CASCADE )
class Customers(models.Model):
company = models.ForeignKey(
Compagnie,
verbose_name=_('Company'),
null=True,
blank=True,
on_delete=models.CASCADE
)
forename = models.CharField(
verbose_name=_('First Name'),
max_length=255,
null=True,
blank=True)
GENDER = [('M', _('Male')),
('F', _('Female'))]
gender = models.CharField(
verbose_name=_('Gender'),
max_length=1,
choices=GENDER,
null=True,
blank=True)
city = models.ForeignKey(
City,
verbose_name=_('City'),
null=True,
blank=True,
on_delete=models.CASCADE
)
additionalNum = models.CharField(
verbose_name=_('Additional Number:'),
max_length=60,
null=True,
blank=True,
)
adressCustomer = models.TextField(
verbose_name=_('Address Customer:'),
max_length=500,
null=True,
blank=True,
)
telCustomer = models.CharField(
verbose_name=_('Phone Customer:'),
max_length=30,
null=True,
blank=True,
)
emailCustomer = models.EmailField(
verbose_name=_('Email Customer:'),
null=True,
blank=True,
)
otherBuyerId = models.CharField(
verbose_name=_('Other Buyer ID:'),
max_length=50,
null=True,
blank=True
)
vatNumber = models.CharField(
max_length=120,
null=True,
verbose_name=_('Vat Number:'),
blank=True
)
needs_attention = models.BooleanField(
verbose_name=_('Needs attention'),
default=False)
biography = models.TextField(
verbose_name=_('Biography'),
null=True,
blank=True)
_is_updating_cache_fields = False
def get_name(self):
first = self.forename or ''
name = "%s" % (first)
return name.strip()
class Meta:
verbose_name = _('Customer')
verbose_name_plural = _('Customers')
def __unicode__(self):
return u'%s %s: %s' % (
type(self).__name__,
self.pk,
self.forename)
def __str__(self):
if self.forename:
return self.forename
else:
return "Unnamed"
Can someone give me an explanation for this problem?

Related

Django Rest API: Serializer won't show Foreign Key Field values

I'm trying to list the values of FacilityAddressSerializer within the FacilitySearchSerializer. This is what i tried. I get all the values of the FacilitySearchSerializer but the values of the FacilityAddressSerializer are showing as Null:
serializers.py
class FacilityAddressSerializer(serializers.ModelSerializer):
class Meta:
model = FacilityAddress
fields = (
"id",
"PrimaryAddress",
"SecondaryAddress",
"City",
"RegionOrState",
"PostalCode",
"Geolocation",
"AddressInfo"
)
class FacilitySearchSerializer(serializers.ModelSerializer):
AddressInfo = FacilityAddressSerializer(source="fa")
class Meta:
model = Facility
fields = (
"id",
"Name",
"AddressInfo",
"ListingVerified",
"mainimage",
"AdministratorCell",
"Capacity",
"PriceRangeMin",
"PriceRangeMax",
)
read_only_fields = ("id", "Name", "ListingVerified", "mainimage", "AdministratorCell", "Capacity", "FeaturedVideo", "PriceRangeMin", "PriceRangeMax")
models.py
class Facility(models.Model):
Name = models.CharField(max_length=150, null=True, blank=False)
mainimage = models.ImageField(null=True, blank=True)
Capacity = models.IntegerField(null=True, blank=True)
TelephoneNumber = models.CharField(max_length=30, null=True, blank=True)
AdministratorCell = PhoneNumberField(null=True, blank=True)
PriceRangeMin = models.IntegerField(null=True, blank=True)
PriceRangeMax = models.IntegerField(null=True, blank=True)
class FacilityAddress(models.Model):
PrimaryAddress = models.CharField(max_length=150, null=True, blank=True)
SecondaryAddress = models.CharField(max_length=150, null=True, blank=True)
City = models.CharField(max_length=150, null=True, blank=True)
RegionOrState = models.CharField(max_length=50, null=True, blank=True)
PostalCode = models.CharField(max_length=30, null=True, blank=True)
Geolocation = models.CharField(max_length=30, null=True, blank=True)
AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa')
It works after i added (many=True) next to the source=fa. I thought i didn't need that since i'm using foreign key fields and not manytomany fields but i guess i was wrong.

Order by related fields of different models in Django Admin

I want to order by the business_name, but the ordering isn't working due to some relationships, below is my first model :
class LoanApplication(models.Model):
loan_id = models.CharField(
'Loan Application ID', max_length=40, unique=True, null=True,
blank=True)
loan_taker = models.ForeignKey(
CustomerProfile, on_delete=models.PROTECT, null=True, blank=True,
verbose_name='Customer Profile', related_name='loan_entries')
submitted_date = models.DateTimeField(
'Submitted Date', null=True, blank=True)
then, I have the CustomerProfile model as below :
class CustomerProfile(models.Model):
customer_id = models.CharField(
'Customer Profile ID', max_length=64, unique=True, null=True)
cooperation_partner = models.ForeignKey(
EmailUser, on_delete=models.PROTECT, null=True, blank=True,
verbose_name=_('Jurisdiction'), related_name='partner_user_profile')
user = models.OneToOneField(
EmailUser, on_delete=models.PROTECT, null=True, blank=True,
verbose_name=_('User'), related_name='user_profile')
tipster_partner = models.ForeignKey(
TipsterPartner, on_delete=models.PROTECT, null=True, blank=True,
verbose_name='Tipster Partner')
So, I wanted to point to the Business model , it's as below :
class Business(models.Model):
business_id = models.CharField(
'Business ID', max_length=64, unique=True, null=True, blank=True)
business_name = models.CharField(_('Business'), max_length=128)
business_address_street = models.CharField(
'Business Address Street', max_length=50, blank=True)
then, we have the last one which is the CustomerProfileBusiness as below :
class CustomerProfileBusiness(models.Model):
business = models.ForeignKey(
Business, on_delete=models.PROTECT, null=True, blank=True,
verbose_name=_('Business'),
related_name='customer_profile_relation')
correlative_id = models.CharField(
_('Business ID'), max_length=64, unique=True, blank=True, null=True)
customer_profile = models.ForeignKey(
CustomerProfile, on_delete=models.PROTECT,
verbose_name=_('Customer Profile'), blank=True, null=True,
related_name='business')
Now, I do the ordering in the Admin page of the LoanApplication as below, but it doesn't work:
#admin.register(LoanApplication, site=admin_site)
class LoanApplicationAdmin(admin.ModelAdmin):
ordering = (
'-modified',
'loan_taker__business__customer_profile_relation__business_name',
)
So my target is to sort the business_name in the ascending order but using a relationship approach in the Admin page of the LoanApplication

Post returns 1364, Field 'ADD' doesn't have a default value

THe error upon clicking the POST button on Djangorest Form
The serializer:
class CreatePolicyBenefitsSerializer(serializers.ModelSerializer):
class Meta:
model = Policy
fields = ('company','name','benefits','price')
The views:
class CreatePolicyBenefits(CreateAPIView):
queryset = Policy.objects.all()
serializer_class = CreatePolicyBenefitsSerializer
The Policy Model
``
class Policy(TimeStampedModel):
POLICY_CHOICES = (
('life', 'Life'),
('health', 'Health'),
('home', 'Home'),
('car', 'Car'),
('vul', 'VUL'),
)
PREMIUM_INTERVALS = (
('one_time', 'One Time'),
('annual', 'Annual'),
('semi_annual', 'Semi Annual'),
('quarterly', 'Quarterly'),
('monthly', 'Monthly')
)
company = models.ForeignKey(
'Company', related_name='Policies', on_delete=models.CASCADE,
null=True, blank=True)
name = models.CharField(max_length=255, blank=True, null=True, default="")
description = models.TextField(blank=True, null=True, default="")
benefits = models.JSONField(null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
category = models.CharField(
max_length=64, blank=True, null=True, choices=POLICY_CHOICES, default="")
premium_details = models.CharField(max_length=255, blank=True, null=True)
policy_details = models.CharField(max_length=255, blank=True, null=True)
available_premium_interval = models.CharField(
max_length=64, blank=True, null=True, choices=PREMIUM_INTERVALS)
icon_name = models.CharField(max_length=32, blank=True, null=True)
icon_file = models.FileField(
upload_to=upload_policy_icon, blank=True, null=True)
primary_color = models.CharField(max_length=32, blank=True, null=True)
# file=models.FilePathField(path=os.path.join(settings.MEDIA_ROOT, 'media'))
adminupload=models.FileField(upload_to=pdf_path,max_length=None)
pdfname=models.CharField(max_length=255, blank=True, null=True)
class Meta:
app_label = samplename
def __str__(self):
return '[%s] %s-%s' % (self.id, self.company, self.name)
Here the form
Is it possible when I hit POST button, the data can be displayed on the form? Thanks

QuerySet: Filter for entries

I want to show all answers for question__focus=QuestionFocus.REASON_FOR_ATTENDING where question__focus=QuestionFocus.RECOMMENDATION_TO_FRIENDS is >= 9.
The answer field is not an integer field, but a TextField as all questions share the same Answer model. I tried a lot, but nothing worked for me so far.
I first tried to go from the Answer model, but that also didn't work as I filter for different answers than what I want to show at the end.
event = Event.objects.get(pk=12)
survey = event.surveys.get(
template=settings.SURVEY_POST_EVENT
).questions.[HOW TO CONTINUE?]
models.py
class Survey(TimeStampedModel):
class SurveyTemplate(Choices):
CHOICES = ((survey, survey) for survey in settings.SURVEY_TEMPLATES.keys())
id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
event = models.ForeignKey(
"events.Event", on_delete=models.CASCADE, related_name="surveys"
)
is_active = models.BooleanField(default=False, verbose_name=_("Is active?"))
template = models.CharField(
max_length=SurveyTemplate.get_max_length(),
choices=SurveyTemplate.CHOICES,
verbose_name=_("Survey template"),
)
class Response(TimeStampedModel):
class Language(Choices):
CHOICES = settings.LANGUAGES
survey = models.ForeignKey(
"surveys.Survey", on_delete=models.CASCADE, related_name="responses"
)
order = models.ForeignKey(
"orders.Order",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="response",
)
attendee = models.ForeignKey(
"attendees.Attendee",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="response",
)
total_time = models.PositiveIntegerField(
null=True, blank=True, verbose_name=_("Total time")
)
ip_address = models.GenericIPAddressField(null=True, verbose_name=_("IP Address"))
language = models.CharField(
max_length=Language.get_max_length(),
choices=Language.CHOICES,
verbose_name=_("Language"),
)
class Answer(TimeStampedModel):
question = models.ForeignKey(
"surveys.Question", on_delete=models.CASCADE, related_name="answers"
)
response = models.ForeignKey(
"Response", on_delete=models.CASCADE, related_name="answers"
)
answer = models.TextField(verbose_name=_("Answer"))
choices = models.ManyToManyField(
"surveys.AnswerOption", related_name="answers", blank=True
)
class Question(TimeStampedModel):
survey = models.ForeignKey(
"surveys.Survey", on_delete=models.CASCADE, related_name="questions"
)
question_set = models.ForeignKey(
"QuestionSet", on_delete=models.CASCADE, related_name="questions"
)
title = models.CharField(max_length=100, verbose_name=_("Title"))
help_text = models.TextField(null=True, blank=True, verbose_name=_("Help text"))
type = models.CharField(
max_length=QuestionType.get_max_length(),
choices=QuestionType.CHOICES,
verbose_name=_("Question type"),
)
focus = models.CharField(
max_length=QuestionFocus.get_max_length(),
choices=QuestionFocus.CHOICES,
verbose_name=_("Question focus"),
)
required = models.BooleanField(default=False, verbose_name=_("Is required?"))
position = models.PositiveSmallIntegerField(
null=True, blank=True, verbose_name=_("Position")
)

django login users to their portal

I have couple of models and one of them is a foreign key to the user model that's extending django admin. I want to display what belongs to a user in their session upon login. I have defined this authentication that will check whether a particular user exist within the database and redirect them to their session with their instances.
def auth_view(request):
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
return HttpResponseRedirect('/studentloggedin/')
Basically, Registration is the first model and a foreign key to Student model, while Student is also a foreign key to UserLog. UserLog is extending the default django admin. I've defined the loggedin session here to filter out details of the individual users upon login.
def studentloggedin(request):
registration = Registration.objects.all()
students = Student.objects.filter(registration=registration)
alluser = UserLog.objects.filter(student=students)
context = {
'registration': registration,
'students': students,
'alluser': alluser,
}
return render(request, "studentloggedin.html", context)
Here is the template rendering the information upon login.
<img
{% for student in students %}
src="{{ student.student_photo.url }}">
<p>{{ student.previous_school }}</p>
{% endfor %}
But I'm getting the below error:
ProgrammingError at /studentloggedin/
more than one row returned by a subquery used as an expression
Just thought to add the models in for your perusal.
class Registration(models.Model):
lastName = models.CharField(
_('Last Name'),
max_length=30,
null=False,
blank=False
)
middleName = models.CharField(
_('Middle Name'),
max_length=30,
null=True,
blank=True
)
firstName = models.CharField(
_('First Name'),
max_length=30,
null=False,
blank=False
)
gender = models.CharField(
_('Gender'),
max_length=30,
choices=GENDER_CHOICES,
default=u' ',
null=False,
blank=False
)
grade = models.CharField(
_('Class'),
max_length=30,
choices=CLASS_CHOICES,
default=u' ',
null=False,
blank=False
)
phone_regex = RegexValidator(
regex=r'^\+?1?\d{9,15}$',
message="Phone number format: '+999999999'. Up to 15 digits allowed."
)
phone_number = models.CharField(
_('Phone Number'),
max_length=255,
validators=[phone_regex],
blank=True
)
email = models.EmailField(
_('Email Address'),
max_length=254,
null=True,
blank=True
)
address = models.CharField(
_('Address'),
max_length=255,
null=False,
blank=False
)
city = models.CharField(
_('City'),
max_length=30,
null=False,
blank=False
)
county = models.CharField(
_('County'),
max_length=30,
choices=COUNTY_CHOICES,
default=None,
null=False,
blank=False
)
nationality = models.CharField(
_('Nationality'),
max_length=30,
null=False,
blank=False
)
dateOfBirth = models.DateField(
_('Date of Birth'),
max_length=30,
null=False,
blank=False
)
placeOfBirth = models.CharField(
_('Place of Birth'),
max_length=255,
null=False,
blank=False
)
regDate = models.DateField(
_('Registration Date'),
max_length=30,
null=False,
blank=False
)
country = models.CharField(
_('Country'),
max_length=255,
null=False,
blank=False
)
emergency = models.CharField(
_('Emergency Contact'),
max_length=255,
null=True,
blank=True
)
emergency_phone = models.CharField(
_('Phone (Emergency Contact)'),
max_length=255,
validators=[phone_regex],
blank=True
)
transcript = models.FileField(
_('Transcript'),
max_length=255,
null=True,
blank=True
)
created = models.DateTimeField(
_('Date Created'),
auto_now=True,
null=True,
blank=True
)
modified = models.DateTimeField(
_('Date Modified'),
auto_now_add=True,
null=False,
blank=False
)
def __str__(self):
return self.firstName
def age(self):
import datetime
return int((datetime.date.today() - self.dateOfBirth).days / 365.25)
def upload_location(instance, filename):
return "%s/%s" % (instance.id, filename)
class Student(models.Model):
import datetime
YEAR_CHOICES = []
for r in range(1980, (datetime.datetime.now().year+1)):
YEAR_CHOICES.append((r, r))
studentID = models.CharField(
_('Student ID'),
max_length=30,
blank=True,
default=''
)
registration = models.ForeignKey(
Registration
)
student_photo = models.ImageField(
_('Picture'),
max_length=255,
null=False,
blank=False,
upload_to=upload_location
)
previous_school = models.CharField(
_('Previous School Attended'),
max_length=255,
null=False,
blank=False
)
previous_school_address = models.CharField(
_('Previous School Address'),
max_length=255,
null=False,
blank=False
)
last_year_attendance = models.IntegerField(
_('Last Year of Attendance'),
choices=YEAR_CHOICES,
default=datetime.datetime.now().year
)
level = models.CharField(
_('Level'),
max_length=255,
choices=LEVEL_CHOICES,
default=None,
null=False,
blank=False
)
enrollment_status = models.CharField(
_('Enrollment Status'),
max_length=255,
choices=ENROLLMENT_CHOICES,
default=None,
null=False,
blank=False
)
enrollment_Date = models.DateField(
_('Enrollment Date'),
max_length=30,
null=False,
blank=False
)
created = models.DateTimeField(
_('Date Created'),
auto_now=True,
null=True,
blank=True
)
modified = models.DateTimeField(
_('Date Modified'),
auto_now_add=True,
null=False,
blank=False
)
class Meta:
ordering = ["-id"]
def __str__(self):
return self.studentID
def save(self, force_insert=False, force_update=False):
if self.studentID == "":
existing_studentIDs = Student.objects.all().order_by('-studentID')
if existing_studentIDs.count() > 0:
new_code = int(existing_studentIDs[0].studentID[1:]) + 1
else:
new_code = 0
self.studentID = 'S%03d' % new_code
super(Student, self).save(force_insert, force_update)
class UserLog(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
student = models.ForeignKey(
Student,
null=True,
blank=True,
default=None
)
staff = models.ForeignKey(
Staff,
null=True,
blank=True,
default=None
)
parent = models.ForeignKey(
Parent,
null=True,
blank=True,
default=None
)
You should query students and alluser this way:
students = Student.objects.filter(registration__in=registration)
alluser = UserLog.objects.filter(student__in=students)
registration and students are multiple objects i.e. queryset. Therefore when querying a foreign key field with multiple objects, we use __in.

Categories

Resources