Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble with the password hashing and salting
I'm trying to implement a login system for my web application, but I'm having trouble with the password hashing and salting. My current code is generating different hash values for the same password, and I'm not sure what I'm doing wrong. Can anyone help me troubleshoot this issue? Here is the relevant code: import hashlib import random def hash_password(password): salt = random.randint(0, 1000000) hashed_password = hashlib.sha256((password + str(salt)).encode()).hexdigest() return (hashed_password, salt) password = 'password123' hashed_password, salt = hash_password(password) print(hashed_password) Any help would be greatly appreciated! -
partial update in django rest viewset(not modelviewset)
i am beginner in django and i was trying to learn work with djangorest viewset(not modelviewset) and i cant find any resource to undrestand it. i want to learn how to write a partial_update in with viewset. here is what i have tried: models.py : class UserIdentDocs(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE, related_name = "user_ident_Docs") code = models.PositiveBigIntegerField(null=True) img = models.ImageField(null=True) video = models.FileField(null=True) is_complete = models.BooleanField(default=False) serializers.py: class AdminUserIdentSerializer(serializers.ModelSerializer): class Meta: model = UserIdentDocs fields = [ "owner", "code", "img", "video", "is_complete", ] views.py: from rest_framework.parsers import MultiPartParser, FormParser class UserDocAdminViewSet(viewsets.ViewSet): """User docs admin view set""" permission_classes = [AllowAny] parser_classes = (MultiPartParser, FormParser) serializer_class = AdminUserIdentSerializer queryset = UserIdentDocs.objects.filter(is_complete=False) def list(self, request): serializer = self.serializer_class(self.queryset, many=True) return Response(serializer.data) def retrive(self, request, pk=None): doc_object = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(doc_object) return Response(serializer.data) def create(self, request ): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) def partial_update(self, request, pk=None): doc_object = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(doc_object,data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({"detail":"item updated succesfuly"}, status=status.HTTP_205_RESET_CONTENT) urls.py: urlpatterns = [ ... # admin viewset for docs # list of accounts with is_complete=False path("admin/userdocs/", UserDocAdminViewSet.as_view({"get":"list", "post":"create"}), name="user-docs-list"), path("admin/userdocs/<int:pk>", UserDocAdminViewSet.as_view({"get":"retrive","patch":"partial_update"}), name="user-docs-detail"), ] i cant create user in browsable api but when i want to use partial update i can't … -
Celery can't find .settings
I installed redis and celery, set everything up, I run celery in terminal - everything is ok: (venv) Air-Evgeny:gunter_site evgenybar$ celery -A gunter_site worker -l info -------------- celery@Air-Evgeny.Dlink v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- macOS-13.0.1-x86_64-i386-64bit 2023-01-02 18:35:10 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: gunter_site:0x106d5a3a0 - ** ---------- .> transport: redis://127.0.0.1:6379/0 - ** ---------- .> results: - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . gunter_site.celery.debug_task Next, through the Python console, I try to run debug_task.delay() from celery.py to check that everything is working fine: >>> from gunter_site.gunter_site.celery import debug_task ^Everything is ok at this stage >>> debug_task.delay() ^Here I get a long list of problems that end with: ModuleNotFoundError: No module named 'gunter_site.settings' Redis launched in docker: docker run -p 6379:6379 --name redis-celery -d redis Redis work: evgenybar@Air-Evgeny ~ % docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 01d5f6356e0f redis "docker-entrypoint.s…" 2 hours ago Up 2 hours 0.0.0.0:6379->6379/tcp redis-celery I have already tried to create a test project with an older … -
i am creating a shayri app in android studio , and using django admin as a backend
My app is simple , django backend has only one model named AddShayri and it has feature image and description as a field . right now i created an api in django . but it is public . i want to protect it using api key . how will i do that ? -
Vue JS Form data not sending to Django Rest database
Im doing a project that include Django, django rest and vue js. I am able to get information from api to vue js frontend. But when I try and use Vue Js frontend to post data in a form after clicking the button nothing posts to django database Ive tried different things but nothing works appreciate any help thanks. heres my vue code: AllNotes.vue <template> <div class="notes_container"> <div class="add_note"> <form v-on:@submit="submitForm"> <div class="form-group"> <label for="content">Content</label> <input type="text" class="form-control" id="content" v-model="content" /> </div> <div class="form-group"> <button>Add Note</button> </div> </form> </div> <div class="note_content"> <h1>Tweets</h1> <ul class="note_list"> <li v-for="note in notes" :key="note.id"> <p>"{{ note.content }}""</p> <button @click="toggleNote(note)"> {{ note.completed ? "Undo" : "Complete" }} </button> <button @click="deleteNote(note)">Delete</button> </li> </ul> </div> </div> </template> <script> import axios from "axios"; export default { data() { return { notes: [], content: "", }; }, methods: { async getData() { try { // fetch tasks axios.get("http://localhost:8000/notes/").then((response) => { this.notes = response.data; }); // set the data returned as tasks } catch (error) { // log the error console.log(error); } }, }, submitForm: function () { // Send a POST request to the API axios .post("http://localhost:8000/notes/", { note: this.content }) .then((response) => { this.content = ""; this.notes.push(response.data); }); // … -
Browsers not caching images from s3
I'm hosting my personal portfolio on AWS Elastic Beanstalk, using s3 to store all the data, such as images, entries etc. This uses Django for the backend, and Reactjs for the frontend. When loading the content, the browser makes a request which gets these datapoints const getAllNodes = () => { fetch("./api/my-data?format=json") .then(response => response.json()) .then((data) => { setMyData(data); }); }; The returned values are the file image urls, something along the lines of https://elasticbeanstalk-us-east-1-000000000000.s3.amazonaws.com/api/media/me/pic.png with the following options ?X-Amz-Algorithm=XXXX-XXXX-XXXXXX &X-Amz-Credential=XXXXXXXXXXXXXXXXXXXXus-east-1%2Fs3%2Faws4_request &X-Amz-Date=20230102T182512Z &X-Amz-Expires=600 &X-Amz-SignedHeaders=host &X-Amz-Signature=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX When using this method of image storage and retreival, the images don't seem to be cached on the browser, so they have to be fetched every time, and slow down the site's functioning on subsequent visits. The following is a screenshot of the network tab when loading my site. How should I handle this situation? I would like to store the images in the database (and therefore on s3) so I can update them as necessary, but also have the advantage of having them be cached -
How to relate two tables with one of the field equal?
I am new with django and django rest framework. Excuse me for my bad english... I am trying to relate two django models: First one (class ModulMess) receives messages from remote numbered modules -moduleA received message "AAA". -moduleB received message "BBB" -moduleA received message "CCC" -moduleC received message "DDD"... Second one (class Owner) is a list of users who own the modules -UserXX owns moduleA and moduleC -UserYY owns moduleB... I am tryng to make search filter in order to list this sort of message for actual user: For example, for UserXX: UserXX received from moduleA messages "AAA" and "CCC" and from moduleC message "DDD" Please could you explain me theorically how to manage it? I am not abble to visualize how to make relations between the two models, as they have one equal field each one... Thank you very much! I tried: class Owner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='usermod') modulkey = models.CharField(max_length=255) date_in = models.DateTimeField(default=timezone.now, blank=True) def __str__(self): return f'{self.user.first_name} {self.user.last_name} | {self.modulkey}' class ModulMess(models.Model): modulkey = models.ForeignKey(Owner, on_delete=models.CASCADE) date_ini = models.DateTimeField(default=timezone.now, blank=True) message = models.CharField(max_length=255) But cannot reach to achieve a good serializer nor view... -
hi, I am using Django Framework and I want to limit the Questions but I want to give the limit from frontend and also to make Questions random
I am using Django Framework and I want to limit the Questions but I want to give the limit number from frontend I am using flutter as frontend so how can I do it, I did something but it is not working for me so how can I do it can someone help me, please when I want to test the URL in postman the limitation is not working, I want this limit for filtering the questions in frontend and I also I want to make questions to random and I do not know how to do it I thing I have to Make it with random here is my code: views.py class QuizQuetionsList(generics.ListAPIView): serializer_class=QuizQuetionsSerializer def get_queryset(self): quiz_id=self.kwargs['quiz_id'] quiz=models.Quiz.objects.get(pk=quiz_id) if 'limit' in self.request.GET: limit=int(self.request.GET['limit']) return models.QuizQuetions.objects.filter(quiz=quiz).order_by('id')[:limit] else: return models.QuizQuetions.objects.filter(quiz=quiz) urls.py path('chapter- quetions/int:quizChapter_id/int:limit/',views.QuizChapterQuetionsList.as_view()), to get solution to my problem -
Django: how to get value from model in view
I have a view that will conditionally display a breadcrumb trail based on the value of the object's "status" field. This works if I manually set the status value (ex status = "completed"). However, as a newbie, I can't figure out how to retrieve the value? status = Project.status is not working. Here is the view: class CompanyProjectsDetailView(DetailBreadcrumbMixin, UpdateView): model = Project queryset = Project.objects.get_with_counted_notes_documents_todos() template_name = 'company_accounts/project_detail.html' context_object_name = 'project' form_class = ProjectStatusForm status = Project.status if status == "completed": @cached_property def crumbs(self): return [ ("projects", reverse( "company_project:" + CompanyProjects.list_view_name, ) ), (f"completed projects", reverse( "company_project:" + CompanyProjects.list_view_name, ) ), ] -
Trying to set a coordinate to be the origin point adds another random point instead of pushing it to the front
I am trying to make a program for the traveling salesman problem that uses a nearest neighbor method. I am using Django for this project. The problem is, when I try to set one of the coordinate objects to the front of the calculation, it adds another different point to be the origin. Is there anything obviously wrong with my program? #calcRoute.py from django.db import models from .models import Coordinate, SortedPoint import math class Point: def __init__(self, longitude, latitude, isPassed, isOrigin): self.longitude = longitude self.latitude = latitude self.isPassed = isPassed self.isOrigin = isOrigin def haversine(lat1, lon1, lat2, lon2): # haversine formula to caluclate distance between points on a globe # convert degrees to radians lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2]) # calculate distance dlat = lat2 - lat1 dlon = lon2 - lon1 a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 c = 2 * math.asin(math.sqrt(a)) r = 6378 # radius of earth in kilometers return c * r def nearest_neighbor(points, origin): # return the nearest neighbor nearestNeighbor = None nearestDistance = float('inf') for point in points: # skip the origin point if point == origin: continue distance = haversine(origin.longitude, origin.latitude, point.longitude, point.latitude) if distance … -
How to properly update the foreign key's property of a Django model?
I have a Django Model named EmailSendingTask. This is the whole model- class EmailSendingTask(models.Model): order = models.OneToOneField(Order, on_delete=models.CASCADE, related_name='order') status = EnumChoiceField(SetupStatus, default=SetupStatus.active) time_interval = EnumChoiceField(TimeInterval, default=TimeInterval.five_mins) immediate_email = models.OneToOneField(PeriodicTask, on_delete=models.CASCADE, null=True, blank=True, related_name='immediate_email') scheduled_email = models.OneToOneField(PeriodicTask, on_delete=models.CASCADE, null=True, blank=True, related_name='scheduled_email') created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'EmailSendingTask' verbose_name_plural = 'EmailSendingTasks' def __str__(self) -> str: return f'EmailSendingTask: Order = {self.order}' The immediate_email and scheduled_email fields are responsible for holding two PeriodicTask objects. I have created a function called disable_scheduled_email, which is responsible for disabling the scheduled_email's periodic task. The detail of the function is here- def disable_scheduled_email(self): print(f'Disabling scheduled email...') self.scheduled_email.enabled = False self.save(update_fields=['scheduled_email']) Now, whenever I call this function and print the value of the self.scheduled_email.enabled, I find it False. But, when I try to look at the Django Admin site, the periodic task's enabled value remains as True. Why is it happening? -
When to make stripe subscription object and assign to user - Django
Tech Stack - Django, Angular I have been implementing stripe subscription model but stuck at some absurd scenario. I am getting Subscription not found by django. Please read the full scenario. Firstly I am successfull in creating stripe session. Code session = stripe.checkout.Session.create( metadata={'price_id':request.data.get('price_id'),'product_id':request.data.get('product_id'),'product_name':request.data.get('product_name')}, client_reference_id=request.user.id, customer=customer.stripe_customer_id, success_url='http://localhost:4200/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://localhost:4200/canceled.html', mode='subscription', line_items=[{ 'price': request.data['price_id'], # For metered billing, do not pass quantity 'quantity': 1, }], ) Webhooks Implementation: checkout.session.completed I am creating customer and subscription model in my db. print(user) customer = RecruiterUserProfile.objects.get(user = user) print(customer) customer.customer_id = session.customer customer.save() stripecustomer = Customer.objects.get(recruiter = customer, checkout_session_id = stripe_session_id) print(stripecustomer) stripecustomer.stripe_customer_id = stripe_customer_id stripecustomer.save() subscription,created = Subscriptions.objects.get_or_create(recruiter = customer, sub_id=stripe_subscription_id,customer_id = stripecustomer,stripe_customer_id = stripe_customer_id, payment_status=stripe_payment_status, amount = stripe_amount, status = stripe_status, product_id = stripe_metadata['product_id'], price_id = stripe_metadata['price_id'], product_name = stripe_metadata['product_name']) invoice.paid Then it triggers Invoice.paid, in which I am getting the subscription model and update others values in it. But since webhooks do not wait for our calls, Sometimes, It doesn't find the subscription. Now if I create subscription and customer in invoice.paid webhook using ger_or_create, How am I supposed to link it to the user. Below are my models: class Customer(models.Model): recruiter = models.OneToOneField(RecruiterUserProfile, on_delete=models.PROTECT) stripe_customer_id = models.CharField(max_length=80, blank=True, null=True) checkout_session_id = … -
How to pass current logged in users pk in django URLs?
So I have this detailview of Profile model (extended from django user model [onetoone]) class ProfileUpdate(UpdateView): model = Profile fields = [ "user", "bio", "fav_music_genre", "fav_Book_genre", "fav_movie_genre", ] success_url ="/home/all" in urls path('ProfileUpdate/<pk>',ProfileUpdate.as_view(),name="ProfileUpdate"), Now I wanna pass current logged in users pk in this path. I tried through template but its taking 1 by default. Is there any way by which I can put the current logged in users pk straight into the path in urls.py ? <a href="{% url 'app:ProfileUpdate' user.pk %}">Change</a> Any idea how can i approach this??? -
django upload image instantly by javascript
I am developing a chat app, working on the chat bubble container background image setting function. @csrf_exempt def chatProfileBackgroundUploadPost(request): if request.is_ajax() and request.method == 'POST': file = request.FILES['file'] try: ct = file.content_type if ct.split('/')[0] != 'image': return JsonResponse({}, status=400) chatProfile = request.user.chatProfile if chatProfile.background: chatProfile.background.delete() chatProfile.background = file chatProfile.save() return JsonResponse({'path': chatProfile.background.url}) except: pass return JsonResponse({}, status=400) window.crud = { backgroundUpload: function( file, success, error, ){ let fd = new FormData(); fd.append('file', file); $.ajax({ type: "POST", url: "{% url 'chat-profile-background-upload' %}", data: fd, processData: false, contentType: false, success: success, error: error, }) }, } chatMain.droppable = true; chatMain.ondragover = e => { e.preventDefault(); } chatMain.ondragenter = e => { chatMain.style.opacity = '0.75'; } chatMain.ondragleave = e => { chatMain.style.opacity = '1'; } chatMain.ondrop = e => { e.preventDefault(); let file = e.dataTransfer.files[0]; window.crud.backgroundUpload( file, res => { chatMain.style.opacity = '1'; setBackground(res.path); }, window.requestError, ) } sorry for the amount of code, the function is pretty straight forward: if a user drag and drop an image to the chat area, it will be set to background. and it works perfectly as I expected. but not friendly for smart phone, therefore, I added an upload button. (there is no form, only a … -
use @property in tow apps in django
app user model `class user(models.Model): name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE) @property def full_name(self) return self.name + self.last_name` app wallet model class wallet(models.Model): amount = models.IntegerField() admin wallet ` class UserrInline(admin.TabularInline): list_display = [full_name]---> but i cant use property in app user class walletAdmin(admin.ModelAdmin): inlines = [UserrInline]` admin.site.register(wallet, walletAdmin) i cant use property in tow apps in django -
Django, unable to filter all items under one or more categories attached to it using dynamic bootstrap 5 nav pills using many to many relationship
Given the files below am unable to filter all items relating to one category or more than one category. Example: let items = A, B, C, D categories = 1, 2, 3, 4 items in category 1 = A and B items in category 2 = C and D category 3 and 4 are not having any items attached to them, they should return empty Have a look at the files and kindly guide below models.py class Category(models.Model): name = models.CharField() class Item(models.Model): name = models.CharField() category = models.ManyToManyField(Category) views.py def filter_item(request): template = 'template.html' cat = Category.objects.all() context = {'cat': cat, } return render(request, template, context) template.html <ul class="nav nav-tabs" id="myTab" role="tablist"> {% for c in cat %} <li class="nav-item" role="presentation"> <button class="nav-link {% if c.id == '{{ c.id }}' %} active {% endif %}" id="{{ c.name|slugify }}-tab" data-bs-toggle="tab" data-bs-target="#{{ c.name|slugify }}" type="button" role="tab" aria-controls="{{ c.name|slugify }}" aria-selected="true">{{ c.name }}</button> </li> {% endfor %} </ul> <div class="tab-content" id="myTabContent"> {% for c in cat %} {% for i in c.item_set.all %} <div class="tab-pane fade {% if i.category.id == c.id %} show active {% endif %}" id="{{ i.name|slugify }}" role="tabpanel" aria-labelledby="{{ i.name|slugify }}-tab">{{ i.title }}</div> {% endfor %} {% endfor %} … -
KeyError at 'body' when i send a request with fecth. Django and ReactJs project
i´m doing a project with django (django rest framework) as backend and React js as Front for some reason the 'body' isn´t send to the backend. here the django view: @api_view(['POST']) def crearTarea(request): data = request.data print(data['body']) tarea = Tarea.objects.create( body=data['body'] ) serializer = TareaSerializer(tarea, many=False) return Response(serializer.data) the request in react with fetch: let crear = () =>{ let tarea_json = { "titulo": document.getElementById("titulo").value , "descripcion": tarea.descripcion, "tiempo_tarea": 1, "fk_idUsuario": 1 } fetch('/api/tareas/create', { method: "POST", body: JSON.stringify(tarea_json), headers: { 'Content-Type': 'application/json' } }) } the model: class Tarea(models.Model): titulo = models.CharField(max_length=50) descripcion = models.CharField(max_length=150) tiempo_tarea = models.ForeignKey(Tiempo_tarea, on_delete = models.CASCADE) fk_idUsuario = models.ForeignKey(User, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["created"] db_table = "Tarea" verbose_name_plural = "Tareas" verbose_name = "Tarea" def __str__(self) -> str: return self.titulo and the error: enter image description here i´m traying to create a new instance with the method POST and fecth but it doesn´t run. I would be grateful if you could help me -
Django file upload returns None, please help me
im trying to learn Python and Django, when i try to upload a file in my form Django detect my file as "None", if someone can help me i would apreciate it a lot, Below is my code. forms.py: from django import forms class FormularioTrabajo(forms.Form): email = forms.EmailField(label="Correo Electrónico:", max_length=254) Currículum = forms.FileField() views.py: In views i want to save the file uploaded in the directory /media/ def trabaja(request): if request.method == 'POST': form = FormularioTrabajo(data=request.POST, files=request.FILES) if form.is_valid(): file = request.FILES.get('file', None) if file is not None: file_name = file.name file_path = '/media/' + file_name with open(file_path, 'wb+') as destination: for chunk in file.chunks: destination.write(chunk) form.save() return HttpResponseRedirect(reverse("miapp:index")) else: return HttpResponse('None') else: form = FormularioTrabajo() return render(request, "web/trabajar.html", {'form':form}) This is my template html: {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} {% bootstrap_messages %} <!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"> {% load static %} <link rel="stylesheet" href="{% static '/style.css' %}"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script> <title>Trabaja con nosotros</title> </head> <body> <header> <br> <ul> <li><a href="conocernos.html">Conócenos</a></li> <li><a href="login.html">Inicio de Sesión</a></li> <li><a href="signup.html">Registro de usuario</a></li> <li><a href="contacto.html">Contacta con nosotros</a></li> </ul> {% load static %} <a href="index.html"><img src="{% static 'img/logo.PNG'%}" class="logo"></a> </header> <div class="work-box"> … -
How to get the results of a queryset to display as a subsection within a another class-based list view
Need help / advice with Django. I have two apps with models. App1 Player with Model player App2 Competition with models Competition and Team the latter being a through table expanding on the Player table Players can be assigned to multiple Competitions Each competition has a Team via a through table expanding on the Player table Extracts of models below Player and Competition have class based list and detail views In the Competition detail view I would like to list all Players for that particular competition. I can only get as far as proving the principle on the command line >>> comp_one = Competition.objects.get(name="comp one") >>> comp_one.team_members.all() <QuerySet [<Player: Armstrong>, <Player: Smith>, <Player: Jones>]> Then as a novice I’m a bit lost how to perform the queryset on the current competition rather than hard coded competition name where to put the queryset function - views.py or models.py how to get the Team listed in the competition detail template class Player(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) first_name = models.CharField(max_length=50) nick_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=100) class Meta: ordering = ["last_name"] def __str__(self): return self.last_name def get_absolute_url(self): return reverse(“player_detail", args=[str(self.id)]) class Competition(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) … -
How to get the row's whose id' value is used in other rows as parent id value
Id parent id 1. Null 2. Null 3. 1 4. 1 5. 1 6. 2 7. 2 8. 2 9. 2 10. 2 I have this table I want something like this I have one parameter Min parent id count Which means if i set min parent id count 2 I should get row with id 1 and raw with id 2 Cause row with id 1 is used in parent id for 3 times And row with id 2 is used in parent id for 5 times If set min parent id count to 4 I should only get row which has id 2 cause id is used in parent id for 5 times What i want is to check for every row how many times its id value used in as value in parent id For here is 1 is used for 3 times And id 2 is used for 5 times -
how can I display the average rating as stars?
I'm working on my web app and I want to display the average rating to doctors but when I tried the avg and created a function in my model it just showed me the last rate, not the average this is my model class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) def averagreview(self): reviews = Comments.objects.filter( doctor=self).aggregate(average=Avg('rating')) avg = 0 if reviews["average"] is not None: avg = float(reviews["average"]) return avg def countreviews(self): reviews = Comments.objects.filter( doctor=self).aggregate(count=Count('id')) cnt = 0 if reviews["count"] is not None: cnt = int(reviews["count"]) return cnt this the Comments model class Comments(models.Model): doctor = models.ForeignKey( Doctor, on_delete=models.CASCADE, related_name='comment') created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comments') # co_email = models.ForeignKey( # User, on_delete=models.CASCADE, related_name='comment') review = models.TextField(max_length=400, verbose_name='التعليق') rating = models.IntegerField(default=0) this is my HTML <div class="rating"> <div class="text"> <span class="rating-star"> <i class="fa fa-star{% if doctor.averagreview < 1%}-o empty checked{% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if doctor.averagreview < 2%}-o empty checked {% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if doctor.averagreview < 3%}-o empty checked{% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if doctor.averagreview < 4%}-o empty checked{% endif %}" aria-hidden="true"></i> <i class="fa fa-star{% if doctor.averagreview < 5%}-o empty checked{% endif %}" … -
Django development Server does not reload in docker container
with cookiecutter-django I use the docker setup in the sync version. Unfortunately, the development server does not restart automatically on any code change. Which means I would need to restart the containers on every change, which is a hassle. Thanks for any help -
In Django, what's the difference between verbose_name as a field parameter, and verbose_name in a Meta inner class?
Consider this class: class Product(models.Model): name = models.Charfield(verbose_name="Product Name", max_length=255) class Meta: verbose_name = "Product Name" I looked at the Django docs and it says: For verbose_name in a field declaration: "A human-readable name for the field." For verbose_name in a Meta declaration: "A human-readable name for the object, singular". When would I see either verbose_name manifest at runtime? In a form render? In Django admin? -
401 Client Error: Unauthorized for url [mozilla-django-oidc - Keycloack]
I'm integrating keycloak authentication in my django app After i am logged in into keycloak server i am facing error in the login callback HTTPError at /oidc/callback/ 401 Client Error: Unauthorized for url: http://keycloak:8080/realms/SquadStack/protocol/openid-connect/userinfo here is my docker-compose.yml services: db: image: postgres:13 environment: - POSTGRES_DB=squadrun - POSTGRES_USER=postgres - POSTGRES_PASSWORD=123456 volumes: - ~/.siq/pg_data:/var/lib/postgresql/data ports: - "5432:5432" networks: - local-keycloak redis: image: redis expose: - 6379 networks: - local-keycloak celery: build: context: . dockerfile: Dockerfile command: celery --app=squadrun worker -Q voice_make_ivr_india_queue,voice_send_email_india_queue,voice_send_email_india_upstox_queue,voice_send_sms_india_queue,voice_workflow_india_queue,celery_voice,ivr_queue,voice_analytics_and_metrics_queue,voice_fsm_india_queue,dnd_queue,voice_bulk_sync,voice_dnd_and_compliance_actions_queue,voice_notifications_queue,voice_make_ivr_india_queue,voice_send_email_india_queue,voice_send_email_india_upstox_queue,voice_send_sms_india_queue,voice_sync_ivr_details_india_queue,voice_workflow_india_queue,voice_sync_sms_details_india_queue,voice_send_sms_india_upstox_queue,voice_dnd_and_compliance_actions_upstox_queue,voice_imports_queue --concurrency=3 --without-heartbeat --without-gossip -n celery.%%h --loglevel=INFO container_name: celery working_dir: /home/docker/code volumes: - .:/home/docker/code depends_on: - db - redis networks: - local-keycloak web: build: context: . dockerfile: Dockerfile command: python -Wignore manage.py runserver 0.0.0.0:8001 container_name: django_web3 volumes: - .:/home/docker/code ports: - "8001:8001" depends_on: - db - redis networks: - local-keycloak keycloak: image: quay.io/keycloak/keycloak:20.0.2 command: start-dev container_name: keycloak ports: - "8080:8080" environment: - KEYCLOAK_ADMIN=admin - KEYCLOAK_ADMIN_PASSWORD=admin networks: - local-keycloak networks: local-keycloak: driver: bridge here is my setting.py AUTHENTICATION_BACKENDS = [ 'apps.voice.voice_auth.auth.KeycloakOIDCAuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ] OIDC_RP_CLIENT_ID = "voice-dashboard" OIDC_RP_CLIENT_SECRET = "rnX0eo0R43xnZficrZTkQQseyBip4V7t" OIDC_RP_SIGN_ALGO = "RS256" OIDC_OP_JWKS_ENDPOINT = "http://keycloak:8080/realms/SquadStack/protocol/openid-connect/certs" OIDC_OP_AUTHORIZATION_ENDPOINT = "http://172.20.0.3:8080/realms/SquadStack/protocol/openid-connect/auth" OIDC_OP_TOKEN_ENDPOINT = "http://keycloak:8080/realms/SquadStack/protocol/openid-connect/token" OIDC_OP_USER_ENDPOINT = "http://keycloak:8080/realms/SquadStack/protocol/openid-connect/userinfo" LOGIN_REDIRECT_URL = "/voice/dashboard/index/" LOGOUT_REDIRECT_URL = "/voice/dashboard/index/" here is auth.py class KeycloakOIDCAuthenticationBackend(OIDCAuthenticationBackend): def create_user(self, claims): """ Overrides Authentication Backend so … -
How can I run the for loop once on html (Django)
enter image description hereHow can I run the for loop once? when I run {% for q in questions|slice:':1'%} I have the problem that other questions in the database are not executed. I would like only one question per page to be displayed and after I click on next the next question will be loaded. I don't know how to solve the problem. See picture how two questions loaded in database on one page instead of just one. I hope someone have solution <form method="POST" action=""> {% for q in questions%} {% csrf_token %} {% if q.kategorie == category and q.flaag == True and forloop.first %} <br/> <div class="flex-containe"> <div class="container1"> <div class="position_startButton"><button type="submit" name="next_question" value="{{q.question}}" class="neuefragenladen_button">Nächste Frage!</button></div> <div class="game_options"> <span> <input type="subit" id="option1" name="option1" class="radio" value="option1"/> <label for="option1" class="option" id="option1_label">{{q.op1}}</label> </span> <span> <input type="subit" id="option2" name="option2" class="radio" value="option2"/> <label for="option2" class="option" id="option2_label">{{q.op2}}</label> </span> <div class="game_question"> <h1 id="display_question">{{q.question}}</h1> </div> <span> <input type="subit" id="option3" name="option3" class="radio" value="option3"/> <label for="option3" class="option" id="option3_label">{{q.op3}}</label> </span> <span> <input type="subit" id="option4" name="option4" class="radio" value="option4"/> <label for="option4" class="option" id="option4_label">{{q.op4}}</label> </span> </div> </div> </div> <footer class="bottom-area"> <a class="information" href="https://www.google.at/?hl=de.">Impressum |</a> <a class="information" href="https://www.google.at/?hl=de.">Datenschutz |</a> <a class="information" href="https://www.google.at/?hl=de.">Support</a> </footer> ..... views.py def quiz(request): global globalCategory global globalQuestions global empty …