Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I show in cart items in my index view?
I'm working on an ecommerce app, and I have a template that displays all my products. I want to show how many of the item are in the cart. But I can't seem to figure out how to get that information from my for loop. Code: template {% for product in products %} {{product.title}} - {{product.quantity_in_cart}} {% endfor %} (As of right now, product.quantity_in_cart does nothing. I would like it to show how many of this product are in the cart) view def product_index(request): title = "My Products" products = Product.objects.all() order = get_cart(request) cart = Order.objects.get(id=order.id, complete=False) items = cart.orderitem_set.all() context = { 'title' : title, 'products' : products, 'cart' : cart, 'items': items } return render(request, "store/product_index.html", context) models class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) complete = models.BooleanField(default=False, null=True, blank=False) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class Product(models.Model): name = models.CharField(max_length=64) slug = models.SlugField(unique=True, null=True) description = RichTextField(blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.IntegerField() -
Django and Microsoft azure services
Is it possible to integrate Microsoft azure services like Custom vision in the Django app? I want to build a web app where users can upload images and train a model using those images. -
django form implement AJAX for show hidden fields
So I got a simple form of COUNTRY, AREA, DISTRICT, CITY. In this form there are 4 more fields: What I'm trying to do is to filter the data. So when the user select a Country, the area field(select) will show all the areas that belong to this Country. Also when the user select a area, the module field(select) will show all the districts that belong to this field. If you check the code, you will see it's kinda simple. I know how to filter the queryset but I don't know how to use AJAX to do that. Tried many tutorials but couldn't find something so I'm sorry for not posting code. If you can point me to the right tutorial, example or give me some code to start working on it... my views.py class OrderCreateView(OrderViewMixin, core.CreateView): form_class = OrderForm template_name = '.....' def form_valid(self, form): .... return super().form_valid(form) def get_ajax(request): if request.is_ajax: logs = Order.objects.filter(country_id=request.GET['country']) data = serializers.serialize("json", logs) return HttpResponse(data, content_type='application/json') urls.py path('get_ajax/',views.get_ajax,name='get_ajax'), forms.py class OrderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['country'].queryset = Order.objects.all() self.fields['area'].queryset = Order.objects.none() class Meta: ..... Here I need using SELECT and option in AJAX open area if I choose country, but … -
document.querySelectorAll('*[id]') doesn't show all form fields ids in django
I am trying to connect js with django (because I am using js google maps api). In the first line of JS I have written: console.log(document.querySelectorAll('*[id]')) I obtain the following results: results I have this django's form: from django import forms class DateInput(forms.DateTimeInput): input_type='date' class userRequest(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lat_Origin'}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lon_Origin'}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lat_Dest'}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lon_Dest'}),required=False,initial=181) origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'origin_address'})) destination_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'destination_address'})) date=forms.DateField(widget=DateInput(attrs={'class':'data_aux data','id':'data_id'})) #date2=forms.DateField(widget=DateInput(attrs={'class':'data_aux data','id':'data_id2'})) maxPrice=forms.FloatField(label='Max price:',widget=forms.NumberInput(attrs={'class':'data_aux data order','step': '0.1'}),required=False) CHOICES_ORDERTYPE =( ('NONE', 'NONE'), ('ASC', 'ASC'), ('DESC', 'DESC'), ) OrderType = forms.ChoiceField(label='Order',choices = CHOICES_ORDERTYPE,initial='NONE',required=False,widget=forms.Select(attrs={'class':'data order'})) CHOICES_ORDERBY =( ('PRICE', 'PRICE'), ('DURATION', 'DURATION'), ) OrderBy = forms.ChoiceField(label='Order by',choices = CHOICES_ORDERBY,initial='PRICE',required=False,widget=forms.Select(attrs={'class':'data order'})) I don't know why lat_Origin, lon_Origin, lat_Dest, lon_Dest are not in document.querySelectorAll('*[id]') Do you have some idea how to fix this ? Thank you -
Download zip and save unzip
I´m working with an react native app that use a rest created in django. This app has an offline mode, for that reason I need be able to download zip files from the server to be played when offline mode will work. I've already tried using the dload library from python it works downloading and unziping the file but it download the file in the same script path (server). I need to save the zip file in the phone. Actual code looks like this... def download(request): url ="https://someirl/sco1.zip" dload.save_unzip(url, "../../") return HttpResponse( content_type="application/json") According with dload documentation second parameter in save_unzip is the folder when the zip will be downloaded and unzipped ¿How can I made to download on the phone? If you know a better way using Django or react native I would be pleasure to testing it -
django template inheritance: how to NOT display a block from parent template?
how can we hide a block in child template which is being rendered by paent template? for ex: my parent template base.html contains- <!DOCTYPE html> <html lang="en"> .... <body> {% block messages %} <div class="alert alert-{% if message.tags == 'error'%}danger{% else %}{{ message.tags }}{% endif %} alert-dismissible fade in" role="alert"> {{message}} </div> {% endblock %} ... </body> </html> and I have inherited this base.html in login.html but I do not want to use {% block messages %} in login.html, any suggestions? Thanks in advance for any solution😊. -
Django error with sites package: "The model Site is already registered in app 'sites'"
I am trying to install the sites package and upon running makemigrations am receiving the error: django.contrib.admin.sites.AlreadyRegistered: The model Site is already registered in app 'sites'. This is my admin.py: from django.contrib import admin # Register your models here. from django.apps import apps models = apps.get_models() for model in models: try: admin.site.register(model) except admin.sites.AlreadyRegistered: pass And here are my installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpage', 'django_user_agents', 'analytical', 'corsheaders', 'django.contrib.sites', ] Any idea what might be causing this issue? Please let me know if there is information missing. -
How to add condition to a manytomany relationship
I'm a little new to Django, so my question may be basic, but bare with me. Let's say I'm sharing my posts with some of my friends (who are manytomany relation with the post), but also giving an extra condition for whether they can comment on it, or not. This condition, together with the name of the user to be shared with are submitted through a forum. Now my problem is that I don't know how/where to save this condition. I will show you some of my code. Models.py class Task(models.Model): name = models.CharField(max_length=50) text = models.TextField() deadline = models.DateTimeField() created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='taskset') shared = models.ManyToManyField(User, blank=True, related_name = 'shared_list') def __str__(self): return f"{self.name}-{self.user.username}" class Comment(models.Model): text = models.TextField() task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments') created = models.DateField(auto_now_add=True) def __str__(self): return f"{self.user.username}-{self.task}" Share form html {% extends 'base.html'%} {% load crispy_forms_tags %} {% block content %} <h3>Enter the Username of the Friend you want to share with</h3> <form method="POST"> {% csrf_token %} {{form|crispy}} <input type="submit", value="Share"> </form> {% endblock content %} And the view processing it def share(request, id): task = Task.objects.get(id = id) if request.method == 'POST': … -
Ran 0 tests in 0.000s even when I have the file tests.py on windows 10
I have my app installed INSTALLED_APPS = [ ... "table_booker.apps.TableBookerConfig", "django_nose", ] My tests.py file I have from django.test import TestCase class AnimalTests(TestCase): def test_name(self): self.assertEqual(True, False) When I try to run my tests with python manage.py test I get Ran 0 tests in 0.000s -
How to send and receive dropdown selected option using AJAX
I have been working on a Django-based web application and I'm trying to send the selected option from a dropdown to services.py which handles models.py updating. I want the user to select one of the options in the dropdown and then send it to services.py to filter the payload coming from AWS. This is my dropdown: <div class="dropdown is-active" style="margin-bottom:10px"> <div class="select" id="dropdown-menu" role="menu"> <select class="dropdown-content" id="select"> <option class="dropdown-item" selected> AWS Accounts </option> <option value="558232680640" class="dropdown-item"> 558232680640 </option> <option value="903500686888" class="dropdown-item"> 903500686888 </option> <option value="183070076065" class="dropdown-item"> 183070076065 </option> <option value="885703380506" class="dropdown-item"> 885703380506 </option> <hr class="dropdown-divider"> <option value="*" class="dropdown-item"> All Accounts </option> </select> </div> </div> This is the javascript: $(document).ready(function() { var dropDown = $("#select"); dropDown.click(function() { $.ajax({ url: "{{ api_refresh_url }}", method: "POST", data: $("#select").val(), dataType: 'json', cache: false, }); }); }); and this is where I want to receive the data in services.py: class AWSEC2InstanceConnector: """ AWS Boto3 wrapper for connecting to the EC2 client and viewing EC2 instances """ last_update_time = datetime.min def update(self): self.last_update_time = datetime.now() instances = [] lambda_client = boto3.client('lambda') lambda_response = lambda_client.invoke(FunctionName='arn:aws:lambda:us-east-1:183070076065:function:cbi-instance-info') lambda_payload = json.loads(lambda_response['Payload'].read()) # HACK: using json.loads seems to avoid escaping the lambda response lambda_response = json.loads(lambda_payload['body']) for instance in lambda_response: instances.append(EC2Instance( … -
How to pass jquery variable into a custom django template tag?
I have a custom template tag that I got from this post. The tag is as follows: @register.filter def get_item(dictionary, key): return dictionary.get(key) In my Django template script: $(document).on('click', function() { var id = "'" + $(this).prop('id') + "'" $('img').prop('src', '{{dict|get_item:id}}'); }); Where dict is a dictionary that I pass to my Django template from my view. When I run the above code, django reads id as 'id' and not the value of the variable I set. How do I pass the jqeury variable into my custom template tag? -
Django prefetch query looping is quite slow
I have the following models. class ReportUserAnswers(models.Model): .... answers = models.ManyToManyField(ReportQuestionAnswerChoices, blank=True) ... class ReportQuestionAnswerChoices(models.Model): name = models.CharField(max_length=500) In my view i need to get all answers users have given. The choices they select are stored in 'answers' field. To get the answers i use the following query: answers = ReportUserAnswers.objects.filter( ... ).prefetch_related( "answers", ).distinct() I then need to loop over to find the answers chosen. for ans in answers: last = len(ans.answers.all()) - 1 for i, answer_given in enumerate(ans.answers.all()): answer_text += answer_given.name if not i == last: answer_text += "|" In a queryset I have 5000 answers, this loop takes around 20 seconds. Which seems very slow (crashes live server). I looked at the prefetch query directly in SQL, and that returns 2270 rows. So i guess the logic is looping 5000 times and looking in a table of 2270 for answers.all() The question is, is there a better approach or any thing i can do to cut the loop time? -
Django Follow-Unfollow System Issue
I'm developing a social media to chat with friends. And I added a follow-unfollow system in the project. However, when it try to view some profiles it gives me an error and I can't figure it. Here's the code: from django.shortcuts import render, redirect from .models import UserProfile from Posts.models import Posts from django.views import View from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin # Create your views here. class ProfileView(LoginRequiredMixin, View): def get(self, request, pk, *args, **kwargs): profile = UserProfile.objects.get(pk=pk) user = profile.user posts = Posts.objects.filter(author= user).order_by('-created_on') followers = profile.followers.all() if len(followers) == 0: is_following = False for follower in followers: if follower == request.user: is_following = True break if follower == request.user: is_following = False number_of_followers = len(followers) context= { 'user': user, 'profile': profile, 'posts':posts, 'number_of_followers': number_of_followers, 'is_following': is_following, } return render(request, 'Profiles/profile.html', context) class AddFollower(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): profile = UserProfile.objects.get(pk=pk) profile.followers.add(request.user) return redirect('profile', pk=profile.pk) class RemoveFollower(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): profile = UserProfile.objects.get(pk=pk) profile.followers.remove(request.user) return redirect('profile', pk=profile.pk) Any suggestions or help will be very helpful. If there are any other alternative to this. -
Onclick of update table button want to show form as a popup in Django
I'm trying to use modal popup as a edit form but I don't know good way. Currently my views.py is like this. #update dependency management def update_jiradata(Request,id): if Request.method == 'POST': pi = jira_Story.objects.get(pk=id) fm = jira_StoryReg(Request.POST, instance=pi) if fm.is_valid(): fm.save() fm = jira_StoryReg() return HttpResponseRedirect('/DependencyManagement') else: pi = jira_Story.objects.get(pk=id) fm = jira_StoryReg(instance=pi) jira = jira_Story.objects.all() return render(Request, 'hello/EditManagement.html', {'jiraform': fm, 'JIRA': jira}) Here's the template files for the view: {% extends 'hello/Dependency_Management.html'%} {% block editmanagement %} <style> </style> <div id="myModal1" class="modal1"> <div class="modal-content1"> <span class="close1">&times;</span> <div class="row"> <div class="col-sm-8 offset-2"> <h4 class="alert alert-info">Update JIRA Stories</h4> <form action="" method="post"> {% csrf_token %} {{jiraform.as_p}} <input type="submit" value="Update" class="btn btn-success"> <!-- <a href="{% url 'addrow' %}" class="btn btn-info">Back to Dashboard</a> --> </form> </div> </div> </div> </div> <script> // document.getElementById('parameter').style.display = 'none'; </script> {% endblock editmanagement %} I want some this like that onclick on my view button -
what is the best way to take user input in multiple step process of registration
I am developing an application using django framework- which has following. model class User: firstname = models.CharField(max_length=50,blank=True, null=True ) lastname = models.CharField(max_length=50,blank=True, null=True ) username = models.CharField(max_length=50,blank=True, null=True ) class A user = models.OneToOneField(User, on_delete=models.CASCADE) field1 = models.CharField(max_length=50,blank=True, null=True ) field2 = models.CharField(max_length=50,blank=True, null=True ) field3 = models.CharField(max_length=50,blank=True, null=True ) class B user = models.OneToOneField(User, on_delete=models.CASCADE) field4 = models.CharField(max_length=50,blank=True, null=True ) field5 = models.CharField(max_length=50,blank=True, null=True ) field6 = models.CharField(max_length=50,blank=True, null=True ) class C user = models.OneToOneField(User, on_delete=models.CASCADE) field7 = models.CharField(max_length=50,blank=True, null=True ) field8 = models.CharField(max_length=50,blank=True, null=True ) field9 = models.CharField(max_length=50,blank=True, null=True ) form class UserForm(forms.ModelForm): firstname = forms.CharField(label='', required=True) lastname = forms.CharField(label='', required=True) username = forms.CharField(label='', required=False) class Meta: fields = ("firstname", "lastname", "username", ) model = models.User class AForm(forms.ModelForm): field1 = forms.CharField(label='', required=True) field2 = forms.CharField(label='', required=True) field3 = forms.CharField(label='', required=False) class Meta: fields = ("field1", "field2", "field3", ) model = models.A class BForm(forms.ModelForm): field4 = forms.CharField(label='', required=True) field5 = forms.CharField(label='', required=True) field6 = forms.CharField(label='', required=False) class Meta: fields = ("field4", "field5", "field6", ) model = models.B class CForm(forms.ModelForm): field7 = forms.CharField(label='', required=True) field8 = forms.CharField(label='', required=True) field9 = forms.CharField(label='', required=False) class Meta: fields = ("field7", "field8", "field9", ) model = models.C views def createuser(request): if request.method == 'POST': … -
Dynamically display crypto prices from cryptocompare using django
I'm trying to make a simple webpage in django where I can display the price of some cryptocurrencies. The user stores in the database the name of the crypto and its initial price. Then I want to fill a table with the ticker and the initial price taken from the database and the current price of each crypto taken with cryptocompare. This is where the problem begin: the value of 'current price' is taken using cryptocompare, but how can I dinamycally display the value of the current price of each crypto in the table? Maybe the problem is easy to solve but I'm really new and I'm stuck, thanks in advance! This is how the index look like -> tabel in the index page models.py from django.db import models # Create your models here. class crypto(models.Model): ticker = models.CharField(max_length=200) initial_price = models.FloatField() def __str__(self): return self.ticker views.py from .models import crypto def index_view(request): chart = FuncAnimation(plt.gcf(), animate, interval=1000) ticker_list = crypto.objects.all() return render(request, 'cryptochart/index.html', {'chart': chart, 'ticker_list': ticker_list}) and last, in a file called utils.py I wrote the functions to get the price import cryptocompare #get price of cryptocurrency def get_crypto_price(cryptocurrency,currency): return cryptocompare.get_price(cryptocurrency,currency=currency)[cryptocurrency][currency] #get fullname of the cryptocurrency def get_crypto_name(cryptocurrency): … -
Admin only foreign key field with support for autcomplete search?
I'm trying to implement a simple system that can send emails directly from a model's change form, as well as have templates that I can use to fill in the subject and text fields. I currently have a foreign key to my template model which I can select from an autocomplete dropdown. Since I only need this field to fill in admin form values. How can I avoid adding the foreign key field to the MailInstance model while still keeping django's autocomplete working? models.py class MailTemplate(Model): subject = CharField(max_length = 1000) text = TextField() class MailInstance(Model): subject = CharField(max_length = 1000) text = TextField() emails = ArrayField(base_field = CharField(max_length = 300), null = True, blank = True) template = ForeignKey(MailTemplate, null = True, blank = True, on_delete = SET_NULL) admin.py class MailInstanceAdmin(admin.ModelAdmin, DynamicArrayMixin): fields = ['subject', 'text', 'template', 'emails'] autocomplete_fields = ['template'] -
I have an issue (Django)
in views.py from django.contrib.auth.decorators import login_required @login_required def index(request): user = request.user posts = Post.objects.filter(user=user) In this code I can't understand inline @login_required Why should we use the decorator And user=request.user user ?? In this project, we hadn't created models named user. Please explain to me. Thanks a lot -
Django how to ssend data to django dispatcher url with AJAX?
so i was trying to send category to django url (that takes category when visited through url) with ajax in this website, but i am getting this error which i don't seem to understand. Please help! urls.py path('category/<str:category>', views.getcategory, name = 'get_category'), ] views.py: #To get category if requested via AJAX if request.is_ajax and request.method == "GET": category = request.GET.get("last_joke_id", category) if category!=None: return HttpResponse('\n Received via Json. \n') else: return HttpResponse('\n Received via URL. \n') index.html: function send_category(category){ $.ajax({ type: 'POST', *url:"{% url 'get_category' %}"*, /*Error in this line*/ data: {'category':category}, success: function(response) { console.log("\n\nCategory data Successfully recived.\n"); console.log( response ); //displayJokes(response); }, error: function (response) { console.log('\n\n error in retriving category data:'); console.log(response); //return 'her'; } }) } </script>``` ***Error Message:*** ```django.urls.exceptions.NoReverseMatch: Reverse for 'get_category' with no arguments not found. 1 pattern(s) tried: ['jokes/category/(?P<category>[^/]+)$']``` -
How to set up an Amazon S3 bucket in secure way to serve media and static files to django
I'm using Amazon S3 to serve my static and media files to my django website. Do I need to Allow Public access in my Amazon S3 bucket or is there any secure way to do this -
Django read choices from a database table
I have an api that accepts requests of the form { "name": "John" "year": "2021" "product":"mask" } I would like to check if the product value is present in a list and reject or accept the request. Furthermore I need to be able to update the values of that list. Right now I am using django choices to implement the above but the prblem is that the list values are hardcoded. from django.db import models class Order(models.Model): product_choices = [ ('mask', 'Mask'), ('mask2', 'Mask1'), ('mask3', 'Mask2'), ('', 'Nothing') ] name = models.CharField(max_length=100, blank=False) year = models.CharField(max_length=4, blank=False) crop = models.CharField(max_length=100, blank=False, choices=crop_choices, default=crop_choices[-1][0]) Is there something I can do? -
'dict' object has not attribute 'pk' when using Django bulk_update()
I have the following code: obj = Products.objects.filter(dump__product_name = 'ABC, dump__product_color = 'black').values() new_price = [100, 200, 300] for item in range(len(obj)): obj[item]['price'] -= new_price[item] Products.objects.filter(dump__product_name = 'ABC, dump__product_color = 'black').bulk_update(obj, ['price']) But I am getting the error, Exception inside application: 'dict' has no attribute 'pk' The value of obj looks like this: <QuerySet [{'id': 1, 'product_name': 'Acer - Laptop', 'price': 350}, {'id': 1, 'product_name': 'Dell - Laptop', 'price': 450}, {'id': 1, 'product_name': 'Samsung- Laptop', 'price': 650}]> I am unable to figure out what's wrong with the code. Any help would be much appreciated. Thanks a lot in advance -
MongoDB doesn't work locally because of SRV error (no answer)
Situation We are working on the backend of our project consisting of two services written in Django and FastAPI. Both services use MongoDB as their database system. In Django we use djongo==1.3.0 for ORM compatibility. In FastAPI we use odmantic==0.3.4. Both of these libraries use pymongo==3.11.3 underneath. This MongoDB SRV error has been an issue for our Django service ever since we created it, but we managed to somehow work around it by not using the latest packages, such as: Django==2.2.20 djongo==1.3.0 pymongo==3.11.3 Recently due to security risks we had to upgrade: urllib3 from 1.25.8 to 1.26.5 pydantic from 1.8.1 to 1.8.2 Django from 2.2.20 to 2.2.22 Those were suggested by GitHub's dependabot. Problem When we run any of these services locally now they break with the following base exception: dns.resolver.NoAnswer: The DNS response does not contain an answer to the question: _mongodb._tcp.cluster0.k1eh0.mongodb.net. IN SRV Full log for Django: > python manage.py test Creating test database for alias 'default'... Traceback (most recent call last): File "/home/bk/inz/backend/authservice/venv/lib/python3.8/site-packages/djongo/database.py", line 10, in connect return clients[db] KeyError: 'djongo_test' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/bk/inz/backend/authservice/venv/lib/python3.8/site-packages/dns/resolver.py", line 212, in __init__ rrset = response.find_rrset(response.answer, qname, File "/home/bk/inz/backend/authservice/venv/lib/python3.8/site-packages/dns/message.py", … -
Django mark_safe and translation
I'm trying to test mark_safe and translation in a Django form. I've added style in help_text of a field in a form by adding mark_safe and everything works as expected. However i cannot figure out how to translate. For example i have: help_text=mark_safe(_('<p style="font-style:Italic; font-size:10px;">Enter your first name</p>')) If i run makemessages inside .po file i see the whole string as '<p style="font-style:Italic; font-size:10px;">Enter your first name</p>')) for translation. Is there any way so i can keep the style and also translate Enter your first name? Thank you! -
Django Form.save method gives error AssertionError at /post/new/ Credentials file not found
I have a django view method that just wont submit a file on post request Here is the view method:- @login_required def create_post(request): user = request.user if request.method == "POST": form = NewPostForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user_name = user data.save() messages.success(request, f'Posted Successfully') return redirect('home') else: form = NewPostForm() return render(request, 'feed/create_post.html', {'form':form}) the data.save() function gives the credentials error. What could be the problem?