Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
token authentication POST method
I have an api(DRF based) for my project which needs token based authentication for POST Method and in my project I use REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } As for frontend , for every POST method I am using const config = { headers: { "Content-type": "application/json", Authorization : `JWT ${localStorage.getItem("access")}`, Accept: "application/json", }, }; axios.post( `...................................`, config, ) This is working fine for POST Methods in my project.But it will expire in 5 min.Which token should I use for authentication. -
Django Login form Using AD
I'm trying to create an App which has a log in page where user should be authenticated using azure AD. Basically the App has a log in form where user puts his id and password from ad and django should check with ad and allow him in or not. Later on ofc would like to add permission depending on AD group. So far I searched a lot on the internet and found nothing. Could you guys help with some example or link to documentation what I could use. -
Django login form not keeping input after bad submit
I have a login form and if a user enters an invalid username or password, the page refreshes and removes the Username value they entered. I would like it so that the username field doesn't empty on failed submit. views.py def login_page(request): if request.user.is_authenticated: return redirect('dashboard:dashboard') elif request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard:dashboard') else: messages.info(request, 'Username or Password is invalid.') return render(request, 'main/login.html', {}) login.html: <form id="login-form" action="" method="post" role="form"> {% csrf_token %} <div class="form-group"> <input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value=""> </div> <div class="form-group"> <input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password"> </div> <div class="form-group"> <div class="row"> <div class="col-sm-6 center" style="border-radius: 16px;"> <input type="submit" name="login-submit" id="login-submit" tabindex="5" class="form-control btn btn-login" value="Login"> </div> </div> </div> <div class="form-group"> <div class="row"> <div class="col-lg-12"> <div class="center"> <a href="#" tabindex="5" class="forgot-password">Forgot Password?</a> </div> </div> </div> </div> </form> -
how avoid reinitilizing AXES_COOLOFF_TIME when user tray again during lock out time?
I integrated django-axes to my django application whith the following configs : 15 minutes (as timedelta object for minutes) AXES_COOLOFF_TIME = timedelta(minutes=15) Here are the spteps : 1 - I tried 3 time to connect with correct user and wrongs password --> result : the user is locked out (i see the messsage : user locked out during 15 min) 2 - after 10 minutes, i try again to connect with correct user and password --> result : the user is locked out again and have to wait another 15 minites ! in total i lost 25 mintes waiting instead to 15 ! Is there a way to avoid this probleme ? I want to use the first duration and not account the second Appreciate you help -
django data migrations: how to manage INSERT with related models?
I have a Django project with Postgresql database. I want to run data migration when deploying my app to create account, etc... I try to write a data migrations files but have an error "NOT NULL constraint failed" on second insert below I understand the error: as RunSQL is atomic, when I try to run the second INSERT INTO auth_user, SELECT id FROM auth_user WHERE username='user' return null because RunSQL is atomic so user is not yet created and commit in database. Django documentation about data migration mentionned possibility to run non-atomic transactions but not sure it is the best way to proceed migration_files class Migration(migrations.Migration): dependencies = [ ('parameters', '0010_auto_20200327_1508'), ] operations = [ migrations.RunSQL( sql = [ "INSERT INTO auth_user (password,is_superuser,username,first_name,last_name,email,is_staff,is_active,date_joined) VALUES ('pbkdf2_sha256$150000$qe1v2XJKkik8$jF6iFZ+4GpK1JzBdHzRG0H3XsYY+YphYpxc9Cbgg+7Y=',False,'user','','','jerome.le-carrou@u-bordeaux.fr',False,True,'2020-10-15 10:00');", "INSERT INTO auth_user_user_permissions (user_id,permission_id) VALUES ((SELECT id FROM auth_user WHERE username='user'),(SELECT id FROM auth_permission WHERE codename='can_manage_randomization'));", ] ) ] -
django: pasting text of a pdf file gathered using choose file button in a textarea
I am new to Django and currently, I am working on a website where I have a choose file button and a text area. I want that when I click on the choose file button and choose a .txt or .pdf file, all the text from that file has to show in the textarea alongside it. here is the GUI here is the look but this thing is not working. I have tried a lot of solutions but nothing is working for me. I am using python version 3.8 and Django version 3.1 here is the models.py class text_file(models.Model): txtfile = models.FileField() text = models.TextField(max_length=10000) date = models.DateTimeField(auto_now=True) #data saved into db def __str__(self): return self.text_file here is my fileactions.py file. It's a model form. from PyPDF2 import pdf, PdfFileReader from django import forms from .models import text_file class filetext(forms.ModelForm): text_file = forms.FileField(required=True, widget=forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'text_file...', 'id': 'input1' } )) class Meta: model = text_file #import text_file model from home models.py fields = {'text_file'} def save(self, commit=True): filename = input('file') textfile = open(filename, 'rb') pdf_reader = pdf.PdfFileReader(textfile) page_numbers = pdf_reader.getNumPages() title = pdf_reader.documentInfo.title print("the document title is: ", title) print("there are total: ", page_numbers, "pages") count = … -
Django CMS Dashboard Customize by React.js
Hope you all are doing well ! I would like to convert my Django CMS Dashboard Customize by React.js .. Is that possible to use React.js only in Dashboard, not in the whole Front-end -
Django Report Builder - invalid literal for int() with base 10: ''
I am trying to use Django-Report Builder to create reports. But after creating the reports when I click on XLSX or CSV it gives me this error Request Method: GET Request URL: https://something.pythonanywhere.com/report_builder/api/report/1/download_file/xlsx/ Django Version: 2.2.7 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: /home/something/.virtualenvs/quizdemo/lib/python3.8/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 972 Python Executable: /usr/local/bin/uwsgi Python Version: 3.8.0 Python Path: ['/var/www', '.', '', '/var/www', '/home/hrtest/.virtualenvs/quizdemo/lib/python38.zip', '/home/hrtest/.virtualenvs/quizdemo/lib/python3.8', '/home/hrtest/.virtualenvs/quizdemo/lib/python3.8/lib-dynload', '/usr/lib/python3.8', '/home/hrtest/.virtualenvs/quizdemo/lib/python3.8/site-packages', '/home/hrtest/quizdemo'] Server time: Tue, 20 Oct 2020 11:49:17 +0000 This works perfectly in my local host. I am not sure what is missing. When I click on Preview I get javascript error: polyfills-es2015.js:1 GET https://something.pythonanywhere.com/report_builder/api/report/1/generate/ 500 (Internal Server Error) This seems to be specific problem to pythonanywhere. How could I get more details for this issue ? Any help from users who have used Report Builder -
Restricted access for different user categories in Django app
I am somewhat new to the django framework so excuse me if this question isn't appropriate. I have a django app wherein I am using the built-in User model which django provides to store user details. I need to give access to some features of the app only to paid users. I have another Activation model which stores a boolean flag which indicates whether this is a free user or a paid user. This Activation model has user as a foreign key. Now, I need access to this boolean flag in my template context. The approach which I don't think is appropriate is to add this in every context response where it would be needed. But this would be a bad design perhaps and would require significant changes in existing code. Is there a way to access this without have to send this flag in every context where it's needed, similar to the way user model is accessed to check if user is authenticated ? Perhaps the most appropriate way would have been to create a custom user model by sub-classing the django user model and add this flag in there. But since this would require significant changes in design, … -
how to pass object id from template to a view upon the click of a button in django
so I am trying to make a website that has different products and that has an add to cart button. what I am trying to do is pass the object id from the template to django view so I can make an instance of the product in the database. but I don't know how. I tried ajax but I don't really know how to use it so it didn't work and I don't know the problem. here is my ajax code : homepage/index.html : {% for product in products %} <li> <figure> <a class="aa-product-img" href="{% url 'home:productdetail' product.id%}"><img src="{{ product.picture.url }}" alt="polo shirt img"></a> #This is the button <a class="aa-add-card-btn" href="#" data-objid="{{product.pk}}"><span class="fa fa-shopping-cart"></span>Add To Cart</a> <figcaption> <h4 class="aa-product-title"><a href="{% url 'home:productdetail' product.id %}">{{product.title}}</a></h4> <span class="aa-product-price">${{product.price}}</span><span class="aa-product-price"></span> </figcaption> </figure> </li> {% endfor %} <script type="text/javascript"> $('.aa-add-card-btn').click(function(){ var objid; objid = $(this).attr("data-objid"); $.ajax( { type:"POST", url: "{% url 'home:cart' %}", data:{ product_id: objid }, success: function( data ) }) }); homepage/views.py : def addtocart(request): if request.method == 'POST': print('it worked') current_user = request.user user = User.objects.get(id=current_user.id) product_id = request.POST['product_id'] cartproduct = CartModel(products=product_id, customer=user) cartproduct.save() ctx = { 'products': CartModel.objects.all() } return render(request, 'homepage/index.html', ctx) homepage/models.py : class CartModel(models.Model): customer = models.ForeignKey(User, … -
Celery periodic task for deleting expired database objects running successfully but the object is not getting deleted from the database
I have a periodic task to delete expired files which is running every 1 minute(just for testing), the task is showing successful everytime, but the object is not getting deleted from the database. I used print to see whether it is getting the correct data and it seems it does receive everything correctly. I also restarted it few times, still doesn't work. Is is because of any time difference problem? But if that's the case, will the task run successfully? @periodic_task(run_every=crontab(minute='*/1')) def delete_expired_files(): files= Post.objects.all() # Iterate through them for file in files: expiry_date = file.created_date + datetime.timedelta(seconds=30) # for testing print(expiry_date) if file.created_date > expiry_date: file.delete() return "Deleted the file at {}".format(timezone.now()) Is there something wrong with the code regarding the expiry date? Thanks -
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I try to install mysqlclient in fedora
I want to connect mysql to my django project I try to install mysqlclient and got error I use Linux fedora os and I want to connect myq to my django project for which I have to install mysqlclient I run command pip install mysqlclient ,then try pip install mysqlclient==1.3.12 I also try that commands in virtual env and got the same error I installed python-devel by using yum install python3-devel inside root after that i try for installing libmysqlclient by using yum install mysql-devel i gives me an error and then I try dnf install libmysqlclient-dev got the error after running pip install mysqlclient i got this error shown in image in the link below -
How can I erase and send a field that is not null from json in django rest framework?
I am going to send an image to the django rest framework. When we try not to put the data in the image field, we are now putting it in the following way: { .... "image": null } By the way, I would like to send you a field called image, instead of sending null like this, delete it from Json as follows. { .... } How can you do this? Here's my code. serializers.py class customRegisterSerializer (serializers.ModelSerializer) : email = serializers.CharField(allow_null=True) password = serializers.CharField(max_length=999, min_length=8, write_only=True, allow_null=True) username = serializers.CharField(allow_null=True) image = serializers.ImageField(allow_null=True, use_url=True) class Meta : model = User fields = ['email', 'username', 'image', 'password'] def validate (self, attrs) : email = attrs.get('email', '') password = attrs.get('password', '') username = attrs.get('username', '') error = {} if email is None and password is None and username is None : error['message'] = '이메일, 비밀번호 그리고 이름을 입력해주세요' raise serializers.ValidationError(error) if email is None and password is None : error['message'] = '이메일과 비밀번호를 입력해주세요.' raise serializers.ValidationError(error) if email is None and username is None : error['message'] = '이메일과 이름 입력해주세요.' raise serializers.ValidationError(error) if email is None and password is None : error['message'] = '이메일과 비밀번호를 입력해주세요.' raise serializers.ValidationError(error) if email is … -
Error: Reverse for 'coach_profile' with arguments '('',)' not found. 1 pattern(s) tried: - Unable to resolve
I am trying to create a directory-based website. I have created a list view, and I have created a detail view that populates when you click on an item in the list view. But, I also want to use a similar detail view to serve the user's own data to them on a profile page. I have done this by creating a queryset in a separate view. The problem is, is that I don't seem to be able to configure the urls and template tag correctly to get it to show on the page, and I am just getting the following error. Reverse for 'coach_profile' with arguments '('',)' not found. 1 pattern(s) tried: ['coach/(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/profile$'] I am trying to access this page from a link on the navbar called your profile. The template tags I am trying are as follows href="{% 'coach_profile' %}">Your Coach Profile</a> href="{% 'coach_profile' coach.id %}">Your Coach Profile</a> href="{% 'coach_profile' coach.pk %}">Your Coach Profile</a> ulrs.py from django.urls import path from .views import CoachListView, CoachDetailView, CoachProfileView urlpatterns = [ path('', CoachListView.as_view(), name='coach_list'), path('<uuid:pk>', CoachDetailView.as_view(), name='coach_detail'), path('<uuid:pk>/profile/', CoachProfileView.as_view(), name='coach_profile'), ] views.py from django.views.generic import ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin from .models import Profile class CoachListView(LoginRequiredMixin, ListView): model = Profile … -
How can i publish a django project on IIS?
Question is quite simple. I've a project that i wrote in PyCharm IDE. This is going to be my first deployment and i couldn't find any source to follow. I am grateful for any help or tip. -
ModuleNotFoundError: No module named 'app.wsgi'; 'app' is not a package
sudo systemctl status gunicorn outputs ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2020-10-19 15:24:42 UTC; 19h ago TriggeredBy: ● gunicorn.socket Main PID: 133699 (code=exited, status=3) Oct 19 15:24:42 django-domainname gunicorn[133714]: return _bootstrap._gcd_import(name[level:], package, level) Oct 19 15:24:42 django-domainname gunicorn[133714]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Oct 19 15:24:42 django-domainname gunicorn[133714]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Oct 19 15:24:42 django-domainname gunicorn[133714]: File "<frozen importlib._bootstrap>", line 970, in _find_and_load_unlocked Oct 19 15:24:42 django-domainname gunicorn[133714]: ModuleNotFoundError: No module named 'app.wsgi'; 'app' is not a package Oct 19 15:24:42 django-domainname gunicorn[133714]: [2020-10-19 15:24:42 +0000] [133714] [INFO] Worker exiting (pid: 133714) Oct 19 15:24:42 django-domainname gunicorn[133699]: [2020-10-19 15:24:42 +0000] [133699] [INFO] Shutting down: Master Oct 19 15:24:42 django-domainname gunicorn[133699]: [2020-10-19 15:24:42 +0000] [133699] [INFO] Reason: Worker failed to boot. Oct 19 15:24:42 django-domainname systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED Oct 19 15:24:42 django-domainname systemd[1]: gunicorn.service: Failed with result 'exit-code'. My directories are as follows My-Project - ./ - ../ - .DS_Store - .git/ - .idea/ - .travis.yml - Dockerfile - docker-compose.yml - env/ ( ./ ../ bin/ include/ lib/ lib64 -> lib/ pyvenv.cfg share/) - requirements.txt - My-Project/ ( ./ … -
How to compare created time to 24 hours to delete a file in django/python?
I am trying to implement a function where a file will be deleted after 24 hours and I have celery doing this task. I don't want to have another field as an expiration_date in the model, so is there a way to compare the created time to 24 hours and delete the file? if file.created_time > 24 hours (# here how can I change this to check with real time): file.delete() and created_time is a DateTimeField(). Thanks -
Django Rest Frawork: Where to put logic that modifies database?
I have a Django project in which I use the Django Rest Framework (DRF). As I'll share this project with another person, I wanted to make sure the person that is going to pull it for the very first time would not encounter any issue, so this is what I did to simulate this situation: Cloning the repo in a new project folder on my computer. Creation of the DB through the commands makemigrations and migrate. django.db.utils.OperationalError: no such table: bar_reference error message pops up. sqlite3.db file not created. Impossible to run the rest of the code to try it out. Here is the file containing the code causing problem, in one of my view: from rest_framework import viewsets from rest_framework import permissions from rest_framework.permissions import AllowAny from ..models.reference import Reference from ..models.stock import Stock from ..models.bar import Bar from ..serializers.reference import * class MenuViewSet(viewsets.ModelViewSet): permission_classes = [AllowAny] references = Reference.objects.all() bars = Bar.objects.all() for reference in references: ref_id = reference.id quantity = 0 for bar in bars: bar_id = bar.id stocks = Stock.objects.filter(ref_id=ref_id, bar=bar_id) for stock in stocks: quantity += stock.stock if quantity == 0: reference.availability = "outofstock" reference.save() else: reference.availability = "available" reference.save() queryset = Reference.objects.order_by('id') serializer_class = … -
Django,saving multiple objects with foreign key, using forms
I have this three model's with relationship 1-N: class Pavimento(models.Model): name = models.CharField("Name", max_length=200) def __str__(self): return self.name class Intervencao(models.Model): ...... class Pavimentacao(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='IntervencaoObjects', on_delete=models.CASCADE) pavimento = models.ForeignKey(Pavimento, on_delete=models.CASCADE, verbose_name="Pavimento") date = models.DateField(blank=True, null=True, verbose_name="Date") def __str__(self, ): return str(self.intervencao) With forms i want to add more than one Pavimentacao to my Intervencao. i already put this working but only save 1 each time , and i want to add 2 or 3 simultaneous. Forms class TabletForm2(forms.ModelForm): class Meta: model=Intervencao fields = __all__ class TabletFormPavimentos(forms.ModelForm): class Meta: model=Pavimentacao fields = __all__ My view @login_required(login_url='/login') def project_detail_chefe(request, pk): instance = Intervencao.objects.get(id=pk) form = TabletForm2(request.POST or None, instance=instance) form2 = TabletFormPavimentacao(request.POST or None, instance=instance) if request.method == "POST": if form.is_valid() and form2.is_valid(): instance_form1 = form.save() instance_form2 = form2.save(commit=False) instance_form2.intervencao = instance_form1 instance_form2.save() return redirect('index') else: form = TabletForm2(request.POST) form2 = TabletFormPavimentacao(request.POST) context = { 'form':form, 'form2':form2, } return render(request, 'tablet/info_chefes.html', context) -
Django is not creating a new user
The problem is in my views.py file, there I am using 2 views at the same time. First one created I and it's solving signup problem and the second is ready django view from django.contrib.auth.views.LoginView, and Login is working successfully, but registration is not ;( that was after adding login view. Here is the code from django.shortcuts import render, redirect from django.contrib.auth import views as auth_views from django.contrib.auth.forms import AuthenticationForm from django.contrib import messages from django.http import HttpResponse from .forms import UserRegisterForm from django.contrib.auth.decorators import login_required def index(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if 'signup' in request.POST: if form.is_valid(): form.supervalid() form.save() username = form.clened_data.get('username') messages.success(request, f'Dear {username} you have been created a new account!') return redirect('main') elif 'login' in request.POST: log_view = auth_views.LoginView.as_view(template_name='main/index.html') log_view(request) else: form = UserRegisterForm() formlog = AuthenticationForm(request) return render(request, 'main/index.html', {'form': form, 'formlog': formlog}) I see the signup form generated in my HTML, but its not working -
Store migration hacks/modifications separately to migration files
I have a Django project with around 1000 migration files. And that project is distributed to 30 vendors and their production servers. The problem is that manage.py migrate takes around 15 minutes on each server. But, in general, it could be solved using "Migrations zero" (combine all migrations per app with squashmigrations or something) to reduce amount of code and files. And that's probably the best way to go. But, that 30 projects are not always migrated/synced with newest migration files (now its very expensive to keep them always updated). So last applied migration on particular project can be very old, so we can not just squash to one single init migration for all projects. And one of the ideas we came up with is not to share migration files at all. But make manage.py makemigrations on each project's server. But, the next problem is that migrations can store some "hacks/modifications") So, to remove migration files from git, we nevertheless have to store hacks somewhere. So, is there a practice to store "hacks/modifications" of migrations separately from migration files? Maybe, somehow in models? Thx for advices -
Not able to perform post request django+react
#accounts.models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from words import models as word_models # Create your models here.class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) last_visited_word = models.ForeignKey(word_models.Word, default=4760, on_delete = models.CASCADE) def create_user_profile(sender, instance, created, **kwargs): if created: profile, created = UserProfile.objects.get_or_create(user=instance) post_save.connect(create_user_profile, sender=User) #words/models.py from django.db import models from django.conf import settings # Create your models here. class Word(models.Model): word = models.TextField(blank=True, null=True) meaning = models.TextField(blank=True, null=True) #accounts/serializers.py: from rest_framework import serializers from .models import UserProfile class UserSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = '__all__' #accounts/views.py: @api_view(['POST']) #@authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def userprofile_create_view(request, *args, **kwargs): user_id = request.data.get('user') try: instance = UserProfile.objects.get(user_id=user_id) except UserProfile.DoesNotExist: instance=None serializer = UserSerializer(instance, data=request.data) if serializer.is_valid(raise_exception=True): # create or update data serializer.save() return Response(serializer.data) So Basically I have to update the last_visited_word of the user when the user visits that particular id. I am not able to do the "post" method to update last_visited_word. Api calling is done using axios. I am using React as my frontend. -
How can i get publish files from PyCharm IDE?
i've a project that has been completed but i want to try it on my local IIS to see if it works fine. I've never deployed any website except some ASP.Net projects that written in visual studio. I've used PyCharm since i've been working on django, i got no idea how to get files for publishing. In visual studio you just right click > publish and you get the folder but how can i do this in PyCharm? -
Passing user input to external link in django
I am trying to create a simple django site that would send information to another site with the requests.post function (I'm assuming that this is a correct method, but maybe there is a better way). So far I have a simple .html file created using bootstrap <div class="form-group"> <label for="exampleFormControlInput1">text_thing</label> <input type="text" class="form-control" placeholder="text_thing" name="text_thing"> </div> <div class="form-group"> <label for="exampleFormControlInput1">number_thing</label> <input type="number" class="form-control" placeholder="number_thing" name="number_thing"> </div> <button type="submit" class="btn btn-secondary">Send data</button> </form> and my views.py from django.shortcuts import render, redirect import requests def my_view(requests): if requests.method == "POST": text_thing= request.GET.get('text_thing') number_thing= request.GET.get('number_thing') post_data = {'text_thing', 'number_thing'} if text_thing is not None: response = requests.post('https://example.com', data=post_data) content = reponse.content return redirect('home') else: return redirect('home') else: return render(requests, 'my_view.html', {}) I want the site to do following: render itself allowing the user to input something in both fields, and after pressing the button to be redirected to another site - in this case 'home' and for the input to get sent to example.com. With this moment the page renders correctly but after pressing the button nothing happens and external site receives no data. -
DRF - Custom Field Json
I created a custom field in my model for calculating "statistics" Models.py class Risk(models.Model): [...] def risk_completion(self): total = self.controls.count() total_completion = self.controls.filter(status="NP").count() response_data = { 'total_controls': total, 'total_controls_planned': total_completion } return JsonResponse(response_data) serializers.py class RiskSerializer(serializers.ModelSerializer): [...] total = serializers.CharField(source='risk_completion') class Meta: model = models.Risk fields = ( [...] 'total', ) But DRF returns : "total": "<JsonResponse status_code=200, \"application/json\">" If i'm not using JsonResponse() DRF returns a string : "total": "{'total_controls': 3, 'total_controls_planned': 2}" How can I return "real" Json ? Thanks,