Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Code running in local does not work on server (Django)
I created a List in views.py to draw a chart in html. In local PC, the chart is printed well whenever connected. But on the server PC, "Cannot resolve keyword 'jan' into field." An error occurs. I wondered if the indent of the for statement was a problem, but it works fine in local without any problem. But, If I proceed with "sudo systemctl daemon-reload" -> "sudo systemctl restart wsgi" on the server PC, For a few minutes the chart is printed normally. However, when I access the page again after a while The above error occurs. I really don't know what's wrong. Please help... [views.py] team_parameter = request.GET.get('team') monthly_kwargs = {} for i in range(1, 13): gte = datetime(today.year, i, 1) lte = get_last_day_of_month(date(today.year, i, 1)) mo = f'{gte:%b}'.lower() monthly_kwargs[mo] = Count('student_id', filter=Q(date__gte=f'{gte:%Y-%m-%d}', date__lte=f'{lte:%Y-%m-%d}')) monthly_kwargs['SPECIAL_' + mo] = Count('student_id', filter=Q(date__gte=f'{gte:%Y-%m-%d}', date__lte=f'{lte:%Y-%m-%d}', student__class__id__in=special)) monthly_kwargs['total'] = Count('student_id', filter=Q(date__year=today.year)) monthly_kwargs['SPECIAL_total'] = Count('student_id', filter=Q(date__year=today.year)) value_list_args = ['uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec', 'total', 'SPECIAL_jan', 'SPECIAL_feb', 'SPECIAL_mar', 'SPECIAL_apr', 'SPECIAL_may', 'SPECIAL_jun', 'SPECIAL_jul', 'SPECIAL_aug', 'SPECIAL_sep', 'SPECIAL_oct', 'SPECIAL_nov', 'SPECIAL_dec', 'SPECIAL_total'] if not request.GET or parameter == 'ALL': monthly_register = Memo.objects \ .annotate(**monthly_kwargs) \ .values_list(*value_list_args) \ else: monthly_register = Memo.objects \ … -
Tinymce HTMLField Doesn't show in StructBlock
I'm trying to use HTMLField inside a StructBlock, but the text editor doesn't show... Any idea if this is the correct way to use the tinymce with blocks.StructBlock ? Thanks from tinymce.models import HTMLField class BodyBlock(blocks.StructBlock): content = HTMLField(null=False, blank=True) # <-- this is the tinymce rich text field show_share_buttons = blocks.BooleanBlock( verbose_name=_('show share buttons'), default=True, help_text=_('Whether "Share" buttons will appear at the top left corner of the article body') ) class Meta: # noqa template = "blocks/body.html" icon = "doc-full" label = "Body Ritch Text" body.html <div class="find-page__body main-content"> {% if self.show_share_buttons %} <dv class="not-mobile"> {% include 'share_buttons.html' with url=page.get_full_url %} </dv> {% endif %} {{ self.content}} </div> -
Django create model variable based on another model
I'm new in Django and I have a question about architecture. I'm not looking for a ready solution, just for some explanations in a simple way, and maybe tips about architecture. I want to create a simple classic RPG helper, and that's why a need three models: Fraction Class Character And Character stats should be based on another two models. Example: class Fraction(models.Model): describe = models.CharField(max_length=300) hp = models.modelIntegerField(default = 0) dmg = models.modelFloatField(default = 0.0) class Char_class(models.Model): describe = models.CharField(max_length=300) hp = models.modelIntegerField(default = 0) dmg = models.modelFloatField(default = 0.0) skills = models.CharField(max_length=50) class Character(models.Model): char_id = models.modelIntegerField(default = 0) fraction = models.ForeignKey(Fraction, on_delete=models.DO_NOTHING) char_class = models.ForeignKey(Char_class, on_delete=models.DO_NOTHING) hp = model.modelIntegerField(default = fraction.hp + char_class.hp) dmg = model.modelFloatField(default = fraction.dmg + char_class.dmg) And what do I want to obtain? I thought I will just create in admin Django some class, and some fraction. Next after that I will create some characters just picking fractions and classes from the list, and then hp, and dmg, should be a sum of the value from that two models. And I got the error, that ForeignKey doesn't have a dmg/hp variable. I just googled and found some information, and now if I understand … -
Django-tables2, Django-filters how to override .empty_text
Hope everyone is well. I'm using django-tables2 and django-filters to display large datasets in html tables. I wanted to use the django-tables empty_text to return a message when there is zero results. However I currently load the tables with an empty queryset to avoid large load times (Better to let the user decide if they want to generate the whole data set), this causes a problem because the empty_text message populates. I want to know if there is a away to stop the empty_text message appearing if there is no filters applied or no filter URL. If I can't do it that way maybe there is a better way to determine empty set on filter result. Thanks in advance, Thomas -
Python/Django project working correctly on a local host server but not working on a heroku server
I have created a web application where Sign Up and login was create using Django’s authentication system. Basically I used the code from this page: https://www.geeksforgeeks.org/django-sign-up-and-login-with-confirmation-email-python/ On my server the project is working perfectly, but when I did the hosting it is not possible to create users. I have a suspicion that my problem is with the database because I am using the default django settings. This is the error I get when I try to create user on the hosted site: The above exception (relation "auth_user" does not exist LINE 1: SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."userna... ^ ) was the direct cause of the following exception: /app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py, line 55, in inner response = get_response(request) Local vars /app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Local vars /app/user/views.py, line 32, in register if form.is_valid(): To Request information I got: **Request information** USER AnonymousUser **GET** No GET data **POST** Variable Value csrfmiddlewaretoken '4tl1onB5FTWa8FhMwHqiiuVsMo9J8yf5yW0qdiubabYOCeDwngMSnJNXFL08baBO' username 'abacaxi10' email 'abacaxi1012@gmail.com' password1 'mtHya2yaWRw2nxK' password2 'mtHya2yaWRw2nxK' As I said on the local host the site works very well. I would like to know how can I fix the error or how can I build a simple database just for user registration? -
Jsonresponse not working in CreateView - Django
I'm trying to get all the users who has the group 'decoration' into a form field by using JsonResponse to get the list in realtime when the user start to type in the field. The problem here is that I'm not getting any data in the form as a Jsonresponse. If I make a print of "titles", is getting the correct data, but is not bringing the data to the form... views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['...'] def get_form(self, form_class=None): form = super().get_form(form_class) if 'term' in self.request.GET: qs = User.objects.filter(groups__name='decoration', username__icontains=self.request.GET.get('term')) titles = list() for product in qs: titles.append(product.username) return JsonResponse(form, safe=False) return form def form_valid(self, form): form.instance.author = self.request.user return redirect(reverse('blog:post-detail', kwargs={'pk': obj.id})) def form_invalid(self, form): messages.error(self.request, self.error_message) form.instance.thumb.checked = True return super().form_invalid(form) models.py class Post(models.Model): title = models.CharField(max_length=100) culture = models.CharField(max_length=100) .HTML <div class="form-group"> <label>Some text</label> {% render_field form.culture class="form-control form-st text-body" style="box-shadow: none;font-size:1.5rem;" id="nightclub" placeholder='...' autocomplete="off" %} </div> script which handles the autocomplete <script> $( function() { $( "#nightclub" ).autocomplete({ source: '{% url 'blog:post-create' %}' }); }); </script> Any help would be grateful! -
Django Form Field Validation - Input fields reset
I need some help. I have a login form where the user is required to provide a username and password. If the user fails to provide the information I present them with a validation error. The issue I have is that if the user provides a username (for example) the validation error disappears and the value that was in the field. The field value resets again. Not sure what I am doing wrong. Here is my template code: # Create your views here. def login(request): message = '' username = request.POST.get('username') password = request.POST.get('password') if request.method == 'POST': form = LoginForm(request.POST or None) if form.is_valid(): user = authenticate( username=form.cleaned_data['username'], password=form.cleaned_data['password'], ) if user is not None: auth_login(request, user) return redirect('expedition:gallery') else: return render(request, 'account/login.html',{'form':form}) else: form = LoginForm() return render(request, 'account/login.html',{'form':form}) -
Django Rest Framework: Will rejecting uploads at the view level still block the event loop?
Our app is scaling and is lagging due to uploads not being done through signed urls. Will the following code still block the event loop if a user tries to POST a large file to this endpoint? Or will it be rejected, allowing our event loop to continue? If this does still block the event loop, what's a better solution to temporarily turn the endpoints off? Is a 405 from DRF a viable way to do this by turning off the method? We prefer a 400 so we can return a custom error. class UploadViewset( mixins.CreateModelMixin, viewsets.GenericViewSet ): permission_classes = [permissions.IsAuthenticated] def create(self, request, room_pk=None): ######################## # Temporarily Disable ######################## return Response( { "detail": "Uploads have been temporarily disabled for performance." }, status=status.HTTP_400_BAD_REQUEST, ) -
Página não popula um Select com os dados da tabela no banco de dados (DJANGO)
Estou tentando fazer com que o select "empresas" retorne os valores do banco armazenados na table "company", porém quando na view coloco para retornar o "objects.all() de "company", a página perde todo o javascript e CSS. HTML QUE DEVE RETORNAR O SELECT {% extends 'layouts/base.html' %} {% load static %} {% block title %} Dashboard {% endblock title %} <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} {% block content %} <div class="container"> <label><b></b></label> <form action="{% url 'update_tool' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" id="tool_id" class="form-control" name="tool_id" value="{{tool.id}}" hidden> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label><b>Nome da Ferramenta</b></label> <input type="text" class="form-control" name="name" value="{{tool.name}}"> </div> </div> <div class="col-md-6"> <label><b>Tag da Ferramenta</b></label> <div class="form-group"> <input type="text" class="form-control" name="tag_tool" value="{{tool.tag_tool}}"> </div> </div> </div> <div class="row"> <div class="col-md-6"> <label><b>Área Responsável</b></label> <div class="form-group"> <input type="text" class="form-control" name="area" value="{{tool.area}}"> </div> </div> <div class="col-md-6"> <label><b>Empresa</b></label> <div class="form-group"> <select class="form-control form-control-md" value="{{tool.company}}"> {% for company in company %} <option value="{{company.name_company}}"> {{company.name_company}} </option> {% endfor %} </select> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <label><b>Tipo de Ferramenta</b></label> <select class="form-control form-control-md" name="type" value="{{tool.type}}"> <option>Manual</option> <option>Eletroportátil</option> </select> </div> </div> <div class="col-md-6"> <label><b>Status</b></label> <select class="form-control form-control-md" name="status" value="{{tool.status}}"> <option>Ativo</option> <option>Inativo</option> <option>Condenada</option> </select> </div> … -
django-ckeditor modal form does not change data on POST
I have a django project using django-ckeditor. I use HTMX to create a bootstrap modal to show my edit form. It renders correctly (I did add the ckeditor.js files at the end of the body in base.html). If I call my form by going to localhost/1/update, change the RTF value, and click save, it works fine. But rendering it in the modal form and clicking save, the form.has_changed() returns false. If I edit another field and it saves, the value of RTF does NOT change. It seems like the POST does not include the changed value for the CKEditor field. I've tried to reduce the code below to make it as short as possible. My model: class MyModel(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=150) comment = RichTextField(blank=True, null=True) def __str__(self): return f'{self.name} - {self.description}' My form: class MyForm(forms.ModelForm): class Meta: model = MyModel fields = ( 'name', 'description', 'comment', ) My View def update_data(request, pk): model = MyModel.objects.get(id=pk) form = MyForm(request.POST or None, instance=model) if request.method == "POST": if form.is_valid(): print(form.has_changed()) form.save() return redirect("detail-form", pk=model.id) My HTML#1 - I click on the update button to open the modal {% extends "layouts/base.html" %} {% load static %} {% block content %} … -
Customizing model primary keys
I have model Mail which saves a mail object. Mail model also has a OneToMany relationship field, that is related to User(User can have many mails, but a mail can have only one owner(User object)). I need to implement its own primary keys reference system for each Mail object, because each mail is supposed to be related to an only one user to display urls the right way. For example if User-1 sends his first two mails in the whole app, they are saved with 1 and 2 id in the database, that's default django primary keys saving system. Then if User-2 sends his first mail, this mail is supposed to be saved with id 1, because it's first User-2 mail, but it's gonna be saved with id 3, because by default primary key reference system, the ids 1 and 2 are already taken. And this is the problem, because the url of first mail for User-2 will be displayed as /sent-mail/3, when it must be /sent-mail/1 So how to customize Mail model and implement it's own primary key references for each user. Here is the model: class Mail(models.Model): url_id = None title = models.CharField(max_length=64) body = models.CharField(max_length=1000) unvisited = … -
DJANGO REST FRAMEWORK - AssertionError
I am getting this error AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> I don't really understand what's wrong views.py class Links(viewsets.ViewSet): def create(self, request): serializer = LinkSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) # return Response({"error": "something went wrong"}) serializers.py class LinkSerializer(serializers.ModelSerializer): class Meta: model = Links fields = ( "title", "niche", "url", "owner", "date", ) valid = {'required': True} extra_kwargs = { 'title': valid, 'niche': valid, 'url': { 'required': True, 'validators': [UniqueValidator(Links, "Link has been posted already"),] } } def create(self, validated_data): newLink = Links.objects.create( title=validated_data['title'], niche=validated_data['niche'], url=validated_data['url'], owner=validated_data.get['owner'] ) newLink.save() return newLink You can check if out on github here -
How to override the default authentication form in django
I've been trying to override the authentication form, i ve inherited from the authenticationform class how do i make the loginview to use my custom form -
Django and Javascript How to Upload Multiple Images with Progress Bar
Good day, I am trying to upload multiple images in django with a progress bar. Currently, I have a working solution for only one image but now I want to add more fields and I need to show progress bar for all the images I am uploading. Below is my working code and the commented out code in the forms.py are the new fields I want to add. models.py class ProductImage(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, null=True, blank=True) main_image = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_one = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_two = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_three = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_four = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) img_five = models.ImageField(max_length=255, upload_to=get_product_image_additional_filepath, null=True, blank=True) forms.py class StoreDashboardProductUpdateForm(forms.ModelForm): class Meta: model = ProductImage fields = [ "main_image", # "img_one", # "img_two", # "img_three", # "img_four", # "img_five" ] views.py def store_dashboard_product_update_view(request, slug, product_slug, pk): product = get_object_or_404(Product, pk=pk) form = StoreDashboardProductUpdateForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.instance.product = product form.save() return JsonResponse({'message': 'hell yeah'}) context = { 'form': form, "object": product } return render(request, 'store/dashboard/product_update.html', context) {% extends 'store/dashboard/base/products-second.html' %} {% load crispy_forms_tags %} {% load widget_tweaks %} {% block content %} <style> .not-visible { display: none; } … -
Django. How to make ModelChoiceField work with SingleObjectMixin, FormView, and inlineformset_factory?
So, I have been trying to make it function as planned, but there might be a tweak away from my knowledge. The objective is to show only related options in a form with a choice field. Model CONTRATO register all contracts Model FATURA register all invoices and it has a ForeignKey with CONTRATO in a relation one-to-many (so one contract has many invoices) Model LANCAMENTO register records from contracts that will be later assigned to an invoice in FATURA. So LANCAMETNO has a ForeingKey with CONTRATO in a relation on-to-many (so one contract has many recors in LANCAMENTO). And LANCAMENTO also has a ForeignKey with FATURA, that is null by default, so later it will be assigned a FATURA to that record in LANCAEMTNO. The goal is to have this logic in a form. So when user goes to LANCAMETNO to assign a FATURA, it can choose only FATURA with the same contract_id as LANCAMETNO. I got here resarching a lot, but this is as far I can go. I'm stuck. Here's the code, in case someone could point me in the right direction. Here is my code for Models: from django.db import models from django.urls import reverse, reverse_lazy # … -
get next page number instead of next page link django rest framework
I'm working with django rest framework but I face this problem with the pagination the output Show in next and previous the page link but I want the page number only my pagination.py from rest_framework.pagination import PageNumberPagination class MycustomPagination(PageNumberPagination): page_size = 5 page_size_query_param = 'page_size' max_page_size = 10 page_query_param = 'page' my views.py from .paginations import MMycustomPagination class AllSerialed(ListAPIView): pagination_class = MycustomPagination queryset = MyModel.objects.filter(blacklist=False).order_by("-date") serializer_class = MyModelSerial simple output { "count": 20, "next": "http://127.0.0.1:7000/data/?page=3", "previous": "http://127.0.0.1:7000/data/?page=1", "results": [ ] } -
How to setup Vue.js SPA when starting it in HTML
I have a django application where I have an area that is made in Vue.js. I would like to know if it is possible to set parameters at the time of initialization of the Vue.js app in HTML. For example a token where the VueApp can use to authenticate and fetch some apis in django. Today it is being done like this: <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!-- built files will be auto injected --> <script> window.config = {{vue_config | safe}}; </script> <script type="text/javascript" src="{% static 'js/app.js' %}"></script> </body> And inside the VueApp I get the configs from window.config Is there a better way to do this? -
Is there a way in Django to order a model using a "custom filter logic"?
I'm currently having a problem in a personal project which involves ordering by 2 custom fields (limit_date and priority). Let's suppose a model like: PRIORITY_CHOICES = [ ("red", "Red"), ("yellow", "Yellow"), ("green", "Green") ] class Todo(models.Model): limit_date = models.DateField() priority = models.CharField(choices=PRIORITY_CHOICES, max_length=15, blank=False, null=True) Let's suppose i want to order them following the following logic: if <current_todo>.priority == 'red': priority_scale = 3 elif <current_todo>.priority == 'yellow': priority_scale = 2 else: priority_scale = 1 priority_scale_with_date = <current_todo>.limit_date - datetime.today() * (<current_todo>.priority_scale) I know i can do some things with "conditional expressions" to get priorities as values, like: Todo.objects.annotate( priority_scale=Case( When(priority='red', then=Value(3)), When(priority='yellow', then=Value(2)), When(priority='green', then=Value(1)), default=Value(0), output_field=models.IntegerField())).order_by('-priority_scale', 'limit_date') But i don't know how can i put them all "together". Let's suppose a object with priority 'red' (value 3), with two days left to be done and another one with priority 'green' (value 1) with one day to be done. Their priorities will be something like: first_obj = 1 * 3 = 3 (days untill limit_date and 'priority_scale') second_obj = 2 * 1 = 2 (days untill limit_date and 'priority_scale') What i want, is to order them with a "junction" of 'priority_scale' and 'limit_date'. I am very confused here and sorry … -
Name error when trying to import API key from .env
I am trying to store my API Keys in a .env file I created the file as a File containing settings for editor file type. Stored my APIKeys TWILIO_ACCOUNT_SID=*** TWILIO_AUTH_TOKEN=*** TWIML_APPLICATION_SID=*** TWILIO_API_KEY=*** TWILIO_API_SECRET=*** Installed decouple, imported and used config to retrieve my API tokens in my settings.py file from decouple import config ... TWILIO_ACCOUNT_SID = config(TWILIO_ACCOUNT_SID) TWILIO_AUTH_TOKEN = config(TWILIO_AUTH_TOKEN) TWIML_APPLICATION_SID = config(TWIML_APPLICATION_SID) TWILIO_API_KEY = config(TWILIO_API_KEY) TWILIO_API_SECRET = config(TWILIO_API_SECRET) I am however getting the error message: TWILIO_ACCOUNT_SID = config(TWILIO_ACCOUNT_SID) NameError: name 'TWILIO_ACCOUNT_SID' is not defined -
Loading Screen for a Form
I am trying to make a loading screen when submitting a form. When I submit a form the page starts to load until the backend responds by downloading an excel file. The idea is to have the effect of "load screen" only until the file manages to download. html: <form action="{% url 'downloadStatusPickingCustomerByCollection' %}" method="POST">{% csrf_token %} <div class="pnl-collection"> <div> <div class="tituloPnl"> <h3>Estado Ordenes de Venta por Colección</h3> </div> <div class="btnExport"> <button onclick="loadDisplay()" class="btn btn-light" type="submit">Exportar</button> </div> </div> <div class="filtro"> <div> <div class="title-select"><span>Colección</span></div> </div> <div> <select class="form-select form-select-sm form-down-report" name="collection-StatusCustomer-name" id="" required> <option value="">- SELECCIONE COLECCIÓN -</option> {% if collections %} {% for collection in collections%} <option value="{{collection.Name}}">{{collection.Name}}</option> {% endfor %} {% endif %} </select> </div> </div> </div> </form> javascript: function loadDisplay() { if (document.querySelector(".form-down-report").value != "") { document.getElementById("preloader-camion").style.display = 'block'; jquery(window).load( function () { document.getElementById("preloader-camion").style.display = 'none'; }); } } I have the bakcend developed in django so in the form route you can see a django "url tag". -
Bootstrap cdn working on Django but doesn't look quite right
I am trying trying to integrate bootstrap into my django site but it doesn't look quite write. I was looking for css clashes but the only stuff i could find is in the static folder and it just has admin related css. All my pages work its just the css that looks a bit off, any help is great, thanks. <!-- templates/base.html --> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body> {% block nav %} <ul id="nav"> <li>{% block nav-home %}<a href="{% url 'home' %}">Home</a>{% endblock %}</li> </ul> {% endblock %} <div id='content' class='main'> {% block content %} {% endblock %} </div> {% block scripts %} <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> {% endblock %} </body> </html> <!-- templates/registration/login.html --> {% extends "base.html" %} {% block title %}Log in{% endblock %} {% block content %} <section class="vh-100" style="background-color: #508bfc;"> <div class="container py-5 h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col-12 col-md-8 col-lg-6 col-xl-5"> <div class="card shadow-2-strong" style="border-radius: 1rem;"> <div class="card-body p-5 text-center"> <h3 class="mb-5">Sign in</h3> <div class="form-outline mb-4"> <input type="email" id="typeEmailX-2" class="form-control form-control-lg" /> <label class="form-label" for="typeEmailX-2">Email</label> </div> <div class="form-outline mb-4"> <input type="password" id="typePasswordX-2" class="form-control form-control-lg" /> <label class="form-label" for="typePasswordX-2">Password</label> </div> … -
GUI Python Simple Calculator Using Django
I'm trying to make a simple calculator with graphical user interface using Django ,I'm having trouble in calculating any of arithmetic operation(+,-,*,/) that what logic I have to apply in views.py files. Could someone help me out with this? I'm beginner in Django... views.py def view_calc(request): a=int(request.POST.get('t1',0)) b=int(request.POST.get('t2',0)) if request.method=='GET': resp=render(request,'calc.html') return resp elif request.method=='POST': if 'btn1' in request.POST: c=a+b elif 'btnsub' in request.POST: c=a-b elif 'btnmult' in request.POST: c=a*b elif 'btndiv' in request.POST: c=a/b d={'a':a,'b':b,'c':c} resp=render(request,'calc.html',context=d) return resp -
Why does SSE work locally, but not when hosted on IIS?
I'm using Django eventstream for SSE and Channels (I'm not able to use Memurai or Redis). When I run the local server, everything works great. The user can submit a file, that information is ran against the external 3rd party API it calls, and real time information is displayed back to the browser from the /events/ URL API. When configuring through IIS, everything works great EXCEPT the /events/ URL is unreachable (404), so the SSE connection doesn't get initiated which halts everything in it's tracks and I'm looking at a blank template that should be getting populated in real time. WebApp is hosted for local network only. I've attempted to use Daphne with various errors: daphne mysite.asgi:application: Traceback (most recent call last): File "C:\Python\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Python\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Python\Scripts\daphne.exe\__main__.py", line 7, in <module> File "C:\Python\lib\site-packages\daphne\cli.py", line 170, in entrypoint cls().run(sys.argv[1:]) File "C:\Python\lib\site-packages\daphne\cli.py", line 232, in run application = import_by_path(args.application) File "C:\Python\lib\site-packages\daphne\utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "C:\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, … -
streamBuilder flutter doesnt display data
im using streamBuilder to rebuild my screen depend on the project_id selected by taping on the project widget i send project_id to the next screen with constructer the streamBuilder read that constructor well but doesnt display that fetched from the http response from django endpoint here the model and api // To parse this JSON data, do // // final task = taskFromJson(jsonString); import 'dart:collection'; import 'dart:core'; import 'package:flutter/foundation.dart'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:project/model/project_model.dart'; import 'package:project/tasksById.dart'; import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; //List<Task> taskFromJson(String str) => List<Task>.from(json.decode(str).map((x) => Task.fromJson(x))); //String taskToJson(List<Task> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class Task { String? url; int? id; String? owner; String? project; String? title; DateTime? start; DateTime? end; String? desc; int? project_id; Task( {this.url, this.id, this.owner, this.project, this.title, this.start, this.end, this.desc, this.project_id}); factory Task.fromJson(Map<String, dynamic> json) => Task( url :json["url"], id: json["id"], owner: json["owner"], project: json["project"], title: json["title"], start: DateTime.parse(json["start"]), end: DateTime.parse(json["end"]), desc: json["desc"], project_id: json["project_id"], ); Map<String, dynamic> toJson() => { "url": url, "id": id, "owner": owner, "project": project, "title": title, "start": start?.toIso8601String(), "end": end?.toIso8601String(), "desc": desc, "project_id": project_id, }; } class SharedProojectId { Future<Future<bool>> setid(int? newId) async { final SharedPreferences prefs = await SharedPreferences.getInstance(); return prefs.setInt("project_id", newId!); } Future<int> getid() … -
image in django won't upload via form
I already found many answers to that question but most of them refer to adding request.FILES wchich doesn't work for me. I can upload an image via admin page, but when it comes to form i am getting an error that image is not loaded (while it is) Here is my model class Player(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=30) position = models.ForeignKey(Position,on_delete=models.CASCADE) shirt_number = models.IntegerField() team = models.ForeignKey(Team,null=True,on_delete=models.SET_NULL) image = models.ImageField(upload_to='images/players/') Here is my form class PlayerForm(forms.ModelForm): class Meta: model = Player exclude = ('team',) Here is views.py def team_detail(request,slug): team = get_object_or_404(Team, slug=slug) players = Player.objects.filter(team_id=team.id) if request.method == "POST": form = PlayerForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('') else: form = PlayerForm() return render(request,'team_detail.html',{'team':team,'players':players,'form':form}) And here is template file <form method = "POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="SUBMIT"> </form> Before submitting After pressing submit button