Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"local variable 'form_b' referenced before assignment django"
def register(request): if not request.user.is_authenticated: if request.POST.get('submit') == 'sign_up': form = RegisterForm(request.POST) if form.is_valid(): form.save() form = RegisterForm() elif request.POST.get('submit') == 'log_in': form1 = LogInForm(request=request, data=request.POST) if form1.is_valid(): uname = form1.cleaned_data['username'] upass = form1.cleaned_data['password'] user = authenticate(username=uname, password=upass) if user is not None: login(request, user) return redirect('/') else: form_b = LogInForm() form = RegisterForm() return render(request, 'auth.html', {'form': form, 'form1': form_b}) This above is my view function <form class="loginForm" action="" method="POST" novalidate> {% csrf_token %} {% for field in form %} <p> {{field.label_tag}} {{field}} </p> {% endfor %} <button type="submit" class="btnLogin" name='submit' value='sign_up'>Sing Up</button> </form> <form class="loginForm" action="" method="post" novalidate> {% csrf_token %} {% for field in form1 %} <p> {{field.label_tag}} {{field}} </p> {% endfor %} <button class="btnLogin" type="submit" name='submit' value='log_in'>Log In </button> </form> rendering two forms in a view function code is working fine but when i click on signup this error occur which says "local variable 'form_b' referenced before assignment django" -
/o/token is not working in django oauth2_provider
I have setup django setup locally with oauth2_provider toolkit, right now https://{domain}/o/applications/ url is working fine, but when I went through documentation I found out oauth2_provider has few more inbuilt URL's like base_urlpatterns = [ re_path(r"^authorize/$", views.AuthorizationView.as_view(), name="authorize"), re_path(r"^token/$", views.TokenView.as_view(), name="token"), re_path(r"^revoke_token/$", views.RevokeTokenView.as_view(), name="revoke-token"), re_path(r"^introspect/$", views.IntrospectTokenView.as_view(), name="introspect"), ] management_urlpatterns = [ # Application management views re_path(r"^applications/$", views.ApplicationList.as_view(), name="list"), re_path(r"^applications/register/$", views.ApplicationRegistration.as_view(), name="register"), re_path(r"^applications/(?P<pk>[\w-]+)/$", views.ApplicationDetail.as_view(), name="detail"), re_path(r"^applications/(?P<pk>[\w-]+)/delete/$", views.ApplicationDelete.as_view(), name="delete"), re_path(r"^applications/(?P<pk>[\w-]+)/update/$", views.ApplicationUpdate.as_view(), name="update"), # Token management views re_path(r"^authorized_tokens/$", views.AuthorizedTokensListView.as_view(), name="authorized-token-list"), re_path( r"^authorized_tokens/(?P<pk>[\w-]+)/delete/$", views.AuthorizedTokenDeleteView.as_view(), name="authorized-token-delete", ), ] But in my case I am not able to access https://{domain}/o/token/ -
Django migrations RunPython reverse function
In the documentation there is a mention of a reverse function in RunPython in django migrations https://docs.djangoproject.com/en/4.0/ref/migration-operations/#runpython When does the reverse function run? Is there a specific command to run the reverse function? -
Cant't remove blue link text decoration from button
I have have link button but I cant remove the blue link decoration inside my update button(class=updatebut) I have tried many thins such as putting !important on my css file and it not working either I also tried .box-table2 .updatebut a {} but it doesnt work either EDIT : I AM USING THE DJANGO FRAMEWORK. CAN THAT CAN CAUSE THE PROBLEM? here is my html file. dashboard.html body { background-color: rgb(29, 26, 39); background-image: linear-gradient(135deg, rgba(255, 102, 161, 0.15) 0%, rgba(29, 26, 39, 0.15) 35%); color: white; } .box-table2 { width: 900px; top: 0; bottom: 0; left: 0; right: 0; margin: auto; margin-top: 120px; } .table { color: white; } .thead-color { background-color: rgb(81, 45, 168); } .updatebut { padding: 4px 20px; border-radius: 4px; color: white; background-image: linear-gradient(to right, rgb(103, 58, 183), rgb(81, 45, 168)); border: none; font-size: 15px; margin-right: 20px; } .updatebut a { text-decoration: none !important; } <div class="box-table2"> <table class="table"> <thead class="thead-color"> <tr> <th scope="col">Account</th> <th scope="col">Server</th> <th scope="col">Telegram</th> <th scope="col">Balance</th> <th scope="col">Risk %</th> <th scope="col">Actions</th> </tr> </thead> <tbody> {% for accounts in data %} <tr> <td>{{accounts.accountid}}</td> <td>{{accounts.mt5server}}</td> <td>{{accounts.telegramchannel}}</td> <td>{{accounts.balance}}</td> <td>{{accounts.riskpertrade}}</td> <td><a href="{% url 'update-account' accounts.id %}" class="updatebut">Update</a><a href="{% url 'delete-account' accounts.id %}" class="deletebut">Delete</a></td> </tr> {% endfor … -
DJANGO STORED PROCEDURES ERROR-> cursor object has not attribute’callproc’”
I’m using mssql driver to make a connection with an sql server database in django, the thing is that in my views.py I’ve already import ‘from django.db import connection’ to open a cursor, then I use the next script to register a new user (django—>sql server): cursor = connection.cursor() cursor.callproc(‘[dbo.SP_UC_CREATE]’,[name, lastname,password,email]) This written inside a views.py called: “def createUser(name,lastname,password,email): The error message in the explorer is ‘pyodbc.Cursor’ object has no attribute ‘callproc’ *in my function request I’m just calling the function ‘createUser()’ giving it the parameters -
How can i used column named class in django?
I need use column named class. But class is a keyword reserved in python. models.py class Colecao(models.Model): class = models.CharField(max_length=50,blank=True,verbose_name="Classe") -
Django. not able to access staticfiles in local development
I am trying serve static files in my local development (on same server I serve my site). I have run ./manage.py collectstatic with the following configs: settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') template.html <img src="{% static 'apis/icons/random-svgrepo-com.svg' %}" style="width: 50px;"> Now I have staticfiles folder in my BASE_DIR folder, but when I try to get an image, it doesn't appear to be working expected. http://127.0.0.1:8000/static/apis/icons/random-svgrepo-com.svg Please help. What I am doing wrong? -
Select two entries from foreign-key/one-to-one field
So I have a Team class: class Team(models.Model): name = models.CharField(max_length=255) players = models.IntegerField() and I want to select team1 and team2 separately in Match class : class Match(models.Model): team1 = models.OneToOneField(Team,related_name=team1 ,on_delete=models.CASCADE) team2 = models.OneToOneField(Team,related_name=team2, on_delete=models.CASCADE) but I get error (Add or change a related_name argument to the definition for 'tournament.Match.team1' or 'tournament.Match.team2'.) what am I missing ? -
How to avoid copy-past with getting the same object, but with different params in Django view
My view: def get(self, request, category_id): category = get_object_or_404(Category, id=category_id) uncompleted_tasks = Task.objects.filter(category_id=category_id, execution_status=False) completed_tasks = Task.objects.filter(category_id=category_id, execution_status=True) context = { "does_not_exist_msg": "There are no todos", "category": category, "uncompleted_tasks": uncompleted_tasks, "completed_tasks": completed_tasks, } return render(request, self.template_name, context) So, I wanna get objects and handle exceptions, but not like this: try: uncompleted_tasks = Task.objects.filter(category_id=category_id, execution_status=False) except (KeyError, Task.DoesNotExist): uncompleted_tasks = None try: completed_tasks = Task.objects.filter(category_id=category_id, execution_status=True) except (KeyError, Task.DoesNotExist): completed_tasks = None How to avoid copy-paste which I demonstrated upper? -
django file displays the contents of a database outside the dropdown menu
I have a delete employee page in my Django project where I get all the names of the employees in the dropdown menu from the database. the main issue is when I run the code the content which is supposed to be shown inside the dropdown menu is shown ouside. the code is as below: ''' {% extends 'app/base.html' %} {% block para %} <title>delete employee</title> <body style="background-color:powderblue;"></body> <style type="text/css"> label{ width: 200px; display: inline-block; margin: 4px; text-align: left; font-weight:bold; } input{ width: 200px; display: inline-block; margin: 4px; text-align: left; border-radius: 10px; } select{ width: 200px; display: inline-block; margin: 4px; text-align: left; border-radius: 10px; } form{ border-radius: 10px; background: rgb(155, 206, 219) ; color: white; width: 450px; padding: 4px; margin:auto; } </style> <form action="" > <h3 class="text-center text-uppercase"style="color:black; font-weight:bold">delete-employee</h3> {% csrf_token %} <label for="" class="text-uppercase">select:</label> {% for emp in emps %} <option value="ceo" class="text-uppercase">{{emp.name}}</option> {% endfor %} <select name="designation" id="designation"> <option value="associates" selected class="text-uppercase">name</option> </select><br><br> <div class="container"> <input type="submit" value="submit" class="text-uppercase text-center"> </div> </form> </div> {% endblock para %}''' -
Python Django or Flask for web development?
I have intermediate Python skills and want to learn web development. Should I start with Django or Flask? When I search for answers I only see benefits or downsides of them, but not anyone saying which one is better. And since I don't have any experience, I cant decide. I know it always comes down to what you want to create etc. But what would you say, is better overall? Is it possible to answer that question? -
how to utilize get_queryset with id parameter foreach particular foreign key items in class based views?
first of all, I am very new to django and thank you for patience, I want to make web site for showing how the league stands and shows the particular team footballer here what I have done so far... models.py class League(models.Model): name = models.CharField(max_length=255) country = models.CharField(max_length=255) founded = models.DateField() def __str__(self): return self.name class Team(models.Model): league = models.ForeignKey( League, blank=True, null=True, on_delete=models.CASCADE) image = models.ImageField( upload_to="images/", default='images/Wolves.png', blank=True, null=True) name = models.CharField(max_length=255) win = models.IntegerField(blank=True, null=True) draw = models.IntegerField(blank=True, null=True) loss = models.IntegerField(blank=True, null=True) scored = models.IntegerField(blank=True, null=True) conceded = models.IntegerField(blank=True, null=True) founded = models.DateField(blank=True, null=True) games = models.IntegerField(blank=True, null=True) point = models.IntegerField(blank=True, null=True) average = models.IntegerField(blank=True, null=True) class Meta: ordering = [ '-point', '-average' ] def __str__(self): return self.name def save(self, *args, **kwargs): self.games = self.win + self.draw + self.loss self.point = self.win*3 + self.draw self.average = self.scored - self.conceded super(Team, self).save(*args, **kwargs) it would be great if I utilize from slug item instead of id To make easy understand of which league you are in urls.py urlpatterns = [ path('', home, name='home'), path(r'^/league/(?P<id>\d+)/$', LeagueListView.as_view(), name='league'), In order to learn what class based views is I should use them somehow once clicked in th base.html 's navbar, … -
'Python.h' file not found on virtualenv in macOS
I use macOS Monterey 12.4 as my OS, and I'm trying to install django inside of a virtual environment created with pipenv. If I run the command pipenv shell to create a new virtualenv, then pipenv install django, I get this output: Installing django... Error: An error occurred while installing django! Error text: Collecting django Using cached Django-4.1.1-py3-none-any.whl (8.1 MB) Collecting sqlparse>=0.2.2 Using cached sqlparse-0.4.3-py3-none-any.whl (42 kB) Collecting backports.zoneinfo Using cached backports.zoneinfo-0.2.1.tar.gz (74 kB) Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'done' Preparing metadata (pyproject.toml): started Preparing metadata (pyproject.toml): finished with status 'done' Collecting asgiref<4,>=3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (pyproject.toml): started Building wheel for backports.zoneinfo (pyproject.toml): finished with status 'error' Failed to build backports.zoneinfo error: subprocess-exited-with-error × Building wheel for backports.zoneinfo (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [43 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.14-arm64-cpython-38 creating build/lib.macosx-10.14-arm64-cpython-38/backports copying src/backports/__init__.py -> build/lib.macosx-10.14-arm64-cpython-38/backports creating build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.macosx-10.14-arm64-cpython-38/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py … -
Django and HTMX realtime for all users
Can I make a realtime data refreshing in all users pages without them refreshing the page, once the database is updated, Using HTMX only, without django channels or AJAX or Json???? -
django python: how to display multiple items from 1 categorie under 1 categorie name in html template
i am new to python django. this is my code. views.py def gerechten(request): template = loader.get_template('café/gerechten.html') mydata = gerecht_info.objects.all() mydata2 = gerechten_Categorie.objects.all() context = { 'mygerecht': mydata, 'mycategories': mydata2 } return HttpResponse(template.render(context, request)) and models.py class gerechten_Categorie(models.Model): categorie = models.CharField(max_length=200) def __str__(self): return self.categorie class gerecht_info(models.Model): categorie = models.ForeignKey(gerechten_Categorie, on_delete=models.CASCADE) gerecht_name = models.CharField(max_length=200) gerecht_description = models.CharField(max_length=500, blank=True, null=True) gerecht_price = models.CharField(max_length=50) def __str__(self): return self.gerecht_name def drinkdesc(self): return self.gerecht_description def drinkprice(self): return self.gerecht_price and gerechten.html {% if mygerecht %} {% for cat in mygerecht %} <div class="flex"> <div class="menu-head center"> <h2>{{cat.categorie}}</h2> </div> <div class="menu-item"> <ul class="price"> <li>{{cat.gerecht_name}}</li> <li>€{{cat.gerecht_price}}</li> </ul> {% if cat.gerecht_description %} <p>{{cat.gerecht_description}}</p> {% else %} <p></p> {% endif %} </div> </div> {% endfor %} {% else %} <div class="menu-head center"> <h2>no items avaible</h2> </div> {% endif %} my site now looks like this: image of my site https://i.stack.imgur.com/lrhhs.png but i want to make all the info from 'Hapjes' into 1 'Hapjes' categorie, not seperated. already thanks for taking your time to respond. kind regards subjoel -
flutter and stripe (setupIntents)
I know this library flutter_stripe, which to me seems to be very limited in stripe interactions, it only does paymentIntent creation and that is basically it. Please do argue if I am wrong. I am looking forward to see if there are other packages, if any, for flutter to interact with stripe in more depth, I am trying to avoid Android/IOS native languages. I do these in backend: create stripe customer, create setup intent for each customer as they try or either add bank card or make purchase. I am looking forward that client will interact to stripe for the following: 1 Confirm setup intents 2 Send card data to stripe Another question, could you please assess my payment flow? If it is faulty please recommend another way Once setupintent is confirmed for the user, they hit backend for whatever purchase they want to make, backend contacts Stripe, fetches the setupintent, creates and confirms the paymentintent. Thank you, I appreciate help. -
How to pass a value in a Django drop down from a ModelForm
I want to display different fonts for users from a drop-down. The drop-down derives its values from the model which has choices option. The problem is when a certain font is chosen, it saves well in the database but the “value” is not caught. Here is the flow of the project: Model: class Company(models.Model): name = models.CharField(max_length=100, null=True, blank=True first_font = models.CharField(max_length=100, choices=header_font, blank=True, null=True) second_font = models.CharField(max_length=100, choices=body_font, blank=True, null=True) class Meta: verbose_name_plural = "Companies" def __str__(self): return self.name Forms.py class CompanyForm(forms.ModelForm): def __init__(self, *args, user=None, **kwargs): super(CompanyForm, self).__init__(*args, **kwargs) self.fields['first_font'].widget.attrs = {'class': 'select',} self.fields['second_font'].widget.attrs = {'class': 'select',} class Meta: model = Company fields = ('first_font', 'second_font',) Template output: I have used HTMX to take the value of the drop-down and pass it to a partial template so that it can be inserted in a class and return a well-formatted sentence with the font applied. <form action="" method="POST" enctype="multipart/form-data"> <div class="column is-4"> <h2>Choose fonts for documents</h2> <div class="field"> <label class="label">Heading Font</label> <div class="select is-fullwidth" name = "heading_font" hx-get="{% url 'main_font' %}" hx-target="#main-font" hx-trigger="change" > {{ form.first_font }} </div> <div id="main-font"> <p>This is your font</p> </div> </div> <div class="field"> <label class="label">Body Font</label> <div class="select is-fullwidth" name = "body_font" hx-get="{% url … -
How can I Filter Two Models at Once using Date Range in Django with Forms and Count
I am working on a Django project and I want to query two different Models; Income and Expenditure using Date Range with Django Forms. I can query one Model at once but don't know how I can query both the Income and Expenditure table at the same time and as well count number of objects in both Models. Below are my Models: class Expenditure(models.Model): description = models.CharField(max_length=100, null=False) source = models.CharField(max_length=100, choices=CATEGORY_EXPENSES, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) amount = models.PositiveIntegerField(null=False) Remarks = models.CharField(max_length=120, null=True) date = models.DateField(auto_now_add=False, auto_now=False, null=False) addedDate = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Expenses' def __str__(self): return self.description class Income(models.Model): description = models.CharField(max_length=100, null=False) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) amount = models.PositiveIntegerField(null=False) remarks = models.CharField(max_length=120, null=True) date = models.DateField(auto_now_add=False, auto_now=False, null=False) addedDate = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Income Sources' def __str__(self): return self.description My Django forms as in forms.py: class IncomeSearchForm(forms.ModelForm): start_date = forms.DateField(required=True, widget = IncomeDateField) end_date = forms.DateField(required=True, widget = IncomeDateField) class Meta: model = Income fields = ['start_date', 'end_date'] My views.py where I am able to use Date Range with Search form to query Income Model for Date Range Report. def SearchIncomeRange(request): #check for user session if 'user' not in request.session: return … -
I cant click on image url in Django
So I wanted to have this logo in the blog app, which was going to be part of each page, so users can always click on it, and ideally, when they click on it, it shall lead them to a page with articles. So this the code that I written in base file, but for some reason its not clickable: base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Articles</title> <link rel="stylesheet" href="{% static 'styles.css' %}" > </head> <body> <div class = "wrapper"> <h1><a href = "{% url 'articles:list' %}"> </a><img src="{% static 'article.png' %}"/> </h1> {% block content %} {% endblock %} </div> </body> </html> Any suggestions how to fix it? -
Retun data from a Django view after a javascript AJAX POST request
I am using Javascript to send an asynchronous request to a Django View. The View is able to receive data from the POST request, but I can't seem to return a message to confirm that everything worked. I was expecting that xhttp.responseText would contain the message Thankyou, but it is empty. The html part looks like this: <textarea id="message"></textarea> <input type="submit" value="Send" id="send_button onclick="submit_message()"/> The javascript looks like this: function submit_message(){ document.getElementById("send_button").value="Sent - Thankyou!"; message = document.getElementById("message").value var xhttp = new XMLHttpRequest(); xhttp.open("POST", "/send-message"); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("csrfmiddlewaretoken={{ csrf_token }}&message="+message); console.log('Sent POST request') console.log(xhttp.responseText) } I was hoping that xhttp.responseText would print Thankyou to the console. The Django View function looks like this: def send_message(request): message = request.POST.get('message') print(message) return HttpResponse('Thankyou') The message variable prints out as expected, but Thankyou doesn't seem to be returned. I am doing AJAX with JS for the first time, so I expect I've just misunderstood something simple. -
Automate raising ImproperlyConfigure if environment variable is missing
I have the following code in one of my views.py: tl_key = os.getenv("TRANSLOADIT_KEY") tl_secret = os.getenv("TRANSLOADIT_SECRET") if not tl_key: logger.critical("TRANSLOADIT_KEY not set") raise ImproperlyConfigured if not tl_secret: logger.critical("TRANSLOADIT_SECRET not set") raise ImproperlyConfigured I know that if Django doesn't find SECRET_KEY or DEBUG environment variable, it will raise ImproperlyConfigured exception. Is there a way I can specify which env variables are required so that the said exception is raised automatically? -
How to pass form field without filling in Django? And add extra field to for answer?
I wanna make patient information register form. I did model.py and form.py but, when i come to use, i couldn't pass the form without filling. Forexample, in this image evlilik tarihi means marriage date, evlilik tarihi 2 means second marriage date, when i filling the form i want to leave empty the evlilik tarihi 2 field. But always i took this error "TypeError: init() got an unexpected keyword argument 'blank'" I used null=True, blank=True, but nothing. How can i pass the form field without filling. And second question is, i made three form field for multiple marriage but is there any way how can i add button to this marriage field, and someone had second or third marriage, he can easily add button and give marriage date to me. How can i do this? Form.py class HastaBilgiForm(forms.ModelForm): class Meta: model = HastaBilgi fields = '__all__' widgets = { 'hasta_ad_soyad' : forms.TextInput(attrs={'class': 'form-control'}), 'hasta_dogum_tarihi' : forms.TextInput(attrs={'class': 'form-control'}), 'hasta_dogum_yeri' : forms.TextInput(attrs={'class': 'form-control'}), 'evlilik_tarihi_1' : forms.TextInput(attrs={'class': 'form-control'}), 'evlilik_tarihi_2' : forms.TextInput(attrs={'class': 'form-control'}), 'evlilik_tarihi_3' : forms.TextInput(attrs={'class': 'form-control'}), 'bosanma_tarihi_1' : forms.TextInput(attrs={'class': 'form-control'}), 'bosanma_tarihi_2' : forms.TextInput(attrs={'class': 'form-control'}), 'bosanma_tarihi_3' : forms.TextInput(attrs={'class': 'form-control'}), 'ogrenim_durumu' : forms.Select(choices=choices2, attrs={'class': 'form-control'}), 'meslek' : forms.TextInput(attrs={'class': 'form-control'}), 'kan_grubu' : forms.Select(choices=choices1, attrs={'class': 'form-control'}), 'boy' : … -
Django export-import use both ExportActionModelAdmin and ExportMixin together
In admin.py, using either: from django.contrib import admin from import_export.admin import ExportActionModelAdmin, ExportMixin class BookAdmin(ExportActionModelAdmin, admin.ModelAdmin): # stuff or from django.contrib import admin from import_export.admin import ExportActionModelAdmin, ExportMixin class BookAdmin(ExportMixin, admin.ModelAdmin): # stuff works well, but I'm not able to have both together: from django.contrib import admin from import_export.admin import ExportActionModelAdmin, ExportMixin class BookAdmin(ExportActionModelAdmin, ExportMixin, admin.ModelAdmin): # stuff In this latter case, the top right 'Export' button is missing (but the drop-down menu is OK). How could I use both ExportActionModelAdmin and ExportMixin from import_export.admin in my admin classes in order to have both the drop-down menu for a fine grain selection, and the 'Export' button for exporting all the model in one click? Doc URL: https://django-import-export.readthedocs.io/en/latest/getting_started.html#exporting-data -
why I am getting 401 error while sending a post request to auth/users in android studio but same request works in browser? wrong with my request?
I have an API which allows post request to register new users. It works in browser but when I try making this post request in my android project.I get 401 unauthorized response, I don't know what is wrong with my request!? private static String makeHttpRequest(URL url, String info) throws IOException { String jsonResponse = ""; if (url == null) { return jsonResponse; } HttpURLConnection urlConnection = null; OutputStream outputStream = null; InputStream inputStream = null; try { urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setDoOutput(true); //write to the stream outputStream = urlConnection.getOutputStream(); byte[] input = info.getBytes(Charset.forName("UTF-8")); outputStream.write(input, 0, input.length); urlConnection.connect(); //read the response if (urlConnection.getResponseCode() == 200) { authenticated = true; inputStream = urlConnection.getInputStream(); jsonResponse = readFromStream(inputStream); } else { Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); } } catch (IOException e) { Log.e(LOG_TAG, "Problem retrieving the JSON results.", e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } return jsonResponse; } -
Fetch Nested Data Using Ajax
I am having difficulties in fetching data which leads the output in this "[object Object]" Here is the sample data that I am fetching: { "id": 1, "logs": [ { "id": 1, "login_time": "2022-09-24T08:43:48.988768Z", "logout_time": "2022-09-24T08:43:48.988768Z", "work_hours": 0, "user": 1 }, { "id": 2, "login_time": "2022-09-24T10:24:59.564850Z", "logout_time": "2022-09-24T10:24:59.564850Z", "work_hours": 0, "user": 1 } ] } And here is the AJAX Code that I am using: function userlist(){ var wrapper = document.getElementById(`userlist`) var url = 'http://127.0.0.1:8000/userapi/' fetch(url) .then((resp) => resp.json()) .then(function(data){ console.log('Data:', data) var list = data for (var i in list){ var item = ` <div id="data-row-${i}"> ${list[i].logs} </div> ` wrapper.innerHTML += item } }) }