Django RelatedObjectDoesNotExist After Upgrade to 2.2 - python

I've recently upgraded one of my Django projects from 1.9.6 to 2.2 and in doing so I'm getting a strange error around a specific ForeignKey relation.
models.py
class MyObject1(models.Model):
myobject2 = models.ForeignKey(MyObject2, on_delete = models.CASCADE)
views.py
def my_view(request, id):
try:
my_object = MyObject1.objects.get(id = id)
except:
# do some stuff
else:
print (my_object.myobject2)
result
RelatedObjectDoesNotExist
MyObject1 has no myobject2
at line print (my_object.myobject2)
I have confirmed via the Django shell that the instance in question does have a valid myobject2 and I don't get that error when performing the same actions in the shell.
All other ForeignKey relations in the application work as expected except for this one.
This is quite puzzling and all help is appreciated. Thanks!

Related

CustomUser matching query does not exist. ERROR( DJANGO)

when i save the form in template.
The error says:
CustomUser matching query does not exist.
Line number 104: teacher=CustomUser.objects.get(id=teachers_id)
Model.py
class Subjects(models.Model):
id=models.AutoField(primary_key=True)
subject_name=models.CharField(max_length=255)
course_id=models.ForeignKey(Courses,on_delete=models.CASCADE,default=1)
teachers_id=models.ForeignKey(CustomUser,on_delete=models.CASCADE)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now_add=True)
objects=models.Manager()
views.py
def add_subject_save(request):
if request.method!="POST":
return HttpResponse("<h2>Method Not Allowed</h2>")
else:
subject_name=request.POST.get("subject_name")
course_id=request.POST.get("course")
course=Courses.objects.get(id=course_id)
teachers_id=request.POST.get("teacher")
teacher=CustomUser.objects.get(id=teachers_id)
try:
subject=Subjects(subject_name=subject_name,course_id=course,teachers_id=teacher)
subject.save()
messages.success(request,"Successfully Added Subject")
return HttpResponseRedirect("add_subject")
except:
messages.error(request,"Failed to Add Subject")
return HttpResponseRedirec("add_subject")
I dont know how to solve this error.
To my understanding, the Django ForeignKeys stores an object, not an integer like you would use in SQL. I think teacher=CustomUser.objects.get(id=teachers_id) is the bandit here. I would try teacher=CustomUser.objects.filter(teacher_id__exact=teacher_id).get(). This will give you an error however if there are more than one objects in the CustomUser model with the same teacher object. There is more information about this on the Django Docs.

django states attibuteError although attribute is assigned

I have a Payment Django model that has a CheckNumber attribute that I seem to be facing issues with, at least whilst mentioning the attribute in the str method. It works just fine on the admin page when creating a Payment instance, but as soon as I called it in the method it gave me the following error message:
Request URL: http://127.0.0.1:8000/admin/Vendor/payment/
Django Version: 3.0.7
Exception Type: AttributeError
Exception Value:
'Payment' object has no attribute 'CheckNumber'
Exception Location: /Users/beepboop/PycharmProjects/novatory/Vendor/models.py in __str__, line 72
Python Executable: /Users/beepboop/Environments/novatory/bin/python3.7
Python Version: 3.7.2
this is my code:
class Payment(models.Model):
Vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
Amount = models.DecimalField(decimal_places=2, blank=True, max_digits=8)
PaymentDate = models.DateField(name="Payment date", help_text="Day of payment")
CheckNumber = models.IntegerField(name="Check number", help_text="If payment wasn't made with check, leave blank", blank=True)
def __str__(self):
return f"Vendor: {self.Vendor.Name} | Amount: {prettyPrintCurrency(self.Amount)} | Checknumber: {self.CheckNumber}"
I would absolutely love any comments/suggestions about the cause of the error
In my opinion, you have introduced CheckNumber field in the Payment models recently with no migration. make sure you run the migration then you can do that using the following command.
python manage.py migrate
This will create a new field in the Payment table. Hopefully, this will resolve your issue.
please clean the database and then run the migration command.
To clean the database you need to write the following command(Don't run this command in production):
python manage.py flush
After the cleaning, you can make an initial migration using the following command:
python manage.py makemigrations
and then migrate those changes to the database table:
python manage.py migrate
So it turns out that when you pass a name value in a model field, it changes the name of the field with it, I personally thought that it would change the name when displayed in the Django admin. My fix was to just remove the name value and migrate, that fixed it for me.

Django - How to fix model with id field

I unintentionally created a model with a field "id" and did the migration. The model at first looked like this:
class VsSession(models.Model):
id = models.TextField(default="123"),
state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10)
Afterwards I rename the field to vs_session:
class VsSession(models.Model):
vs_session = models.TextField(default="123"),
state = models.CharField(choices=VSSESSION_CHOICES, default='dead', max_length=10)
Now whenever I try to use the model e.g., like this:
def get(self, request):
try:
sessionid = uuid.uuid4()
new_session = VsSession(vs_session=sessionid, state="active")
new_session.save()
return Response({'success': 'true', 'vssession': sessionid})
except Exception as e:
print(str(e))
return Response({'success': 'false'})
I get this error:
VsSession() got an unexpected keyword argument 'vs_session'
Can anybody please tell me what I did wrong and how to fix this.
Thank you very much!
So I have no idea why this is working now, but I fixed it. What I did is
Removed vs_session variable from the model
Added created_at = models.DateTimeField(auto_now_add=True) to the model
makemigration and migrate
Run code/stop code
Add vs_session variable to model
makemigration an migrate
Everything is fine :)
Did you try running python manage.py makemigrations? After running this you should see a message telling you the field was renamed. To actually apply the migration to your database you can run python manage.py migrate

