ValueError: Cannot assign "(<User: testuser>,)": "Message.user" must be a "User" instance - python-3.x

Trying to create a simple real-time chat application with multiple chat rooms. When trying to add new message in the message model, getting ValueError.
The model.py:
class Message(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
room = models.ForeignKey(Room, on_delete=models.CASCADE)
body = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
The view.py:
def addMessage(request):
user = User.objects.get(username = request.POST['username']),
room = Room.objects.get(id = request.POST['room_id']),
message = request.POST['message'],
Message.objects.create(
user = user,
room = room,
body = message
)
return HttpResponse("Message Sent Sucessfully!")
I have seen many similar questions, but none of the solutions worked.
Thanks.

Since you added trailing commas in the following lines
user = User.objects.get(username = request.POST['username']),
room = Room.objects.get(id = request.POST['room_id']),
message = request.POST['message'],
These variables become a python tuple and result in the error since the values are wrong types.
Remove those trailing commas should fix the issue.
user = User.objects.get(username = request.POST['username'])
room = Room.objects.get(id = request.POST['room_id'])
message = request.POST['message']

Related

Not able to add a project ID/name to a list in Jira/Groovy/Scriptrunner

The following question I present is the following: I'm doing a code that is been tested in the Scriptrunner console and tried into Jira. What I want to reach is the following: I have an issue in any project, at any moment a workflow transition allows me to copy the current issue and all the linked issues in a new project.
The cfProjectPicker is a custom field Project Picker that allows me to select a project.
What I'm having trouble right now on the code is the following:
1- projectKey is returning null valor but projectPicker is returning the correct project selected in the custom field.
2- createNewIssue is not allowing me to recognize the "params" field as a mutable issue, and it is a mutable (if I replace with newIssue it does take it)
3- the list "issuesCopied" is not allowing me to issuesCopied.id.toString() but I'm guessing is giving error due to the point 2.
Any help regarding the matter would be much appreciated because I'm not understanding what I'm doing wrong at moment.
def issueMgr = ComponentAccessor.getIssueManager();
def issueTypeSchemeManager = ComponentAccessor.getIssueTypeSchemeManager()
def customFieldManager = ComponentAccessor.getCustomFieldManager();
def projectMgr = ComponentAccessor.getProjectManager();
def groupManager = ComponentAccessor.getGroupManager();
def issueFactory = ComponentAccessor.getIssueFactory();
IssueLinkManager issueLinkManager = ComponentAccessor.getIssueLinkManager();
def cfProjectPicker = customFieldManager.getCustomFieldObjectByName("Seleccionar Proyecto") //cf project picker
def issue = issueMgr.getIssueObject("MART1-1")
ApplicationUser user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser() //User Admin
ApplicationUser currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()
def currentIssue = issueFactory.getIssue()
//def issue = issueMgr.getIssueObject()
def newIssue = issueFactory.getIssue()
def exit = false
// Array list of the issues created to save them
List<String> issuesCopied = new ArrayList<>();
// ***** CREATE ISSUE *****
if (issuesCopied.isEmpty()){
String projectPicker = issue.getCustomFieldValue(cfProjectPicker)
log.error("Gengar")
log.error(projectPicker)
def projectKey = projectMgr.getProjectObjByKey(projectPicker)
log.error(projectKey)
newIssue.setProjectObject(projectKey)
newIssue.setIssueType(issue.getIssueType())
newIssue.setSummary(issue.getSummary())
newIssue.setDescription(issue.getDescription())
newIssue.setReporter(currentUser)
def params = ["issue":newIssue]
log.error(params)
def createNewIssue = issueMgr.createIssueObject(user,params);
issuesCopied.add(createNewIssue.id.toString())
}

Sum felds with with sqlalchemy and marshmallow

I'm using the python's framework pyramid, sqlalchemy for the data and marshmallow to serialize.
I'm want to send a sum of value to the client
I have Challenge and player whom use this challenge, each actions of the player is an event and each events has a duration.
For each challenge, i want to send the sum's duration for each player and also send this value only for one player. I try to use hybrid attribute or pre_dump function but i didn't succeeded
First method : with hybrid attribute
__tablename__ = "Challenge"
id = Column(Integer, primary_key=True)
name = Column(String(255), unique=True, nullable=False)
description = Column(TEXT(length=65535))
map_url = Column(String(255))
end_date = Column(DateTime(timezone=False))
alone_only = Column(Integer)
level = Column(String(255))
scalling = Column(Integer)
draft = Column(Boolean, server_default=text("0"))
admin_id = Column(Integer, ForeignKey("User.id"))
admin = relationship("User", backref="challenge_manager")
event_sum_user = relationship("Events")```
#hybrid_property
def event_sum(self):
return sum(Events.duration for Events in self.event_sum_user)
But i have sum for all user, not by user or for one user
Second method :with pre_dump method
id = fields.Int()
name = fields.Str()
description = fields.Str()
end_date = fields.DateTime()
alone_only = fields.Int()
level = fields.Str()
scalling = fields.Int()
draft = fields.Bool()
admin = fields.Nested(UserSchema)
admin_id = fields.Int(load_only=True)
event_sum = fields.Int(dump_only=True)
#pre_dump
def get_eventsum(self,data, **kwargs):
data["event_sum"] = DBSession.query(func.sum(Events.duration)).filter(Events.challenge_id==data["id"]).filter(Events.user_id==1).first()
return data```
With this method, i've have an error TypeError: 'Challenge' object is not subscriptable'
The purpose of this is to send with each challenge the total duration realise by a user or for each user on the challenge : id_user and total duration.
Thanks for your help
Marilyn

how do I add to a JSON field in Django

AIM --- I am using Django to make a mock trading website for a project. I am running into problems trying to keep track of stocks a person owns. The problem is if someone buys 4 TSLA stocks and then 4 again it should be treated as 8 stocks of TSLA out of which they can sell 7 if they want. (BTW, I am using postgresql)
Problem --- Turns out this is very difficult to do, I couldn't find anything that would help me keep track of the stocks a person owns. so, I read and read and finally turned to JSON fields. but, I am running into an issue there are well when I do
u.stocks_owned = {f"{ticker}" : f"{stocks_bought_here}"}
u.save()
it works, it adds a key-value pair with the ticker and a number, but I don't know how to create a new row using this, or if someone already owns some stock of a company then how do I add to that??
Conclusion --- I don't need to to write code for me, just point me in the right direction I will figure it out myself!
User Model -
class User_Info(models.Model):
user = models.OneToOneField(User, null=True, related_name='info', on_delete = models.CASCADE)
username = models.CharField(max_length=200, null=True)
name = models.CharField(max_length=200, null=True, blank = True)
phone = models.CharField(max_length=200, null=True, blank = True)
email = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
balance = models.FloatField(null = True)
virtual_money_bought = models.BigIntegerField(null=True)
stocks_owned = models.JSONField(null=True)
def __str__(self):
return self.username
the view I am using --
if new_balance >= 0 and balance_pre_trade >= latestPrice * stocks_bought_here :
Trade.objects.create(
ticker = ticker,
stocks_bought = stocks_bought_here,
action = "Bought",
trader = user.info,
price_trade_at = latestPrice,
company_name = companyName,
balance_of_trader_after_purchase= new_balance
)
u = User_Info.objects.get(user = user)
u.balance = new_balance
u.stocks_owned = {f"{ticker}" : f"{stocks_bought_here}"}
u.save()
messages.success(request, f"You bought {stocks_bought_here} from {companyName} at a price of {latestPrice} ")
return redirect ("user")
else:
messages.error(request, "You dont have enough money in your account")

PostGIS geography does not support the "~=" function/operator

I am trying to save point field in the database via update_or_create method but it is giving me this error.
My function to save data:
for city in cities_data:
obj, created = models.City.objects.update_or_create(
name = city["name"],
country = city["country"],
state = city["state"],
point = Point(
float(city["longitude"]),
float(city["latitude"])
),
radius = city["radius"],
is_curated = city["is_curated"],
is_metro_city = city["is_metro_city"]
)
obj.save()
Model:
class City(models.Model):
name = models.CharField(max_length=50)
country = models.CharField(max_length=50)
state = models.CharField(max_length=50)
point = gis_models.PointField(geography=True, null=True)
is_metro_city = models.BooleanField(default=False)
is_curated = models.BooleanField(default=False)
radius = models.IntegerField(null=True)
when I try to run this I get this error:
ValueError: PostGIS geography does not support the "~=" function/operator.
I want to know why I am getting this error, I did not find any useful information related to this. Thanks in Advance.
If you want to use this you can use it like this:
obj, created = models.City.objects.update_or_create(
**city_data,
defaults={'point': Point(
float(city["longitude"]),
float(city["latitude"])
)}
)
I do not know why it does not work that way, but I made it work this way, if you find it out why it does not work you can improve the answer.
I have the same error and the problem was that I have a unique together constraint in model's class Meta eg:
class Meta:
unique_together = 'name', 'geom'
After deleting it, the error disappears although you must check by yourself if you need such constraint.

Django Haystack return related insances

Hi I´m using django with haystack search. I have one model for Events. Thats the model I'm doing the search on. I have a second model to count the hits/views for the Events. I wan't to return the number of hits for every event additional to the search results.
my view:
def event_search(request):
if request.method == 'POST':
query = str(request.POST['search'])
events = SearchQuerySet().auto_query(query).models(Event).order_by('date')
return render_to_response('event_search.html', {"events": events}, context_instance=RequestContext(request))
else:
return render_to_response('event_search.html', context_instance=RequestContext(request))
my models:
class Event(models.Model):
name = models.CharField(max_length = 70)
date = models.DateTimeField()
description = models.TextField()
active = models.BooleanField(default=True, editable=False)
featured = models.BooleanField(default=False)
class EventHitcount(models.Model):
hit = models.ForeignKey(Event)
ip = models.CharField(max_length=40)
session = models.CharField(max_length=40)
created = models.DateTimeField(default=datetime.datetime.now())
By giving the ForeignKey field a related name it can call and count the related objects.
class Foo(models.Model):
fk = models.ForeignKey(Event,related_name='foofk')
some more fields...
In the template:
{{ foo.foofk.count }}

Resources