Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djnago Rest frame work custom authentication
I am new to DRF . I have a django application and my project need to create a rest api for the applications. Inside the application I have a model to create api users and password. The model is as follows, class APIManger(models.Model): id = models.BigAutoField(primary_key=True) user = models.CharField(max_length=50, unique=True, verbose_name='API Name') apiuid = models.CharField(max_length=128, default=None, blank=True, null=True, verbose_name='API ID') password = models.CharField(max_length=128, default=None, blank=True, null=True, verbose_name='API Password') REQUIRED_FIELDS = ['user'] class Meta: managed = True db_table = 'adminapi' verbose_name_plural = "Admin API" def get_name(self): return self.user def __str__(self): return self.user def __unicode__(self): return self.user Now I setup the rest frame work as follows, authentication.py from rest_framework import authentication from rest_framework import exceptions from myapp.models.adminapi import APIManger class APIUser(authentication.BaseAuthentication): def authenticate(self, request): username = request.data.get('username', None) password = request.data.get('password', None) if not username or not password: return None try: user=APIManger.objects.get(apiuid=username) except Exception: raise exceptions.AuthenticationFailed('No such user') return (user, None) The views.py is as follows, from .authentication import APIUser class LoginView(APIView): authentication_classes = (APIUser,) def post(self, request, format=None): content = { 'username': str(request.user), 'auth': str(request.auth), # None } return Response(content) Settings.py is as follows, REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'api.authentication.APIUser', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } Now my AIM … -
Edit item within views in Django
There is some problem, I'm trying to update the product on the client by making changes and clicking on the update button - my page is refreshing w/o updating info, so the product has the same data as before. But in the logs, the status code of the GET request is 200 and shows the updated object in the database. When I try to update through the admin Django dashboard, everything works successfully, the problem is only on the client side of the web application. What issues can there be? Thank you in advance! @login_required(login_url='user-login') @allowed_users(allowed_roles=['Admin']) def product_edit(request, pk): item = Product.objects.get(id=pk) if request.method == 'POST': form = ProductForm(request.POST, instance=item) if form.is_valid(): form.save() return redirect('dashboard-products') else: form = ProductForm(instance=item) context = { 'form': form, } return render(request, 'dashboard/products_edit.html', context) -
Django FormMixin with DetailView
below is my BlogDetailView with FormMixin for separate comment form. Everything is working fine except for the form validation. At the moment Iam able to have CommentForm with initial data where I need the hidden values or have request.POST data sent in, but the hidden value will be missing. What I want is for the form to use the initial data on create and use request.POST data when its an error or update. class BlogDetailView(FormMixin, DetailView): model = Post form_class = CommentForm def get_success_url(self): return self.object.get_absolute_url() def get_context_data(self, **kwargs): context = super(BlogDetailView, self).get_context_data(**kwargs) context['form'] = CommentForm(self.request.POST, initial={ 'post_id' : self.object.id, 'user_id' : self.request.user.id }) context['comments'] = self.object.comment_set.all() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): print(form.data) form.save() return super(BlogDetailView, self).form_valid(form) -
How to host django with grpc in Production with ssl?
I am using Django with grpc , for this I am using django-rpc-framework. For development , I have used python manage.py grpcrunserver --dev. Now, I have to go for production. Can I use python manage.py grpcrunserver 127.0.0.1:8000 --max-workers 5 for production if yes, then how?, because I don't know how to run it in detached mode. I was thinking to use hypercorn because hypercorn handles http2 , But it also requires ssl certificate, which is good, but when I am connecting client to the server( I am using self signed certificate ,Just to test), I am receiving following error. To generate certificate, I ran following command. openssl req -x509 -newkey rsa:4096 -days 3650 -nodes -keyout ca-key.pem -out ca-cert.pem openssl req -newkey rsa:4096 -nodes -keyout server-key.pem -out server-req.pem openssl x509 -req -in server-req.pem -days 3650 -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem To run server , I tried following command. hypercorn --keyfile server-key.pem --certfile server-cert.pem kumpali.asgi:application With kreya, I am using ca-cert.pem file as certificate. -
django admin specific redirects
I have a Django website where all urls are pointed to admin like this : urls.py (Root) from django.contrib import admin from django.urls import path urlpatterns = [ path('', admin.site.urls), ] I would like to know how to make specific redirects from one url to another, as I only have one model to manage : localhost/ => localhost/app/computer localhost/app/ => localhost/app/computer I tried adding this to urls.py but it does not work : from django.http import HttpResponseRedirect path('/', lambda request: HttpResponseRedirect('/app/computer/')) I also thought of adding urls.py to app, but I think there might be a conflict as path('') will be on both urls.py, the root and the app -
Web Programming with Python Django and C++
I wonder that Django and C++ are a good couple to code web programming. What do you suggest to develop it? I want to write back-end processes in C++, and other stuffs in Django. -
How to print values horizontally from the list followed by comma after each integer value in Django
I want to print values horizontally from list followed by comma after each integer value alist = [1, 2, 3 4,5] print(alist) result should be like this: 1, 2, 3, 4, 5 -
Template is already exist but template does not exist is showing of user registration
In this Users app, template does not exist showing but template is already exist. I am new in Django. I have tried so many times but unable to solve this. Please help to solve this. Users App: urls.py: from Users import views as user_views from django.contrib.auth import views as auth_views path('register/',user_views.register,name='register'), path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/',auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), views.py: from django.shortcuts import redirect, render from django.contrib import messages from .forms import RegisterForm # Create your views here. app_name = 'Users' def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid: form.save() username = form.cleaned_data.get('username') messages.success(request,f'Welcome { username }, your account is created') return redirect('login') else: form = RegisterForm() return render(request,'users/register.html',{'form':form}) forms.py: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm app_name = 'Users' class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] Templates: register.html: <form method="post"> {% csrf_token %} {{form}} <button type="submit">SignUp</button> </form> login.html: <form method="post"> {% csrf_token %} {{form}} <button type="submit">Login</button> </form> logout.html: <h1>You have been logged out</h1> dashboard app: user_home.html: <div> {% if users.is_authenticated %} <a href="{% url 'logout' %}" class="dashboard-nav-item"><i class="fas fa-sign-out-alt"></i> Logout </a> {% else %} <a href="{% url 'login' %}" class="dashboard-nav-item"><i class="fas fa-sign-out-alt"></i> Login </a> {% endif %} </div> {% if messages … -
Can't enable HSTS on Django Application
I've been working on a Django web application and I'm trying to increase its security level from A to A+ on the SecurityHeaders website (https://securityheaders.com/). The only thing I seem to miss is the "Strict Transport Security" header. That's the only reason I get an A. I saw that the HSTS Headers can be easily added in Django using some settings parameters. After reading some stuff online, I added these lines of code in my settings.py: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_PRELOAD = True (...) but when navigating on my site, I don't see the Strict Transport Policy header in the Response section (when pressing F12). This is how my Response looks like: alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400, h3-28=":443"; ma=86400, h3-27=":443"; ma=86400 cf-cache-status: DYNAMIC cf-ray: 6c9ba77f4c128bbd-FRA content-security-policy: default-src 'self' 'unsafe-inline'; img-src 'self' 'unsafe-inline' data:; connect-src 'unsafe-inline' *.fontawesome.com; object-src 'self' 'unsafe-inline'; font-src 'self' 'unsafe-inline' *.fontawesome.com fonts.gstatic.com; style-src 'self' 'unsafe-inline' *.fontawesome.com *.w3.org maxcdn.bootstrapcdn.com fonts.googleapis.com; script-src 'self' 'unsafe-inline' https://use.fontawesome.com https://kit.fontawesome.com *.jquery.com *.cloudflare.com *.jsdelivr.net content-type: text/html; charset=utf-8 cross-origin-opener-policy: same-origin date: Fri, 07 Jan 2022 08:00:46 GMT expect-ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" location: / nel: {"success_fraction":0,"report_to":"cf-nel","max_age":604800} permissions-policy: accelerometer=(), ambient-light-sensor=(), autoplay=(), camera=(), display-capture=(), document-domain=(), encrypted-media=(), fullscreen=(), geolocation=(), gyroscope=(), interest-cohort=(), magnetometer=(), microphone=(), midi=(), payment=(), … -
null value in column "user_id" violates not-null constraint in post request , serialzier
This is my views and serializer , when I post some data , getting null value in column "user_id" violates not-null constraint after passing user_id also same issue views serializer_class = subSerializer() class subView(): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) serializer.py class UserSerializer(serializers.ModelSerializer): .................... class subSerialzier(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = RecipeSubmission fields = ( 'id', 'user', 'name', .......) -
Hello i need to know how to represent an object with this specific in django models
I'm creating a web app based on Django for inventory system and i have an object with this specific: I have a Box that contains : class PalletN(models.Model): qr_type=models.CharField(max_length=50,blank=True,null=True) customer_partnum=models.CharField(max_length=50, blank=True,null=True) partsnum=models.CharField(max_length=50, blank=True,null=True) boxquantity= models.IntegerField(default='0',blank=True,null=True) Ponum =models.CharField(max_length=50,blank=True,null=True) designation= models.CharField(max_length=50, blank=True,null=True) production_date=models.DateField(blank=True , null=True) suplier=models.CharField(max_length=50,blank=True,null=True) shipment_date=models.DateField(blank=True, null=True) Customer_code= models.CharField(max_length=50,blank=True,null=True) Snumber= models.CharField(max_length=50,blank=True,null=True) status=models.CharField(max_length=20,blank=True, null=True) creation_date=models.DateField(auto_now_add=True) zone=models.ForeignKey(zone,on_delete=models.CASCADE, null=True) rack=models.ForeignKey(rack,on_delete=models.CASCADE, null=True) position=models.ForeignKey(position,on_delete=models.CASCADE, null=True); My problem is how to represent a Mixt Pallet meaning a mixt pallet can have multiple customer_partnum designation and so on. i'm reading the data using a Qr code and this an example for better understanding. Pallet Normal: QR|XX5125B219|2021/07/13|2021/08/26|XXX2125-B|XX-T4311311E-4IX|XX-T43-11311-E-XXX|Some description|300|40|12000| Pallet Mixte: QR|XX5125B182|2021/07/13|2021/08/26|XXX2125-B| XX-L8814313A-9PX|XX-L88-14313-G-XXX|Some description|1000|12|12000| XX-L8814314A-9PX|XX-L88-14314-G-XXX|Some description|1000|13|13000| XX-L8814316E-9PX|XX-L88-14316-E-XXX|Some description|1000|15|15000| in the case of pallet mixte i have a lot of references for the user to add a new mixte pallet it's a bit chalenging to choose between them if i a do a drop down menu it will contain like 200 and plus reference and as i told you befor a mixte pallet can have 2 or plus references. I would love your sugestions if that's possible THANK YOU -
REST API Django Authentication does not return refresh in package Simple Rest
I am learning DJANGO REST API and my source of learning is UDEMY course 2017 and the teacher uses django 1.1 for Rest framework for JWT whereas on my system it does not support. So Django REST API site recomends using Simple JWT. So I have decided to use Simple JWT in settings i put : from datetime import timedelta REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_FILTER_BACKENDS':( 'rest_framework.filters.SearchFilter', 'rest_framework.filters.OrderingFilter', ), 'SEARCH_PARAM':'search', 'ORDERING_PARAM':'ordering', } JWT_AUTH = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': True, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } in my scripts/rest_framework_api.py : import requests import json AUTH_ENDPOINT = "http://127.0.0.1:8000/api/auth/jwt/" REFRESH_ENDPOINT = AUTH_ENDPOINT + "refresh/" ENDPOINT="http://127.0.0.1:8000/api/status/" headers = { "Content-Type": "application/json" } data = { 'username':'lulu', 'password':'lulu' } r = requests.post(AUTH_ENDPOINT,data=json.dumps(data),headers=headers) token = r.json()['access'] refresh_data = { 'token': token } new_response = requests.post(REFRESH_ENDPOINT,data=json.dumps(refresh_data),headers=headers) new_token = new_response.json() print(new_token) in urls : from django.contrib import admin from django.urls import path,include from rest_framework_simplejwt.views import (TokenObtainPairView,TokenRefreshView,) urlpatterns = [ path('admin/', admin.site.urls), path('api/auth/jwt/', TokenObtainPairView.as_view()), path('api/auth/jwt/refresh/', TokenRefreshView.as_view()), path('api/status/', include('status.api.urls')) ] in urls.py : from rest_framework import generics, mixins, permissions from … -
trying to start site with docker, gunicorn, nginx, docker, uwsgi, and django but it will not start up
I've read everywhere about getting the site running that I can possibly search for. However, I cannot get the site to run, I either get a 403 error or a 502 error (depending on the configuration). Currently what I'm trying to do is run uwsgi from command line and gunicorn from command line (to make sure my ini files are configured properly). I'm not getting any errors from command line now, but the site still will not load. Can anyone please help me figure out what I'm doing wrong? uwsgi --close-on-exec -s unix:///run/uwsgi/django/socket --chdir /var/www/html/mysite/ --pp .. -w blog.wsgi -C666 -p 32 -H /virtualenvpython3/ --uid www-data -gid www-data /virtualenvpython3/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock mysite.wsgi:application My nginx is file is configured like so (in /etc/nginx/sites-enabled/blog): server { listen 80; server_name your.program.sucks; location /assets { autoindex on; alias /var/www/html/mysite/assets; } location / { autoindex on; uwsgi_pass unix:///run/uwsgi/django/socket; include /var/www/html/mysite/mysite/uwsgi_params; } } Please let me know if you require any other information. Here is a sample from my error logs (nginx/error.log) 2022/01/07 07:17:34 [crit] 34#34: *17 connect() to unix:///run/uwsgi/django/socket failed (2: No such file or directory) while connecting to upstream, client: 154.21.22.142, server: your.program.sucks, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:///run/uwsgi/django/socket:", host: "your.program.sucks" -
Django - settings.DATABASES is improperly configured. Please supply the ENGINE value
I've got a postgres DB which Django successfully connects to but when trying to create a new model I'm getting the error settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I know settings.DATABASES is correctly configured as I've already created models which then Django used to create tables in the DB but for whatever reason it is now causing this error. You can also see that I have already "supplied the ENGINE value". DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['POSTGRES_DB'], 'USER': os.environ['POSTGRES_USER'], 'PASSWORD': os.environ['POSTGRES_PASSWORD'], 'HOST': 'db', 'POST': '5432', } } All help is appreciated. -
kombu.exceptions.EncodeError: Object of type ShiftBooking is not JSON serializable in Django 3.0
I have updated my project from Django 1.8 tom Django 3.0 Here when sending an confirmation email through celery i am getting this error Django = 3.0 Python = 3.7 celery = 5.1.2 Here is my views.py class JobShiftCreateView(CreateView): template_name = 'contract_worker/job_shift_form.django.html' form_class = JobShiftForm context_object_name = "job_shift" model = ShiftBooking def get_context_data(self, **kwargs): .... .... def get_form_kwargs(self): .... .... def form_valid(self, form): addtional_days = form.cleaned_data['addtional_days'] booked_with = form.cleaned_data['booked_with'] or None date = form.cleaned_data['date'] location = form.cleaned_data['location'] week_start = date - datetime.timedelta(days=(date.weekday())) x = datetime.datetime.strftime(week_start, '%d-%m-%Y') week_start = datetime.datetime.strptime( x, '%d-%m-%Y').strftime('%d-%m-%Y') self.object = form.save(commit=False) for i in range(0, int(addtional_days) + 1): self.object.pk = None if i == 0: days = 0 else: days = 1 date = date + datetime.timedelta(days=days) self.object.client = self.request.user.client self.object.created_by = self.request.user self.object.booked_with = booked_with self.object.date = date self.object.save() messages.success(self.request, 'Shift created successfully.') send_shift_mail_for_booking.delay(self.object, self.request.user) Here is my tasks.py @celery_app.task(bind=True) def send_shift_mail_for_booking(self, object, user): template_src = 'contract_worker/shift_confirmation_mail.html' template = get_template(template_src) from_email = settings.DEFAULT_FROM_EMAIL if user.client.email_validated_status == 'Validated': from_email = user.client.replay_to_email context = { 'user': user, 'client': user.client, 'object': object } context = Context(context) html = template.render(context) subject = 'Shift offer from ' + ' ' + str(user) + ' ' message = get_template('contract_worker/shift_confirmation_mail.html').render(Context(context)) email = EmailMessage(subject, … -
django forms for widget
I am working on a manual form for creating a post for a forums, I cannot get the categories to work, for the different forums. My forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ["title", "content", "categories", "tags"] def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.fields['categories'].widget.attrs['readonly'] = True Here is my views.py def posts(request, slug): category = get_object_or_404(Category, slug=slug) posts = Post.objects.filter(approved=True, categories=category) context = { 'posts': posts, 'forum': category, 'title': 'Posts' } return render(request, 'forums/posts.html', context) @login_required def create_post(request): context = {} form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): print("\n\n form is valid") author = Author.objects.get(user=request.user) new_post = form.save(commit=False) new_post.user = author new_post.save() form.save_m2m() return redirect('forums') context.update({ 'form': form, 'title': 'Create New Post' }) return render(request, 'forums/create_post.html', context) And last my html for creating a post <form method="POST" action="." enctype="multipart/form-data"> {% csrf_token %} <div class="mb-4"> <label for="{{ form.categories.id_for_label }}" class="form-label">{{ form.categories.label }}:</label> <input class="input is-medium" name="{{ form.categories.html_name }}" type="text" class="form-control" id="{{ form.categories.id_for_label }}" value="{{ request.forum }}"readonly> </div> </form> If I use the django build inn form, it all works, but I wanted to use own form so that it look a bit better and can be placed around. So if anyone know a … -
I want to compress an image in view before saving, but the file size stays the same
I have a functional update view that I am trying to compress uploaded images before saving them. However, when I try to compress the image, nothing happens and instead just saves the image with the exact same size. I think I might be saving it wrong, but I am unsure of how to save it correctly. Please let me know. Thank you! import io from PIL import Image def get_compressed_image(file): image = Image.open(file) with io.BytesIO() as output: image.save(output, format=image.format, quality=20, optimize=True) contents = output.getvalue() return contents def updated_form_view(request) ... if initial_form.is_valid(): initial_form.clean() updated_form = initial_form.save(commit=False) updated_form.username = request.user.username # compressing image here updated_form.form_image.file.image = get_compressed_image(updated_form.form_image) updated_form.save()``` -
Django Filtering - Field 'testcaseidstring' expected a number but got 'tc123'
I am trying to apply a filter on a Django model based on a column name That column is a Foreign Key Code - Inside models.py - testcaseidstring = models.ForeignKey('Testcaseidstructure', models.DO_NOTHING, db_column='testCaseIdString') Inside views.py - sessid_qs=History.objects.using("otherdb").filter(testcaseidstring="tc123") This gives me the following ERROR - Field 'testcaseidstring' expected a number but got 'tc123' How am I supposed to filter on this column? -
Build Django Query Dynamically based on kendo UI filter
I'm trying to query a database based on user filter. i received following input from kendo UI grid. { "filter":{ "filters":[ { "logic":"or", "filters":[ { "field":"aging", "operator":"eq", "value":24 }, { "field":"aging", "operator":"eq", "value":13 } ] }, { "logic":"or", "filters":[ { "field":"follow_up_name", "operator":"eq", "value":"Call Insurance Provider" } ] }, { "logic":"or", "filters":[ { "field":"patient_name", "operator":"eq", "value":"kartik" } ] }, { "logic":"and", "filters":[ { "field":"created_date", "operator":"eq", "value":"2022-01-09T18:30:00.000Z" }, { "field":"created_date", "operator":"gte", "value":"2022-01-04T18:30:00.000Z" } ] }, { "logic":"or", "filters":[ { "field":"follow_up_status", "operator":"eq", "value":"Open" } ] }, { "logic":"or", "filters":[ { "field":"role_name", "operator":"eq", "value":"Pharmacist" } ] }, { "logic":"or", "filters":[ { "field":"last_response", "operator":"eq", "value":"To-Patient" } ] } ], "logic":"and" }, "skip":0, "take":10 } Based on above data i need both 'and' & 'or' condition to build query dynamically. and pass it to database. also filter can contain multiple list. also want to make these class common which can take only UI arguments build query and return. please provide a solution for these. -
django - add l<a> tag - render_to_string
in my view.py: subject = "Thank you for your payment!" template = render_to_string('cart/email_template2.html', {'name': request.user.first_name, 'transaction_id' : transaction_id, 'total':total, 'items': items}) to = request.user.email res = send_mail(subject , template , settings.EMAIL_HOST_USER, [to], fail_silently=True) in my email_template2.html: Dear {{name}}, Thank you for making your payment towards: Your Transaction ID is {{transaction_id}} Total Amount Paid is {{total}} AED It’s been a pleasure doing business with you and below you will see the links to download your purchased items. {% for i in items %} <a href="l{{ i }}"></a> {% endfor %} Best wishes, here is the email i receive (output): Email received from the app "i" are the links for the items to be downloaded but they are presented as text not links. How to add a link? I tried to add tag but in the email it stays that way. Thanks... -
Is there a way to render a React component *UI* into Django without calling APIs?
I've been working on my Django App for a couple of months now and decided to use React as my front-end, which I know is bad habit for development and makes everything a lot more complicated. I run npm build for my front-end app with Django, but when I launch the Django Project, it shows me the Django Rest Apis. When I wanted it to show me my UI, I built in React. Everything in my Django settings should be correct from tutorials and documentations, so I believe that isn't the issue. I've tried calling the my API's but I believe that isn't the issue either. I am trying to keep everything as simple as possible, so if I'm missing stuff in my code I apologize, I just want to understand the very basics of React without having a lot of side code. Here is my App.js import React from 'react'; import './App.css'; import Form from './Form'; class App extends React.Component { render(){ return( <Form /> ) } } export default App; index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); -
Data is saving as [object Object] in database
form.html <form data-bind="submit: save" enctype="multipart/form-data" > {% csrf_token %} <table border="1"> <tr> <td>Title: <input type="text" name="title" id="title" data-bind="value: $data.title"></td> <br> </tr> <tr> <td>Description: <textarea name="description" id="description" data-bind="value: $data.description">Description</textarea></td> <br> </tr> <tr> <td>Image: <input type="file" name="image" id="image" ></td> <br> </tr> <tr> <td><button type="button" id="submit" data-bind="click: save">Submit</button></td> </tr> </table> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); </script> <script> var ViewModel = function () { var self = this; self.save = function () { var formdata = new FormData(); formdata.append('image', $('#image').get(0).files[0]); formdata.append('title', ko.observable("")); formdata.append('description', ko.observable("")); console.log(formdata) $.ajax({ type: 'POST', url: "{% url 'productsadd' %}", data: formdata, headers: {'X-CSRFToken': csrftoken}, processData: false, contentType: false, success: function (){ alert('The post has been created!') window.location = '{% url "productslist" %}'; }, error: function () { alert("fail"); } }); }; }; ko.applyBindings(new ViewModel()) </script> views.py class ProductsCreate(CreateView): model = … -
How to connect React native with django rest api
I build a simple django rest api now i need to fetch data from it in frontend using React Native. I can make a request to the api but the data is not coming from there. I search about it a lot but didn't find any help Thanks in advance... -
Django-treebeard with Django rest framework
class Category(MP_Node): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, null=True) node_order_by = ['name'] def save(self, *args, **kwargs): if not self.slug: slug = self.name self.slug = slugify(slug) super(Category, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('brands', args=[self.slug]) def __str__(self): return self.name class CategorySerializer(ModelSerializer): class Meta: model = Category fields = '__all__' read_only_fields = ['slug'] class CategoryCreateSerializer(ModelSerializer): parent_id = SerializerMethodField(allow_null=True, method_name='parent_id', read_only=True) def get_parent_id(self, data): if 'parent_id' in data: return data['parent_id'] else: return None class Meta: model = Category fields = ('name', 'parent_id') read_only_fields = ['parent_id'] def create(self, validated_data, *args, **kwargs): value = self.initial_data.dict() parent_id = self.get_parent_id(value) if parent_id is None: data = Category.add_root(**validated_data) value = Category.objects.get(id=data.id) data_serializer = CategoryCreateSerializer(value) return Response(data_serializer.data, status=status.HTTP_201_CREATED) else: if Category.objects.filter(id=parent_id).exists(): date = Category.objects.get(id=parent_id) value = date.add_child(**validated_data) return Response(value.name) class CategoryModelViewSet(ModelViewSet): queryset = Category.objects.all() lookup_field = 'slug' def get_serializer_class(self): if self.action == 'create': return CategoryCreateSerializer else: return CategorySerializer 'CategoryCreateSerializer' object has no attribute 'parent_id' what should i return in Response ? E:\nth\django_tree_drf\venv\lib\site-packages\rest_framework\fields.py, line 1885, in to_representation -
How to restore integers from my json.dumps file (for display in my javascript chart) when using Django
In my Django application, I have a very basic Pie Chart model with the name column as a CharField and the stats column as an IntegerField. I also have some javascript code on my html page that displays a pie chart -- but I'm only able to get it working if I hardcode the values as an array. I was hoping to instead display the data from my model/ DB as {{ values|safe }} in pie chart form, pulling the values from json dumps of my DB data. Here's what I've tried, as seen in my views.py file: def metrics(request): pietitle = serializers.serialize('json', PieChart.objects.all(),fields=('title')) piestats = serializers.serialize('json', PieChart.objects.all(),fields=('stats')) piedata=[[pietitle, piestats]] json_data = json.dumps(piedata) data_json= json.loads(json_data) return render(request, "metrics.html", {"values": data_json}) On my HTML page, the message I'm getting is simply "No Data", and I'm fairly certain that's because when I serialize the stats field, it's converted to a string and is unable to be interpreted as integers. Would anyone kindly be able to assist? Thanks so much, in advance.