Mongonaut error: 'Mongonaut does not work with models which have fields beginning with id_'

I'm using the following combination of packages to work with mongodb in Django.
django-mongonaut==0.2.21
mongoengine==0.8.7
pymongo==2.7.2
I'm trying to set up my admin panel using mongonaut.
These are my two simple mongo engine models:
class Question(Document):
text = StringField(max_length=200)
def __str__(self):
return self.text
class QuestionList(Document):
title = StringField(max_length=200)
questions = EmbeddedDocumentField('Question') #This is the problem
def __str__(self):
return self.title
Currently I'm not using a ListField yet. When I try to add a new QuestionList using Mongonaut the following error pops up:
KeyError at /mongonaut/api/QuestionList/add/
u'Mongonaut does not work with models which have fields beginning with id_'
The mongonaut docs state that it allows working with EmbeddedDocumentFields. Still I get this error. What am I doing wrong?
Regards,
Swen

Django error with ForeignKey reference

I have a question about a ForeignKey reference problem with django.
This is a part of my code :
App ticketsTrader
class TicketsTrader(models.Model):
seller = models.ForeignKey(User, related_name='ticketsTrader_seller')
buyer = models.ForeignKey(User, related_name='ticketsTrader_buyer')
inscription = models.ForeignKey(Inscription)
transactionCode = models.CharField(max_length=30,blank=False,null=False)
...
App inscription
class Event(models.Model):
title = models.CharField(max_length=75)
description = models.TextField()
...
class Inscription(models.Model):
event = models.ForeignKey(Event)
packs = models.ManyToManyField(PackChoise)
user = models.ForeignKey(User)
...
def __unicode__(self):
return self.event.__unicode__() + u': ' + self.user.__unicode__()
def inscriptionKey(self):
return str(self.pk) + '_' + str(self.valkey)
But when I try to acces to the "Add Ticket Trader" interface in my Grapelli admin, I get an error message :
User matching query does not exist.
Python27\lib\site-packages\django\db\models\query.py in get, line 366
In template \grappelli\templates\admin\includes\fieldset.html, error
at line 19
What I want to get is : in the "inscription" column of my ticketTrader table get the value of the unique id (pk) of my "Inscription" table.
Or the value of the "inscriptionKey" but I don't think it's possible.
Django Version:1.4 / Python Version: 2.7.3 / South last version
Thanks for your help :)
I can only guess:
TicketsTrader has a foreign key to Inscription, which has a foreign key to User and uses that key in its __unicode__() method.
Now, I don't know Grapelli but the default admin app would render a dropdown for Inscription-s on the Add TicketsTrader page. If some of the Inscription-s pointed to non-existing User-s, then their __unicode__() method would fail with the error message you specified.
The question is how could some User-s be missing and Inscription-s pointing to them not. Well, if you use e.g. MySQL+MyISAM, foreign keys are not enforced there so all sorts of weird things can happen.
I think because you don't have any User... try create User before create Ticket Trader

Categories

Resources