Форум сайта python.su
Есть модель:
class UserAbout(models.Model): user = models.ForeignKey(User, related_name='UserAboutToUser', unique=True) about = models.TextField(max_length = 1000, blank=True, null=True, unique=False) family = models.TextField(max_length = 140, blank=True, null=True, unique=False) why = models.CharField(max_length = 140, blank=True, null=True, unique=False) trust = models.TextField(max_length = 140, blank=True, null=True, unique=False) hobby = models.CharField(max_length = 1000, blank=True, null=True, unique=False) job = models.TextField(max_length = 140, blank=True, null=True, unique=False) politic = models.CharField(max_length = 140, blank=True, null=True, unique=False) book = models.TextField(max_length = 140, blank=True, null=True, unique=False) film = models.TextField(max_length = 140, blank=True, null=True, unique=False) music = models.TextField(max_length = 140, blank=True, null=True, unique=False) class UserAboutForm(ModelForm): class Meta: model = UserAbout exclude = ('user',)
def UserProfileEdit(request, *offset): if request.user.is_authenticated() and request.user.username == offset[0]: if request.method == 'POST': if offset[1] == 'person': form = UserAboutForm(request.POST) mainProfile = User.objects.get(username = offset[0]) if form.is_valid(): addProfile = UserAbout(user = mainProfile, about = request.POST.get('about'), family = request.POST.get('family'), why = request.POST.get('why'), trust = request.POST.get('trust'), hobby = request.POST.get('hobby'), job = request.POST.get('job'), politic = request.POST.get('politic'), book = request.POST.get('book'), film = request.POST.get('film'), music = request.POST.get('music'),) addProfile.save() return HttpResponseRedirect("/profile/print/%s/%s/" %(offset[0], offset[1]))
Офлайн
Ой-ой. Что это Вы делаете, какой страшный код.
1. Почему Вы не используете формы для валидации и сохранения данных?
form.save()
about = request.POST.get('about'),
You may have noticed Django database objects use the same save() method for creating and changing objects. Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save(), Django follows this algorithm:
If the object's primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes a SELECT query to determine whether a record with the given primary key already exists.
If the record with the given primary key does already exist, Django executes an UPDATE query.
If the object's primary key attribute is not set, or if it's set but a record doesn't exist, Django executes an INSERT.
The one gotcha here is that you should be careful not to specify a primary-key value explicitly when saving new objects, if you cannot guarantee the primary-key value is unused. For more on this nuance, see Explicitly specifying auto-primary-key values above and Forcing an INSERT or UPDATE below.
Отредактировано FishHook (Дек. 3, 2012 18:24:53)
Офлайн
FishHookЯ использовал формы весьма успешно, пока не столкнулся с exclude.
Ой-ой. Что это Вы делаете, какой страшный код.1. Почему Вы не используете формы?2. Откуда фреймворк должен знать, что Вам нужно апдейтить, а не инсертить?
If the record with the given primary key does already exist, Django executes an UPDATE query.Запись то с таким первичным ключом уже существует, в том-то и загвоздка, что Django не выполняет UPDATE.
form = UserAboutForm(request.POST) mainProfile = User.objects.get(username = offset[0]) if form.is_valid(): addProfile = UserAbout(user = mainProfile, form) addProfile.save()
Офлайн
Самый тупой и простой вариант
..... user = models.ForeignKey(User, related_name='UserAboutToUser', unique=True, null=True, bkank=true) ..... if form.is_valid(): mainProfile = User.objects.get(username = offset[0]) addProfile =form.save() addProfile.user=mainProfile addProfile.save()
Офлайн
FishHookЯ попробовал в лоб, для простоты. На что postgre выругался:
Самый тупой и простой вариант
2012-12-04 03:51:51 VLAT ERROR: duplicate key value violates unique constraint "users_userabout_user_id_key" 2012-12-04 03:51:51 VLAT DETAIL: Key (user_id)=(1) already exists. 2012-12-04 03:51:51 VLAT STATEMENT: UPDATE "users_userabout" SET "user_id" = 1, "about" = '1', "family" = '2', "why" = '3', "trust" = '4', "hobby" = '5', "job" = '6', "politic" = '7', "book" = '8', "film" = '9', "music" = '10' WHERE "users_userabout"."id" = 2 2012-12-04 03:51:51 VLAT ERROR: current transaction is aborted, commands ignored until end of transaction block 2012-12-04 03:51:51 VLAT STATEMENT: SHOW default_transaction_isolation
Отредактировано SorrowFuck (Дек. 3, 2012 19:03:12)
Офлайн
addProfile = form.save(commit=False)
Офлайн
reclosedevТо же самое выходит:
?
2012-12-04 05:00:57 VLAT ERROR: duplicate key value violates unique constraint "users_userabout_user_id_key" 2012-12-04 05:00:57 VLAT DETAIL: Key (user_id)=(1) already exists. 2012-12-04 05:00:57 VLAT STATEMENT: INSERT INTO "users_userabout" ("user_id", "about", "family", "why", "trust", "hobby", "job", "politic", "book", "film", "music") VALUES (1, '1', '2', '3', '4', '5', '6', '7', '8', '9', '10') RETURNING "users_userabout"."id"
Офлайн
Так если он существует, значит надо сначала его найти
... try: addProfile = UserAbout.objects.get(user=request.user) except UserAbout.DoesNotExist: addProfile = None form = UserAboutForm(request.POST, instance=addProfile) if form.is_valid(): addProfile = form.save(commit=False) addProfile.user = request.user addProfile.save() ...
request.user.username == offset[0]
Отредактировано reclosedev (Дек. 4, 2012 07:18:45)
Офлайн
reclosedevДа, действительно, так работает, спасибо.
Так если он существует, значит надо сначала его найти
Офлайн