I am making a change to a record in a sqlite3 database using Django, and the save() function doesn't seem to work.
I am able to save changes using the graphical admin app however.
Here is the code to the specific model I'm trying to do the save in:
def pickup(self,item):
room_items = Item.objects.filter(roomID = self.room.id)
items = [ri.item_name for ri in room_items]
if item in items:
i = Item.objects.filter(item_name = item)
i[0].roomID = 0
i[0].playerID = self.id
i[0].save()
return f'{self.name} picked up the {item} from {self.room}'
else:
return f"{item} is not in the room. can't pick it up."
the pickup function is in a class called Player. I am updating an Item record. Any solutions?
Here is the entire models file for those who want more context:
from django.db import models
import string,random
class Room(models.Model):
### Field Columns in Room Table ###
room_name = models.CharField(max_length = 64)
description = models.CharField(max_length=500, default=f"No Room description'" )
up = models.CharField(max_length = 64, default="")
down = models.CharField(max_length = 64, default="")
left = models.CharField(max_length = 64, default="")
right = models.CharField(max_length = 64, default="")
def items(self):
items = Item.objects.filter(roomID = self.id)
return [i.item_name for i in items]
def __str__(self):
return self.room_name
class Player(models.Model):
# uuid = models.UUIDField(default=uuid.uuid4, unique=True)
HP = models.IntegerField(default=10)
name = models.CharField(max_length=64, default=f"Room {random.choice(string.ascii_letters)}")#attempting to generate a random room name using ascii_letters from string library and random.choice()
room = models.ForeignKey(Room, on_delete=models.CASCADE, null=True)
# inventory = models.ForeignKey(Inventory)
def inventory(self):
inventory = Item.objects.filter(playerID = self.room.id)
return [i.item_name for i in inventory]
def pickup(self,item):
print(self.room.id)
room_items = Item.objects.filter(roomID = self.room.id)
items = [ri.item_name for ri in room_items]
if item in items:
i = Item.objects.filter(item_name = item)
i[0].roomID = 0
i[0].playerID = self.id
i[0].save()
i[0].persist()
return f'{self.name} picked up the {item} from {self.room}'
else:
return f"{item} is not in the room. can't pick it up."
def drop_item(self,item):
pass
def initialize(self,start):
# start = input(f"{self.name}, you are outside the PyTower. It is a 10 story tower. There is a treasure chest on the top floor. Do you have what it takes to reach the top??? type 'y' to enter Pytower: ")
if start == 'y':
self.room = Room.objects.get(room_name = "Foyer")
print(f"{self.name}, you have now entered the {self.room.room_name}")
return f"{self.name}, you have now entered the {self.room.room_name}"
else:
print(f"{self.name}, when you're ready for Pytower, you may enter!")
return f"{self.name}, when you're ready for Pytower, you may enter!"
print(self.room.description)
print('in room: ', self.room, 'up:',self.room.up, 'down:',self.room.down, 'left:',self.room.left, 'right:', self.room.right)
return self.room
def move(self,way=""):
# print(self.room[way]) #causes error, Room object not subscriptable
# print(way)
# if self.room[way]:
# pass
if way == 'up':
if not self.room.up:
print('you cannot go that way. no rooms there...')
return 'you cannot go that way. no rooms there...'
else:
self.room = Room.objects.get(room_name = self.room.up)
print('in room: ', self.room, 'up:',self.room.up, 'down:',self.room.down, 'left:',self.room.left, 'right:', self.room.right)
return self.room
elif way == 'down':
if not self.room.down:
print('you cannot go that way. no rooms there...')
return 'you cannot go that way. no rooms there...'
else:
self.room = Room.objects.get(room_name = self.room.down)
print('in room: ', self.room, 'up:',self.room.up, 'down:',self.room.down, 'left:',self.room.left, 'right:', self.room.right)
return self.room
elif way == 'left':
if not self.room.left:
print('you cannot go that way. no rooms there...')
return 'you cannot go that way. no rooms there...'
else:
self.room = Room.objects.get(room_name = self.room.left)
print('in room-', self.room, 'up-',self.room.up, 'down-',self.room.down, 'left-',self.room.left, 'right-', self.room.right)
return self.room
elif way == 'right':
if not self.room.right:
print('you cannot go that way. no rooms there...')
return 'you cannot go that way. no rooms there...'
else:
self.room = Room.objects.get(room_name = self.room.right)
print('in room: ', self.room, 'up:',self.room.up, 'down:',self.room.down, 'left:',self.room.left, 'right:', self.room.right)
return self.room
else:
print('you have entered an invalid direction')
return 'you have entered an invalid direction'
def __str__(self):
if not self.room:
return f"{self.name} is outside."
else:
return f"{self.name} in {self.room}"
class Item(models.Model):
item_name = models.CharField(max_length=64)
strength = models.IntegerField(default=5)
item_type = models.CharField(max_length=64,default="weapon")
# playerID = models.ForeignKey(Player, on_delete=models.CASCADE, null=True)
# roomID = models.ForeignKey(Room, on_delete=models.CASCADE, null=True)
playerID = models.IntegerField(blank=True,null=True)
roomID = models.IntegerField(default=1,null=True,blank=True)
def persist(self):
self.save()
def __str__(self):
return self.item_name
To understand why your model isn't saving, you must first understand how querysets are evaluated. Essentially, anytime you iterate over them, or slice them, they will hit the database, however there are caveats to this.
Consider the following abstract example:
def MyModel(models.Model):
column = models.IntegerField()
>>> MyModel.objects.create(column=1)
<MyModel: MyModel object (1)>
>>> queryset = MyModel.objects.all()
Slicing:
>>> queryset[0].column = 2
>>> queryset[0].save()
>>> queryset[0].column
1
In the example above, I took a slice, eg. queryset[0], which hits the database, then immediately took a second slice, to try and save the changes made, which hits the database a second time. Finally, I took a third slice, which hits the database again.
Since the first slice is not the same object as the object I called .save() on, the changes are not reflected in the database. To fix this, simply save a reference to the slice as a variable:
>>> instance = queryset[0]
>>> instance.column = 2
>>> instance.save()
>>> instance.column
2
In this example, I only hit the database twice: once when I call instance = queryset[0], and a second time in instance.save().
Here is the optimized version of your code:
def pickup(self, item_name):
items = Item.objects.filter(item_name=item_name, roomID=self.room.id)
if items:
item = items[0]
item.roomID = 0
item.playerID = self.id
item.save()
return 'message'
return 'no item'
I am making a retweet function and it works quite smooth but I am not able to retweet my own tweets , I am able to retweet other users tweets but not mine
. It shows that matching query doesn't exist.
Here is the tweets models
class TweetManager(models.Manager):
def retweet(self,user,parent_obj):
if parent_obj.parent:
obj_parent = parent_obj.parent
else:
obj_parent = parent_obj
qs = self.get_queryset().filter(user = user, parent = obj_parent)
if qs.exists():
return None
obj = self.model(
user = user,
parent = obj_parent,
content = parent_obj.content
)
obj.save()
return obj
class Tweet(models.Model):
parent = models.ForeignKey("self",blank = True,null = True)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
content = models.CharField(max_length = 130)
time = models.DateTimeField(auto_now_add = True)
objects = TweetManager()
def __str__(self):
return self.content
class Meta:
ordering = ['content']
Here's the views.py
class Retweet(View):
def get(self, request, pk, *args, **kwargs):
tweet = get_object_or_404(Tweet, pk=pk)
if request.user.is_authenticated:
new_tweet = Tweet.objects.retweet(request.user, tweet)
return HttpResponseRedirect("/")
return HttpResponseRedirect(tweet.get_absolute_url())
How to add field value manually from view?
model.py
class Connect(models.Model):
username = models.CharField(max_length=255)
password = models.CharField(max_length=255,null=True, blank=True)
conft = models.TextField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return unicode(self.username)
form.py
class NacmForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput,required = False)
conft = forms.Textarea()
class Meta:
model = Connect
fields = ['username', 'password','conft']
labels = {'conft':_('Config'),}
view.py
class config_static(View):
def post(self, request, *args, **kwargs):
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
userValue = formm['username'].value()
passValue = formm['password'].value()
if ipform.is_valid() and formm.is_valid():
simpanForm = formm.save()
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
vendor = form.cleaned_data.get('vendor')
.......
//some code//
.......
simpanIp = form.save(commit=False)
simpanIp.connect_id = simpanForm
simpanIp.save()
simpanForm.save()
.........
//some code//
i want to set "conft" value manually, maybe like
configuration = "some config"
conft = configuration
i already tried
configuration = "some config"
NacmForm(initial={'conft': configuration })
or
formm.fields['conft'].initial = configuration
or
formm = NacmForm(request.POST, initial={"conft": configuration })
when i use that code above, the value isnt save to database, then i tried this
Connect.objects.create(conft=configuration)
its save to database but not in same row
formm.cleaned_data returns dictionary. So, you can add/update/remove keys manually. initial={} This is for rendering purposes (Which adds in html forms initial values value="something"). As far as i understand you want to modify incoming data when HTTP POST is made. Try like this.
class config_static(View):
def post(self, request, *args, **kwargs):
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
userValue = formm['username'].value()
passValue = formm['password'].value()
if ipform.is_valid() and formm.is_valid():
# If both form is valid
formm.cleaned_data['conft'] = '<new_value>' # + this is added logic
simpanForm = formm.save()
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
vendor = form.cleaned_data.get('vendor')
.......
//some code//
.......
simpanIp = form.save(commit=False)
simpanIp.connect_id = simpanForm
simpanIp.save()
simpanForm.save()
.........
//some code//
forms.py
class NacmForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput,required = False)
# conft = forms.Textarea()
class Meta:
model = Connect
fields = ['username', 'password','conft']
labels = {'conft':_('Config'),}
Hope, it helps you.
so after googling, i just add this line
class config_static(View):
def post(self, request, *args, **kwargs):
formm = NacmForm(request.POST or None)
ipform = IpFormset(request.POST)
userValue = formm['username'].value()
passValue = formm['password'].value()
if ipform.is_valid() and formm.is_valid():
# If both form is valid
simpanForm = formm.save()
for form in ipform:
ipaddr = form.cleaned_data.get('ipaddr')
vendor = form.cleaned_data.get('vendor')
.......
//some code//
.......
simpanForm.conft = "ip route configuration" # i add this
simpanIp = form.save(commit=False)
simpanIp.connect_id = simpanForm
simpanIp.save()
simpanForm.save()
.........
//some code//
I have 3 models
Do I need to change connections in the models, and make the key field not an id, but a name?
class Category(models.Model):
name = models.CharField(max_length=150, unique=True)
description = models.CharField(max_length=250)
class Company(models.Model):
name = models.CharField(max_length=150, unique=True)
country = models.CharField(max_length=50)
class Motobike(models.Model):
name = models.CharField(max_length=150)
company = models.ForeignKey('Company', on_delete=models.CASCADE)
category = models.ForeignKey('Category', on_delete=models.CASCADE)
And tests:
def test_category(setup):
client = Client()
category_id = Category.objects.get(name='Мотоциклы').id
response = client.get(f'/categories/{category_id}/')
assert response.status_code == 200
response_data = json.loads(response.content.decode('utf-8'))
assert len(response_data) == 2
assert response_data[1]['name'] == 'Ninja Turbo'
assert response_data[1]['vendor'] == 'Kawasaki'
assert response_data[1]['category'] == 'Мотоциклы'
assert response_data[1]['description'] == ''
response = client.get(f'/categories/25/')
assert response.status_code == 404
In view I do so:
class CategoryView(DetailView):
model = Category
template_name = 'bikes_site/categories_detail.html'
def get_context_data(self, id, **kwargs):
context = get_object_or_404(self.model, id)
context['motobikes'] = Motobike.objects.filter(category_id=id).all()
return context
I get an error:
get_context_data() missing 1 required positional argument: 'id'
The function signature for get_context_data is wrong it should be
def get_context_data(self, **kwargs):
//todo
your detail view should like this
class CategoryView(DetailView):
model = Category
template_name = 'bikes_site/categories_detail.html'
pk_url_kwarg = "id"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
category = self.get_object()
context['motobikes'] = Motobike.objects.filter(category_id=category.pk)
return context
My "Event" object has a "Name" field. There is the possibility that the name is wrong, so a user may suggest a new name. That name gets put into the event's "suggestedN" list. However, I don't want there to be duplicates of one suggestion in that list. I felt like this was a straightforward problem, but for some reason am not finding much success.
Here is how my view currently looks:
#login_required
def suggestName(request):
name = request.POST['name'].strip()
event_id = request.POST['event_id']
try:
e = Event.objects.get(event_id = event_id)
except Event.DoesNotExist:
e = customEvent.objects.get(event_id = event_id)
if name in e.suggestedN.all():
pass
else:
(some code)
Is my if name in e.suggestedN.all() statement wrong?
Here's a brief view of my Event's model:
class Event(models.Model):
def __unicode__(self):
return self.title
suggestedN = models.ManyToManyField('suggestedName', blank = 'TRUE', null = 'TRUE')
class suggestedName(models.Model):
def __unicode__(self):
return self.name
name = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
votes = models.IntegerField(default = 0)
You should use the name attribute on m2m not the m2m itself to compare
#login_required
def suggestName(request):
name = request.POST['name'].strip()
event_id = request.POST['event_id']
try:
e = Event.objects.get(event_id = event_id)
except Event.DoesNotExist:
e = customEvent.objects.get(event_id = event_id)
if name in e.suggestedN.values_list('name', flat=True):
pass
else:
(some code)