def get_merge_form(user, other): chats = get_private_chats(user, other) choices = [] for ch in chats: choices.append(ch.get_choice()) class MergePrivateChatsForm(forms.Form): new_title = forms.CharField(max_length=255, initial="{0} <--> {1}".format(user.username, other.username)) new_topic = forms.CharField(max_length=255, required=False) chats = forms.TypedMultipleChoiceField(coerce=lambda x: Chat.objects.get(id=x), choices=choices) def clean_chats(self): clean_data = self.cleaned_data['chats'] if len(clean_data) < 2: raise forms.ValidationError('Please, select at least 2 chats') return clean_data return MergePrivateChatsForm
def profile(request, username): private_chats = None chats_without_user = None private_chat_form = None open_new_chat_form = False context = RequestContext(request) logged_user = request.user user = get_object_or_404(User, username=username) user_profile = UserProfile.objects.filter(user=user)[0] if request.user != user: chats_without_user = get_chats_without_user(request.user, user) private_chats = get_private_chats(request.user, user) if request.method != 'POST': new_private_chat = Chat() new_private_chat.name = "{0} <-> {1}".format(request.user.username, user.username) private_chat_form = PrivateChatForm(instance=new_private_chat) else: private_chat_form = PrivateChatForm(request.POST) if private_chat_form.is_valid(): new_private_chat = private_chat_form.save() new_private_chat.participants.add(request.user) new_private_chat.participants.add(user) new_private_chat.save() return HttpResponseRedirect(reverse('chat:chat', kwargs={'chat_id': new_private_chat.id})) else: open_new_chat_form = True return render_to_response("django_project/profile.html", {"self": logged_user == user, "get_user": user, "user_profile": user_profile, "private_chats": private_chats, "private_chat_form": private_chat_form, "open_new_chat_form": open_new_chat_form, "chats_without_user": chats_without_user}, context)