Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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): … -
CSRF token missing or incorrect error when using accessing from client network
CSRF token missing or incorrect error when using accessing from the client network My python Django web app is deployed in the Nginx server on CentOS 7. It has some ajax POST calls. I have included header : {"X-CSRFToken": '{{ csrf_token }}'}, in every ajax post request. It was working fine when we use the application from any open network/WiFi. But when using in client network, it's failing for ajax POST calls(Intial login is fine). Django logs display the message "WARNING 2021-02-03 14:44:56,895 log 14776 140049620125504 Forbidden (CSRF token missing or incorrect.): /employee". FYI, it's not SSL enabled and it's directly accessed with server IP, which is public. -
How to display row data from a table
I want to display the row data from a table to be displayed as a mail while we click on the row. But my doubt is how can I fetch only that row item(data) from the database and display. Can anyone suggest a possible way for this? -
How to update form with get approval from another specific user in Django?
I want to create a basic approval system in my Django project. In this system there are several ranks, but for this question I only use Lead and Manager. I created forms and this forms are representing limits. Only Lead can fill these forms. But what I want is when a Lead update the form it shouldn't display without Manager's approval. How can I do that? approvals/models.py class DoaTable(models.Model): LIMITS = ( ('Low Risk', 'Low Risk'), (...), ('Strict Credit Check', 'Strict Credit Check'), ('No Credit Check', 'No Credit Check'), ) RANKS = ( ('Analyst', 'Analyst'), ('Senior Analyst', 'Senior Analyst'), ('Lead', 'Lead'), ('Manager', 'Manager'), ('...Officer'), ) rank = models.CharField(max_length=200, choices=RANKS) risk = models.CharField(max_length=200, choices=LIMITS) limit = models.FloatField() comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) user/models.py class UserProfile(AbstractUser): ... password = models.CharField(max_length=250) email = models.EmailField(max_length=254) rank = models.CharField(max_length=200) ... class Rank(models.Model): rank_name = models.CharField(max_length=200) company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False) Ranks in this model is same as Doa table ranks. We assume that user ranks are Lead and Manager for this scenerio. approvals/forms.py class DoaTableForm(forms.ModelForm): class Meta: model = DoaTable fields = ('rank', 'risk', 'limit',) class UpdateDoaTableForm(forms.ModelForm): class Meta: model = DoaTable fields = ('limit',) aprovals/views.py def update_limit(request, id): limiting = get_object_or_404(DoaTable, id=id) form … -
Exporting issues to excel using openpyxl(django) (cant seems to work with fetchall())
def export_as_xls(self, request, queryset): opts = self.model._meta file_name = unidecode(opts.verbose_name) sql_query = '''SELECT COUNT(id) AS No_Of_Report, vendor, country_code, SUM(new_code)*100/SUM(sent) AS 'failure_rate', SUM(case when new_code =0 then 1 ELSE 0 end)*100/sum(sent) AS 'success_rate' FROM sms_statistics WHERE FROM_UNIXTIME(date) >= curdate() - interval 30 day GROUP BY vendor, country_code ORDER BY vendor DESC;''' This is mysql query i used to call for the data in mysql schema field_names = ('No of report', 'Vendor', 'Country Code', 'Failure Rate', 'Success Rate') wb = Workbook() ws = wb.active ws.append(ExportExcelAction.generate_header(self, self.model, field_names)) with connection.cursor() as cursor: cursor.execute(sql_query) objects = list(cursor.fetchall()) for row in cursor.fetchall(): objects = list(row) ws.append(objects) print(ws.append(row)) ws = style_output_file(ws) I think the issue is right here for not being able to export to excel. Im not be using the right method to export the file from action.py response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename={file_name}.xlsx' wb.save(response) return response export_as_xls.short_description = "Reports of Past 30 days" export_as_xls.acts_on_all = True Blockquote I believe this part is fine as i tried exporting an empty file and its working as expexted -
Compare two dates in Django Template
In my template i have the two variable from the view: {{data.purchase_date}} and {{data.approval_granted}}. i would like to check if there are more than two days between the two dates and alert the user. I tried the following: {% if data.trade_date|timeuntil:data.approval_granted > 2 %} Purchase was executed after clearance had expired, investigate possible breach. {% endif %} But it shows nothing. Can you please help me? i am coming from Ruby where this is super easy to do actually. -
Python get two value difference and their remaining percentage
In python i have a two variable like : toatalCount = 4 completedCount = 2 what i actually want is i want 50 as a result what i am getting through this . formula = 100/(toatalCount - completedCount) but when i am having values like: toatalCount = 1 completedCount = 0 or toatalCount = 0 completedCount = 1 it is not working in that case i want only remaining percentage of variables.Please help me related this i am stuck here -
ERR_CONNECTION_REFUSED via localhost access( React -> Django )
I made dev environment underbelow. Container is Docker container. +-----------------------------------------------------+ | ◎http://192.168.1.1:8040/ | | | +---------------------------------------------------------------------------+ | | | [ubuntu] | | | | (192.168.1.1) | | | +-----------------------------------------------+ | | | | | ✖ http://172.17.0.1:8040/ | | | | | | | | | +-------------------------------------------------------------------------+ | || | | | | [container]| | || | | | | (172.17.0.1)| | || +--+--+--+ | | | | || | React | | | | | +--------> nodejs +-----------------------------------------+ | | | | | || | | ✖ http://localhost:8040/ | | | | | | || +--------+ ✖ http://127.0.0.1:8040/ | | | | | | || v v v | | | || +--------+ ++--+--+---+ | | | || | | | | | | +---------+ | +------> nodejs +--------------------------------------->+ Django | | | | | | | || | | ◎ http://localhost:8040/ | | | | | +-+ | || +--------+ ◎ http://127.0.0.1:8040/ ++--+------+ | | | | | || ^ ^ | | | +---+ || +--------+ | | | | | Browser | || | | | | | | | (winPC) +----------> Flask +-----------------------------------------+ | | | | | || | | ◎ http://localhost:8040/ | | | … -
raise exception as http response
I'm using django and vue to write a Programmer. Could I raise an exception as a http response, so I can raise the exception anywhere, and do not need to catch it in the django view function, and then reassemble it into a new http response. Pseudocode try: a = ['0'] b = a[2] except IndexError as e: raise ExceptionAsHttpResponse(status=404, reason='haha') # Not implemented, hope to get your help. after the raise ExceptionAsHttpResponse, the frontend can just accquire the status and reason -
env issue running local version of Django site
I am trying to run a Django project locally on my computer but I keep running into some issues trying to get it started. I installed all dependencies in my anaconda local environment. I'm not sure if maybe my system is not reading read the .env file and how to fix that? I'm juat not sure what's going on here. Any help would be greatly appreciated! Here is the error in my terminal when I try running the server. (FSS_Link) ➜ company_name git:(data-dashboard) python manage.py createsuperuser Traceback (most recent call last): File "manage.py", line 30, in <module> execute_from_command_line(sys.argv) File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/abelrenteria/Library/Python/2.7/lib/python/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/abelrenteria/Documents/CWC_Website_Code/cwc/config/settings/local.py", line 1, in <module> from .base import * # noqa File "/Users/abelrenteria/Documents/CWC_Website_Code/cwc/config/settings/base.py", line 9, in <module> ROOT_DIR = environ.Path(__file__) - 3 AttributeError: 'module' object has no attribute 'Path' Any ideas on how to fix? Thanks!