1
import json
from django.http import Http404, HttpResponse
from main.models import Personnages
def store_data(request):
    if request.is_ajax() and request.POST:
        value = request.POST.get("value")
        toChange = request.POST.get("name")
        id = request.POST.get("id") #A IMPORTER
        perso = Personnages.objects.get(id=id)
        perso.toChange = value
        perso.save()
        return HttpResponse(value+toChange)
    else :
        raise Http404

I have written this code but the problem is that this part does not work:

perso.toChange = value

This doesn't seem to work. I figure it is because I extract the string from JSON instead of the field.

This is the model for reference:

class Personnages(models.Model):
    id = models.AutoField(primary_key=True)
    Joueur = models.ForeignKey(User, on_delete=models.PROTECT)
    Nom = models.CharField(max_length=40)
    Age = models.CharField(max_length=20)
    Genre = models.CharField(max_length=30)
    Date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution")
    Image = models.ImageField(upload_to="imagePerso/", null=True)
3
  • Can you show your Personnages model? Commented Dec 11, 2018 at 21:30
  • in order to improve the quality of the question and to make it more useful to others, I'd recommend editing the title to something like: "changing model attribute by string in Django" Commented Dec 11, 2018 at 22:16
  • It's done. I have difficulties to put word on my problem ^^ Thank you for the proposal. Commented Dec 11, 2018 at 22:18

1 Answer 1

4

I guess you are trying to set an attribute based on a dynamic value. You are looking for setattr method (https://docs.python.org/3/library/functions.html#setattr)

In your case, replace

perso.toChange = value

with

setattr(perso, toChange, value)

On an unrelated note, when writing python code, it is advisable to follow Python coding standards as stated in PEP-8. For instance, toChange should be to_change and so on.

Sign up to request clarification or add additional context in comments.

3 Comments

Almost there, but setattr is a standalone function, not a method: setattr(perso, toChange, value).
It works, thank you ! I will notice about the coding standards, i am learning so it's hard to write a working code. I will wait for a standard code ^^
If you use a python friendly IDE or editor (Sublime, PyCharm...), it will automatically check for PEP-8 compliance... and it really makes it easier to ask for help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.