Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django use related_name in all query set
So I have model class Category(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='upload') created_at = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=128) updated_at = models.DateTimeField(auto_now=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) I want to make response look like { title: '', children: { title: '', chidlred:{ title: '', children } } } Im trying to use this in my views: @api_view(('GET',)) @permission_classes((AllowAny,)) def get_all_cats(req): queryset = Category.objects.all() for item in queryset: item['sub'] = queryset.children But it gives me enter image description here I understand I can use single query like Category.objects.first() and them use .children on it But i need all categories Thanks you so much! -
Python or JavaScript POST HTTP 1.1 error 404
I use python and JavaScript to make the website that you can register by linking with SQl. However, when I use the command flask run, there is POST /register HTTP 1.1 error. I can't register on the website and the website shows "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again." I would like to know that is the py or js is incorrect or something with the server. Thank you in advance I would like to know that is the py or js is incorrect or something with the server. -
How to filter by request user in Django-filter model
Im using django-filter package and i want to know how can i pass queryset in ModelChoiceFilter of request user in my django-filter model filters.py class PresenceDateFilter(django_filters.FilterSet): presence_info__counter_presence = ModelChoiceFilter(queryset=CounterParty.objects.filter(counter_user=request.user)) #request.user is not working work_date = DateTimeFromToRangeFilter( widget=django_filters.widgets.RangeWidget( attrs={'type': 'date', 'class': 'form-control'}, )) class Meta: model = PresenceDetailInfo fields = ('presence_info__counter_presence', 'work_date', ) -
Django e-commerce
I am having trouble saving and viewing the order history of my shopping cart after checkout. I am saving the order in the checkout session and trying to view it with the order history view. @login_required def order_history(request): orders = Order.objects.filter(user=request.user).order_by('-date_ordered') return render(request, 'order_history.html', {'orders': orders}) stripe.api_key = settings.STRIPE_SECRET_KEY YOUR_DOMAIN = @csrf_exempt def create_checkout_session(request): if request.method == 'POST': try: cart_items = CartItem.objects.filter(user=request.user) line_items = [] total_price = 0 for item in cart_items: line_items.append({ 'price': item.item.stripe_price_id, 'quantity': item.quantity, }) # Create checkout session with line items and total price checkout_session = stripe.checkout.Session.create( line_items=line_items, mode='payment', success_url=YOUR_DOMAIN + '/success', cancel_url=YOUR_DOMAIN + '/cancel.html', automatic_tax={'enabled': True}, ) # Create a new Order object and save it to the database order = Order.objects.create( user=request.user, total_price=sum(item.item.price * item.quantity for item in cart_items), ) order.checkout_session_id = checkout_session.id order.save() # Associate each cart item with the order instance for item in cart_items: item.order = order item.save() # Clear the user's cart cart_items.delete() except Exception as e: return HttpResponse(str(e)) return redirect(checkout_session.url) else: return HttpResponse("This page is only accessible via POST requests") @csrf_exempt def complete_hook(request): # Retrieve the request body and the Stripe signature header payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: # Verify the Stripe signature event … -
Access multilevel v-model from HTML (Nested element)
The HTML code is here <section id="id_element"> <label for="x1">x1 </label> <input type="text" id="x1" v-model="product.xs.x1" ></input> <label for="x2">x2</label> <input type="text" id="x2" v-model="product.xs.x2" ></input> </section> here is my javascript : <script> const create = Vue.createApp({ delimiters: ['[[', ']]'], data() { return { product : { xs: { "x1" : "alpha", "x2" : "beta" }, ys: { "y1": "one", "y2": "two", "y3": "three", "y4": "four" } } } } create.mount("#id_element"); </script> I want to access a nested element, but i had the error of Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'x1') how to access a multi level vue.js element from HTML. I tried both : v-model="product.xs["x1"]" and v-model="product.xs.x1" So please anyone having a solution for this, it will be great. -
Access Variable in Python fstring in Django Template
I have created a variable called item using a fstring which is a combination of other variables: item = f'{item_id}_{flavour}_{strength}' Is there a way to now access the variables within this fstring to display them in a django template. At the moment all I have done is pull the whole item string into the template: <td class="py-3"> <p class="my-0"><strong>{{ item.product.name }}</strong></p> <p class="my-0"><strong>Flavour: </strong>{% if item.product.has_flavours %}{{ item.item|upper }}{% else %}N/A{% endif %} </p> Which renders in the html template as: front end display I want to access the flavour variable in the string and the strength variable in the string and display them in the template against the Flavour and Strength headings. -
Are there alternative fields for many-to-many?
I have this code in models.py (left only key fields for easier perception): class Album(models.Model): title = models.CharField(max_length=200) class Song(models.Model): album = models.ManyToManyField('Album', through='AlbumSong') class AlbumSong(models.Model): album = models.ForeignKey('Album') song = models.ForeignKey('Song') serial_number = models.CharField(max_length=3) And admin.py: class SongsInline(admin.TabularInline): model = AlbumSong fields = ['song', 'serial_number'] extra = 0 @admin.register(Album) class AlbumAdmin(admin.ModelAdmin): inlines = [SongsInline] Using TabularInline means that the songs will be shown in the dropdown lists. Imagine that there are 100 songs in one album. Then there will be 100 dropdown lists. And it's hard to edit. What are alternative more convenient field types? It is important that on the edit album page I should be able to create and delete songs. -
Django - Jsonfield get all values in an array without specifing an index
Assume we have a queryset of the MyJsonModel. How can I get all json key-values for lets say key "a" in my jsonfield "a_json"? Lets assume each a_json include a list with multiple dictionaries which all have the "a" key. How can I then get those "a" key-values in an Array via .values_list or values? So that it results in tuples where each of them represent an object and the "a" key of its "a_json" field. I couldn't find anything online related to this question. I am using django=4.1 and postgres -
Use Azure active directory as custom authentication backend for Django
I have Django running on an Azure web app and have followed this example to integrate the MSAL library so that users from the active directory can log in. This works to the extent that I can use @ms_identity_web.login_required in my views to limit access to specific pages only to sign in AD users. However, what I'm really aiming to do is to use the active directory as a custom authentication backend so that all django users come from the the active directory and that they can all access the admin section. My employer unfortunately does not allow me to use any third-party packages such as django_microsoft_auth though. For now I've read the Django documentation, particularly the section on Customizing authentication in Django. That clarifies some things, but I am still at a loss about how to proceed as every answer I've found so far recommends using some third-party package to implement some custom backend. If anyone can point me in the right direction in terms of how to proceed I would appreciate it immensely. -
How to make pagination with first page and last page Django
I have some code with template helpers bcs im using django-filter but it doesnt rly matter I want to make better pagination in my template with first and last page and with '...' when you`re going trough pagination How can i do this? template.html {% load templatehelpers %} {% if page_obj.has_other_pages %} <nav aria-label="paginator"> <ul class="pagination"> {% if page_obj.has_previous %} <li class="page-item "> <a class="page-link" href="{% relative_url page_obj.previous_page_number 'page' request.GET.urlencode %}"> <i class="bi bi-arrow-left"></i> </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link"> <i class="bi bi-arrow-left"></i> </a> </li> {% endif %} {% for i in page_obj.paginator.page_range %} {% if page_obj.number == i %} <li class="page-item active" aria-current="page"> <a class="page-link" href="{% relative_url i 'page' request.GET.urlencode %}">{{ i }}</a> </li> {% elif i > page_obj.number|add:-3 and i < page_obj.number|add:3 %} <li class="page-item"> <a class="page-link" href="{% relative_url i 'page' request.GET.urlencode %}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li class="page-item"> <a class="page-link" href="{% relative_url page_obj.next_page_number 'page' request.GET.urlencode %}"> <i class="bi bi-arrow-right"></i> </a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#"> <i class="bi bi-arrow-right"></i> </a> </li> {% endif %} </ul> </nav> {% endif %} -
Group by month and year but include 0 counts also
I have created a queryset which counts all the instances in a month and in a year. What I'd like it to do is also include the months that have 0 count. How do I do that even though there are no instances of the months in my database? payments_per_month = PaymentRequest.objects .annotate(year=Extract('arrival_date', 'year')).values('year') .annotate(month=Extract('arrival_date', 'month')).annotate(count=Count('*')) .values('year', 'month', 'count').order_by('-year', '-month', 'count') Output is: <QuerySet [{'year': 2023, 'month': 3, 'count': 8}, {'year': 2023, 'month': 2, 'count': 5}, {'year': 2023, 'month': 1, 'count': 18}, {'year': 2022, 'month': 11, 'count': 2}, {'year': 2022, 'month': 10, 'count': 1}, {'year': 2022, 'month': 8, 'count': 1}]> For example December(12) is missing but I'd like that to be in my queryset as: {'year': 2022, 'month': 12, 'count': 0} -
Docker, Django, Nginx: Admin cannot be reached HTTP 302
I am building a Django app in a docker enviroment. This app is served with nginx. I have made an app from scratch. Using docker-compose, I configured two services, the app and nginx. The default.conf is pretty simple. Like most tutorials, I passed in server the container name. I set the static the same from the STATIC_ROOT of the app. upstream api { server sinag_api:8000; } server { listen 80; location / { proxy_pass http://api; } location /static/ { alias /static/; } } In the settings, I did not modify much. I just added the STATIC_ROOT location. I also modified the allowed hosts. ALLOWED_HOSTS = ["*"] ... STATIC_URL = "/static/" STATIC_ROOT = "/static/" In my entrypoint for Django, I execute the collecstatic command. I can confirm the static files are generated since I inspected the volume. When I visit the localhost i.e. 127.0.0.1, I am welcomed by the Django debug web page. However when I visit the admin site 127.0.0.1/admin, the page cannot be reached. The log in nginx has HTTP 302. nginx | 192.168.144.1 - - [10/Mar/2023:10:44:25 +0000] "GET /admin/ HTTP/1.1" 302 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.63" "-" What … -
Iterate over Queryset backwards with Foreign Keys
I am trying to iterate over a queryset for a certain model and want to go over a table to another table. My models are the following (shrinked to a smaller version): class Erp(models.Model): erp_id = models.AutoField(primary_key=True) target_item = models.ForeignKey('Items', models.DO_NOTHING,related_name='target_item') class PE(models.Model): pe_id = models.AutoField(primary_key=True) item = models.ForeignKey(Items, models.DO_NOTHING, related_name='pe_item') class Items(models.Model): item_id = models.AutoField(primary_key=True) item_name = models.Charfield(max_length=20) My Queryset looks like this where I am trying to loop through and want to print stuff for the class Erp: pe_queryset = PE.objects.filter(item_id=2) for pe in pe_queryset: print(pe.item.item_name) # is working print(pe.item.target_item.erp_id) # is not working print(pe.item.target_item) # gives back Erp.None Is it possible to iterate through the entry to another tables Foreign Key like this or how could I accomplish to get the value from ERP with my Queryset? I tried to iterate through every possible column name. pe_queryset = PE.objects.filter(item_id=2) for pe in pe_queryset: print(pe.item.item_name) # is working print(pe.item.target_item.erp_id) # is not working print(pe.item.target_item) # gives back Erp.None -
How to query Django many-to-many relationship which has an intermediate model to handle the relationship?
It is probably a very simple question but I did not manage to figure it out so far. I have a many-to-many relationship in Django models like that: class Post(models.Model): ... class PostCategory(models.Model): ... class PostPagePostCategory(models.Model): """A connection class needed for other things to work. It is not possible to sily have the ParentalManyToMany field.""" post = ParentalKey( 'models.PostPage', on_delete=models.CASCADE, related_name='post_categories', ) post_category = models.ForeignKey( 'models.PostCategory', on_delete=models.CASCADE, related_name='posts', ) class Meta: unique_together = ('post_page', 'post_category') As mention in the class docstring, I cannot use simply ParentalManyToMany field due to other requirements. Now my question is how to perform the following query. Suppose I've selected some posts, e.g. posts = Post.objects.filter(...), and I want to select all the categories for only these posts. How to perform such a query? If I query categories = PostCategory.objects.filter(post__in=posts), I get the following error: ValueError: Cannot query 'posts': Must be "PostPagePostCategory" instance. If I query PostPagePostCategory.objects.filter(post__in=posts), I get obviously PostPagePostCategory queryset with PostPagePostCategory. How do I now get from PostPagePostCategory queryset for distinct PostCategory objects? -
Django PWA - Periodic Background Sync
I have a django application (not yet PWA) in which I got asked to implement a feature that makes the app upload the users location to an API. This is because the app is used for truck operators. The client wants to be able to follow where the truck is. To monitor if all scheduled deliveries can be succeeded that day. My question: Is it possible to somehow make a background task that, even when the user is not using the app (its closed or not focussed), sends its location to the API? What technologies should I be using for this? I have already looked into a lot of technologies (that for me are very new). Just as PWA (service workers), workers, periodic-background-sync-api, background-sync-api,... But I am getting lost in all the information that there exists. -
Cannot get metadata (current-total) from state/info of celery task after calling update_state
I am building a web application with Django. I need to display a progress bar. To track the progress inside a celery task I am passing an ajax call to the backend containing information needed for the process and another one with a timeout to keep watching for progress of the celery task. I can not understand what I am doing wrong, but I cannot get back the information regarding the information I stored in the 'meta' of the update_state. Following relevant part of code. tasks.py @shared_task def myFunction(): current_task.update_state(state='PROGRESS', meta={'current':0, 'total':100}) . do stuff . current_task.update_state(state='PROGRESS', meta={'current':25, 'total':100}) . do stuff . current_task.update_state(state='PROGRESS', meta={'current':50, 'total':100}) . do stuff . current_task.update_state(state='PROGRESS', meta={'current':75, 'total':100}) . do stuff . current_task.update_state(state='PROGRESS', meta={'current':100, 'total':100}) return result views.py def view(): ****GET PART**** if 'processing' in request.POST: result = myFunction.delay() request.session['id'] = result.id result_out = result.get() return JsonResponse() elif 'checkstate' in request.POST: proc_id = request.session['id'] task = AsyncResult(proc_id) return JsonResponse({'state':task.state, 'info':task.info}) -
How to get the text of a template without parsing the template?
Imagine I have a template that uses a custom template tag. During the processing of the template tag, I discover a problem I could help the user solve. I want to provide a pointer to where the error happened (and what they need to do to solve the problem). How do I get the template text and the current position (line) in the template file? (in a way that doesn't re-parse the template, since that would cause the error to be detected again recursively..) -
Filter queryset with same DateTime fields
I'm trying to filter a queryset with the same DateTime fields: objects = Obj.objects.filter(start_date_time=F('end_date_time')) objects <QuerySet []> models.py: start_date_time = models.DateTimeField(default=now, blank=True) end_date_time = models.DateTimeField(default=now, blank=True) If I remove microseconds, then the fields are equal: obj = Obj.objects.filter(id='id').first() obj.start_date_time datetime.datetime(2023, 3, 10, 9, 24, 29, 326238, tzinfo=<UTC>) obj.end_date_time datetime.datetime(2023, 3, 10, 9, 24, 29, 326241, tzinfo=<UTC>) obj.start_date_time == obj.end_date_time False obj.start_date_time.replace(microsecond=0) == obj.end_date_time.replace(microsecond=0) True How to make a request to the database correctly? -
How do i pass a QR value from javascript to my python view function in Django
I have created a QR scanner using html and javascript using instascan.min.js as shown in the code below. Currently, I am able to scan and see the content of the QR code displayed on the website but I am not sure how I can POST the QR code output {scan.content} . The QR value is passed into {scan.content} in the html. I want to post it to the python function: doctor_qrscan in view_doctor.py so that it can be written into the database Any help is greatly appreciated! The following are the relevant codes: {% block mainbody %} {% verbatim %} <div id="app2" class="container"> <head> <title>Instascan &ndash; Demo</title> <link rel="icon" type="image/png" href="favicon.png"> <!--<link rel="stylesheet" href="../static/css/style.css">--> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/webrtc-adapter/3.3.3/adapter.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script> <script type="text/javascript" src="https://rawgit.com/schmich/instascan-builds/master/instascan.min.js"></script> </head> <body> <div id="app"> <div class="sidebar"> <section class="cameras"> <h2>Cameras</h2> <ul> <li v-if="cameras.length === 0" class="empty">No cameras found</li> <li v-for="camera in cameras"> <span v-if="camera.id == activeCameraId" :title="formatName(camera.name)" class="active">{{ formatName(camera.name) }}</span> <span v-if="camera.id != activeCameraId" :title="formatName(camera.name)"> <a @click.stop="selectCamera(camera)">{{ formatName(camera.name) }}</a> </span> </li> </ul> </section> <section class="scans"> <h2>Scans</h2> <ul v-if="scans.length === 0"> <li class="empty">No scans yet</li> </ul> <transition-group name="scans" tag="ul"> <li v-for="scan in scans" :key="scan.date" :title="scan.content">{{ scan.content }}</li> </transition-group> </section> </div> <div class="preview-container"> <video id="preview"></video> </div> </div> </body> </div> {% … -
Cannot connect to Django admin in Docker environment
I am building a Django app with Nginx in Docker. I have been able to visit the app in the localhost i.e. 127.0.0.1 however the admin page 127.0.0.1/admin is unreachable. I have this directory: . └── project/ ├── nginx/ │ ├── default.conf │ └── Dockerfile ├── sinag_api/ │ ├── sinag_api/ │ │ ├── ... │ │ └── settings.py │ ├── manage.py │ ├── Dockerfile │ └── entrypoint.sh ├── docker-compose.yml └── .development.env I only have a simple docker-compose file version: "3.9" services: sinag_api: container_name: sinag_api build: dockerfile: ./sinag_api/Dockerfile volumes: - static:/static ports: - "8000:8000" env_file: - .development.env nginx: container_name: nginx build: dockerfile: ./nginx/Dockerfile volumes: - static:/static ports: - "80:80" depends_on: - sinag_api volumes: static: My Django app is clean from scratch. I only added the STATIC_ROOT config to serve the static files. # settings.py STATIC_URL = "/static/" STATIC_ROOT = "/static/" Content of my nginx config is pretty basic. upstream api { server sinag_api:8000; } server { listen 80; location / { proxy_pass http://api; } location /static/ { alias /static/; } } My Django entrypoint is also just basic. #!/bin/sh python manage.py migrate --no-input python manage.py collectstatic --no-input gunicorn sinag_api.wsgi:application --bind 0.0.0.0:8000 How can I debug the pages in Docker? I have … -
Datatables server-side processing Django
I am trying to get datatables server-side processing to work with a Django backend. I have the following code: views.py to load HTML: def clients(request): path = '/path/to/csv/file.csv' date_time = os.path.getmtime(path) date = datetime.datetime.fromtimestamp(date_time) html_template = loader.get_template( 'XXXX/clients.html' ) return HttpResponse(html_template.render({"date":date,},request)) HTML table code: <table id="table" class="table table-striped"> <thead style="white-space: nowrap;"> <tr> <th>Network</th> <th>Description</th> <th>IP</th> <th>Mac</th> <th>Manufacturer</th> <th>Operating system</th> <th>Conntect to device</th> <th>VLAN</th> <th>Switchport</th> <th>Status</th> </tr> </thead> <tbody style="white-space: nowrap;"> </tbody> </table> Javascript in the same HTML file as the table code: <script> $( document ).ready(function() { $("#table").DataTable({ "processing": true, "serverSide": true, "scrollX":true, "ajax" :{url:'{% url "json_response" %}',dataSrc:"data"}, }); }); </script> views.py to get data from url 'json_response': def json_response(request): draw = int(request.GET.get('draw')) length = int(request.GET.get('length')) start = int(request.GET.get('start')) substring = str(request.GET.get('search[value]')) if start == 0: start == 0 else: length = start + length path = '/XX/XX/XXX/XXX.csv' clients = pd.read_csv(path) recordsTotal=len(clients) clients = clients.rename(columns={"Client description":"client_descr","Client IP":"client_ip","Client MAC":"client_mac","Client Manufacturer":"client_man","Client OS":"client_os","Connected to device":"connected_to",}) clients['VLAN'] = clients['VLAN'].fillna(0) clients['Switchport'] = clients['Switchport'].fillna(0) clients['client_man'] = clients['client_man'].fillna('Unknown') clients['client_os'] = clients['client_os'].fillna('Unknown') clients = clients.astype({"VLAN":int}) clients = clients.astype({"Switchport":str}) clients = clients.fillna('None') clients = clients.iloc[start:length] clients = clients.values.tolist() page = 1 per_page = 25 response = { "draw":draw, "recordsTotal": recordsTotal, "recordsFiltered":recordsTotal, "data":clients, } clients = JsonResponse(response,safe=False) return clients With … -
Django: Running inspectdb command produces ImportError: cannot import name 'NoArgsCommand'
What I am currently trying to achieve is to map the database that I have in sqlite3 to Django (version 4.1) models. I have tried using inspectdb but it keeps throwing ImportError: cannot import name 'NoArgsCommand' from 'django.core.management.base'. I first tried running the command below: python manage.py inspectdb --database \transactions\db.sqlite3 Which gave me the error: from django.core.management.base import NoArgsCommand, CommandError ImportError: cannot import name 'NoArgsCommand' from 'django.core.management.base' (C:\Users\E.Musonda\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py) I then moved my sqlite3 to my projects base directory and run the command below: python manage.py inspectdb > models.py Which still produced the same error. Django database configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } Has anyone encountered this problem before and solved it? Or maybe I'm using the inspectdb command in a wrong way? Any help appreciated! -
how to save all python requests going out and set a proxy
how to save all API requests going out and then set a proxy in a Django or python project import requests proxies = { "https": "8.219.97.248:80" } url = "http://127.0.0.1:8000/api/product" r = requests.get(url, proxies=proxies) print(r.text) -
Django serialize custom user model
I have CustomUser model which inherits from AbstractUser clas. I have a serializer which throw me following errors: When I use from django.contrib.auth.models import User, the error is "AttributeError: 'NoneType' object has no attribute '_meta'". When I use from users.models import User, the error is "'QuerySet' object has no attribute 'email'", but the email field exists within the model. Here is what my serializer looks like: from rest_framework import serializers from users.models import User # from django.contrib.auth.models import User class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = ['id', 'title', 'is_active'] class CustomUserSerializer(serializers.ModelSerializer): department = DepartmentSerializer() class Meta: model = User fields = ['id', 'email', 'ad_login', 'sap', 'user_type', 'language', 'first_name', 'last_name', 'department'] In my settings I have also defined "AUTH_USER_MODEL = 'users.User'". Hoping this is enough information, what may be the cause of these errors? -
How to Insert in SQL using django app but getting COUNT field incorrect or syntax error
I want to insert data from django to sql but getting error : ('07002', '[07002] [Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error (0) (SQLExecDirectW)') My code is below: for connection: def connsql(): server = '' database = '' username = '' password = '' conn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password) return conn for storing data in db: connectionString=self.connsql() saveDetails=ModelClass() todayDate=date.today() saveDetails.Date=todayDate.strftime('%m/%d/%Y') saveDetails.Questions=question saveDetails.Result=str(result) cursor=connectionString.cursor() cursor.execute("insert into [dbo].[testtable] (Date,Questions,Result) values ("+saveDetails.Date+"','"+saveDetails.Questions+"','"+saveDetails.Result+");") cursor.commit() As I'm new to this any help will be thankfull.