Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-ninja vs djangorestframework
Which of above rest framework do you prefer as of 2022 and django v4? djangorestframework django-ninja I will appreciate if you give me the pros and cons of each for rest-api implementation with django v4. -
I want to disable password in Django's User table
I am currently using django to develop a web app. I want to use an external Idaas and use the uuid issued by the external Idaas as the ID in the User table of django. I don't need the password column in Django at that time, can I disable it? I tried to create a new table without AbstractBaseUser and use the one without the password, but that didn't seem to work with Django's group feature. Therefore. ・Use an external UUID as the key for the Django User table. ・I'm not sure how to do that. ・Use Django's standard group function. I'd like to implement this in a way that satisfies the above three points. If anyone knows more about this, I would appreciate it if you could let me know. Thank you. -
Why am I getting a TemplateDoesNotExist error in Django 4.0 when the template does exist?
I'm new to Django, and I've been struggling with this TemplateDoesNotExist error for a while. I looked at many other users who were having these issues, but none of the proposed solutions seem to work for me. Django cannot find my blog/base.html file and claims it looks in '/home/agile/django_project/blog/templates/blog/base.html' for it, but when I check in my ubuntu, it says the directory exists fine? When I run on my localhost, the site works fine, but when working with ubuntu and Linode is when I run into this problem. Image of Django error Image of the path that exists but Django can't find? Here is my settings.py file, too: Django settings for django_project project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-e5oqam$0o(1158xprooll%5dg)xk01nw8alh6z1cv@)674^48k' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = … -
Instagram auto refresh the redirect URI which sending oauth2 code
I have pushed my django project onto pythonanywhere, a free hosting website. The code works fine in my local and onto the web as well, but somehow have an issue with instagram authentication. Instagram uses an oauth2 authentication system, in which when the user allows your application, it redirects the user to a specified URI and appends the code inside the URL which further can be used to authenticate the user. Instagram doesn't allow localhosts as valid redirect URL, therefore for the testing I have used something like this InstaAuth.html <script> history.pushState(null, null, '?code=AQD_4...q6#_'); function reloadThePage() { window.location.reload(); } </script> <button type="submit" class="btn btn-primary" onclick="reloadThePage()">Continue</button> which changes the state of the url but doesn't actually refresh it. Then I have button which refresh the current page, which directly trigger below code in my views.py and gets the code through request.GET['code']. Views.py def instaAuth(request): if 'code' in dict(request.GET).keys(): code = request.GET['code'] print('the given code is', code) core = instaCore() user_id, short_lived_access_token = core.code_to_short_access_with_userid(code_string=code) print(user_id) obj = InstaModel.objects.get(username=request.user) obj.instagram_userid = user_id obj.short_lived_access_token = short_lived_access_token obj.is_active = True obj.save() print('all data saved!') messages.success(request, "Your instagram is connected!") return render(request, 'authentication/success.html') return render(request, 'authentication/instaAuth.html') Above code works perfectly fine when I add the code … -
ckeditor not show in my admin panel this contains as a textarea
using the Django framework, add ck-editor in the admin panel, but show textarea I use python manage.py runserver and it works, but it doesn't work when deployed with Apache2. -
getting error while join two serializer in django
serializers.py -while joining HiringstatusSerializer in DriverEditListSerializer getting error class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ('id', 'name') class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ('id', 'name') class HiringstatusSerializer(serializers.ModelSerializer): class Meta: model = Hiring fields = ('driver_id', 'status') class DriverEditListSerializer(serializers.ModelSerializer): city = CitySerializer(read_only=True) location = LocationSerializer() hstatus=HiringstatusSerializer() class Meta: model = Driver fields = ( 'id','employee_id','employer', 'name','uber_name','uber_device_no', 'mobile', 'location', 'city','shift','status', 'aadhar_no','hstatus') views.py class DriverViewSet(viewsets.ModelViewSet): queryset = Driver.objects.filter(is_active=1) serializer_class = DriverEditListSerializer def get_queryset(self): queryset = Driver.objects.filter(is_active=1, city_id=self.request.GET.get('city_id')) return queryset output error this is output error while hit url raise type(exc)(msg) AttributeError: Got AttributeError when attempting to get a value for field `hstatus` on serializer `DriverEditListSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Driver` instance. Original exception text was: 'Driver' object has no attribute 'hstatus'. ERROR "GET /fleet/dt/editdrivers/ HTTP/1.1" 500 187937 -
How to use the attribute : save() in views.py?
** When I use the attribute save() in views.py the page gets this error : NOT NULL constraint failed: pages_login.username def about(request): username = request.POST.get("username") password = request.POST.get("password") data = Login(username=username,password=password) data.save() return render(request, 'pages/about.html') ** -
ValueError at /quiz/None/newquestion Field 'id' expected a number but got 'None'
in my quiz app here is my views.py code def NewQuiz(request): quizForm=forms.QuizForm() if request.method=='POST': quizForm=forms.QuizForm(request.POST) if quizForm.is_valid(): quiz= quizForm.save(commit=False) quiz_id = quiz.id else: print("form is invalid") return redirect('quiz:new-question',quiz_id=quiz_id) return render(request,'quiz/createquiz.html',{'quizForm':quizForm}) #create new question def NewQuestion(request,quiz_id): user = request.user quiz = get_object_or_404(Quizzes, id=quiz_id) questionForm=forms.QuestionForm() if request.method=='POST': questionForm=forms.QuestionForm(request.POST) if questionForm.is_valid(): question=questionForm.save(commit=False) #quiz=models.quiz.objects.get(id=request.POST.get('quizID')) question.quiz=quiz question.save() else: print("form is invalid") return redirect('quiz:new-question',quiz_id=quiz_id) return render(request,'quiz/createqusetion.html',{'questionForm':questionForm}) and here is my urls.py from django.urls import path from . import views app_name="quiz" urlpatterns = [ path('quiz/newquiz', views.NewQuiz, name='new-quiz'), path('quiz/<quiz_id>/newquestion', views.NewQuestion, name='new-question'), path('quiz/<quiz_id>/quizdetail', views.QuizDetail, name='quiz-detail'), path('quiz/<quiz_id>/take', views.TakeQuiz, name='take-quiz'), path('check-marks/<quiz_id>', views.check_marks_view,name='check-marks'), path('quiz/calculate-marks', views.calculate_marks_view,name='calculate-marks'), path('calculate-marks', views.calculate_marks_view,name='calculate-marks'), path('check-marks/<int:pk>', views.check_marks_view,name='check-marks'), ] and i got the above error i tray to change the path to like int:quiz_id but the error is still the same any who can help me please? -
how to fetch only the newest rows from the model in django and show it as a table?
views.py def inventory_display(request): if request.user.vendor == True and request.user.vendor_approval == True: vendor = CustomUser.objects.get(id=request.user.id) vendor_product = vendor.vendor_user.all() items = vendor_product[0].product_variants.all() return render(request, 'vendor/inventory_display.html',{'vendor_product':vendor_product, 'items':items}) Html {% for product in vendor_product %} {% for item in items %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{product.created|date:"d-m-y"}}</td> <td>{{product.edited|date:"d-m-y"}}</td> <td>{{product.vendoruser}}</td> <td><a href="{% url 'loomerang_admin:product_details' %}">{{product.product_id}}</a></td> <td>{{item.item_num}}</td> <td>{{item.variant_value}}</td> <td>{{item.initial_stock}}</td> <td>2</td> <td>{{item.approval_status}}</td> <td>{{item.approved_date|date:"d-m-y"}}</td> <td>{{product.approved_by}}</td> </tr> {% endfor %} {% endfor %} I am fetching data from 3 different models. I do fetch all the data from these models every time. What if I want to get the newest row only whenever the new row is added? Please, needed help. -
Unable to read Paginator in django template
I am setting up a pagination in my Django APP. Following is my view code: class ClaimsView(ListView): context_object_name = "archives" template_name = "myapp/claims.html" def get_queryset(self, **kwargs): query = self.request.GET.get("q", "") response = self.get_archives(query) paginator =Paginator(response, 4) pages = paginator.get_pages(4) return {'archives': response, 'pages': pages} When I print pages in the viwes file. It give correct result "<page 1 of 1>" but when I am passing it to the HTML file its not give any results there. 'archives' in above dict has a list as value its working fine but not the 'pages' This is how I am reading it in HTML file: {{pages}} -
raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs)) TypeError: 'class Meta' got invalid attribute(s): constraints
#For Battery Manger Project 16-12-2021 class BatteryManager(models.Model): slno = models.AutoField(db_column='Slno', primary_key=True) # Field name made lowercase. lithiumionbattery = models.DecimalField(db_column='LithiumIonBattery', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. bty_voltage = models.DecimalField(db_column='Bty_Voltage', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. bty_current = models.DecimalField(db_column='Bty_Current', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. batterytemp = models.DecimalField(db_column='BatteryTemp', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. ambienttemp = models.DecimalField(db_column='AmbientTemp', max_digits=18, decimal_places=2, blank=True, null=True) # Field name made lowercase. bty_username = models.CharField(db_column='Bty_Username', max_length=30, blank=True, null=True) # Field name made lowercase. bty_circlename = models.CharField(db_column='Bty_circlename', max_length=30, blank=True, null=True) # Field name made lowercase. bty_payload = models.CharField(db_column='Bty_payload', max_length=100, blank=True, null=True) # Field name made lowercase. bty_createddate = models.DateTimeField(db_column='Bty_createdDate', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'BatteryManager' def __str__(self): return str(self.Slno) -
Embed tag not showing the pdf inside "Django template"
I need to display a pdf inside the table, but the embed tag there is not working. The HTML file, I am using is a template of the Django app. Following is the code, I am writing to display the pdf:- {% if awp.Supporting_documents %} <td id=displayrecord><a href="{%url 'component_progress:download_file_Supporting_documents' awp.id %}">download</a> <embed src="/home/vvdn/Downloads/Preview.pdf" width="500" height="375" type="application/pdf"> </td> {% else %} The output that is being displayed in the UI is as follows:- -
prevent user to access login page in django when already logged in?
def admin_login(request): if request.method == 'POST': username = request.POST["username"] password = request.POST["password"] user = authenticate(request,username = username, password = password) if user is not None: if(user.is_superuser): auth_login(request, user) return redirect(reverse("dashboard")) else: messages.info(request, "invalid credentials") return redirect(reverse("admin")) return render(request,'login.html') this is mylogin function for admin , how to prevent user to access login page once logged in? -
Python Django, struggling to create a dynamic list
I want to create a section on my site, where for each subject, links to corresponding past papers can be found, but I am struggling to get any output. Looking for ideas: My views.py: def index(request): subjects = Subject.objects.all() context = {'subjects': subjects} return render(request, 'alevelspastpapers/index.html', context=context) My models.py: class Subject(models.Model): subject = models.CharField(max_length=30) def __str__(self): return self.subject class past_paper(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) exam_date = models.DateField('Examination Date') paper_number = models.IntegerField('Paper Number: ') paper_urllink = models.TextField() markscheme_urllink = models.TextField() solved_paperslink = models.TextField(null=True) def __str__(self): return f"{self.subject} Paper {self.paper_number}, {self.exam_date}" My html content: {% if subjects %} {% for subject in subjects %} <p>{{ subject.subject }}</p> {% for papers in subject.subject.past_papers_set.all %} <p>{{ papers.paper_urllink }}</p> {%endfor%} {% endfor %} {% endif %} -
Django TypeError: Expected str, bytes or os.PathLike object, not NoneType
I am writing a webpage that can run a python script by clicking a button on html. Here is what I have: views.py from django.shortcuts import render import requests import sys from subprocess import run,PIPE def external(request): inp= request.POST.get('param') out= run([sys.executable,'test.py',inp],shell=False,stdout=PIPE) print(out) return render(request,'home.html',{'data1':out.stdout}) urls.py from django.urls import path from . import views # urlconf urlpatterns = [ path('external/', views.external) ] home.html <html> <head> <title> Python button script </title> </head> <body> <form action="/external/" method="post"> {% csrf_token %} Input Text: <input type="text" name="param" required><br><br> {{data_external}}<br><br> {{data1}} <br><br> <input type="submit" value="Execute External Python Script"> </form> </body> </html> directory screenshot The problem is with this line of code: out= run([sys.executable,'test.py',inp],shell=False,stdout=PIPE) from views.py. How can I fix this? Thanks! -
How to execute a django or SQL query after clicking the toggle button?
I have two tables: class DibbsSpiderDibbsMatchedProductFieldsDuplicate(models.Model): nsn = models.TextField() nsn2 = models.TextField() cage = models.TextField() part_number = models.TextField() company_name = models.TextField(blank=True, null=True) supplier = models.TextField(db_column='Supplier', blank=True, null=True) # Field name made lowercase. cost = models.CharField(db_column='Cost', max_length=15, blank=True, null=True) # Field name made lowercase. list_price = models.CharField(db_column='List_Price', max_length=15, blank=True, null=True) # Field name made lowercase. gsa_price = models.CharField(db_column='GSA_Price', max_length=15, blank=True, null=True) # Field name made lowercase. hash = models.TextField() nomenclature = models.TextField() technical_documents = models.TextField() solicitation = models.CharField(max_length=32) status = models.CharField(max_length=16) purchase_request = models.TextField() issued = models.DateField() return_by = models.DateField() file = models.TextField() vendor_part_number = models.TextField() manufacturer_name = models.TextField(blank=True, null=True) product_name = models.TextField(blank=True, null=True) unit = models.CharField(max_length=15, blank=True, null=True) class Meta: managed = False db_table = 'dibbs_spider_dibbs_matched_product_fields_duplicate' class DibbsSpiderSolicitation(models.Model): line_items = models.IntegerField() nsn = models.TextField() nomenclature = models.TextField() technical_documents = models.TextField() purchase_request = models.TextField() class Meta: managed = False db_table = 'dibbs_spider_solicitation' I want to display these in the format : The original link is on : http://develop-330.gsa-cs.com/test/ After Clicking on the toggle button, how to execute the query ? Line #1 means Line line_items First row is of first table. After clicking on the toggle, I want to execute a django query or a sql query which joins two tables … -
How to render month and monthly total using attributes in django filter class and calling to a class based view?
in my models.py, i have this, class Expenditure(models.Model): item = models.ForeignKey(Item, on_delete=models.SET_NULL, null=True, related_name='items') author = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING, null=True) bank = models.ForeignKey(Bank, on_delete=models.DO_NOTHING, blank=True, null=True) date = models.DateField(blank=False, null=False, default=datetime.date.today) amount = models.DecimalField(max_digits=20, decimal_places=2, validators=[MinValueValidator(Decimal('0.01'))]) remarks = models.CharField(max_length=200, blank=True, null=True) def __str__(self): template = '{0.item}, {0.date}' return template.format(self) def get_absolute_url(self): return reverse('expenditure_detail',kwargs={'pk':self.pk}) in my filters.py, i have this MONTH_CHOICES = [ ('1','January'),('2','February'),('3','March'),('4','April'),('5','May'),('6','June'), ('7','July'),('8','August'),('9','September'),('10','October'),('11','November'),('12','December'), ] YEAR_CHOICES = [ ('2021','2021'),('2022','2022'),('2023','2023'),('2024','2024'),('2025','2025'), ] class ExpenditureFilter(django_filters.FilterSet): month = django_filters.ChoiceFilter(field_name='date',label='Month',choices=MONTH_CHOICES,widget=forms.Select(attrs={'class':'form-control'}),lookup_expr='month') year = django_filters.ChoiceFilter(field_name='date',label='Year',choices=YEAR_CHOICES,widget=forms.Select(attrs={'class':'form-control'}),lookup_expr='year') class Meta: model = Expenditure fields = ('year','month') in my views.py, i have this class ExpenditureListView(LoginRequiredMixin, ListView): context_object_name = 'expenditures' login_url = 'login/' model = Expenditure # paginate_by = 10 ordering = ["-date"] today = datetime.date.today() def get_queryset(self): queryset = super().get_queryset() filter = ExpenditureFilter(self.request.GET, queryset) return filter.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) queryset = self.get_queryset() filter = ExpenditureFilter(self.request.GET, queryset) context["filter"] = filter context['total'] = float(Expenditure.objects.aggregate(Sum('amount')).get('amount__sum', 0.00)) context['current_month_total'] = float(Expenditure.objects.filter(date__year=self.today.year, date__month=self.today.month).aggregate(Sum('amount')).get('amount__sum', 0.00)) return context in my HTML template i have this, <section class="section"> <div class="container"> <div class="row"> <div class="col-lg-2 col-md-2 mb-80"> <div class="row"> <div class="col-lg-10 mx-auto text-center"> <p class="font-tertiary"> Total amount spent<br> <span class="font-red">৳ {{ total|intcomma }}</span> </p> <p class="font-tertiary"> {% now "F Y" %} total <br> <span>৳ {{ current_month_total|intcomma }}</span> </p> </div> … -
python requests not recognizing params
I am requesting to mindbodyapi to get token with the following code using requests library def get_staff_token(request): URL = "https://api.mindbodyonline.com/public/v6/usertoken/issue" payload = { 'Api-Key': API_KEY, 'SiteId': "1111111", 'Username': 'user@xyz.com', 'Password': 'xxxxxxxx', } r = requests.post(url=URL, params=payload) print(r.text) return HttpResponse('Done') gives a response as follows {"Error":{"Message":"Missing API key","Code":"DeniedAccess"}} But if I request the following way it works, what I am doing wrong with requests library conn = http.client.HTTPSConnection("api.mindbodyonline.com") payload = "{\r\n\t\"Username\": \"username\",\r\n\t\"Password\": \"xxxxx\"\r\n}" headers = { 'Content-Type': "application/json", 'Api-Key': API_KEY, 'SiteId': site_id, } conn.request("POST", "/public/v6/usertoken/issue", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8")) -
How can I display Error Messages for the logging funtion in Django?
I am a new Django Developer, and I have some trouble with the login function. My problem is that my system does not show error messages even though it is invalid. I try to enter the wrong username and password, and I expect there are some error messages displayed. However, it does not work. Here is my code: login_register.html <div class="login-form"> <form action="" method="POST"> {% csrf_token %} {% if form.errors %} {% for field in form %} {% for error in field.errors %} <p> {{ error }} </p> {% endfor %} {% endfor %} {% endif %} <h2 class="text-center">Sign in</h2> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <span class="fa fa-user"></span> </span> </div> <input type="text" class="form-control" name="username" placeholder="Username" required="required" /> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-lock"></i> </span> </div> <input type="password" class="form-control" name="password" placeholder="Password" required="required" /> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary login-btn btn-block"> Sign in </button> </div> <div class="clearfix"> <a href="{% url 'reset_password' %}" class="text-center" >Forgot Password?</a > </div> </form> <p class="text-center text-muted small"> Don't have an account? <a href="{% url 'register' %}">Register here!</a> </p> </div> view.py def loginUser(request): page = 'login' if request.user.is_authenticated: return redirect('starting-page') if request.method == 'POST': username … -
XOR showing same value after 17 characters in python
Am trying to encrypt a integer for hiding primary keys in URLs of Django. So after research I found that encrypting "int" can be done using XOR! So I thought of trying those for example: id = 1 masked_id = id ^ 0xABCDEFAB unmasked_id = masked_id ^ 0xABCDEFAB print(masked_id) //2882400170 print(unmasked_id) //1 The above works well until the id character count reaches to 10. For example check below Output: When id character count is greater than 10, id = 11111111111 masked_id = 1032582764 unmasked_id = 2521176519 Its weird that, the output is not as expected when it crosses 10 count. So how this works and how to fix this ? Is there any way to encrypt int (pk) form database ? -
How to request existing files from a form in django
i'm trying to add a feature for users to update thier profile, but i want to be able to get thier existing informations so they don't have to fill all the form again. I have tried request.POST on the form but it doesn't work, it does not update the form with the existing user informations. views.py def profile_update(request): info = Announcements.objects.all() categories = Category.objects.all() Profile.objects.get_or_create(user=request.user) if request.method == "POST": 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() messages.success(request, f'Acount Updated Successfully!') return redirect('userauths:profile') else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'info': info, 'categories': categories } return render(request, 'userauths/profile_update.html', context) # profile update function def profile_update(request): info = Announcements.objects.all() categories = Category.objects.all() Profile.objects.get_or_create(user=request.user) if request.method == "POST": 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() messages.success(request, f'Acount Updated Successfully!') return redirect('userauths:profile') else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, 'info': info, 'categories': categories } return render(request, 'userauths/profile_update.html', context) -
Django AttributeError: 'int' object has no attribute 'pk'
I am stuck :(. I have an API that I can't seem to get working with the DRF. I am forming my queryset in my view and the result that I want is coming out in the console: web_1 | {'company_exchange': 969, 'company_exchange__company__name': 'LIGHTSPEED POS', 'company_exchange__stock_symbol': 'LSPD', 'strategy': 1, 'periodic_buy_period': 5, 'periodic_sell_period': 10, 'month': datetime.datetime(2021, 11, 1, 0, 0, tzinfo=<UTC>), 'periodic_sum': Decimal('1.2300000000')} web_1 | {'company_exchange': 969, 'company_exchange__company__name': 'LIGHTSPEED POS', 'company_exchange__stock_symbol': 'LSPD', 'strategy': 1, 'periodic_buy_period': 2, 'periodic_sell_period': 14, 'month': datetime.datetime(2021, 12, 1, 0, 0, tzinfo=<UTC>), 'periodic_sum': Decimal('7.4200000000')} web_1 | {'company_exchange': 969, 'company_exchange__company__name': 'LIGHTSPEED POS', 'company_exchange__stock_symbol': 'LSPD', 'strategy': 1, 'periodic_buy_period': 13, 'periodic_sell_period': 11, 'month': datetime.datetime(2021, 12, 1, 0, 0, tzinfo=<UTC>), 'periodic_sum': Decimal('100.9600000000')} I can see that the obj gets passed into my serializer, but for the life of me I can not understand where I am going wrong. Here is my view.py class TopHistoricalGainViewSet(viewsets.ModelViewSet): queryset = TopHistoricalGains.objects.all() twelve_months_ago = datetime.datetime.now()+relativedelta(months=-12) serializer_class = TopHistoricalGainsSerializer def get_queryset(self): ids = self.queryset\ .values('id')\ .order_by('company_exchange__id') twelve_months_ago = datetime.datetime.now()+relativedelta(months=-12) hg_list = TopHistoricalGains.objects.filter(id__in=ids, periodic_date_time__gte=twelve_months_ago) hg_list = hg_list\ .annotate(month=TruncMonth('periodic_date_time')) \ .values('month') \ .annotate(periodic_sum=Sum('periodic_gain_max')) \ .values('company_exchange', 'company_exchange__company__name', 'company_exchange__stock_symbol', 'month', 'periodic_sum', 'strategy', 'periodic_buy_period', 'periodic_sell_period') \ #.order_by('company_exchange', '-periodic_sum', 'strategy', 'periodic_buy_period', 'periodic_sell_period')[:10] for hg in hg_list: print(hg) return hg_list class Meta: ordering = ['periodic_sum', … -
How to get the user id of the currently connected account in models.py
I want to give a condition by distinguishing when the user.id of the Leave object and the user id of the current access account are the same and when they are not. The original get_html_url function only had a 'self' argument. If 'request' is added to the argument to get the user id of the currently connected account, the error get_html_url() missing 1 required positional argument: 'request' occurs. It seems that I need to add request to utils.py to fix the error. But I don't know which function to add. Help. [models.py] class Leave(models.Model): name = models.CharField(max_length=50, blank=True, null=True) kind = models.CharField(choices=KIND_CHOICES, max_length=20, blank=True, null=True) from_date = models.DateField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) memo = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) @property def get_html_url(self, request -----> dAre there any errors?): url = reverse('leave:leave_edit', args=(self.id,)) user = request.user.id -----> Are there any errors? if self.kind == 'Annual' and self.user.id == user: return f'<div class="Annual-title"><a href="{url}" style="color:black;"> {self.name}</a></div>' elif self.kind == 'Half' and self.user.id == user: return f'<div class="Half-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Holiday' and self.user.id == user: return f'<div class="Holiday-title"><a href="{url}" style="color:black;"> {self.name} </a></div>' elif self.kind == 'Annual' and self.user.id … -
how i create box like recent action admin menu django
how can I create the recent actions box in Django admin? pic -
How to pass and interpret a complex render context in Django?
I'm pretty new to Django and am not sure if I'm approaching this problem correctly. My view code generates a many to many map. So something like {'penguin' : ("bird", "black", "flightless", "arctic")}, {'axolotl' : ("reptile", "green")} {'rhino' : ("mammal", "horn", "heavy")} and so on... for a lot of different procedurally generated animals Out of this I'm trying to render page that would just have the animal's name and underneath it a few bullet points with the characteristics, like this Penguin bird black flightless and so on for every animal. The number of these animals and the descriptions are unknown and are parsed at runtime from an xml file I thought I could just pass this structure into the template and use the template language to iterate over it and render it out, but so far I feel like I'm having to jump through hoops, so I'm not sure if I'm doing something wrong or if this is just outside the scope of Django and I should be using a different framework for this kind project. The problems I'm running into: I'm having issues figuring out how to even pass this structure into the context and have it available for …