Django unique_together custom error message - python

I'm trying to create a custom error message for unique_together:
class Recipient(models.Model):
mobile = PhoneNumberField()
mobile2 = PhoneNumberField()
class Meta:
unique_together = (("mobile", "mobile2"),)
def unique_error_message(self, model_class, unique_check):
print("I don't seem to run")
if model_class == type(self) and unique_check == ('mobile', 'mobile2'):
return 'My custom error message'
else:
return super(Recipient, self).unique_error_message(model_class, unique_check)
However my error message is not running instead I get:
Duplicate entry '+4473192817212-+4478192817210' for key 'mobile'\"
why?

The error message you pasted seems more like an error caused by a unique constraint on the mobile field of the recipient table, indicating that at one point you had unique=True at one point. Check for this constraint in the database or if this is just in development, delete the database and syncdb again.

Related

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

Django RelatedObjectDoesNotExist After Upgrade to 2.2

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!

How to set 'email' in author_id inherit mail.thread on Odoo

I inherit mail.thread on Odoo12
_inherit = ['mail.thread', 'mail.activity.mixin']
and publish a message:
msg = 'message test.'
self.message_post(body=msg, email_from='Otro <otro#otro.com>', subtype='mail.mt_comment',)
image
These messages are added with the administrator user. How can I place the mail of the external user who sends the message in the field author_id?
Try out self.message_post(body=msg, email_from='Otro <otro#otro.com>', subtype='mail.mt_comment', author_id=False)
author_id=False will tell Odoo to use the email_from as author.
I've found that "trick" here:
author_id = kwargs.get('author_id')
if author_id is None: # keep False values
author_id = self.env['mail.message']._get_default_author().id
The semi-valuable comment # keep False values solved the big secret ;-)
With None the user of the current environment would be used.

Error with "__str__ returned non-string (type int)"

I have a problem with a Django Project.
I'll be direct. I am connecting my Django admin to a database that I have on a server, the problem is that when accessing the models in the browser, throws the following error:
TypeError at /admin/crm/asentamiento/78967/
__str__ returned non-string (type int)
Request Method: GET
Request URL: http://127.0.0.1:8080/admin/crm/asentamiento/78967/
Django Version: 1.8
Exception Type: TypeError
Exception Value:
__str__ returned non-string (type int)
Exception Location: C:\Spameando\crm_denue2\myvenv\lib\site-packages\django\utils\encoding.py in force_text, line 90
Python Executable: C:\Spameando\crm_denue2\myvenv\Scripts\python3.exe
Python Version: 3.4.4
And the code for my model is this:
class Asentamiento(models.Model):
id_asentamiento = models.AutoField(primary_key=True)
nom_asentamiento = models.CharField(max_length=150)
tipo_centro = models.CharField(max_length=100)
nom_centro = models.CharField(max_length=100)
num_local = models.CharField(max_length=20)
tipo_asentamiento_id_tipo_asent = models.ForeignKey('TipoAsentamiento', db_column='tipo_asentamiento_id_tipo_asent')
codigo_postal_id_codpostal = models.ForeignKey('CodigoPostal', db_column='codigo_postal_id_codpostal')
localidad_id_localidad = models.ForeignKey('Localidad', db_column='localidad_id_localidad')
class Meta:
managed = False
db_table = 'asentamiento'
def __str__(self):
return self.nom_asentamiento
I have no idea what the problem is, since I have done the model many times and I always throw the same error, in all other tables and models I have no problem.
The error occurs when I click on some value of my model to see in a window the selected value.
Just put str() here:
def __str__(self):
return str(self.nom_asentamiento)
Maybe this will help, I had a similar problem recently:
def __str__(self):
return 'Asentamiento: {} {} {} {} {} '.format(self.id_asentamiento, self.nom_asentamiento, self.tipo_centro, self.nom_centro, self.num_local)
I hope it works for you, regards
Here you're not getting this error because of the return type of Asentamiento model. It return CharField not an Integer type (as mentioned in the error message.)
The error may be due to the return type of TipoAsentamiento, CodigoPostal or the Localidad model. Since these models have One to Many Relationship with the Asentamiento model.
If you're not sure about the return types of these models, then you need to add __str__() method in the model and return a CharField or any other non integer field.
For example, If you want to return a PositiveIntegerField,
def __str__(self):
return str(self.positive_integer_field_name)
# here, you need to use the str() method to convert the return type into a string.
If you want to return a Non Integer Field,
def __str__(self):
return self.non_integer_field_name
I had default code created by VSCode, which was returning pk.
Changed
def __str__(self):
return self.pk
to:
def __str__(self):
return self.title # title is the field from my model
For me its because i returned object instead of string, so i changed
def __str__(self):
return self.user
to
def __str__(self):
return self.user.email
I just face this issue and I think if we put str() before self.field will not solve our problem. even tho I commented out that __str__ method after running the migrations command I'm facing this issue again and again.
issue cause:-
the main issue is with your other model that is having any relationship to this model and in that model, you are doing as usual __str__ method!
you should check put str() before that model that is having Manytoone relation ship with your model!
I use which field we want to represent in our admin pannel.
Put that field in a string representation, in my case:
def__str__:
return self.user.username
This issue could arise if one of the foreign key fields returns models.IntegerField(). This happened to me, and I had to be sure that the foreign keys also returned models.Charfield() types.

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