Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does this weird "content" attribute has no file associated with it error comes up in Django?
This question might have been asked several times before but I referred to them but I was not able to fix my problem. That is why I am having to ask it. So, I have a Django app where users can set up tasks. They can also upload attachments. I was successfully able to implement this but for some reason it has stopped working now. These are the relevant code: models.py def get_attachment_dir(instance, filename): return f"users/{instance.parent_task.creator.username}_{instance.parent_task.creator.pk}/task_attachments/{instance.parent_task.pk}/{filename}" class Attachments(models.Model): content = models.FileField(null=True, blank=True, upload_to=get_attachment_dir, help_text="Add important documents or pictures") parent_task = models.ForeignKey(ToDo, on_delete=models.CASCADE) uploaded_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Attachments of {self.parent_task.title}" forms.py class TaskAttachmentForm(forms.ModelForm): class Meta: model = Attachments fields = ["content"] Relevant part of the view function that renders the attachment form if request.method == "POST": attachment_form = TaskAttachmentForm(request.POST, request.FILES) if attachment_form.is_valid(): # Making sure we get no Integrity Errors attachment_form.instance.parent_task = todo attachment_form.save() if not todo.has_attachments: todo.has_attachments = True todo.save() messages.success(request, "Your files were uploaded successfully") else: attachment_form = TaskAttachmentForm() attachments = Attachments.objects.filter(parent_task=todo) context = { "todo": todo, "note_form": ToDoNotesForm(), "note": note, "subtask_form": SubTaskForm(), "attachment_form": attachment_form, "subtasks": subtasks, "due_form": DueDateForm(), "title": todo.title, "percentage": percentage, "attachments": attachments } return render(request, "ToDo/detailed_view.html", context=context) detailed_view.html relevant code where attachments are handled … -
how to change image in database by Modelform in django
I will do change image in database by model forms. But i can not do it. My code details in blew Here is models.py: class About_Profile(models.Model): about_info = models.TextField(null=True, blank=True) about_title = models.CharField(max_length=50, null=True, blank=True) about_sumary = models.TextField(null=True, blank=True) about_image = models.ImageField(upload_to='images/', null=True, blank=True) name = models.CharField(max_length=30, null=True, blank=True) age = models.IntegerField(null=True, blank=True) birthday = models.DateField(max_length=30, null=True, blank=True) phone = models.IntegerField(null=True, blank=True) city = models.CharField(max_length=30, null=True, blank=True) degree = models.CharField(max_length=20, null=True, blank=True) website = models.CharField(max_length=20, null=True, blank=True) mail = models.EmailField(max_length=20, null=True, blank=True) freelance = models.CharField(max_length=20, null=True, blank=True) here is forms.py class About_ProfileForm(ModelForm): class Meta: model = models.About_Profile fields = '__all__' labels = { 'city':'Enter Your Address', 'about_title':'Enter Your About Title', 'name':'Enter Your Name', 'birthday':'Enter Date of Birth', 'age':'Enter Your Age', 'mail':'Enter Email Id', 'about_sumary':'Enter Your Personal Summary', 'about_info':'Enter Your About Information', 'phone':'Enter Your Phone Number', 'freelance':'Enter Present Working Place', 'website':'Enter Website Address', 'degree':'Enter Your Educational Title', 'about_image':'Enter Profile Image', } widgets = { 'about_image': forms.FileInput(attrs={'class': 'form-control-file', 'required':'True'}), 'name': forms.TextInput(attrs={'class': 'form-control', 'required':'True'}), 'birthday': forms.DateInput(attrs={'class': 'form-control', 'required':'True'}), 'age': forms.NumberInput(attrs={'class': 'form-control', 'required':'True'}), 'phone': forms.NumberInput(attrs={'class': 'form-control', 'required':'True'}), 'mail': forms.EmailInput(attrs={'class': 'form-control', 'required':'True'}), 'degree': forms.TextInput(attrs={'class': 'form-control', 'required':'True'}), 'city': forms.TextInput(attrs={'class': 'form-control', 'required':'True'}), 'website': forms.TextInput(attrs={'class': 'form-control', 'required':'True'}), 'freelance': forms.TextInput(attrs={'class': 'form-control', 'required':'True'}), 'about_title': forms.TextInput(attrs={'class': 'form-control', 'required':'True'}), 'about_info': forms.Textarea(attrs={'class': 'form-control', … -
Run script in form submission with command line arguments
I have a form where I am putting some parameter and when the form submission will take place, form parameters will go to the script as an argument. But when I am calling subprocess.call or subprocess.run with the scripts it is throwing a syntax error. What will be the correct syntax for that? I have to run script like below python script.py --ar1=formlparameter1 --ar2=formlparameter2 --ar3=formlparameter3 The above line should be the same. import subprocess from django.contrib import messages def nboarding(request): if request.method == 'POST': form = NForm(request.POST, request.FILES) if form.is_valid(): operation = form.cleaned_data['operation'] partner = form.cleaned_data['partner'] file = form.cleaned_data['file'] output = script_function(operation, partner, file) messages.success(request, '%s Successfully...' %operation) return redirect('nboarding') #messages.success(request, success_message, extra_tags='safe') #return redirect('/xxx') else: form = NForm() context = { 'form': form, 'menu_device':'active', 'submenu_nboarding':'active', } return render(request, 'monitor/nboarding_form.html', context=context) def script_function(operation, partner, file): #--operation = operation, --partner = partner, --filepath = file return subprocess.call(['python', '/path/to/script.py', operation '--partner' = partner '--filepath' = file], shell=False, timeout=1800) How to run this using right syntax ? return subprocess.call(['python', '/path/to/script.py', operation '--partner' = partner '--filepath' = file], shell=False, timeout=1800) Thanks -
Formset shows invalid when updating the form
Can anyone help me why my formset is showing invalid when trying to update the form. It works perfectly when creating the form. The normal form is editing but the formset is not. `def content_edit_view(request, id): course = get_object_or_404(Course, id=id) LectureFormset = modelformset_factory(Lecture, fields=('lecture_title', 'lecture_content', 'youtube_url'), extra=0) if course.user != request.user: raise Http404() if request.method == 'POST': content_edit_form = ContentEditForm(request.POST or None, request.FILES or None, instance=course) formset = LectureFormset(request.POST or None, request.FILES or None) if content_edit_form.is_valid(): content_edit_form.save() data = Lecture.objects.filter(course=course) # give index of the item for a formset item strting form 0 and (f)the item itself if formset.is_valid(): for index, f in enumerate(formset): if f.cleaned_data: if f.cleaned_data['id'] is None: video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content'), youtube_url=f.cleaned_data.get('youtube_url')) video.save() else: video = Lecture(course=course, lecture_title=f.cleaned_data.get('lecture_title'), lecture_content=f.cleaned_data.get('lecture_content'), youtube_url=f.cleaned_data.get('youtube_url')) d = Lecture.objects.get(id=data[index].id) #get slide id which was uploaded d.lecture_title = video.lecture_title # changing the database tiitle with new title d.lecture_content = video.lecture_content #changing the database content with new content d.youtube_url = video.youtube_url # changing the database content with new content d.save() return redirect('teacher-profile') else: print('formset is invalid') else: print("form is invalid") else: content_edit_form = ContentEditForm(instance=course) formset = LectureFormset(queryset=Lecture.objects.filter(course=course)) context = { 'contentForm': content_edit_form, 'course': course, 'formset': formset, } return render(request, 'apps/contentEdit.html', context)` -
Excel file cannot open with uwsgi + django?
The excel file generated cannot be open when my project started with uwsgi as it can be opened successfully with manage.py runserver My main codes like below: ── test_excel ├── urls.py ├── wsgi.py └── settings.py ── manage.py urls.py from django.contrib import admin from django.urls import path from django.views import View from openpyxl.writer.excel import save_virtual_workbook import pandas as pd from django.http import HttpResponse, StreamingHttpResponse import xlrd import openpyxl from openpyxl import Workbook from openpyxl.styles import Font, Alignment from openpyxl.writer.excel import save_virtual_workbook from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE class TestExcelView(View): def get(self, request): # indexs = {0: ['cost', '2020-01', 'testing'], # 1: ['cost', '2020-01', '360 Limited'], # 2: ['cost', '2020-02', 'Korea Co.,LTD'], # 3: ['cost', '2020-02', 'ADS4EACH HK TECH LIMITED']} # columns = [['1'], ['amy'], ['tom'], ['zara'], ['jay'], ['Lee'], ['Uzi'], ['Zome'], ['Qoe'], ['Aoi'], ['Yeezy'], # ['Hazy'], ['Wash'], ['pany'], ['zoey'], ['Moe'], ['total']] # datas = { # 0: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.85], # 1: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.85], # 2: [0.0, 0.0, 0.0, 0.0, 0.0, 7.85, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 7.85], # 3: … -
Error while working on Stripe --> As per Indian regulations, export transactions require a customer name and address
The complete error is, InvalidRequestError at /orders/charge/ Request req_r6yTG446gAmhYr: As per Indian regulations, export transactions require a customer name and address. More info here: https://stripe.com/docs/india-exports i followed the above link to fix this issue but no luck :( import stripe from django.conf import settings from django.contrib.auth.models import Permission from django.views.generic.base import TemplateView from django.shortcuts import render stripe.api_key = settings.STRIPE_TEST_SECRET_KEY class OrdersPageView(TemplateView): template_name = 'orders/purchase.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['stripe_key'] = settings.STRIPE_TEST_PUBLISHABLE_KEY return context def charge(request): # Get the permission permission = Permission.objects.get(codename='special_status') # Get user u = request.user # Add to user's permission set u.user_permissions.add(permission) if request.method == 'POST': charge = stripe.Charge.create( amount=3900, currency='usd', description='Purchase all books', source=request.POST['stripeToken'] ) return render(request, 'orders/charge.html') to see my complete project here is the link: https://github.com/YashMarmat/Bookstore-Project-django -
How do you assign a Charfield instead of ID in a Django API endpoint?
Hi I want to have an API endpoint that is based on name instead of ID in Django. Supposed I have: #models.py class Tag(models.Model): name = models.CharField(max_length=255, blank=True, unique=True) description = models.CharField(max_length=255) def __str__(self): return self.name #serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name', 'description') #views.py class TagViewSet(viewsets.ModelViewSet): queryset = Tag.objects.all().order_by('id') serializer_class = TagSerializer #urls.py router.register(r'tags', TagViewSet, basename='tag') If I have: { "id": 1, "name": "Urban", "description": "Urban" } I want my to access that data and the endpoint to look like: https://testserver/myapp/tags/Urban and not: https://testserver/myapp/tags/1 -
Best secure solution to login in web page python [closed]
What's the most secure solution to login (user/password) using TCP/80 port to access a resource like a web page or a simple Hello World? -
connect to instance sql server remotly django
I connect to instance sql server remotly using odbc sql server from lunix. when I sue server = host_ip,port , It works. but when I use server = instance name , I get error ''' import pyodbc import sqlserverport server = 'DESKTOP-7VQIKEC\SQLEXPRESS' serverspec = '{},{}'.format(server, sqlserverport.lookup(server, 'SQLEXPRESS')) connection_params = 'DSN=ODBC Driver 17 for SQL Server;DATABASE=test;UID=sa;PWD=123456;server={};'.format(serverspec) ''' error : socket.gaierror: [Errno -2] Name or service not known error in : serverspec = '{},{}'.format(server, sqlserverport.lookup(server, 'SQLEXPRESS')) github link for sqlserverport: https://github.com/gordthompson/sqlserverport -
email field is showing twice on profile update form
building a basic blog website using Django. In profile update page, i am getting email field twice. And one email field shows * mark for compulsory field and other one doesnt. I want both fields in update profile page to be compulsory(*), i.e username and email fields. Codes are as follow: forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): mail = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] user.views.py from django.shortcuts import render,redirect # from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm # @csrf_protect def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to login!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm() p_form = ProfileUpdateForm() u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() … -
django database structure to like entries
I have unique titles and entries which are connected to the titles by foreignkeys: Title model: class Title(models.Model): first_author = models.ForeignKey("auth.user", on_delete= models.CASCADE) title = models.CharField(max_length = 50, unique = True) created_date = models.DateTimeField(auto_now=True) def __str__(self): return self.title Entry model: class Entry(models.Model): title = models.ForeignKey("titles.title", on_delete= models.CASCADE) user = models.ForeignKey("auth.user", on_delete= models.CASCADE) created_date = models.DateTimeField(auto_now= True) updated_date = models.DateTimeField(null = True) content = models.TextField(max_length=10000,) def __str__(self): return self.content I want to create a liking system where users can like entries. After doing my research I decided to create a like model such as: class Like(models.Model): title = models.ForeignKey("titles.title", on_delete= models.CASCADE) entry = models.OneToOneField("entries.entry", on_delete= models.CASCADE) liker = models.ManytoManyfield("auth.user,symmetrical = False) def __str__(self): return self.content But I'm not sure if that is the most efficient method for my situation as later on I want to be able to detect every title's most liked entry in order to mark it. Also track like amounts of entries and check whether an entry is already liked by request.user. I wonder if there is anything I'm missing or I'm confused about. I'm Open to any suggestions. Thank you for reading! -
Periodic task celery every world minute
The celery tasks stops every minute, but the countdown starts from the time when I start the celery. Can I create a periodic task that will be executed every minute of time (like on a clock) and not related to when I started the task. @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(60.0, do_something.s(), expires=10) Now it work like this, I'am started celery on 10:10:24 (H:M:S): do_something - 10:11:24 do_something - 10:12:24 do_something - 10:13:24 do_something - 10:14:24 ... But I want to see do_something - 10:11:00 do_something - 10:12:00 do_something - 10:13:00 do_something - 10:14:00 ... exactly at 00. Can I do that with easy way? Thank you! -
Passing a dynamic variable from html template to a view in Django
I am creating a Habit tracking app with Django. I am a beginner. In my app, I create a habit then I want to add progress to it. I have created two models one is "Habit" and the other is "Progress" with a foreign key to Habit object Now when I click add progress button it should pass the habit object id to a view so that I can fetch and set the foreign key of this progress model to habit object and also display some heading on the progress HTML page. After reading some post I got to know that I can pass the value with javascript. But it is not working. Here is my HTML code `{% for habit in habit_list %} <div class="card mb-4" style="background-color: #6c757d;" > <div class="card-body"> <h2 class="card-title">{{ habit.title }}</h2> <!-- <p class="card-text text-muted h6">{{ post.author }} | {{ post.created_on}} </p>--> <p class="card-text">{{habit.description|slice:":200" }}</p> <!-- <p>{{habit.id}}</p>--> <a href="{% url 'detail' habit.id %}" class="btn btn-primary">Read More &rarr;</a> <a class="btn btn-primary text-white" onclick="addProgress()" name={{ habit.id }}>Add Progress</a> </div> </div> {% endfor %} </div> </div> <script> function addProgress(){ var habit_id = $(this).data('name'); $.ajax({ type: "POST", url: {% url 'add_progress' %}, data: habit_id, success:function(result){ alert("Success"); } }); } … -
Django JWT and Social Auth
So I'm using jwt authentication and I'm facing a problem. I have no idea how to properly redirect my users after a successful Google login. From what I'm understanding, when a user logged in, he receives an access and a refresh token via : path('token/obtain/', jwt_views.TokenObtainPairView.as_view(), name='token_create'), path('token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), But now, what should I do after my users successfully logged in with their google account ? Should I force them to redirect to those urls ? I'm very confused about that. Thank you for your time -
Have slugfield be as the same value as other field
I am trying to get a Slugfield saved with the same value as another field. I can't get this to work.. I trie the following (as well as countless of others like changing the datacenter textfield to a slugfield.. Didn't work at all) # View that saves the model to the database: class save_device(CreateView): model = AddDevice form = add_device fields = ['merk', 'model', 'locatie', 'datacenter', 'device_naam', 'aantal_poorten'] template_name = 'Item/Save_Device.html' def get(self, request, *args, **kwargs): device_form = self.form() context = {'device_form': device_form} return self.render_to_response(context) #Model: class AddDevice(models.Model): merk = models.CharField(max_length=100) model = models.CharField(max_length=100) locatie = models.CharField(max_length=100) datacenter = models.TextField(max_length=40, null=False) device_naam = models.CharField(max_length=100) aantal_poorten = models.CharField(max_length=500) slug = models.SlugField(null=False) def get_absolute_url(self): return reverse('dc_name', kwargs={'slug': self.slug}) # And the urls: urlpatterns = [ path('<slug:slug>/', dc_view.as_view(), name='dc_name'), ] The Slugfield saves with no value. # Full traceback: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/save_device/ Django Version: 3.0.5 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Dokuwiki_updatet'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/nickdevries/PycharmProjects/Dokuwiki_updatet/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/nickdevries/PycharmProjects/Dokuwiki_updatet/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/nickdevries/PycharmProjects/Dokuwiki_updatet/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, … -
How to invoke a postgres function in django?
def get_Data(self, number): data = User.objects.filter(Q(p_m__icontains=number) | Q(altphones__icontains=number), ).first() return leadData; This altPhones is an array in db and the following function in my db create function string_array_to_string(text[], text, text) returns text as $$ select array_to_string($1, $2, $3) $$ language sql cost 1 immutable I want to invoke this function in the filter clause for altphones. How can I achieve this? -
My api returns HTTP-201 but nothing changes in db?
I am trying to create an article,it gives me HTTP-201,it is successful but i can't see any registered article in django-admin. Serializers.py class ArticleCreateSerializer(serializers.ModelSerializer): caption = serializers.CharField(required=False) details = serializers.CharField(required=False) class Meta: model = Article fields = ('caption','details') def create(self, validated_data): author = self.context['request'].user.profile return author return Article.objects.create(**validated_data) Views.py class ArticleView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def perform_create(self, request, format=None): try: serializer_context = { 'request': request } serializer_data = request.data.get({}).get('author') serializer = self.get_serializer_class(data=serializer_data, context=serializer_context, ) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_201_CREATED) else: return Response(status=status.HTTP_400_BAD_REQUEST) except: return Response(status=status.HTTP_406_NOT_ACCEPTABLE) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleCreateSerializer() return Response(serializer.data) When i register user it does it successfully.But not this one.Does anyone know why? -
Using Django and Bootstrap Stylesheet not importing with the following error: MIME type ('text/html') is not a supported stylesheet MIME type
I'm using Django with a Bootstrap template (SB Admin 2). I'm wrapping href and src tags in the template with "{% static 'link_goes_here' %}". I have already tried this with another template where it worked fine. Here, it gives the following errors when I inspect it. when I click inspect element in my localhost This contains the code associated with the errors above. I'm still really new to programming and this is my first question here so I apologize if I didn't explain it in a better manner. -
hi i want to show my articles latest article should appear first
hi i want to show my articles latest article should appear first i used class Meta in models but its not working it does not show any error but it it shows old articles on top. models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone class Article(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(default=timezone.now) thumb = models.ImageField(default='default.png', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) class Meta: ordering = ['-date'] def __str__(self): return self.title def snippet(self): return self.body[:100]+'...' -
Is there an easy way to submit a single form field when more than one is required?
I have a model with 3 fields: class MySuperSimpleModel(models.Model): field1 = models.CharField(max_length=255, blank=False, null=False) field2 = models.CharField(max_length=255, blank=False, null=False) field3 = models.CharField(max_length=255, blank=False, null=False) I want to display this using a class based generic UpdateView. Simple enough: class MySimpleUpdateView(UpdateView): model = MySuperSimpleModel fields = ['field1', 'field2', 'field3'] template_name = 'mytemplate.html' // etc. However, in mytemplate.html I want to use bootstap tab panels to display field1, field2, and field3 all on separate tabs. I also want the user to just be able to update/save this single field on the tab, without validating the whole model. This is easy enough when using {{ form }} if I just split the fields over different tabs: <ul class="nav nav-tabs" id="myTab"> <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#field1">field1</a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab">field2</a> </li> <li class="nav-item"> <a class="nav-link" id="contact-tab" data-toggle="tab" href="#field3">field3</a> </li> </ul> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade show active" id="field1"> <form method="post"> {{ form.field1 }} <input type="submit"> </form> </div> <div class="tab-pane fade" id="field2"> <form method="post"> {{ form.field2 }} <input type="submit"> </form> </div> <div class="tab-pane fade" id="field3"> <form method="post"> {{ form.field3 }} <input type="submit"> </form> </div> </div> However, because each field is required (blank=False), if I only submit a single field … -
Execute GROUP BY HAVING in django orm on a many to many relationship?
Consider two models like: class Tag(models.Model): name = models.CharField(max_length=255, unique=True, default="") class Problem(models.Model): tags = models.ManyToManyField(Tag, related_name="problems") index = models.CharField(max_length=5) name = models.CharField(max_length=255) rating = models.IntegerField(default=-1) I want to execute the following query: SELECT "p"."index", "p"."name", "p"."rating" FROM problem p WHERE p.id IN ( SELECT pt.problem_id FROM problem_tags pt JOIN tag t ON pt.tag_id = t.id WHERE t.name IN ('math', 'binary search', 'implementation') GROUP BY pt.problem_id HAVING COUNT(*) = 3 ) ORDER BY rating, index; I used something like: Problem.tags.through.objects.values("problem_id").filter( tag__name__in=("math", "binary search", "implementation") ).annotate(count=models.Count("*")).filter(count=3) But it issues the following query which the first COUNT(*) in SELECT is redundant and wrong: SELECT "api_problem_tags"."problem_id", COUNT(*) AS "count" FROM "api_problem_tags" INNER JOIN "api_tag" ON ("api_problem_tags"."tag_id" = "api_tag"."id") WHERE "api_tag"."name" IN ('math', 'binary search', 'implementation') GROUP BY "api_problem_tags"."problem_id" HAVING COUNT(*) = 3 How can I get rid of the first COUNT(*) -
360-Degree-Feedback in django
I want to make 360-Degree-Feedback in Django. I think the easiest method is forms.py. For example: We have 3 group users: First: rates: second-group-user. Second: rates: another second-group-user, third-group-user, himself;rated by first-group-user, another second-group-user, third-group-user. Third: rates: second-group-user That is, the second-group-user in db must have the following ratings: Himslef From first-group-user From second-group-user From third-group-user These ratings must be summed and show average rating. And form which gave us rating must be look like this: blank img The problem is that there can be a different number of points in level, because we have 8 forms which must be summed and gave us summed rating.For example: first-group-user fill all eight's forms where summed rating are 100 points second-group-user fill all eight's forms where summed rating are 90 points third-group-user fill all eight's forms where summed rating are 93 points As a result, second-group-user have a 94,3 points. How to make these 360-Degree-Method in Django? I mean i can use forms.py and make 8 forms per user (who can log in), but how i can summed their? Logic is there we have one form include all eight's form, which gave us a rating for user. -
ERROR IN ADDING ANOTHER TEMPLATE IN EXISTING APP
Using the URLconf defined in rldjango.urls, Django tried these URL patterns, in this order: [name='index'] <int:destinations_id [name='destionations'] admin/ accounts/ ^media/(?P<path>.*)$ The current path, destinations.html, didn't match any of these. ***"***from main urls.py****** urlpatterns = [ path('', include('travello.urls')), path('admin/', admin.site.urls), path('accounts/',include('accounts.urls')), ] urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) *from urls.py travello * from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('<int:destinations_id', views.destinations, name='destionations') views.py of travello from django.shortcuts import render from .models import Destination # Create your views here. def index(request): dests=Destination.objects.all() return render(request,"destinations/index.html",{'dests':dests}) def destinations(request): return render(request, "index.html") please tell what i am doing wrong i am a newbii i am wanting to add one more template to my app index.html is added and i am trying to add destinations.html to it i am taking tutorials from telesko django course please help -
Django Admin Change View is stuck because of __str__ method of related field
I have this model in accounts.models: from django.contrib.auth.models import User class UserProfile(BaseModel): user = models.OneToOneField( User, related_name="user_profile", on_delete=models.CASCADE ) # ... def __str__(self) --> str: return self.user.username And the following in memberships.models: class ExternalServiceProfileMembership(BaseModel): created_at = models.DateTimeField() expires_at = models.DateTimeField() profile = models.ForeignKey( "accounts.UserProfile", on_delete=models.CASCADE, related_name="ext_memberships", ) plan = models.ForeignKey("memberships.MembershipPlan", on_delete=models.CASCADE) ext_subscription_id = models.CharField(max_length=128) When I try to access an individual ExternalServiceProfileMembership object (for example: http://localhost:8000/admin/memberships/externalserviceprofilemembership/1/change/), the site gets stuck, eventually returning a 503. So I started out commenting out fields in the AdminModel, and once I remove profile, the object change view loaded fine. I brought back profile into AdminModel but removed UserProfile's __str__() method, and it also worked. Which makes me think the whole issue is with this method; but I have no idea why. Any help is appreciated! -
Confusion of codes in the django views part
class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=category_choices, max_length=2) label = models.CharField(choices=label_choices, max_length=1) slug = models.SlugField() description = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse("product", kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("add-to-cart", kwargs={ 'slug': self.slug }) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,null=True) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) return redirect("product",slug=slug) i am learning it. here above i am trying to adding products to the cart. first i am taking the objects of particular slug,and then store inside OrderItem class.but i am confuse how : if order.items.filter(item__slug=item.slug).exists(): this line work. what is the function of double undescore before slug?