Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django implementation go bcrypt. GenerateFromPassword and bcrypt.Com pareHashAndPassword function
Django implementation go bcrypt. GenerateFromPassword and bcrypt.Com pareHashAndPassword function,whether Django bcrypt can be implemented? -
Django permission denied to delete comment
i have a problem with my blog comment delete. It works properly when the user is superuser, but keep getting "django.core.exceptions.PermissionDenied [07/Jan/2022 01:47:09] "GET /blog/comentario/eliminar/6/ HTTP/1.1" 403 135" when the user is comment autor but no superuser. here is my code: Model. class BlogComentario(models.Model): post = models.ForeignKey(BlogPost,on_delete=models.CASCADE,related_name="comentarios") nombre = models.ForeignKey(Usuario,on_delete=models.CASCADE) email = models.EmailField(max_length=100) contenido = models.TextField(max_length=500) publicado = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class Meta: ordering = ('-publicado',) db_table= "blog_comentario" def __str__(self): return f"comentado por {self.nombre}" view class ComentarioEliminar(UserPassesTestMixin,DeleteView): template_name = 'Blog/Comentarios/comentario_eliminar.html' model = BlogComentario def get_success_url(self, **kwargs): return reverse('blog:blog_inicio') def test_func(self): obj = self.get_object() return obj.nombre == self.request.user or self.request.user.is_superuser -
django-Ajax Getting same button value for autogenerated Button's
Iam having a webpage which contains Multiple Buttons Generated using django.Using ajax,When I click a button the value send to server is of first button only.The button value is set according to value passed through context from django.Heres's the Code: <form method="POST" id='form'> {% csrf_token %} <div class="shadow p-3 mb-5 bg-body rounded" style="height: fit-content;"> <h5 class="card">Choose A Day!</h5> <p class="card-text">Booking Can be made for Next 15 Days.</p> <div class="btn-group" role="group" aria-label="Basic example"> <div class="row row-cols-3 row-cols-md-5 g-4"> {% for d,y in dates.items %} <div class="col"> <div class="card"> <button id='dt' name="date" type="submit" value={{d}} class="btn btn-success card-body shadow" style="font-size: 15px; width: fit-content;"> <div style=" margin-top: -15px; width: 100%; margin-bottom: 5px;"> <p style="font-weight: bolder;" class="card-text">{{y}}</p> </div> <div> <p class="card-text">{{d}}</p> </div> </button> </div> </div> {% endfor %} </div> </div> </div> </form> Ajax Code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $('#form').on('submit', function(e){ e.preventDefault(); $.ajax({ type : "POST", url: "", data: { date : $('#dt').val(), csrfmiddlewaretoken:'{{ csrf_token }}', }, success: function(data){ /* response message */ }, failure: function() { } }); }); </script> When i try to print the request.POST on views.py it shows same value of every button. Thanks In Advance -
React .map function not working after Django backend GET with axios
I am trying to make a simple React frontend while using Django Rest Framework as a backend. When I make the call to Django and then try to use the .map function to display the data, I get an "Uncaught (in promise) TypeError: this.state.users.map is not a function". I am a React noob so it is definitely something I am doing. import React from 'react'; import axios from 'axios'; class App extends React.Component { state = { users: [] } componentDidMount() { axios.get('http://127.0.0.1:8000/api/users/') .then(res => { const users = res.data; this.setState({ users }); }) } render() { return ( <ul> { this.state.users.map(user => <li>{user.username}</li>)} </ul> ) } } export default App; -
Likes, Dislikes & Views using Django Rest Framework
I'm working on a News Model where I want to perform the likes, dislikes & no of views functionality using the Django Rest Framework(ModelViewset). I have created a model for it Models.py class Post(models.Model): NEWS_TYPE = (('Images','Images'),('Multi-Images','Multi-Images'),('Image-Text','Image-Text'), ('Audio-Video','Audio-Video'),('Audio-Video-Text','Audio-Video-Text'),('Audio','Audio'), ('Audio-Text','Audio-Text')) POST_STATUS = (('Pending','Pending'),('Verified','Verified'),('Un-Verified','Un-Verified'), ('Published','Published'),('Mint','Mint')) category = models.ForeignKey(Category, on_delete=models.CASCADE) post_type = models.CharField(max_length=100, verbose_name='Post Type', choices=NEWS_TYPE) title = models.TextField(verbose_name='News Title') content = models.TextField(verbose_name='News Content') hash_tags = models.CharField(max_length=255, verbose_name='Hash Tags') source = models.CharField(max_length=255, verbose_name='News Source') author = models.ForeignKey(User, related_name='Post', on_delete=models.CASCADE) views = models.ManyToManyField(User,related_name='Views') likes = models.ManyToManyField(User, related_name='Likes') dislikes = models.ManyToManyField(User, related_name='Dislikes') status = models.CharField(max_length=20, verbose_name='Status', choices=POST_STATUS) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return (self.post_type)+ '-' +self.title serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' views.py class PostAPI(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer I have tried a lot of ways,but i'm not able to like, dislikes or view the post by multiple users. When a post is liked or disliked by one user & try to like or dislike by another user, it says Like with this post already exist Is there anything that I have left out. Please help it would be a great support. Thanks alot. -
How do I remove the ticks or inner circles of my polar area chart Chart.js
I have written the code for my chart in Jquery and I am using the chart to display data on my Django Web Page, I want to remove the inner circles which I think are called ticks along with the small numbers that are displayed with them. I have tried to use the ticks:{ display: false, } and scale:{ display: false, } but have had no luck with either I am not sure how to do it. Code for Chart: new Chart("chart_{{ i.pk }}_{{ t.pk }}", { type: "polarArea", data: { labels: labels_{{ t.pk }}, datasets: [{ fill: true, pointRadius: 1, {# borderColor: backgroundColors_{{ t.pk }} ,#} backgroundColor: backgroundColors_{{ t.pk }} , data: totals_{{ i.pk }}_{{ t.pk }}_arr, }] }, options: { responsive: false, maintainAspectRatio: true, plugins: { legend: { display: false, }, scale: { ticks: { display: false, }, gridLines: { display: false, lineWidth: 7, tickMarkLength: 30// Adjusts the height for the tick marks area }, }, title: { display: false, text: 'Chart.js Polar Area Chart' } } } }); {% endfor %} {% endfor %} {% endblock %}