Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to increase loading time of post request in IIS windows server 2019
I have deployed Django on a windows server using IIS Windows Server 2019. When I submit the form, the time limit of the backend process is 100 Seconds, But after 40 seconds, IIS server responds with error 500. How can I increase this loading time of IIS. -
How to display the MQTT values in UI through Django framework
I am trying to get the values from the MQTT broker and wanted to display the values in the web UI through the Django framework. I have all the code files. I don't know where to place the python MQTT code to get the values from the broker to pass it to the UI. -
Django, DRF: How to send permission class details while making an API call using POSTMAN?
# views.py @login_required @permission_classes([IsAdminUser]) @api_view(['GET']) def say_hi_admin(request): return Response({'msg': 'Hi Admin'}) On making a GET request using POSTMAN with the following request Body(raw/json): { "user": { "id": 1, "email": "example@email.com", "password": "pass" } } But I get this as the response, { "detail": "Authentication credentials were not provided." } How can I solve this? -
In Django 1.11, how can I cache an entire page only for logged out users, but still be able to drop the cache if something substantial changes?
I would like to cache a whole page for logged out viewers, but I have a couple of requirements: The page should be cached per language If something major changes on the page, I should manually drop the cache key (i.e. from the view that performs a major change in the database that affects that page) If something minor changes on the page, I can keep the cache I'm pretty sure I can do it with a template fragment, e.g.: {% cache 600 CACHE_KEY request.user request.LANGUAGE_CODE %} And CACHE_KEY would be something that is computed by the view and passed to the template so that whenever I change something major I can recalculate CACHE_KEY and drop it. But is it possible to also do this without touching the template? Thanks! -
Partial update in action without UpdateModelMixin
I have a viewset without UpdateModelMixin and I need to able update name in extra action but it doesn't work and requires all fields of serializers: class PlacementMappingViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = serializers.CampaignManagerPlacementMappingSerializer @action(detail=True, methods=['patch']) def change_name(self, request, pk=None): instance = self.get_object() serializer = self.serializer_class(instance, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And my serialier: class CampaignManagerPlacementMappingSerializer(ExtendedModelSerializer): is_synchronized = serializers.BooleanField(read_only=True) failed_synchronization_reason = serializers.CharField(read_only=True) tile = serializers.IntegerField(required=True, allow_null=False) platform_item_external_id = serializers.IntegerField(required=True, allow_null=False) active = serializers.BooleanField(read_only=True) class Meta: model = models.CampaignManagerPlacementMapping fields = ( 'id', 'tile', 'site_mapping', 'tile_mapping', 'placement_id', 'placement_name', 'platform_item_id', 'platform_item_external_id', 'failed_synchronization_reason', 'is_synchronized', 'active', 'is_name_changed', 'click_through_url', 'is_click_through_url_changed', ) def update(self, instance, validated_data): if validated_data.get('placement_name') != instance.placement_name: validated_data['is_name_changed'] = True if validated_data.get('click_through_url') != instance.click_through_url: validated_data['is_click_through_url_changed'] = True return super().update(instance, validated_data) What I am doing wrong? -
django admin field level persmission
i'm trying to customize my Django admin panel for different user groups. i have three types of user's which are simple_user, admin, support .i'm trying to restrict my support user's to edit some specific model fields .this is my model and tried adding custom permissions for that. t_code = models.CharField(max_length=14, null=True) t_type = models.ForeignKey('Coding', on_delete=models.CASCADE, null=True) t_user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) t_Title = models.CharField(max_length=200, null=True, blank=True) class Meta: permissions = ( ('edit_t_Title', 'can Edit title '), ) the problem is after migrations the permission is added to django permissions but when i assign it to support group the permission has no effect !. i tried two ways to check that.first i set view_ticket and edit_ticket,edit_t_Title permission to support,second i tried only view_ticket and edit_t_Title ,but non of them was working . it seems when i add edit_ticket permission support can edit all fields,and when i remove it support can only view it even when i set edit_t_Title. -
Django el pagination limit number of pages in pagination
I've got small issue and I don't know how to fix it. I'm using Django EL(Endless) Pagination. I want to limit number of pages displayed. For now is like 40 and it doesn't look so good. How can I change this? Here is my html template fragment of pagination: {% paginate advertisements %} {% get_pages %} <ul class="pagination" style="margin: auto;"> {% if pages.paginated %} <nav aria-label="Blog pagination"> <li class="page-item mr-3 {& if pages.previous.path == None %} disabled {% endif %}"> <a class="page-link text-sm rounded" href="{{ pages.previous.path }}" aria-label="Poprzednia"> <i class="fa fa-chevron-left mr-1"></i> Poprzednia</a></li> <span class="sr-only">Poprzednia</span> </a> </li> {% for page in pages %} <li class="page-item mr-3 {% if page.is_current %} active {% endif %}"> <a class="page-link text-sm rounded" href="{{ page.path }}" aria-label="Page {{page.number}}"> {{page.number}} </a> </li> {% endfor %} <li class="page-item {% if pages.next.path == None %} disabled {% endif %}"> <a class="page-link text-sm rounded" href="{{ pages.next.path }}" aria-label="Następna"> Następna<i class="fa fa-chevron-right ml-1"></i></a></li> <span class="sr-only">Next</span> </nav> </ul> -
Django rest framework - including an api key for access authorization
I'm creating a Restful API using Django Rest Framework, i'm not serving sensitive data but still i wanted to add some sort of authorization system for viewing my API endpoints. Basically each user has an API key assigned, and in order to view any endpoint, the user needs to provide the key when performing any request. All the endpoints use only GET to retrieve the data, so what i did is the following: The API key is provided in the GET params, so something like myURL/api/endpoint/?key=1234&filter=test A middleware checks if that API key exists in my database, and if it does the user is able to get the data. Here is my middleware: TOKEN_QUERY = "key" class TokenMiddleware(AuthenticationMiddleware): def process_request(self, request): if request.user.is_authenticated: return None else: try: token = request.GET[TOKEN_QUERY] except Exception as e: # A token isn't included in the query params return JsonResponse({'error': 'Missing parameter: make sure to include your key.'}) try: query = API_keys.objects.get(api_token=token) except: token = None if token != None: return None else: return JsonResponse({'error': 'Authentication failed. Make sure to provid a valid API key.'}) This system works without any problem, but i'm concerned about safety. How safe is this? Should i not use a … -
Django Group By in QuerySet
I have a table of transaction, and i am looking to extract a table summary with data grouped by year, month, user, account, id of transaction, and name of issuer of the good. I managed to do so in the view using: def monthly_activity(request): results = Personalaccountpurchase.objects.all().filter(quantity__isnull=False)\ .values_list('trade_date__year', 'trade_date__month','user','account','id' ,'name_of_issuer')\ .annotate(Sum('quantity'))\ .order_by('trade_date__year', 'trade_date__month') context = { 'results': results, } return render(request, "paccounts/monthly_activity.html", context) In the template i would like to make a clean display of the query set that came up in the form of : <QuerySet [(2021, 1, '4', '17', 35, 'Fresh Oil', 4584), (2021, 2, '4', '15', 8, 'face Sebum', 405500), (2021, 2, '4', '15', 9, 'Vegetal Oil', 450063)]> I tried using : {% for result in results %} .... </tr> {% endfor %} but I am not sure how to move from there since my column name have all been changed. result.user for example will return nothing. Is someone familiar with the grouping of record in QuerySet please ? -
Django view-specific CORS headers?
I'm using the django-cors-headers module to handle CORS. I'm wondering if there's a way to have different behaviour for different views. For /api/ I want to have only one origin access it (a different domain to the one I'm hosting the app on) For other endpoints, I want to allow all origins Can you do this with the CORS package? Or will I have to add headers manually? Also, I'm using Django Rest Framework, if that changes anything. -
Error deploying a Django app using gunicorn
Im trying to deploy my Django app in a linux server by following this tutorial https://www.digitalocean.com/community/tutorials/como-configurar-django-con-postgres-nginx-y-gunicorn-en-ubuntu-18-04-es but keep getting an error when trying to set gunicorn with my django project ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; disabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2021-02-04 17:45:34 +01; 25min ago TriggeredBy: ● gunicorn.socket Main PID: 754981 (code=exited, status=217/USER) Feb 04 17:45:34 vps141106 systemd[1]: Started gunicorn daemon. Feb 04 17:45:34 vps141106 systemd[754981]: gunicorn.service: Failed to determine user credentials: No such process Feb 04 17:45:34 vps141106 systemd[754981]: gunicorn.service: Failed at step USER spawning /home/root/venv/bin/gunicorn: No such process Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Start request repeated too quickly. Feb 04 17:45:34 vps141106 systemd[1]: gunicorn.service: Failed with result 'exit-code'. Feb 04 17:45:34 vps141106 systemd[1]: Failed to start gunicorn daemon. This is my service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/home/root/test ExecStart=/home/root/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ test.wsgi:application [Install] WantedBy=multi-user.target Im getting those errors gunicorn.service: Failed to determine user credentials: No such process gunicorn.service: Failed at step USER spawning /home/root/venv/bin/gunicorn: No such process … -
makemigrations shows No changes detected
I totally beginner in django. I create one model which is in models folder and run python manage.py makemigrations still its show No changes detected product.py from django.db import models class Product(models.Model): name = models.CharField(max_length=50) price = models.IntegerField(default=0) description = models.CharField(max_length=200, default='') image = models.ImageField(upload_to="products/") init.py (models/init.py) from .product import Product Thanks in advance -
How to make an API from already existing model data
I am new to DRF and i want to get an api from already existing model data and i could just use templates for that but i want to make an api for frontend For normal template i would use this views def view_most_urgent(request): a, b = most_needing_attention(request.user) top_entries = list(zip(a, b)) print(top_entries) context = {'top_entries': top_entries} return render(request, 'most_urgent.html', context) and i have tried this for serializing @api_view(['GET']) @renderer_classes([JSONRenderer]) def Most_Urgent_Items(request, format=None): """ A view that returns the count of most urgent Items. """ a, b = most_needing_attention() top_entries = list(zip(a, b)) # context = json.JSONEncoder().encode({'top_entries': [top_entries]}) # tried this one as well context = json.dumps(top_entries) return Response(context) and my usecases for most_needing_attention() is: def most_needing_attention(): tl = TopList(size=5) for item in Item.objects.all(): tl.push(individual_item_overdue_score(item), item) def score_to_number(score): x = math.log(score) if x > 2: return 'red' elif x > 1: return 'orange' else: return 'green' Colors = map(score_to_number, tl.get_scores()) return tl.get_elements(), Colors Thank you in advance ... -
How to set a default value for a form in every update?
I want to set a default value in a form and it will be reset as approval = False in every update. I tried something but it did not work it doesn't change. How can I fixed it? forms.py class UpdateDoaTableForm(forms.ModelForm): approval = forms.BooleanField(required=False, initial=False, label='Approved', widget=forms.HiddenInput() ) class Meta: model = DoaTable fields = ('limit', 'approval') views.py def update_limit(request, id): limiting = get_object_or_404(DoaTable, id=id) form = UpdateDoaTableForm(request.POST or None, request.FILES or None, instance=limiting) limiting_item = DoaTable.objects.filter(id=id) if form.is_valid(): form.save() return redirect('approvals:update_limit_list') context = { 'form': form, 'limiting_item': limiting_item, } return render(request, 'limitUpdate.html', context) models.py class DoaTable(models.Model): ... approval = models.BooleanField(default=False) -
Django / python REDIRECT не получается добавит в базу данных запись методом POST из формы по уроку дударя
Не получается отправить в базу данных данные с формы которая размещена в модальном окне ( на обычной странице так же не получается), при попытке добавить запись в базу данных, модальное окно закрывается и не добавляется запись в базу данных. При попытке перезагрузить страницу, пишется, что форма отправленна будет утеряна вы уверены, что согласны перезагрузить страницу? models.py from django.db import models class Turn(models.Model): city = models.CharField('Город', max_length=20) def __str__(self): return self.description forms.py from .models import Turn from django.forms import ModelForm, TextInput class TurnForm(ModelForm): class Meta: model = Turn fields = ['city'] widgets = { 'city': TextInput(attrs={ 'class': 'container-xl marning', 'placeholder': 'Ваш город' }) } turn.html {% extends 'main/main/main.html' %} {% block content %} <div> {% if turn %} {% for el in turn %} <div class="container border marning"> <div class="row row-cols-2 border"> <div class="col right"> Город: {{ el.city }} </div> </div> </div> <div class="row border"> <div class="col center"> {{ el.date }} </div> </div> </div> {% endfor %} {% endif %} </div> <!-- Modal --> <div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-xl modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Добавить заказ</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" action="turn"> <div class="modal-body"> {% … -
Django admin form process file upload: 'InMemoryUploadedFile' object has no attribute 'width'
I have this model class CauroselImage(models.Model): title = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=400, blank=True) image = models.ImageField(upload_to=settings.UPLOAD_DIR,) visible = models.BooleanField(default=True) def __str__(self): return self.title that i want to set the image file minimum dimensions and I've found out the forms.py file is the way to go class CauroselImageForm(forms.ModelForm): class Meta: model = CauroselImage exclude = ('',) def clean(self): cleaned_data = self.cleaned_data image = cleaned_data.get('image') if image.width < 1300 or image.height < 400: raise forms.ValidationError("Image dimensions is too small, minimum is 1300x400") return cleaned_data and admin class CauroselImageAdmin(admin.ModelAdmin): form = CauroselImageForm admin.site.register(CauroselImage, CauroselImageAdmin) it however throws this error Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/pages/cauroselimage/1/change/ Django Version: 3.1.2 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'guides', 'pages', 'sorl.thumbnail', 'ckeditor', 'django.contrib.sites', 'django.contrib.humanize'] 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 "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 233, in inner return view(request, *args, **kwargs) File … -
Write value on Input type from Django Form
I'm new on this site, but I read a lot of questions in this page. I don't find information about this and I need help. I have a form created automatically for django. It's good working but I need write values on input when I find values, it's possible?? I trying this, and if I print misHoras.horas_trabajo I can read the good value, but I don't kwno how can write this value on input html type. Thanks. def horas(request): #horas_todas = Horas.published.all() horas = get_object_or_404(Horas, autor= '2', dia='2021-01-26', ) if request.method=='POST': misHoras=FormularioHoras(request.POST) if misHoras.is_valid(): infForm=misHoras.cleaned_data misHoras.horas_trabajo = horas.horas_trabajo return render(request, "BieleGastosApp/formulario_horas.html", {"form": misHoras}) else: misHoras = FormularioHoras() #return render(request, "BieleGastosApp/horas.html", {"horas": horas}) return render(request, "BieleGastosApp/horas.html", {"form": misHoras}) -
Permissions Django in its own template
How to transfer admin django functionality? So that I could set permissions for user groups without logging into the admin panel as it is done by default in Django .enter image description here I have the output of all user groups enter image description here You need to click on a group to go to it and configure permissions for that group. I only want to do three permissions for now. Add/delete/update. Maybe someone has already done something similar, please help with advice or a link where it is written how to do it. -
How to assign objects to specific user?
I am working on a tasks app using Django, I want to assign a task to the user who created it. the app model: class Task(models.Model): title = models.CharField(max_length=200) content = models.TextField(blank=True) pub_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) due_date = models.DateField(default=timezone.now().strftime("%Y-%m-%d")) completed = models.BooleanField(default=False) completed_date = models.DateField(blank=True, null=True) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE, ) class Meta: ordering = ["-pub_date"] # Ordering by the pub date field def __str__(self): return self.title the app views: class TaskListView(LoginRequiredMixin, ListView): model = Task template_name = 'task_list.html' login_url = 'login' class TaskCreateView(LoginRequiredMixin, CreateView): model = Task template_name = 'task_create.html' fields = ('title', 'content') login_url = 'login' def get_success_url(self): return reverse('task_list') class TaskUpdateView(LoginRequiredMixin, UpdateView): model = Task template_name = 'task_update.html' fields = ('title','content',) login_url = 'login' def get_success_url(self): return reverse('task_list') class TaskDeleteView(DeleteView): model = Task template_name = 'task_delete.html' success_url = reverse_lazy('task_list') any help would be helpful to me since I am just a beginner :D -
TypeError at / string indices must be integers : Django and Vue3
Error during teError during template renderingplate rendering Exception Type: TypeError Exception Value: string indices must be integers The following is my webpack loader in settings.py config in django {% render_bundle 'app' %} WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'dist/', `enter code here`'STATS_FILE': str(BASE_DIR.joinpath('frontend', 'dist', 'webpack-stats.json')), } } This is vuejs 3x webpack-bundle-tracker config const BundleTracker = require("webpack-bundle-tracker"); module.exports = { // on Windows you might want to set publicPath: "http://127.0.0.1:8080/" publicPath: "http://127.0.0.1:8080/", outputDir: "./dist/", chainWebpack: config => { config .plugin("BundleTracker") .use(BundleTracker, [{ filename: "./webpack-stats.json" }]); config.output.filename("bundle.js"); config.optimization.splitChunks(false); config.resolve.alias.set("__STATIC__", "static"); config.devServer // the first 3 lines of the following code have been added to the configuration .public("http://127.0.0.1:8080") .host("127.0.0.1") .port(8080) .hotOnly(true) .watchOptions({ poll: 1000 }) .https(false) .disableHostCheck(true) .headers({ "Access-Control-Allow-Origin": ["*"] }); } // uncomment before executing 'npm run build' // css: { // extract: { // filename: 'bundle.css', // chunkFilename: 'bundle.css', // }, // } }; -
How to change funcionality of DRF framework depending on authentication?
I wanted to know how to change the output of a Django Rest Framework depending on whether the request has an authentication token (E.g. a JWT in header) or not. Basically, I want to achieve something like this: (Not auth, email exists) /user/:email { "email": :email, "active": true, } (Auth, email exists) /user/:email { "email": :email, "active": true, "username": "...", "...": "...", } (Not auth, email doesn't exist) /user/:email Status: 404 -
Setting Django Radio button id
I am trying to set the id for the radio button options. One with M and one with F. How to do that? What is the right way to do it? genders = { "M":"Male", "F":"Female" } Gender = forms.ChoiceField(widget=forms.RadioSelect(attrs={"label":"Gender", "id":genders.fromkeys}), choices=genders.items) #Expecting one "id"="M" and one with "id"="F" -
Reportlab generate pdf from center
Following is code from views that generate a pdf file and return it. def pdf_file(request,id): pti=Pti.objects.get(pk=id) po=PurchaseOrder.objects.get(pk=id) inv=Invoices.objects.get(pk=id) reimbinv=Reimbursement.objects.get(pk=id) buffer=io.BytesIO() pdf=canvas.Canvas(buffer) pdf.pagewidth=A4[0] pdf.pageheight=A4[1] pdf.setTitle(inv.title) MARGIN_LEFT=MARGIN_RIGHT=10 MARGIN_TOP=MARGIN_BOTTOM=10 MT_WIDTH=A4[0]-(MARGIN_LEFT+MARGIN_RIGHT) MT_HEIGHT=A4[1]-(MARGIN_BOTTOM+MARGIN_TOP) HT_HEIGHT=MT_HEIGHT*35/100 BT_HEIGHT=MT_HEIGHT*30/100 FT_HEIGHT=MT_HEIGHT*35/100 mainTable=Table( [ #[jazz_top_header(MT_WIDTH,HT_HEIGHT*15/100)], [genHeader(MT_WIDTH,HT_HEIGHT,po.poNumber)], ], MT_WIDTH,HT_HEIGHT ) mainTable.setStyle([ style.BOTTOM_PADDING_ALL_ZERO, style.LEFT_PADDING_ALL_ZERO, style.TOP_PADDING_ALL_ZERO, style.VALIGN_ALL, ]) mainTable.wrapOn(pdf,0,0) mainTable.drawOn(pdf,MARGIN_LEFT,MARGIN_BOTTOM) pdf.showPage() pdf.save() #response=HttpResponse(content_type='application/pdf') buffer.seek(0) return FileResponse(buffer,as_attachment=True,filename='hello.pdf') and it calls following functions def genHeader(width,height,po_number): heightList=[ #height*10/100, # 10% for Jazz height*10/100, #20% for PTI heading height*10/100, #10% for agreement etc height*10/100, #10% for location etc height*10/100, #10% for certificate of PTI #height*50/100 #40% for text ] data_row=[ [generateTable(width,heightList[0],'''<b>Permission To Invoice</b>''',style.TEXT_ALIGN_CENTER)], ['Department:','''<u>Marketing</u>''','Agreement/PO No:',str(po_number)], ['Location:','''<u>Islamabad</u>''','Contractor Name:','Fish Bowl Pvt. Ltd'], ['Certificate Of Permission to Invoice:-','','','',''], ] head_section_table=Table( data_row, #[jazz_top_header(width,heightList[0])], #[generateTable(width,heightList[0],'<b>Permission To Invoice</b>',style.TEXT_ALIGN_CENTER)], #[custom_colBasedTables(width,heightList[1],arr_data_row1,style.TEXT_ALIGN_RIGHT)], #[custom_colBasedTables(width,heightList[2],arr_data_row2,style.TEXT_ALIGN_RIGHT)], width/4, heightList ) return head_section_table and another method def generateTable(width,height,txt,txt_align_position): res_table=Table([[txt]], width,height) res_table.setStyle([txt_align_position,style.VALIGN_ALL]) return res_table Here styles are properly adjusted in styles.py class style: TEXT_ALIGN_CENTER=( 'ALIGN',(0,0),(-1,-1),'CENTER' ) TEXT_ALIGN_RIGHT=( 'ALIGN',(0,0),(-1,-1),'RIGHT' ) TEXT_ALIGN_LEFT=( 'ALIGN',(0,0),(-1,-1),'LEFT' ) BOTTOM_PADDING_ALL_ZERO=( 'BOTTOMPADDING',(0,0),(-1,-1),0 ) TOP_PADDING_ALL_ZERO=( 'BOTTOMPADDING',(0,0),(-1,-1),0 ) LEFT_PADDING_ALL_ZERO=( 'LEFTPADDING',(0,0),(-1,-1),0 ) RIGHT_PADDING_ALL_ZERO=( 'RIGHTPADDING',(0,0),(-1,-1),0 ) VALIGN_ALL=( 'VALIGN', (0,0), (-1,-1), 'TOP' ) Code works perfectly fine but pdf is generated in the middle vertically. I tried to set VALIGN also still it does not works. Any suggestions to resolve this issue. -
Ask for 2nd authentication on a specific button to call a function
on my django app. I have a button that have sensitive data on it when accessed by someone. I need something like, when the button is clicked. the button will ask for a password or an OTP, to access the restricted page. how can I do it? is there a django package for this? Thanks! <button class="btn btn-md btn-danger" onclick="**Do something**">Enter</button> -
Object returning true even if it is None
So i'm trying to see if the user has something in their cart, if they don't and they click on chekout then it should say that their cart is empty but it just makes an order object. makeorder and createorder function handles creating orders. CartItem objects returns True even if user does not have it. makeorder function handles checking if user has that object or not. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from .forms import BookForm from django.core.exceptions import ObjectDoesNotExist import random # Create your views here. removederror = '' def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in oof: fianlprice += item.book.price def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def signinuser(request): …