Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't render nested relationship in Django Rest Framework
The problem is I have a 'details' field which should render into a nested relationship with it's parent serializer. I have tried a bunch of stuff and nothing seems to be working. Here's my models: class BusinessOrderModel(OrderToModel): reference = models.IntegerField() business_num = models.ForeignKey('BusinessModel', on_delete=models.CASCADE) def __str__(self): return str(self.reference) class BusinessModel(models.Model): Business_num = models.IntegerField(primary_key=True) def __str__(self): return str(self.Business_num) class DetailModel(models.Model): id = models.AutoField(primary_key=True) detail = models.TextField() order = models.ForeignKey('BusinessOrderModel', on_delete=models.CASCADE) and here's my serializers which aren't working: class DetailSerializer(serializers.ModelSerializer): class Meta: model = DetailModel fields = ('id', 'detail') class BusinessOrderSerializer(serializers.ModelSerializer): details = DetailSerializer(many=True) class Meta: model = BusinessOrderModel fields = ('reference', 'business_num', 'details') I've tried many different things but I get this error: Got AttributeError when attempting to get a value for field details on serializer BusinessOrderSerializer. The serializer field might be named incorrectly and not match any attribute or key on the BusinessOrderModel instance. Original exception text was: 'BusinessOrderModel' object has no attribute 'details'. Any help is much appreciated. Thank you very much. -
How to integrate Chart(Bar,Line) with Django Project
I want to create Charts like Bar, line, and so on how to integrate with the Django project. -
How to call a function from views.py to tasks.py?
I'm trying this: but its throwing an TypeError: auto_sms() missing 1 required positional argument: 'request' error. Now I'm thinking of getting the function from views.py instead and calling it on tasks.py if requests is not working on tasks.py, how can I do it? Thanks! @shared_task def auto_sms(request): responses = Rainfall.objects.filter( level='Torrential' or 'Intense', timestamp__gt=now() - timedelta(days=1), ) count = responses.count() if not (count % 10) and count > 0: send_sms(request) return -
Django foreign key field not updating with selected value from React Select dropdown
I have a webpage in my issue tracker project that allows a project manager to assign a user to a project. I am using React Select to allow the manager to select a user from a dropdown. When they click the add user button, the selected value gets sent to the backend through an api call. I have an APIView called assignuser, which takes in the post request and updates the user foreign key field in my Project model. Am I referencing the selected value wrong? I have tried sending selectedValue.value to my backend but it keeps on coming up as undefined. Django Backend class assignuser(APIView): serializer_class = ProjectSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): user = serializer.data.get('user') project_name = serializer.data.get('project_name') project = Project.objects.get(name=project_name) project.user = user project.save(update_fields=['user']) return Response(ProjectSerializer(project).data, status=status.HTTP_201_CREATED) else: return HttpResponse("Incorrect Credentials") React Frontend import React, { Component } from "react"; import { useState, useEffect } from "react"; import { Grid, TextField, Button, Typography } from "@material-ui/core"; import { FixedSizeList as List } from 'react-window'; import css from './style.css'; import Select from 'react-select'; import {useLocation} from "react-router"; const manageusers = () => { const [role, setRole] = useState([]); const location = useLocation(); const [project_name, … -
Return appropriate error for unactivated users in Djoser
I am using Django 2.2.14 with the configuration below for Djoser 2.1.0 but when trying to get JWT token for an inactive user, it returns the same error as using a wrong password which makes it tricky to differentiate. I get HTTP STATUS 401 with the detail below { "detail": "No active account found with the given credentials } My configuration Djoser is shown below: 'LOGIN_FIELD': 'email', 'SEND_CONFIRMATION_EMAIL': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'USER_CREATE_PASSWORD_RETYPE': True, 'TOKEN_MODEL': None, 'SEND_ACTIVATION_EMAIL': True, "LOGOUT_ON_PASSWORD_CHANGE": False, "PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND": True, "USERNAME_RESET_SHOW_EMAIL_NOT_FOUND": True, 'PASSWORD_RESET_CONFIRM_URL': 'account/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'account/username/reset/ /{uid}/{token}', 'ACTIVATION_URL': 'account/activate/{uid}/{token}', I am also using AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend'] -
Django 3 Dynamic Default Value in Model
There are similar questions but none recent and based on Django 3 so here it goes: I am using py nanoid to generate some unique IDs so in my models I have from nanoid import generate and then class Work(models.Model): title = models.CharField(max_length=200) body = models.TextField() published = models.BooleanField(False) date = models.DateTimeField() nanoid = models.CharField(max_length=15, default = generate(size=10) ) def __str__ (self): return self.title my aim is to ensure that a new nanoid is generated each time a new work post is added. At the moment is the same repeated each time I try to add a new Work via admin. I read some replies about creating a custom class but I am a bit at a loss here! -
Adding pandas dataframe to the initial db.sqlite database in django + no duplicates
How can i convert and assign the fetched information (that is modified with pandas) to a predefined model + not include duplicate rows? As i understood, pandas.DataFrame.to_sql should be used, but i'm a bit confused how to do this / connect both things. models.py class Article(models.Model): article_author = models.CharField(blank=True, max_length=500) article_date_publised = models.CharField(blank=True, max_length=500) article_title = models.CharField(blank=True, max_length=500) article_description = models.CharField(blank=True, max_length=500) article_url = models.CharField(blank=True, max_length=500) article_urlToImage = models.CharField(blank=True, max_length=500) article_content = models.CharField(blank=True, max_length=500) article_network = models.CharField(blank=True, max_length=500) fetched information + pandas dataframe import pandas as pd import requests import time fox_url = "https://saurav.tech/NewsAPI/everything/fox-news.json" fox_news = requests.get(fox_url).json() df = pd.json_normalize(fox_news) fox_articles = pd.json_normalize(df["articles"].loc[0]) del fox_articles['source.id'] fox_articles["date_publised"] = pd.to_datetime(fox_articles['publishedAt']) del fox_articles['publishedAt'] fox_articles holds this table (snippet) author title description url urlToImage content source.name date_publised 0 Ronn Blitzer Dershowitz calls Trump impeachment a 'loaded w... Harvard Law professor emeritus and constitutio... https://www.foxnews.com/politics/dershowitz-tr... https://static.foxnews.com/foxnews.com/content... Harvard Law professor emeritus and constitutio... Fox News 2021-01-10 17:39:49+00:00 1 Evie Fordham Post-Capitol riot censorship shows 'unelected'... Online censorship in the wake of violence at t... https://www.foxnews.com/politics/capitol-censo... https://static.foxnews.com/foxnews.com/content... Online censorship in the wake of violence at t... Fox News 2021-01-10 17:30:15+00:00 settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', … -
Is there a possibility to pass fields from different models to CreateView in Django?
I'm extending polls app from official Django tutorial and want to pass Question field question_text along with Choice field choice_text to CreateView generic View, to let the user create a Question along with it's choices at the same time. Unfortunately I can only pass Question model with question_text to the CreateView I know CreateView takes only one model so is there a possibility to maybe overwrite it somehow? Question is a foreignKey in a database to the Choice model. I found some answers using extra_views but i do not want to use some external source to do that Below my code Views class CreateView(LoginRequiredMixin, generic.CreateView): success_url = reverse_lazy('polls:index') redirect_field_name = 'accounts:signup' model = Question fields = ['question_text'] template_name = 'polls/poll_form.html' def form_valid(self, form): form.instance.author = self.request.user response = super(CreateView, self).form_valid(form) return response Models class Question(models.Model): question_text = models.CharField(max_length=200) author = models.ForeignKey(User, default='Default', on_delete=models.CASCADE) pub_date = models.DateTimeField('date published', default=timezone.now) def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Urls app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('new/', views.CreateView.as_view(), name='create'), path('<int:pk>/', views.DetailView.as_view(), name='detail'), path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), path('<int:question_id>/vote/', views.vote, name='vote'),] -
How to save address form data and display in template using Django
Brand new to Django/Python and have almost completed my first big project. I've built a small ecommerce store with a staff backend to update/delete and create products. I would like to display the address entered in by the User at checkout with in the Staff template. My code so far looks like this: models.py: class Address(models.Model): ADDRESS_CHOICES = ( ('B', 'Billing'), ('S', 'Shipping'), ) user = models.ForeignKey( User, blank=True, null=True, on_delete=models.CASCADE) street_address = models.CharField(max_length=150) town_or_city = models.CharField(max_length=100) county = models.CharField(max_length=100, default=True) postcode = models.CharField(max_length=20) address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES) default = models.BooleanField(default=False) def __str__(self): return f"{self.street_address}, {self.town_or_city}, {self.county}, {self.postcode}" class Meta: verbose_name_plural = 'Addresses' I would like to captcha the data from the 'street_address', 'town_or_city', 'county' and 'postcode' fields and have that info displayed with in my staff template. The idea I had was to import my Address model and grab all objects using Address.objects.all() and have this display with in the template using something like {{ user_address}} views.py / StaffView: class StaffView(LoginRequiredMixin, generic.ListView): template_name = 'staff/staff.html' queryset = Order.objects.filter(ordered=True).order_by('-ordered_date') paginate_by = 10 context_object_name = 'orders' def get_address(self): user_address = Address.objects.all() return user_address staff.html: <tr> <td><a class="order-ref-number-link" href="{% url 'cart:order-detail' order.pk %}">#{{ order.reference_number }}</a> </td> <td>{{ order.ordered_date }}</td> <td>{{ order.user.email }}</td> … -
Django model be related to objects of different types
I have a model called Assignment. Each Assignment can hold multiple questions of different types. That is, an Assignment can have Multiple Choice Questions, Essay Questions, True or False Questions. Each of the question types have their own model. Of course, they are related to the assignment by ForeignKey. How can I related them to the assignment such that to get all the questions (of different types) all I have to do is call. assignment1.questions.all() I have seen a few write-ups on things like GenericForeignKey, ContentType, etc. but I am yet to make them work. -
Error when trying to add python in javascript django
I'm new to Django and javascript, I've been trying to add a leaflet map in my Django template, I achieved this but I am trying to centre this map with the location of my model but I'm having problems to access the location property in my model, I've been looking how to add python in javascript and almost everywhere they said it had to be done the same way I do it in the HTML {{ object.location }}. But it is not detecting it as python so it is giving 3 different errors (Property assignment expected, ',' expected and declaration or statement expected). My intention is to replace [41.38, 2.17] with the var I declared. Here is the leaflet javascript code: <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script> <script type="text/javascript"> var event_location = {{ object.location }}; // Here I get the errors var mymap = L.map('mapid').setView([41.38, 2.17], 13); L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', maxZoom: 18, id: 'mapbox/streets-v11', tileSize: 512, zoomOffset: -1, accessToken: 'myaccesstoken' }).addTo(mymap); </script> In my template, I have no problems accessing the location with {{ object.location }} -
How to wait or stop a celery task in the middle?
I have a form in my Django app which creates an object car. I use celery to run operations, once new object car was created (by using post_save signal). I have an option to delete the car. So it should delete it from the database and it should run deleting operations with Celery. I use pre_save for that. The problem is as following: The creating operations can take some time (a few minutes). This means, that user can create a new car and while running the Celery creation operation, he will ask to delete the object. The celery tasks: @app.task(bind=True) def create_car(self, car_pk): from cars.models import car if car_pk is None or not isinstance(car_pk,int): return False car_obj = car.objects.get(pk=car_pk) # Creation operations car_obj.save() return creation_status @app.task(bind=True) def delete_car(self, car_pk): from cars.models import car if car_pk is None or not isinstance(car_pk,int): return False car_obj = car.objects.get(pk=car_pk) # deletion operations return deletion_status The signals in models.py: @receiver(post_save, sender=Car) def queue_car_create_request(sender, instance, created, **kwargs): if not created: return create_car.delay(instance.pk) @receiver(pre_delete, sender=Car) def queue_car_delete_request(sender, instance, using, **kwargs): delete_car.delay(instance.pk) So my question is - how should I handle this case? Can I somehow "stop" the creation task? Or can I somehow "wait" until the creation … -
View didn't return an HttpResponse object, it returned None instead
That's my views.py file from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import ReviewForm # Create your views here. #COMMENT_PAGE def Comment_page(request): if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): return HttpResponseRedirect('') else: form = Review(request.POST) return render(request, 'comment_page.html', {'form':form}) And my output is The view games.views.Comment_page didn't return an HttpResponse object. It returned None instead. -
How to create a custom Form Field for the Foreign Key Django
My models class Address(TimeStampModel): street_number = models.CharField(_("Street Number"), max_length=5, blank=True, null=True) street_line_1 = models.CharField(_("Street line 2"), max_length=250, blank=True, null=True) street_line_2 = models.CharField(_("Street line 1"), max_length=150, blank=True, null=True) postcode = models.CharField( _("Post/Zip-code"), max_length=64, blank=True, null=True ) city = models.CharField(_("City"), max_length=60, blank=True, null=True) state = models.CharField(_("State"), max_length=255, blank=True, null=True) country = models.CharField(max_length=50, choices=COUNTRIES, blank=True, null=True, default='France') class UserProfile(TimeStampModel): user = models.OneToOneField(CoreUser, related_name='userprofile', on_delete=models.CASCADE, verbose_name="Email") first_name = models.CharField(max_length=50, verbose_name="First name", null=True) last_name = models.CharField(max_length=50, verbose_name="Last name", null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,12}$', message="Phone number must be entered in the format: '+999999999'. Up to 12 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=12, blank=True) birthdate = models.CharField(max_length=200, null=True) profile_picture = models.ImageField(default='default.jpg', upload_to=get_path) profile_address = models.ForeignKey( Address, related_name="userprofile_address", on_delete=models.SET_NULL, blank=True, null=True, ) agency = models.ForeignKey( Agency, on_delete=models.SET_NULL, null=True, blank=True ) My form class ProfileForm(forms.ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=254) phone_number = forms.CharField(max_length=254) profile_picture = forms.ImageField() def __init__(self, *args, **kw): super(ProfileForm, self).__init__(*args, **kw) self.fields['first_name'].initial = self.instance.user.userprofile.first_name self.fields['last_name'].initial = self.instance.user.userprofile.last_name self.fields['phone_number'].initial = self.instance.user.userprofile.phone_number self.fields['profile_picture'].initial = self.instance.user.userprofile.profile_picture def save(self, *args, **kw): super(ProfileForm, self).save(*args, **kw) self.instance.user.userprofile.first_name = self.cleaned_data.get('first_name') self.instance.user.userprofile.last_name = self.cleaned_data.get('last_name') self.instance.user.userprofile.phone_number = self.cleaned_data.get('phone_number') self.instance.user.userprofile.profile_picture = self.cleaned_data.get('profile_picture') self.instance.user.userprofile.save() class Meta: model = UserProfile fields = ['first_name', 'last_name', 'phone_number', 'profile_picture', 'agency', 'profile_address', ] In my view I'm looking for how to access the … -
Passing Generated Data in generic.CreateView Django
I have the following in views.py class BookCreateView(generic.CreateView): model = Book template_name = 'papertools/bk_create.html' fields = ['title', 'authors', 'genre'] Whenever the user creates a new book I would like it to update another field I have to know as library_number. I already know how to count the number of books in the library (database) in order to generate this number but I do not know how to save it to the book model. I have been searching for several hours now and I am hoping someone will have an answer for me. -
Asynchrnous WebSocket
I have problem with asychronous WebSocket communication. I have a function yeilding me data for about 3min and during that time my page is not responsing to uras actions, because onmessage is being processed. What's strangest is it sometimes worked when I made onmessage only async, without function part, but only sometimes. How can I make this piece of code really asychronous? Or how can I make page responsive when its processed? <script> ws = new WebSocket('ws://localhost:8000/ws/'); ws.onopen = async function(event) { ws.send("{{ synergy_card }}"); }; ws.onmessage = async function(event) { document.getElementById("synergyBox").innerHTML = event.data; }; </script> -
Update to tables at the same time
Please blow are my code and a screenshot of my error. What I'm not doing right. def UpdateStock(request, pk): stock = Stock.objects.get(id=pk) stock_form = StockForm(instance = stock) history_form = StockHistoryForm(instance = Stock) if request.method == 'POST': stock_form = StockForm(request.POST, instance = stock) history_form = StockHistoryForm(request.POST, instance = Stock) if stock_form.is_valid() and history_form.is_valid(): stock = stock_form.save() history = history_form.save() return redirect('inventory') context = { 'stock_form': stock_form, 'history_form': history_form } return render(request, 'inventory/edit.html', context) -
Why does create_task in testing case for DRF not work?
so I'm very new to writing test cases and I'm confused as to why my test in failing. Here is the view: from rest_framework import generics, filters from todo import models from .serializers import TaskSerializer from django_filters.rest_framework import DjangoFilterBackend #lists, creates and filters tasks class ListTask(generics.ListCreateAPIView): queryset = models.Task.objects.all() serializer_class = TaskSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['date'] search_fields = ['description'] Here is the test view: from django.test import TestCase from rest_framework.test import APITestCase, APIRequestFactory from rest_framework import status from todo.views import ListTask, DetailTask class ListTaskViewTest(APITestCase): def setUp(self): self.data = {'title':'Any title', 'description': 'Any description', 'Completed':False, 'date':'Any date'} self.factory = APIRequestFactory() def test_create_task(self): response = self.create_task() expected_code = status.HTTP_201_CREATED self.assertEqual(response.status_code, expected_code) response = self.client.get('') expected_data = {'id':1, 'title': 'supermarket', 'description':'buy fruit','completed':False} self.assertEqual(len(response.data), 1) entry = response.data[0] self.assertEqual(entry, expected_data) Why does create_task not work and what should I replace it with? I thought since I had ListCreateAPIView I could use it for my test but it seems I cannot. Any help would be very useful. -
Using default URL value in Django throws 404 error
I am trying to use a default value for url in my views, however, I keep getting a 404 error. I have set the default value both in my view and in my url path settings: This is my url: path('u/<str:username>/<obj>/', views.get_user, kwargs={'obj':None}, name="get_user"), This is my view: def get_user(request, username, obj=None): How can I set the default value of `obj` to none so I can for instance visit `u/jack/posts/` and `u/jack/` using the same URL pattern -
Mongodb, create update in python
Here is my mongodb object. I need to write update function for "graded" field. Sometimes i need to create this field, sometimes update. @api_view(['POST']) def updateGrade(request): db = connect_to_db() data = json.loads(request.body) db.update({ '_id': ObjectId(data["id"])}, { "$set" : { "worksheetSolutions.$[idx]": {"graded": data["status"]} } }, {"arrayFilters":[{"idx":data["answerId"]}]} ) q = db.find_one({'_id': ObjectId(data["id"])}) q['_id'] = str(q['_id']) return JsonResponse(q, safe=False) Here is my python code. (not correct at all as I see now) data.id => _id data.answerId => id of answer data.status => true/false var -
Using serializer how to Create Category in django rest framework
I want to create category in django rest framework with serializer. name will be provided from frontend input field. I'm getting the user_id from user = request.user and cafe_id from request.user.cafe. I need to create category with name, user_id and cafe_id. How can I do this? here is the model class Category(models.Model): user = models.ForeignKey(User, related_name="cat", blank=True, null=True, on_delete=models.CASCADE) cafe = models.ForeignKey(Cafe, related_name="category", blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Meta: verbose_name_plural='Categories' def __str__(self): return self.name Here is the serializer class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['name'] and the views.py @api_view(['POST']) @permission_classes((IsAuthenticated,)) def categoryCreate(request): user = request.user user_id = Category(user = user) cafe = request.user.cafe cafe_id = Category(cafe = cafe) serializer = CategorySerializer(user_id, cafe_id, data=request.data) data={} if serializer.is_valid(): serializer.save() data["success"] = "Category Has Been Created!" return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Thank You In Advance -
Best way to serve large media files on a website
I'm trying to build a website with Django where you can view different 360 videos. The videos are created with a software that generates a web build with some javascript code and other media files, the size is approximately 200 Mb. Since I don't have any experience in deploying websites I don't know if it's better to host the videos on other platforms, like Amazon S3, in terms of costs and performance or I've to keep the videos on the same server that hosts my website? -
Query that excludes irrelevant ManyToMany fields Django
I'm trying to build a reddit clone and want my REST API to return info in my Post model. I have a M2M field 'Votes' where I would like to filter out any fields that don't belong to the user making the request, but still return all of the same info in the Post Model regardless if there are any matches in the vote field. Try except block is commented out just so I can see the error messages at the moment. Thanks Post View: class GetPost(viewsets.ModelViewSet): serializer_class = GetPostSerializer http_method_names = ['get'] def get_queryset(self): name = self.request.GET.get('subreddit', None) post_id = self.request.GET.get('post_id', None) # try: if name is not None and post_id is not None: if Subreddit.objects.filter(name__icontains=name).exists(): votes = Vote.objects.filter(user=self.request.user) post = Post.objects.filter( id=post_id) if len(post) > 0: return post else: pass # raise Http404 # except: # pass # raise Http404 Serializers: class VoteSerializer(serializers.ModelSerializer): updated_value = serializers.IntegerField(required=False, read_only=True) class Meta: model = Vote fields = ('value', 'updated_value', 'user') class GetPostSerializer(serializers.ModelSerializer): comments = GetCommentsSerializer(read_only=True, many=True) votes = VoteSerializer(read_only=True, many=True) class Meta: model = Post fields = ('id', 'author_profile', 'title', 'text', 'created_at', 'score', 'subreddit', 'votes', 'comments') depth = 1 Models: class Vote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) value = models.IntegerField() submission_type … -
Django Application Using GMAIL API, Oauth Token Deleted Error
I am currently trying to create an application in Django that fetches emails from an Inbox using the gmail API. I was able to successfully perform this in Nodejs, but I wanted to switch to using Django. I used the Python Gmail API quickstart: https://developers.google.com/gmail/api/quickstart/python. I created a view for the function found in the tutorial and the first issue I encountered was "invalid redirect uri" which is an issue I encountered in the past, which I still don't understand. I tried editing the redirect uris in the Oauth Token to fix this issue, but it didn't work (I probably was doing it wrong). Eventually, I deleted the Oauth Token and tried creating a new GCP project but it said "Oauth Token deleted". I kept trying to create new ones (I updated the credentials.json everytime). I even tried starting a new Django project with a new GCP Project+ Oauth token, but I'm still getting the same "Oauth Token Deleted" error. I'm not sure whats going wrong and was wondering if someone with experience using the API would know what to do. Thanks! -
How to save data in django models taken from bootstrap form?
I'm new in Django and now I'm working on my first project. I created model 'nom' to store data and also bootstrap form in html temlplate. My question is how can I save data in my model after clicking submit button in my form in html. All answers i have found recommended me to create Form as class. Is any easy way to use data from my form? Thanks home.html <!DOCTYPE html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Title</title> <style> body { margin: 40px } .my-container { border: 1px solid green} .my-row { border: 2px solid blue} .my-col { border: 2px solid red} btn-primary { margin-left: 50px} .align-right { text-align: center; border: 0; } </style> </head> <body> <div class="container my-container"> <form action="{% url 'home' %}" method="Post"> {% csrf_token %} <div class= "row my-row"> <div class="col-3 my-col"> <input type="number" placeholder="0" name="nom200" size="1" /> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if liczba %} {{ liczba }} {% endif %} </span></h3> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if ls %} {{ ls }} {% endif %} </span></h3> </div> </div> <div class= "row my-row"> <div class="col-3 my-col"> <input type="number" placeholder="0" name="nom100" size="1" /> </div> <div class="col my-col"> <h3><span …