Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The jinja code is being read as HTML text instead of getting executed
I don't know if I'm asking this question in the right way. Please see this screenshot: https://i.stack.imgur.com/Idl0l.png directory: weatherApp core urls views templates index.html weatherApp urls This is the main project urls from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')) ] These are app urls and views: core.urls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] views from django.shortcuts import render import urllib.request import json def index(request): if request.method == 'POST': city = request.POST['city'] source = urllib.request.urlopen('https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&appid=').read() data_list = json.loads(source) data = { "country_code" : str(data_list['sys']['country']), "temp" : str(data_list['sys']['country']), "temp_min" : str(data_list['main']['temp_min']), "temp_max" : str(data_list['main']['temp_max']), "pressure" : str(data_list['main']['pressure']), "humidity" : str(data_list['main']['humidity']), "wind_speed" : str(data_list['wind']['speed']), "wind_dir": str(data_list['wind']['dig']), "main" : str(data_list['weather'][0]['main']), "description" : str(data_list['weather'][0]['description']), "icon" : str(data_list['weather'][0]['icon']), } print(data) else: data = {} print(data) return render(request, 'index.html', data) -
SignatureDoesNotMatch when calling PutObject with Django, Django-Storage, AWS S3, boto3
I created a Django App and host it on Heroku where I specified all setting vars such as Access Key ID (see Settingsfile). Settingsfile Settingsfile2 Relevant requirements: django-storages==1.12.3 boto3==1.26.31 Anyone any ideas on how to solve this? I tried the IAM user with full access, only S3 Full access, the Access Keys of the global account and I just keep geeting the error: "botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when calling the PutObject operation: The request signature we calculated does not match the signature you provided. Check your key and signing method." when trying to upload something to S3. The website then outputs: Internal Server Error The server encountered an unexpected internal server error (generated by waitress) The logger I added to the settings file on django is not helpful at all as it just shows me a SignatureDoesNotMatch error. I tried Access Keys with + and without as this might be the source of the error. I couldnt find any best practice on how to insert the keys to the heroku settings but a lot of ppl reporting errors when copying the keys from the aws website. I cheched it with the csv file and the website output. I tried … -
Auto populate form field - django
I am trying to auto populate a field in a form so the user does not have the input the data. In this case, the user will start from a show_venue page which is going to display a number of products. By clicking on one of these products, the user is redirected to a product page where a review can be left as part of a form. The form requries the user to select the venue where the review took place. I am looking to simplify this. Since the user already come from a venue_id page, I would like to auto fill this field. I tried different things found in this forum and left my last attempt, which currently deliver the following error message: cannot unpack non-iterable NoneType object. Slight quirk - you will notice the form is actually being saved in the show_venue function and not on the show_product_from_venue function (product page). This is due to a redirection process I had to implement: the user is redirected to the previous venue_ID page after submitting the form: made this happen with a javascript in the template. I am not adding the template page to keep the question concise and dont … -
Optimization Subquery Django ORM
I have function with some calculations. Subquery with OuterRef running too long, how i can optimization or find another way to get id for average_ndmi? def get_ranking_manager_ndvi_regions( year: str, month: int, pk: Optional[int] = None ) -> List[Region]: return ( get_regions(pk=pk) .annotate( year=SearchVector("commune__field__fieldattribute__date__year"), month=SearchVector( Cast("commune__field__fieldattribute__date__month", CharField()) ), size=Sum(F("commune__field__fieldattribute__planted_area")), field_count=Count("commune__field"), ) .filter(year=year, month=str(month)) .annotate( average_ndvi=Subquery( Field.objects.filter(commune__region__id=OuterRef("pk")) .values("commune__region__id") .annotate(ndvi_avg=Avg("fieldattribute__ndvi")) .values("ndvi_avg"), output_field=FloatField(), ) ) .annotate( standart_deviation=( Sum( (F("commune__field__fieldattribute__ndvi") - F("average_ndvi")) ** 2, output_field=FloatField(), ) / F("field_count") ) ** (1 / 2) ) )``` -
How to add columns to auth_user in django postgresql?
Hello i want to register user in django. In django there is just fileds for basic datas email and username, but i want to add more like; about, user_profile_picture_url, address etc. It creates the model perfectly but... It's not saving it to database also makemigrations and migrate does not work! there is just username, first_name, last_name and email views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.contrib import messages from profiles.forms import Register_User_Form from profiles.models import User_Profile def register_user(request): if request.method == 'POST': form = Register_User_Form(request.POST) if form.is_valid(): form.save() username = form.cleaned_data["username"] password = form.cleaned_data["password1"] email = form.cleaned_data["email"] about = form.cleaned_data["about"] phone_num = form.cleaned_data["phone_num"] picture_url = form.cleaned_data["picture_url"] User_Profile(name=username, email=email, about=about, phone_num=phone_num, picture_url=picture_url) print("Model Created") user = authenticate(username=username, password=password) login(request, user) messages.success(request, "Registration Successfull") return redirect('/') else: form = Register_User_Form() return render(request, 'registration/register.html', {"form": form}) models.py from django.db.models import * class User_Profile(Model): picture_url = CharField(max_length=120, default="") name = CharField(max_length=30, default="") about = CharField(max_length=250, default="") email = CharField(max_length=50, default="") phone_num = CharField(max_length=15, default="") forms.py from django.forms import * from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class Register_User_Form(UserCreationForm): username = CharField(label="Username", max_length=36) email = CharField(label="Email", max_length=120, widget=EmailInput()) password1 = CharField(label="Password", max_length=36, widget=PasswordInput()) password2 = CharField(label="Confirm Password", max_length=36, widget=PasswordInput()) … -
Fetching data from multiple api in django rest framwork
First I don't know I'm asking a good question or not. I'm trying to integrate Paytm Payment in my django rest framework. There are many api from paytm like Initiate transaction , fetch all payment, send OTP etc, like in the image below Im able to initiate transaction but not all payments are available, Inorder to do that I have to call the Fetch Payment Options API. But I don't know how to do that because I'm already calling Initiate transaction API in the view with parameters but I don't know how to call other api with different parameters in the same view. Like when I initiate transaction, the API gets fired and frontend shows the paytm page. So these api should be called on frontend?. I actually don't know how to ask this question properly. I need help -
Django & PostgreSQL- Store Random Numbers in the database
In order to strengthen my basic knowledge in Django, I have decided to create something ther than a "to-do" list, I want to create a app that: "will need to create a number of unique 6 digit codes and store in the database. This will be used to verify unique entries." so my question is as follows: How can I quickly generate and store 50 random entries in my db How can I check if the user has a number that matches or not What is the best way to approach this, I need to start thinking like a dev so I am looking for a bit of guidance and not the result, a nudge in the right direction, I have attached a mock up of the design where the user is requested to submit their "unique entry" and see if it matches to any one of them stored in the db I am obviously reading the official django documentation too, but its not as straight forward for me to understand Regards Trevor -
Create multiple instances with given fields
I have these models class Guest(models.Model): name = models.CharField(max_length=50, blank=True, null=True) surname = models.CharField(max_length=100, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) adress = models.CharField(max_length=200, blank=True, null=True) table = models.ForeignKey(Table, on_delete=models.CASCADE, blank=True, null=True) class Dish(models.Model): name = models.CharField(max_length=50, blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) class GuestOrder(models.Model): comment = models.CharField(max_length=400, blank=True, null=True) guest = models.ForeignKey(Guest, on_delete=models.SET_NULL, null=True) dish = models.ManyToManyField(Dish) ingredient = models.ManyToManyField(Ingredient) And I get this data from postman { "guests":{ "23": [1, 2, 3], "24": [1, 2], "25": [1] } } So here 23-25 are guest ids and 1-3 are dish id. This is the view (I also get table_id from posman but that's irrelevant for question) class CreateOrderView(APIView): def post(self, request): table_id = request.data.get('table_id') table = Table.objects.get(id=table_id) number_of_guests = int(request.data.get('number_of_guests')) guest_orders = [] guests = [] for i in range(number_of_guests): guest = Guest() guest.table = table guest.first_name = str(i) guests.append(guest) Guest.objects.bulk_create(guests, number_of_guests) guests = request.data.get('guests') for key, value in guests.items(): guest = find_guests(key) print(guest) # print(value) dish = find_dish(value) print(dish) GuestOrder.objects.create(guest=guest, table=table) guest_orders = GuestOrder.objects.filter(table=table) for guestorder in guest_orders: guestorder.dish.set(dish) return Response("5") these are the helper functions used in the view. def find_guests(id): found_guest = Guest.objects.get(id=id) return found_guest def find_dish(list): for y in list: found_dishes = [] found_dish … -
Can't move validation from view to serializer
I need to move validation from views.py to serializators.py. How can I do it? Validation must check: user can't follow himself user can't follow author that his already follow I have a ViewSet with @action: my view.py: @action( detail=True, methods=['post', 'delete'], permission_classes=(permissions.IsAuthenticated,) ) def subscribe(self, request, id=None): """Following""" author_id = id if request.method == 'POST': author = get_object_or_404(CustomUser, id=author_id) if author == request.user: raise serializers.ValidationError( {'errors': 'You can't follow yourself.'} ) if self.request.user.follower.filter(author=author).exists(): raise serializers.ValidationError( {'errors': 'You already follow this author.'} ) author = get_object_or_404(CustomUser, id=author_id) Follow.objects.create( user=request.user, author=author ) serializer = FollowSerializer(author, context={'request': request}) return Response(serializer.data, status=status.HTTP_201_CREATED) if request.method == 'DELETE': user_id = request.user.id subscribe = get_object_or_404( Follow, user__id=user_id, author__id=author_id ) subscribe.delete() return Response(status=status.HTTP_204_NO_CONTENT) and I have a FollowSerializer in serializers.py my serializers.py class FollowSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('email', 'id', 'username', 'first_name', 'last_name', 'is_subscribed', 'recipes', 'recipes_count') I try to add a validate method like def validate(self, data): but it doesn't work. -
Django - gcloud error - Error processing tar file(duplicates of file paths not supported):
I'm deploying the django app on gcloud and it has been deployed before but I'm uploading newer version and it's been a long time since last deployment was done. now I'm trying but facing following error. all packages and dependencies are getting installed on gcloud but it's getting failed on next step: -
Is there any way to register a table which is created without using Django Model?
How to register the following table in apps.py or how to show this Table in admit panel? from django.db import connection cursor = connection.cursor() cursor.execute("CREATE TABLE appName_{} LIKE appName_table".format(str(request.user)+"_table")) -
How to develop a rest api without using serializer in Django Rest Framework?
I want to create a Student Register and Login Api without using serializer in django Rest Framework. So I want to know how I make CRUD operation for those api using ApiView Any one please solve this -
Check if the user who is making the request correspond to the connected user, inside "form_valid" django
I'm currently trying to improve my form, I would like to check if the connected user correspond to the user who publish the data is it possible to add a condition inside the form_valid to see if the user from the model correspond to user from the request before posting the form Model: class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=200, null=True, blank=True) view : class TaskUpdate(LoginRequiredMixin, UpdateView): model = Task template_name = "tasks/task_form.html" form_class = DateInputForm I already tried to do that : def form_valid(self, form): if self.request.user.is_staff and self.object.user != self.request.user: return super().form_valid(form) if self.object.user != self.request.user: form.add_error(None, "You can't do that") return super().form_invalid(form) also if I'm not a staff user, I can't have access to the input to select users, it's automatically assigns <form action="" method="post"> <div style="flex-direction: column"> {% csrf_token %} <div style="margin-bottom: 10px"> {% if admin %} <label for="user">User name : </label> {{ form.user }} {% endif %} </div> I also thought of doing an sql query to see if the user making the query corresponds to the user registered for the task. no solution for the moment -
Do Server work while i dont connect? If yes how can i do?
I deployed my django app in ubuntu server. I want to give to API for mobile application. So i followed some source and i deployed. For I want to deploye django, I use gunicorn and ngnix. Server is working with this command: gunicorn --bind 0.0.0.0:8000 myapp.wsgi I can give API with this way. Everything is okey. But when i close cmd which connected to server, server stop. Can server work while i dont connect by my computer? Must not close cmd and my computer? Or can i do other way? -
Django & Bootstrap: On Load Modal
Good day I have the following issue, I have, as far as my knowledge allows me, I have tried using the bootstrap CDN and also the pip package installer method, but when I try get my modal to show then I cant get it work, could someone have a look at my code and let me know index.html {% load static %} {% load bootstrap5 %} <!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>Landing Page</title> {% comment %} Bootstrap {% endcomment %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous" ></script> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> <script type="text/javascript"> $(window).on("load", function () { $("#myModal").modal("show"); }); </script> </head> <body> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <div class="modal hide fade" id="myModal"> <div class="modal-header"> <a class="close" data-dismiss="modal">x</a> <h3>Modal header</h3> </div> <div class="modal-body"> <p>One fine body…</p> </div> <div class="modal-footer"> <a href="#" class="btn">Close</a> <a href="#" class="btn btn-primary">Save changes</a> </div> </div> {% comment %} header {% endcomment %} <header> <img src="" alt="" /> </header> {% comment %} Main Conntent {% endcomment %} <main> <div class="row"> <div class="text-center"> <button id="btnSubmit" type="submit" class="btn btn-danger py-2 px-5 text-center d-flex align-items-end" > Enter … -
Django send_mail: Only send Bcc Email when someone enters an email address
I'm using the Django Rest framework and send_mail to send out an email from a react form. There is two email fields but sometimes the bcc field does not get filled out and the email sending will fail. Is there a way to add an if statement or to tell django some other way to ignore bcc if there is no bcc value being sent? I'm getting this error in the backend log: anymail.exceptions.AnymailInvalidAddress: Invalid email address '' parsed from '' in `bcc`. views.py @api_view(['POST',]) def proposal(request): if request.method == "POST": serializer = PropEmailSerializer(data=request.data) if serializer.is_valid(): ClientName = request.POST['ClientName'] Sender = request.POST['Sender'] Bcc = request.POST['Bcc'] Facilities = request.POST['Message'] AgentPhone = request.POST['AgentPhone'] AgentName = request.POST['AgentName'] merge_data = { 'greetings': ClientName, 'facilities': Facilities, 'agentname': AgentName, 'agentphone': AgentPhone, } html_body = render_to_string("email-templates.html", merge_data) message = EmailMultiAlternatives( subject='Test', body="", from_email='noreply@test.com', to=[Sender], bcc=[Bcc] ) message.attach_alternative(html_body, "text/html") message.send(fail_silently=False) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Order page after selection of product
models.py ` class Product(models.Model): name = models.CharField(max_length=50 , verbose_name='العنوان') disc = models.TextField (null=True , verbose_name='وصف المنتج') price = models.DecimalField (max_digits=5 , decimal_places=0 , null=True , verbose_name='السعر') photo = models.ImageField (null=True, upload_to='static\product_images', verbose_name='صورة المنتج') active = models.BooleanField(default=True , verbose_name='حالة المنتج') category = models.CharField(max_length=50,null=False) slug = models.SlugField(blank=True, null=True) urls.py ` urlpatterns = [ path('', views.Product_list , name= 'home'), path('product/<int:product_name>/', views.Product_details , name= 'Product_details'), path('product/<int:product_name>/order', views.Product_order , name= 'order'), path('qa/', views.Question_list , name= 'Question_list'), path('annoncement/', views.Blog_list , name= 'Blog_list'), path ('about/' , views.about , name='about'), `` views.py ` def Product_order (request, product_name): if request.method == 'POST': order = OrderForms(request.POST) return render (request , 'order.html' , {'order' : order,}) ` error UnboundLocalError at /product/2/order cannot access local variable 'order' where it is not associated with a value solution for my probleme -
How to make API requests after authenticating with django-allauth?
I've integrated Github and GitLab authentication in my Django app using django-allauth. After authentication, how do I get access to the request token to make API calls to Github and GitLab? I'm using django-allauth v0.51.0 and django v4.1.4. -
Django Vue3 access-control-allow-origin is not allowed
I have a Django rest-api project. Vue is used on the front of the project. I get the following error when requesting via Vue: print console: Access to XMLHttpRequest at 'https://api.iyziwell.com/api/user/register' from origin 'https://main.d398abgajqt044.amplifyapp.com' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpack_loader', 'account', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'https://main.d398abgajqt044.amplifyapp.com', 'http://localhost:8082', ] CORS_ALLOWED_ORIGIN_REGEXES = [ 'https://main.d398abgajqt044.amplifyapp.com', 'http://localhost:8082', ] CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) request page = https://main.d398abgajqt044.amplifyapp.com -
How to iterate dictionary to template in Django
I have two loops that works perfect if I print the results. It gives me a list that show the name and the value but I have difficulties to show it in a template. It just shows the last results. for u in Performance.objects.raw('SELECT * FROM...') name = u.last_name + ' ' + u.first_name for e in Projekt_perf.objects.raw('SELECT stressz_profile.id...') total = e.total results = {'name':name, 'total':total} context = { 'results': results, 'name': name, 'total': total, } return render(request, 'performance/list.html', context)` This is the dictionary I get, it's OK: {'name': 'Someone01', 'total': 25} {'name': 'Someone02', 'total': 7} {'name': 'Someone03', 'total': 10} {'name': 'Someone04', 'total': 0} I like to have the dictionary above in the template and I tried these methods but I did not get all the elements just the last one. {% for r in results %} {{ r }} {% endfor %} {% for r in results %} {{ r.name }} - {{ r.total }} {% endfor %} What am I doing wrong? -
django javascript: Custom request header throwing CORS error and redirecting to OPTIONS
I am trying to create an API library in Django. This API will be called by javascript. Django-API and javascript is running in two different servers. The django API library is expecting a custom request header from javascript front end. I am parsing this header from django request object. Everything is fine when I am trying in postman. But when I am trying this from browser, browser rejects my custom request header. and it automatically calls OPTIONS method. Previously some cors issue was happening. And I solved it by adding: response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Headers"] = "*" Also already implemented: - django-cors-headers module installed - corsheaders.middleware.CorsMiddleware middleware installed - set ALLOWED_HOSTS = ['*'] & CORS_ORIGIN_ALLOW_ALL = True The current issue actually due to the custom header added in the request. Can anyone help please? I am in a do or fire situation. I tried various response headers from django. Is it related to back end or front end ? how to solve this? -
Django Inline Tabular admin: delete an object not working
I'm using Django admin.TabularInline class inorder to add multiple objects in a Foreinkey relationship as below: admin.py: class HeadFlowDatasetInline(admin.TabularInline): model = HeadFlowDataset extra = 0 class ProductAdmin(admin.ModelAdmin): list_display = ( ... ) search_fields = ( ... ) fields = ( ... ) inlines = [HeadFlowDatasetInline] def save_model(self, request, obj, form, change): obj.created_by = request.user obj.last_updated_by = request.user obj.save() def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: instance.user = request.user instance.save() And for this purpose, this approach is working just fine. But the problem occurs when I'm trying to remove a HeadFlowDataset object from the add product object page. As shown in the picture below, there is a checkbox item in front of each HeadFlowDataset object, but checking it and saving does not work. I could not find any other way to make this work neither. Can anyone show me a way to do this? -
Django cannot authenticate or password hashing is wrong
I use a custom user model so I can authenticate using email instead of username. from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) class UserManager(BaseUserManager): def create_user( self, email, password, confirm_code=None, username=None, role=None, ): user = self.model(email=self.normalize_email(email)) user.set_password(password) user.confirm_code = confirm_code user.save() return user def create_superuser(self, email, password, role, username=None): user = self.model(email=self.normalize_email(email)) user.set_password(password) user.role = role user.is_staff = True user.is_active = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): EM = "EM" SM = "SM" DH = "DH" ST = "ST" ROLES = [ (EM, "Executive Management"), (SM, "Senior Management"), (DH, "Department Head"), (ST, "Staff Member"), ] objects = UserManager() role = models.CharField(max_length=2, choices=ROLES, default=US, blank=True) username = models.CharField(max_length=20, unique=True, blank=True, null=True) email = models.EmailField(max_length=255, unique=True) slug = models.SlugField(blank=True, null=True) confirm_code = models.CharField(max_length=20, null=True, blank=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) has_profile = models.BooleanField(default=False) email_verified_at = models.DateTimeField(auto_now=False, null=True, blank=True) code = models.CharField(max_length=8, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") class Meta: verbose_name = "User" verbose_name_plural = "Users" ordering = ["username"] db_table = "users" def get_absolute_url(self): return f"{self.slug}" USERNAME_FIELD = "email" REQUIRED_FIELDS = ["role"] When I register a user the user is created in the database correctly and the … -
How do i get information from my django project to my react project?
Js file ` import React, {useState, useEffact} from 'react' const CSearchPage = () => { let [users, setUsers] = useState([]) useEffact(() => { getUsers() }, []) let getUsers = async () => { let response = await fetch('http://127.0.0.1:8000/userApi/getUsers/') let data = await response.json() console.log(data) setUsers(data) }; return ( <div> <div className="users-list"> User List<br /> {users.map((user, index) => { <h3 key={index}>{user.usermane}</h3> })} </div> </div> ) } export default CSearchPage ` view.py ` from django.shortcuts import render from rest_framework.response import Response from rest_framework.decorators import api_view from .models import Users from .serializers import UsersSerializer # Create your views here. @api_view(['GET']) def getUsers(request): users = Users.objects.all() serializer = UsersSerializer(users, many=True) return Response(serializer.data) @api_view(['GET']) def getUser(request, pk): users = Users.objects.get(uid=pk) serializer = UsersSerializer(users, many=False) return Response(serializer.data) ` model.py ` from django.db import models # Create your models here. class Users(models.Model): uid = models.CharField(primary_key=True, max_length=8, unique=True) username = models.CharField(max_length=35) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) search_permission = models.BooleanField() user_cud_permission = models.BooleanField() c_cud_permission = models.BooleanField() os_permission = models.BooleanField() class UsersPasswords(models.Model): uid = models.ForeignKey(Users, on_delete=models.CASCADE) password = models.CharField(max_length=12) ` I added corsheader in installed apps and the middelware as well. I have allowed all origins too. Still i am unable to get any results in react project. I … -
How to auto update django model field after a day?
How can i update is_new field tobe False after a day class post(models.Model): title = models.CharField(max_length = 250) body = RichTextField(blank= True, null =True) created_at = models.DateTimeField(auto_now_add=True) is_new = models.BooleanField(default=True)