Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got AttributeError when attempting to get a value for field `name` on serializer
I'm new with this django rest framework thing and I'm having a problem showing one of my models in the api interface. I have 3 models that are related License, Profile and Rules. I can see Profile and License clearly but Rules (which is related with profile and license) gives me the next error: Got AttributeError when attempting to get a value for field name on serializer LicenseSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Rule instance. Original exception text was: 'Rule' object has no attribute 'name'. This is my model file: models.py: class License(LogsMixin, models.Model): """Definicion de modelo para licencias""" name = models.CharField( "Nombre de la licencia", max_length=100, null=False, blank=False) billable = models.BooleanField(default=False) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) class Profile(LogsMixin, models.Model): """Definición de modelo para Perfiles""" name = models.CharField( "Nombre de la perfil de usuario", max_length=100, null=False, blank=False ) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) class Rule(LogsMixin, models.Model): """Definición de modelo para Reglas""" FIELDS = [ ('user_name', 'Nombre de usuario'), ('user_code', 'Codigo de usuario') ] string = models.CharField("Cadena de referencia", max_length=100, null=False, default="", blank=False) profile = models.ForeignKey(Profile, null=False, default=None, on_delete=models.DO_NOTHING) license = models.ForeignKey(License, null=False, default=None, on_delete=models.DO_NOTHING) field = models.CharField("Campo … -
Prevent Nginx from changing host
I building an application which is right now working on localhost. I have my entire dockerized application up and running at https://localhost/. HTTP request is being redirected to HTTPS My nginx configuration in docker-compose.yml is handling all the requests as it should. I want my application accessible from anywhere hence i tried using Ngrok to route the request to my localhost. Actually i have a mobile app in development so need a local server for apis. Now, when i enter ngrok's url like abc123.ngrok.io in the browser, the nginx converts it to https://localhost/. That works for my host system's browser, as my web app is working there only, but when i open the same in my mobile emulator. It doesn't work. I am newbie to nginx. Any suggestions will be welcomed. Here's my nginx configuration. nginx.conf upstream web { ip_hash; server web:443; } # Redirect all HTTP requests to HTTPS server { listen 80; server_name localhost; return 301 https://$server_name$request_uri; } # for https requests server { # Pass request to the web container location / { proxy_pass https://web/; } location /static/ { root /var/www/censr.me/; } listen 443 ssl; server_name localhost; # SSL properties # (http://nginx.org/en/docs/http/configuring_https_servers.html) ssl_certificate /etc/nginx/conf.d/certs/localhost.crt; ssl_certificate_key /etc/nginx/conf.d/certs/localhost.key; root … -
How To Use Scope Variable In NG-REPEAT Angular JS
Since I am quite new to AngularJS, Have a problem with this code. var app = angular.module("demoModule",['infinite-scroll']); app.controller("demoController",function($scope){ $scope.result = []; $('#subCategory').on('change',function(){ subID= $(this).val(); category = new URLSearchParams(window.location.search); $.ajax({ type:'POST', url:'/filter/', data:{'sub_cat_id':subID,'csrfmiddlewaretoken':'{{ csrf_token }}','cat_id':category.get('category')}, success: function(response){ $scope.result = response; } }); }); $scope.lazyLoad = function(){ console.log("LAZY LOAD!"); } }); My HTML Template is:( Am using Django ) {% verbatim %} <div ng-app="demoModule" ng-controller="demoController"> <div class="container mt-2"> <div class="row"> <div class="col-md-12"> <div class="row"> <h1>Results are {{result}}</h1> <div class="col-md-4 mb-3" ng-repeat="item in result"> <div class="card"> <img src="#" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.product_name}}</h5> <button id="{{item.id}}" class="btn btn-primary btn-block">Details</button> </div> </div> </div> </div> </div> </div> </div> </div> {% endverbatim %} The problem is, whenever I select an option from a select menu, the javascript ajax function is called & JSON is responded. (I want to print these JSON objects (which as stored in $scope.result) by using ng-repeat in angular js) Really, can't understand why it is not printing? -
Why does the value of request.user appear to be inconsistent?
I am wanting an application to be able to check whether the user that is currently logged in is "test2". I'm using Django and running the following code: <script> console.log('{{ request.user }}') {% if request.user == "test2" %} console.log('The user that is currently logged in is test2.') {% else %} console.log('There was an error.') {% endif %} </script> And my console is logging the following: test2 There was an error. Why is this? How do I get the application to recognise that "test2" is logged in? -
How to convert each items of list into a dictionary?
Here I have a list like this. ls = ['Small:u', 'Small:o'] What I want is to create a dictionary of each list items like this. dict1 = {'Small':'u'} dict2 = {'Small':'o'} How can I do it ? Is it possible? -
How can I convert list into dictionary in python?
Here I have list and I want to convert this list into the dictionary How can I do it ? I have a list like this ['Small:u,', 'Small:o,'] Now I want to convert this list into this format {'small':'u', 'small':'o'} -
Create modalForm Django
I tried to create modalForm in base.html to call add-article view in any page. Here is how I do views.py def add_article(request): new_article = None if request.method == 'POST': add_article = ArticleCreateForm(request.POST, request.FILES) if add_article.is_valid(): add_article.save(commit=False) new_article.author = request.user new_article.save() else: add_article = ArticleCreateForm() context = { 'add_article': add_article, } return render(request, 'add_article.html', context) urls.py path('article/add-article/', views.add_article, name='add-article') base.html <a class="nav-link" id="add-article"><i class="fa fa-pencil fa-2x" aria-hidden="true"></i></a> <script type="text/javascript"> $function () { $("#add-article").modalForm({ formURL: "{% url 'add-article' %}", }); }); </script> But it doesn't show anything when clicking into write icon. Can anyone help me where I went wrong? -
Cancel button the form doesnt work properly
This is my form. Submit works properly fine. BUt with this I can only CANCEL, only when I fill all the fields. What I want is to cancel anytime and reach the main airlines page. Also, I want the cancel button in the form page.What will the be the solution?? <form action="{% url 'addairlines' %}" method="POST"> {% csrf_token %} {{form|crispy}} <button type="submit" class="btn btn-success" formaction="{% url 'addairlines' %}">Submit</button> <button class="btn btn-primary" formaction="{% url 'airlines' %}">Cancel</button> </form> -
Adding a field to custom Django Form Field
I just need one custom extra attribute in my Django form fields which is icon. I will take the example of my custom CharField. custom_fields.py: class ICharField(forms.CharField): """ Django CharField with custom icon field to use along with Bulma. """ icon = '' def __init__(self, *, icon='', max_length=None, min_length=None, strip=True, empty_value='', **kwargs): super().__init__(**kwargs) self.icon = icon forms.py: from utils.forms import custom_fields class SignUpForm(forms.Form): company_name = custom_fields.ICharField( icon='fas fa-envelope', widget=forms.TextInput(attrs={ 'class': 'input', 'placeholder': _('Name of your company'), 'label': _('Company'), }) ) That's it, but when in the HTML I try to access to {{ field.icon }} I'm getting nothing. the.html: {% extends 'template_composition/main.html' %} {% load i18n %} {% block content %} {% for field in form %} <div class="field"> <b>{{ field.label }}:</b> <p class="control has-icons-left"> {{ field }} <span class="icon is-small is-left"> <i class="{{ field.icon }}"></i> </span> </p> </div> {% endfor %} {% endblock %} It's obvious I'm overriding __init__ wrong, right? -
Django: How to detect the focus out in django template and call a function on it
I am working on a project. Need help in template focus out events on Django. model.py class Route(models.Model): route_no = models.SmallIntegerField(default=0) xname = models.CharField(max_length=40) class Booth(models.Model): booth_no = models.SmallIntegerField(default=0) route_no = models.ForeignKey(Route, on_delete=models.CASCADE, db_column='route_no') View.py class BoothCreateListView(CreateView, ListView): model = models.Booth form_class = booth.BoothForm template_name = 'booth/booth_create_list.html' context_object_name = 'booth_list' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) js_data = list(models.Route.objects.all().values_list('route_no', 'xname')) context['js_data'] = json.dumps(list(js_data), cls=DjangoJSONEncoder) return context template/booth_create_list.html <div class="col-sm-12 col-md-5"> <form method="post"> {% csrf_token %} <table class="table table-borderless"> {{ form.as_table }} </table> <input class="btn btn-success" type="submit" value="Save"> </form> {{ form.route.value }} </div> <div id='route_no'></div> <script> var route_no = document.getElementById('route_no') var myfunction = function (){ console.log('changing'); route.innerHTML = '{{ check_route_no form.route.value }}' } </script> form/booth.py class BoothForm(ModelForm): class Meta: fields = [ 'route_no', 'booth_no', ] model = models.Booth widgets = { 'route_no': forms.TextInput(), } labels = { 'route_no': 'Route No.', 'booth_no': 'Booth No', } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['route_no'].widget.attrs.update( {'onfocusout':'myfunction()'} ) for name, field in self.fields.items(): field.widget.attrs.update( {'class': 'form-control form-control-user'} ) templatetags/booth_template_tags.py from booth import models register = template.Library() @register.simple_tag def check_route_no(route_no): print(route_no) route = models.Route.objects.filter(route_no=route_no) if route.count() == 1: return route.xname else: return "not present" I want to check the route as user types it in the form … -
I'm facing some issues with pip verrsion 20.1.1. Down below is the exact error I'm getting in CMD
Here is the code which I'm geting from CMD. I'm running winows 10 What to do here? I can vsee pip version and other options with main but can't download/install any packages. D:\Python>python.exe -m pip install --upgrade pip Traceback (most recent call last): File "D:\Python\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "D:\Python\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\Python\lib\site-packages\pip\__main__.py", line 26, in <module> sys.exit(_main()) File "D:\Python\lib\site-packages\pip\_internal\cli\main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "D:\Python\lib\site-packages\pip\_internal\commands\__init__.py", line 104, in create_command module = importlib.import_module(module_path) File "D:\Python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Python\lib\site-packages\pip\_internal\commands\install.py", line 24, in <module> from pip._internal.cli.req_command import RequirementCommand, with_cleanup File "D:\Python\lib\site-packages\pip\_internal\cli\req_command.py", line 16, in <module> from pip._internal.index.package_finder import PackageFinder File "D:\Python\lib\site-packages\pip\_internal\index\package_finder.py", line 21, in <module> from pip._internal.index.collector import parse_links File "D:\Python\lib\site-packages\pip\_internal\index\collector.py", line 14, in <module> from pip._vendor import html5lib, requests File "D:\Python\lib\site-packages\pip\_vendor\html5lib\__init__.py", line 25, in <module> from .html5parser import HTMLParser, parse, parseFragment File "D:\Python\lib\site-packages\pip\_vendor\html5lib\html5parser.py", line 7, in <module> from … -
Using CSRF in an AJAX Call causes Uncaught TypeError: Cannot read property 'value' of null
I am struggling to figure out why my code is returning an error that is being caused by using CSRF in an Ajax call. The error is this: Uncaught TypeError: Cannot read property 'value' of null at HTMLUListElement.<anonymous> Here is my AJAX Call including setup: var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax({ type: "POST", url : '/api/uservenue/', data: { 'cafeName': cafeName, 'list_id': 1, csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value }, success: function(data){ console.log('User clicked: ' + data) }, failure: function(errMsg) { alert(errMsg); } }); Here is my views.py file [...] class UserVenue(viewsets.ModelViewSet): serializer_class = UserVenueSerializer queryset = UserVenue.objects.all() @ensure_csrf_cookie def get_queryset(self): cafeName = self.request.GET.get('cafeName', None) print(cafeName) return UserVenue.objects.all() [...] What I've tried My JS script is at bottom of html file. I've tried a bunch of different edits and tweaks based on reading through documentation/SO/Reddit suggestions. I tried using method_decorators, but this seemed to raise more errors. I'd be grateful for any advice. Thanks! -
Delete item from InlineForm in Django
I've created an InlineForm to add some Staff Members to a Project, but the form needs to be editable, and when I try to delete 1 of the Staff Members I get an error: get() returned more than one Colaboradores -- it returned 8! I can't send the ID to the view and can't get the Staff Member to be deleted. How can I fix it? edit_form.py def editar_projeto(request, projeto_id): if request.method == 'GET': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = EditForm(instance=projeto_editar) form_colab_factory = inlineformset_factory(Projeto, Colaboradores, form=ColabForm, extra=1, max_num=5) form_colab = form_colab_factory(instance=projeto_editar) context = { 'form': form, 'form_colab': form_colab, } return render(request, 'editar_projeto.html', context) elif request.method == 'POST': projeto_editar = Projeto.objects.filter(id=projeto_id).first() if projeto_editar is None: return redirect(reverse('projeto')) form = EditForm(request.POST, request.FILES, instance=projeto_editar) form_colab_factory = inlineformset_factory(Projeto, Colaboradores, form=ColabForm, extra=1, max_num=5) form_colab = form_colab_factory(request.POST, instance=projeto_editar) if form.is_valid() and form_colab.is_valid(): projeto_editado = form.save() form_colab.instance = projeto_editado form_colab.save() return redirect('projeto', projeto_editar.id) else: context = { 'form': form, 'form_colab': form_colab, } return render(request, 'editar_projeto.html', context) def deletar_colaborador(request, colaborador): colaborador = Colaboradores.objects.get(colaborador_projeto=colaborador) colaborador.delete() return redirect('editar_projeto') urls.py path('deletar_colaborador/<str:colaborador>', views.deletar_colaborador, name='deletar_colaborador') models.py class ColabForm(forms.ModelForm): class Meta: model = Colaboradores fields = '__all__' colaborador_projeto = forms.CharField(label="Colaborador do Projeto", widget=forms.TextInput( attrs={ 'class': 'form-control col-8', 'maxlength': '200', … -
Django cyclic imports and typechecking with mypy
I'm trying to create a simple custom manager with one of my Django models. It causes a cyclic import since I'm trying to import the manager from models.py and the model from managers.py. However, because my manager is creating the model and adding some extra attributes, the type hint for the method is the model instance. I'm having trouble with fixing that type hint since it's not yet imported. # models.py from .managers import PublishedBundleManager class PublishedBundle(models.Model): data = JSONField() md5_checksum = models.CharField(max_length=128) objects = PublishedBundleManager() The manager has a method to help me create the model instance, but as a convenience, calculates a checksum to fill in during creation. To fix the cyclic imports, I made use of typing.TYPE_CHECKING # managers.py import typing as t from django.apps import apps from django.db import models if t.TYPE_CHECKING: PublishedBundle = apps.get_model(app_label="the_hugh", model_name="PublishedBundle") class PublishedBundleManager(models.Manager): # Error 1 def create_publish(self, data: t.Dict, description: str) -> PublishedBundle: # Error 2 PublishedBundle = apps.get_model(app_label="my_app", model_name="PublishedBundle") json_data = json.dumps(data, sort_keys=True) md5_checksum = hashlib.md5(json_data.encode("utf-8")).hexdigest() return PublishedBundle.objects.create(data=data, md5_checksum=md5_checksum) However, I'm getting 2 errors. Missing type parameters for generic type "Manager" [type-arg]mypy(error) name 'PublishedBundle' is not defined I'm fairly new with typed python and never faced this issue before. … -
how to solve problem related to add to cart function in views.py
Basically, I am a beginner and following a tutorial of e-commerce project in django. when it comes to add_to_cart() function I do not understand the main concept of add_to_cart(). Code is given below and I want to clear my concepts that how add_to_cart's code is functioning? please help me to understand the concept. def add_to_cart(request): item = get_or_404(Item, slug=slug) order_item = OrderItem.objects.get_or_create(item = item ) # it is bothering me order_qs = Order.objects.filter(user = request.user, ordered = False) # it is bothering me if order_qs.exists(): order = order_qs[0] # it is bothering me. # check if order item is in the order. if order.items.filter(item__slug = item.slug).exists() order_item.quantity += 1 order_item.save() else: order.items.add(order_item) else: ordered_date = timezone.now() order = Order.objects.create(user = request.user, ordered_date =ordered_date) order.items.add(order_item) return render(request, 'URL's Name') -
Django 3: get_object_or_404 for UpdateView
I have a problem: I'd like to update a specific data/product, but a can't use get_object_or_404 views.py from django.shortcuts import render,get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib import messages from django.views.generic import ( UpdateView, DeleteView ) from product.models import Product from pages.forms import ProductForm def ProductUpdateView(request, pk): # queryset = Product.objects.all()[0].pk_id <-- I tried this # queryset = Product.objects.get() <-- and this queryset = Product.objects.all() product1 = get_object_or_404(queryset, pk=pk) #product1 = get_object_or_404(Product, pk=pk) <-- and this if request.method == 'POST': productUpdate_form = ProductForm(data=request.POST,files=request.FILES,instance=request.product1)) # Check to see the form is valid if productUpdate_form.is_valid(): # and profile_default.is_valid() : # Sava o produto productUpdate_form.save() # Registration Successful! messages.success messages.success(request, 'Produto Modificado com Sucesso') #Go to Index return HttpResponseRedirect(reverse('index')) else: # One of the forms was invalid if this else gets called. print(productUpdate_form.errors) else: # render the forms with data. productUpdate_form = ProductForm(instance=request.product1) context = {'productUpdate_form': productUpdate_form,} return render(request, 'base/update.html',context) urls.py from django.urls import include, path from pages.views import (ProductListView, ProductUpdateView, ProductDeleteView) urlpatterns = [ path('listProduct/', ProductListView, name='listProduct'), path('<int:pk>/update/', ProductUpdateView, name='product-update'), <--this link is ok ] Error: AttributeError at /1/update/ 'WSGIRequest' object has no attribute 'product1' Request Method: GET Request URL: http://127.0.0.1:8000/1/update/ Django Version: 3.1.1 Exception Type: AttributeError … -
How can a unique timestamp be incremented on constraint violation in a Django model?
As part of using TimescaleDB, which requires a timestamp as the primary key (time in SensorReading), I need to handle the case when the same timestamp is used by different sensor values. One elegant solution might be to smear colliding timestamps (add a microsecond on collision). How can this problem be solved in a robust and performant manner for the following models? class Sensor(models.Model): name = models.CharField(max_length=50) class SensorReading(models.Model): time = models.DateTimeField(primary_key=True, default=datetime.now) sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE) value = models.FloatField() P.S. This is a workaround as Django does not support composite primary keys. Otherwise it would be possible to set the sensor and timestamp as a composite primary key. -
ImportError Django (but I think its because of python)
I working in a project that uses python 3.6.9 and django 3.1.1 using it on a virtual enviroment with virtualenv, somerall python in my computer updated to the version 3.8.2 and somerall changed the virtual enviroment too , and now i can't even run the server. this is the steps that i do: source bin/activate in the folder of my project i do that: python manage.py runserver but It keeps given this error: Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? if I enter : $ python3 --version Python 3.8.2 if I miss some information about the problem please tell me... I new here :) -
Template is giving wrong path to media directory and Django can't find the images
I have 2 models and their relationship it's OneToMany. So, one "imovel" (portuguese word to property) has many pictures ("fotos" or "imagens" in portuguese). My web application structure is very simple and I configured at settings: settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('', index, name='index'), path('sobre_nos/', sobre_nos, name='sobre_nos'), path('', include('imoveis.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) So every picture that is uploaded, goes directly to 'media' structure and the images for properties goes to 'media/imoveis/%Y/%m/%d'. I want to show all pictures associated to a property in a template using a basic bootstrap carousel: imovel.html <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for foto in fotos_do_imovel %} {% if foto.imagem %} <div class="carousel-item activate"> <img class="d-block w-100" src="{{ foto.imagem }}"> </div> {% else %} <div class="carousel-item"> <img class="d-block w-100" src="{{ imovel.foto_principal }}"> </div> {% endif %} </div> {% endfor %} <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Anterior</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Proxima</span> </a> </div> The problem is, when I access the page to imovel.html, the pictures are not found: imoveis/2020/10/01/pexels-photo-1571463.jpeg imoveis/2020/10/01/pexels-photo-1643383.jpeg [01/Oct/2020 21:20:35] "GET /imovel/3 HTTP/1.1" 200 5952 Not Found: /imovel/imoveis/2020/10/01/pexels-photo-1643383.jpeg Not Found: /imovel/imoveis/2020/10/01/pexels-photo-1571463.jpeg [01/Oct/2020 … -
Unable to run Django Test Server in Ubuntu Server 16.04
I have 2 servers. I am attempting to setup one for continuous integration for my main website server Web server 1(cloud-hosting): Python3.6 Django3.1 Ubuntu16.04 Webserver 2(VPS): Python3.7 Django3.1 Ubuntu16.04 Jenkins --ShiningPanda(plugin) Im new to web development, so if it seems odd as far as my web server types, that is why. I have been following along in the book Test Driven Development with Python. My issue is that when running python manage.py test [app] My [app] inherits from the class StaticLiveSever to generate a testing environment. On webserver 1, this works fine. On webserver 2, i get an error that the request address cannot be assigned. I use jenkins to build the environment, but the error i get is OSerror[99]:cannot assign to requested address. I dont understand why this is happening when i run the same commands in Web Sever 1. It runs fine. Although again, the commands are run by jenkins and jenkins is configured to run python3.7 Full Traceback(Main Issue) Traceback (most recent call last): File "/var/lib/jenkins/shiningpanda/jobs/ddc1aed1/virtualenvs/d41d8cd9/lib/python3.7/site-packages/django/test/testcases.py", line 1449, in setUpClass raise cls.server_thread.error File "/var/lib/jenkins/shiningpanda/jobs/ddc1aed1/virtualenvs/d41d8cd9/lib/python3.7/site-packages/django/test/testcases.py", line 1374, in run self.httpd = self._create_server() File "/var/lib/jenkins/shiningpanda/jobs/ddc1aed1/virtualenvs/d41d8cd9/lib/python3.7/site-packages/django/test/testcases.py", line 1389, in _create_server return ThreadedWSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False) File "/var/lib/jenkins/shiningpanda/jobs/ddc1aed1/virtualenvs/d41d8cd9/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 67, in … -
Automatically update database field to True with django background tasks
I have a Model Job that has a field filled. I want to automatically update filled to True if the current date and time is greater than or equal to the Job's end date and time. The end date is set when creating the job. I am using Django background task to check all Jobs in the DB and repeat the process always, but I can't get it to work. Here is my code Model.py class Job(models.Model): # title, description, requirements, job type etc. end_date = models.DateTimeField() current_date = models.DateTimeField(null=True, blank=True) filled = models.BooleanField(default=False) created_at = models.DateTimeField(default=timezone.now) def __str__(self): return self.title task.py @background(schedule=60) def auto_mark_as_filled(job_id): jobs = Job.objects.filter(pk=job_id, filled=False) for job in jobs: job.current_date = timezone.localtime(timezone.now()) if job.current_date >= job.end_date: job.filled = True job.save() I am calling the task from my forms.py. when I create a new job I register it. forms.py class CreateJobForm(forms.ModelForm): def __init__(self, *args, **kwargs): # first call parent's constructor super(CreateJobForm, self).__init__(*args, **kwargs) # there's a `fields` property now self.fields['end_date'].required = True class Meta: model = Job fields = ('title', 'location', 'description', 'requirement', 'years_of_experience', 'job_type', 'end_date') exclude = ('user', 'created_at', 'current_date', 'filled') widgets = { 'end_date': DateTimePickerInput(format='%Y-%m-%d %H:%M') } def save(self, commit=True): job = super(CreateJobForm, self).save(commit=False) job.save() … -
How to use an image generated in Javascript in a function inside my Django's view?
I'm making an application where my view renders a template with information, then inside my template with Javascript I create a canvas element, I have the data:URI in my Javascript code, but I want to save correctly that image in my MEDIA_ROOT (supposed in /media/report directory) on my server in a Django's way, as I do in another view with a form, but this is not a form! Is a success page where render the template with information and in the same view I have a function that I need that image, maybe my problem can be a little tricky but I will put a screenshot and my view to show what I want to do. I don't know if I'm thinking correctly. I really don't need to save that image, just need to use in the function do_something_with_image() def success(request, report_id): data1 = data2 = '' try: report = Report.objects.get(id=report_id) data1= report.data1 data2= report.data2 #picture_path is /media/report/report_id.png or the file generated in Javascript do_something_with_image(picture_path) except: messages.error(request, "Error") context={ 'report_id': report_id, 'data1': data1, 'data2': data2, } return render(request, 'exito.html', context) Maybe I need to do a POST request? Here is my template code with the javascript code: <div id="report"> {{data1}} … -
who to write url in django
form in navbar I have one form in navbar template and I want to fetch the data of this form from any page of my site how should I write my URL. views.py url.py -
How to assign a value to AArrayField?
In my models: class User(models.Model): ... transactions = ArrayField(models.CharField(max_length=100), default=list()) my views: @api_view(['GET', 'POST', 'DELETE']) def user(request): if request.method == 'POST': user_data = JSONParser().parse(request) user_serializer = UserSerializer(data=user_data) if user_serializer.is_valid(): user_serializer.save() return JsonResponse(user_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST) When try to test the api with postman with this input, the transaction stays empty. { ... "transactions": ["test"] } -
django rest framework serializer - doesn't return empty list field
I have a serializer for a model that contains JsonField. I want to always return specific fields, even when they are not found within the jsonField. When calling 'get' - it does return all fields in the serializer, but when calling 'update', it returns the instance with the updated fields and allow_null=True, so default=list field that wasn't update - would not return in the response. The question is how can I still return all serializer fields in response, including the default=list fields, even when they weren't updated and not exist? this is the serializer - class ObjectsListSerializer(serializers.Serializer): days = serializers.IntegerField(allow_null=True, source='objects_list.days') user_list = serializers.ListField(child=serializers.CharField(), default=list, allow_empty=True, required=False, source='objects_list.user_list') manager = serializers.CharField(allow_null=True, source='objects_list.manager') def update(instance, validated_data): if 'objects_list' in validated_data: for attr, value in validated_data['objects_list'].items(): instance.objects_list[attr] = value instance.save() return instance As mentioned, when sending 'get' request, even when 'objects_list' is empty, I would get days=None user_list=[] manager=None in the response But when user_list doesn't exist and I'm updating other field ('days' for example), 'user_list' will not exist in the response. Any idea how can I still return the empty list when it doesn't exist?