Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to correctly send a date input from form to backend
I am trying to update date values in a database. The format they're currently stored in is yyyy-MM-dd. I am picking the date using ng-bootstrap datepicker, and sending it to backend in a PUT request using ngModel. I can see in the network tab that when I choose a new date it tries to send it as Date Sat Aug 03 2019 12:00:00 GMT+0100 (British Summer Time). If I don't change it is sends as End_Date: "2019-08-13". I have tried having it as different types on the model, tried to use [(ngModel)]="project.Start_Date | date:'yyy-MM-dd'". I have also tried to change the type on the Django model I am sending it to as well. HTML: <input type="text" class="form-control" placeholder="{{project.Start_Date}}" name="Start_Date" [(ngModel)]="project.Start_Date" ngbDatepicker #d="ngbDatepicker"> <div class="input-group-append"> <button class="btn btn-outline-secondary" (click)="d.toggle()" type="button"> <span class="oi oi-calendar"></span> </button> </div> Model: export class Project { Start_Date: Date; End_Date: Date; } I want the PUT reques to send it as yyyy-MM-dd so that it can update what it currently stored. But it sends it as the full extended type. -
Allowing only superuser to call template column - Django
I have developed a template column using Django tables but i want that only super users should be able to view that column. MyTables.py class DeviceTable(tables.Table): def view(request): if request.user.is_superuser: edit = tables.TemplateColumn(template_code) class Meta: attrs = {"class": "table table-striped table-hover"} model = Devices fields = ( "name", "location", "phone_number", "ip_address", "created_date", ) The above code is not working. -
Celery can not find periodic tasks after importing libraries
I am trying to create periodic task with celery, which every day download some file from the web. But I run into a problem when I try to import libraries in file where I create the task. I get an error Received unregistered task of type 'download_data_nist.tasks.download_data'. If I delete the imports, the task is executed without errors. I have configured Celery in settings.py: from celery.schedules import crontab CELERY_BROKER_URL = 'amqp://localhost' CELERY_TIMEZONE = 'CET' CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'download_data_nist.tasks.download_data', 'schedule': crontab(minute='*/1'), }, } I have created celery.py in root folder of my app: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AplikacijaZaPregledRanljivosti.settings') app = Celery('AplikacijaZaPregledRanljivosti') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) I add this code to init.py in root folder: from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django … -
Permission denied: '/root/.invoke.yaml' when trying to open a connection with Fabric
Here is my problem : I integrated Fabric for ssh connection, but when I try to open a connection (the connection use ssh key, passed in connection_kwargs), I get a Permission denied: '/root/.invoke.yaml' Here is my code : with ssh_connection(host=settings.JMETER_HOST_IP, user='admin') as conn: # we create a folder for the test conn.run('mkdir ' + remote_scenario_folder, hide=True) print("Uploding : " + jmx_file_path) extract of ssh_connection : ssh_connection(host, user, key_filename=settings.SSH_KEY_FILENAME, connect_timeout=settings.SSH_CONNECT_TIMEOUT, use_bastion=settings.SSH_USE_BASTION, bastion_username=settings.SSH_BASTION_USERNAME): connect_kwargs = {'key_filename': key_filename} try: connection = Connection(host, user=user, connect_timeout=connect_timeout, connect_kwargs=connect_kwargs) And the trace of error : Internal Server Error: /automatic_test/launch_test/ web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py", line 35, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 128, in _get_response web_1 | response = self.process_exception_by_middleware(e, request) web_1 | File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py", line 126, in _get_response web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) web_1 | File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view web_1 | return view_func(request, *args, **kwargs) web_1 | File "/data/web/automatic_test/views.py", line 23, in launch_test web_1 | run_test(c,s,request.user) web_1 | File "/data/web/automatic_test/views.py", line 52, in run_test web_1 | with ssh_connection(host=settings.JMETER_HOST_IP, user='admin') as conn: web_1 | File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__ web_1 | return next(self.gen) web_1 | File "/data/web/ssh/connection.py", line 46, in … -
How to retrieve data from Elasticsearch query to be used for D3.js histogram?
I want to create a d3 histogram that shows the number of loads per day using the data from my elasticsearch query with the following agggregations: { "size": 0, "aggs": { "group_by_date": { "date_histogram": { "format": "yyyy-MM-dd", "interval" : "day", "field": "date_visited" } } } } Here is a snippet of the result: "aggregations": { "group_by_date": { "buckets": [ { "key_as_string": "2019-07-31", "key": 1564531200000, "doc_count": 8 }, { "key_as_string": "2019-08-01", "key": 1564617600000, "doc_count": 15 }, How exactly do I fetch the data? I have read and tried this but it seems to be outdated and doesn't work. It gives me the "no living connections" error. Most of the answers that I've found were also outdated and doesn't seem to be an elegant solution for me. I was wondering if there was a simpler way of fetching data from elasticsearch, like fetching data from an API. -
why image is not showing in a HTML page in Django framework?
I need to show images in html page but those are not showing. <label for="song{{forloop.counter}}"> {{song.song_title}} {% if song.is_favourite %} <img src="C:\Python Projects\Test_App\website\music\Image\fav.png" /> {% endif %} </label><br> -
Why template recognises object as unexpected identifier?
I am trying to populate multiple markers on google maps, using django. From Django views.py I am passing listing name and coordinates to the template, I receive coordinates and can use it as variable in JavaScript. But for some reason, listing name gets error saying "Uncaught SyntaxError: Unexpected number". I can't figure it out. tried to send it as a string, but still got the same. Template code: var single_listing_coordinates = []; // Function retrieves listing names and coordinates from View Class and stores them inside the single_listing_coordinates list, // inserts list into hotels array and clears the single_listing_coordinates array, so it is empty for next hotel to be stored. {% for coordinate in coordinates %} var a = {{coordinate.listing_lat}}; single_listing_coordinates.push(a); var b = {{coordinate.listing_lng}}; single_listing_coordinates.push(b); var c = {{ coordinate.listing_name }}; single_listing_coordinates.push(c); //Lists of coordinates gets pushed to listings array. listings.push(single_listing_coordinates); single_listing_coordinates = []; {% endfor %} views.py code : class ShowMapView(TemplateView): template_name = 'listing_data/show_maps.html' def test_func(self, user): return (not user.is_anonymous) and ( user.is_superuser or is_user_host(user) or is_user_cohost(user) or is_user_housekeeper(user)) def get_context_data(self, **kwargs): listings_id_parameter = self.request.GET['listings_id'] listing_ids_list = listings_id_parameter.split(",") context = {} listing_ids_list = [int(x) for x in listing_ids_list] all_locations = ABListingData.objects.filter(listing__pk__in=listing_ids_list) coordinates_list = [] for location in all_locations: … -
Django Tempus Dominus Datetimepicker time and date conversion
I've been trying for hours to change the format of my datetimepicker (Tempus DOminus for bootstrap 4) but the format won't change so now I'm trying to find a better way to convert it on the backend when it inserts to my Django model or database. The issue is, the datetimepicker currently puts the user selected date into the input as 10/02/2018 2:15 PM The problem is, I need to insert it into the database like so: 2018-10-02 02:15:00 Is there a better way that I can just auto convert that to fit the djano model timestamp format I need? I'm thinking there would have to be a way for me to look at the AM/PM from the datetimepicker and make it either 02:00:00 or 14:00:00 accordingly. in my model.py from django.db import models class CountryDirectorRequestTable(models.Model): countryDirectorRequestTo = models.CharField(max_length=50,choices=REQUEST_TO, default='accountant',verbose_name="Request To") countryDirectorRequestDetail = models.TextField(max_length=3000,null=False,blank=False, verbose_name="Request Detail",help_text="Content not more than 3000 letters") countryDirectorRequestExpectingDateAndTime = models.DateTimeField(default=timezone.now, verbose_name="Expecting Date and Time") in my form.py from django import forms from Home.models import CountryDirectorRequestTable from tempus_dominus.widgets import DateTimePicker class CountryDirectorRequestForm(forms.ModelForm): countryDirectorRequestExpectingDateAndTime = forms.DateTimeField(widget=DateTimePicker( options={ 'useCurrent': True, 'collapse': False, 'minDate': '2009-01-20', 'maxDate': '2017-01-20', # Calendar and time widget formatting 'time': 'fa fa-clock-o', 'date': 'fa fa-calendar', 'up': … -
Migrating Birthdays from old system to new django db with postgres
I have an old system that sadly accepts birthdate like 0000-01-01. I am migrating that personal data to a new system that is written in Python (Django) and uses the DateTime Model field on the PostgresDB. The old DB saves the birthday as '%Y-%m-%d'. While running the code, i now get the following error: File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime tt, fraction, gmtoff_fraction = _strptime(data_string, format) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 544, in _strptime datetime_date(year, 1, 1).toordinal() + 1 After some googling, i found it this is intended behvior. since Python 3, the minimum datetime value is: 0001-01-01 00:00:00 and the maxium datetime value is: 9999-12-31 23:59:59.999999 My current approach at fixing this is the following is this: When a birthday is between 0001-1-1 and timezone.now(), so not in the future, then accept it, if not, set it to None (yes, the field is nullable) in code, i tried it like this: birthday = item.get("birthday") # Comes from the old system, this gets sent as '0001-01-01', so a string min_datetime = datetime.date.min (the minimum python 3 accepts) current_day = datetime.date.today() (cant be a birthday in the future) if birthday and not isinstance(birthday, datetime.date): birthday = datetime.datetime.strptime(birthday, '%Y-%m-%d') if not birthday or birthday … -
TypeError: 'module' object is not callable after filtering datetime
I want to write a django-orm to filter datetime field and some other fields. then convert it to pandas dataframe. this code works correctly : order_order_df = pd.DataFrame(list(Order.objects.filter(canceled=False, order_time__isnull=False).values())) but this code is not working: order_order_df = pd.DataFrame(list(Order.objects.filter(canceled=False, order_time__isnull=False, order_time__gte=datetime(2018, 10, 1)).values())) why did this happen? how can I filter datetime and convert it to pandas correctly? NOTE: I know it can be filtered properly after converting to pandas but I need it to be done by queryset here. -
django-rest ModelSerializer select fields to display in nested relationship
I'm going to reference the django-rest-framework API example on this. Lets say we have two serializers defined as below. class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Now if i do a GET request and retrieve an Album instance, it will return me a response with a list of Track instances inside it where each instance contains all the fields of Track. Is there a way to return only a selected subset of the fields in the Track model? For example to only return the title and duration field to the client but not the 'order' field. -
How to Access and Control a Document Scanner[ADF Front and Back] like Kodak or Hp from Python and Django
I already tried Pyinsane2 to access the scanner. It communicate with Kodak scanner but it Scan only first page as clear and remaining pages are fully blur. and also pyinsane2 is no more maintainable. and also i don't know how to use Libinsane which is successor of Pyinsane2. I need a help to control and scan from Python Django. def scan_process(request): pyinsane2.init() try: devices = pyinsane2.get_devices() assert (len(devices) > 0) device = devices[0] print("I'm going to use the following scanner: %s" % (str(device))) try: pyinsane2.set_scanner_opt(device, "source", "ADF Front") # pyinsane2.set_scanner_opt(device, 'duplex', ['both']) except PyinsaneException: print("No document feeder found") pyinsane2.set_scanner_opt(device, 'mode', ['Color']) pyinsane2.maximize_scan_area(device) source = 'Auto' if (device.options['source'].constraint_type == pyinsane.SaneConstraintType.STRING_LIST): if 'Auto' in device.options['source'].constraint: source = 'Auto' elif 'FlatBed' in device.options['source'].constraint: source = 'FlatBed' else: print("Warning: Unknown constraint type on the source: %d"% device.options['source'].constraint_type) res = 200 colour = 'Color' # set_scanner_opt(device, 'resolution', res) # set_scanner_opt(device, 'source', source) # set_scanner_opt(device, 'mode', colour) set_scanner_opt(device,'quality','maximum') # set_scanner_opt(device,'duplex','both') # pyinsane2.maximize_scan_area(device) scan_session = device.scan(multiple=True) try: while True: try: scan_session.scan.read() except EOFError: print("Got a page ! (current number of pages read: %d)" % (len(scan_session.images))) except StopIteration: print("Document feeder is now empty. Got %d pages" % len(scan_session.images)) for idx in range(0, len(scan_session.images)): image = scan_session.images[idx] file_name = … -
how to check the string contain AND and OR query params django admin search
Hi I need to make our the query from the query string for filter data from the given model, the Query will be http://127.0.0.1:3007/admin/test/testfilter/?q=user:cadmus@test.com AND age:15, Need to get result in following format from django.models import Q models.objects.filter(Q(user=cadmus@test.com) & Q(age=15)) -
Is it possible to Filter and Sort at the same time with in a single template using Class Based Generic ListView? If yes, how?
I have a template which shows the list of all the products in a template using ListView. I have this link for the sorting using different parameters on my model Product. Below is a snippet from my Template. <th> <span> Product &nbsp; </span> <a class="fa fa-sort-up fa-lg" href="{% url 'admin:product_list' %}?sort_by=name"></a> </th> {% for product in products %} <td><a href="{% url 'admin:product_update' pk=product.pk %}">{{ product.name }}</a></td> and the url that refers to a ListView called "ProductListView" is - path('products/list/', views.ProductListView.as_view(), name='product_list'), and ProductListView is as folllows - class ProductListView(UserPassesTestMixin, ListView): model = Product template_name = 'admin_app/product_list.html' context_object_name = 'products' def get_ordering(self): ordering = self.request.GET.get('sort_by') return ordering def test_func(self): return self.request.user.is_superuser I have a search box like this <form method="get" class="form-inline"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search Products..."> <span class="input-group-btn"> <button type="submit" name="search" id="search-btn" class="btn btn-flat"> <i class="fa fa-search"></i> </button> </span> </div> </form> I just want to know the path of how can I use the Search box to show me queries. I can redirect all the queries to a different page but is it possible to implement the queries on the same page? and then apply sorting on these queries. For example if I search example_product, then I want … -
What's the difference between fields outside and Inside the Meta() class?
I'm making a django Blog website. When I defined my user registration form and I'm inheriting from UserCreationForm I give two email fields one inside my Meta() class and one outside it. I read django documentaion but couldn't understand clearly. class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username','email','password1','password2') So why am I giving email field twice in my UserRegistrationForm. Can someone explain it in simple words. -
How to uplaod a file in blob storage using django
I just want to upload some file in blob storage using the Django framework. I have followed this link also Django storage -
My django tag doesn't apply and is displayed on the site
I have a problem, I would like to apply a {% if user.is_authenticated %} tag on my template to hide a button. But when I add the tag, it display the if statement on the page. <div class="col-xs-2"> {% if user.is_authenticated %} <h4> <button class="btn btn-default btn-xs pull-right" ng-if="cart" ng-click="cart.toggleItem(item)" data-toggle="tooltip" data-placement="bottom" title="Select"><i ng-class="cart.getFaClass(item.id)" class="fa fa-lg"></i></button> </h4> {% endif %} </div> -
Django / Python: Generate random timezone respecting datetime within the next 24h
I need to generate a random datetime within the next 24 hours (so any hour, minute, and second but within 24h of when the method is run). This will go in a django model.DateTimeField(). I know that I can get the current timezone-aware datetime with from datetime import timezone timezone.now() but it's not quite clear to me how to pick a random time 24h into the future from timezone.now(). -
Where to specify "use_natural_primary_keys" with generic class views?
I've been reading about natural_keys and have added the get_by_natural_key() and natural_key() methods to my model(s), but the Django docs (and several posts here in SO) say: "Then, when you call serializers.serialize(), you provide use_natural_foreign_keys=True or use_natural_primary_keys=True arguments" ...followed by this example: >>> serializers.serialize('json', [book1, book2], indent=2, ... use_natural_foreign_keys=True, use_natural_primary_keys=True) But that example is from running in a python shell, not in the actual context of where to put it in code. From DRF, I'm using generic class based views. Where should I specify those arguments in that case? -
Gitlab CI setup: reset database
I setup Gitlab Cloud CI and everything worked fine, but I have reset the database on my local machine and so cleaned up all migration files(Django). Now on python manage.py migrate step I get the issue about incorrect migration dependencies. On my local machine, everything works fine and so I just need to reset the database on Gitlab Cloud. Does anybody know how to do it? Here is my config file(.gitlab-ci.yml): image: python:3.6 services: - name: postgres:latest stages: - test variables: POSTGRES_DB: python-test-app cache: paths: - ~/.cache/pip/k test job: stage: test script: # use attached postgres database that is run on `postgres` host - export DATABASE_URL=postgres://postgres@postgres:5432/$POSTGRES_DB - apt-get update -qy - make clean - make requirements-dev - make migrate - make lint - make test only: - merge_requests - master - tags -
Can I use this pattern on the visual studio for Angular?
I am trying to do the previous and next record just like way back Visual Studio's Automated TableDataAdapter with Recordset embedded. I got the picture somewhere in the internet. But what I'm trying to do is the [|< < 1 of 3 > >| Delete Save] and then I manipulate the fields on record next fill the next record on the fields. Can I achieve this using any PlainPHP with pagination or what? can I also achieve this using Angular or React? -
When I added default in foreign-key, "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet." occurred
I am developing Django&Wagtail blog app. Unfortunatly, "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet." is occurred. If there is no default, app works propely. However, if I added default, it does not work... I researched some article but they could not help me. class hoge(models.Model): """ ... """ page = models.ForeignKey( "blog.BlogIndexPage", on_delete=models.CASCADE, verbose_name=_("blog"), default=BlogIndexPage.objects.latest("id"), # add here ) Environment: Mac(Mojave 10.14.6) Virtualenv python 3.7 Django 2.2.4 wagtail 2.6.1 Error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
what is meaning of this error below and how to connect Django to SQL Server
I have a django project that must use Sql Server database in order to stored and retrieve data. I changed the engine in the settings.py and perform the migration. the database was successfully migrate into the sql server. The problem is when I tried to create a model in django and try to insert data to the model it seams that as there is no connection between the model and the sql server. I tried to open django shell and try to connect to sql server using this command : import pyodbc connection = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};' 'Server=localhost;' 'Database=testDB;') it display the below error : Traceback (most recent call last): File "", line 1, in pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [2]. (2) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books … -
map(lambda,list) return None instead object
I want add attribute to all object (that are model instance in django) in a list. for example the list is: persons = [ {"age":"12","name":"John"}, {"age":"10","name":"Joye"} ] and we assume that i want put value of person.age in person.numberand i have a new list that all of person have new attribute number so my function is : new_persons_list=list(map(lambda person:setattr(person, 'number', person.age), persons)) but the output is [None,None] while i expect that output be: persons = [ {"age":12,"name":"John","number":12}, {"age":10,"name":"Joye","number":10} ] if possible i don't like to add new function in map and i want use lambda.what is the problem?thank you -
how to set value for column from another column when insert from django admin form
I have book stock form and it has two columns to indicate the the stock value: current stock, and the stock, current stock and stock should be the same when inserting the first time, but, when borrow a book the current stock should be decreased, and the stock column will be at the first value: for instance: book1 has stock 5 and current stock 5, someone borrowed the book1, so book1 stock 5 and current stock 4, I don't want to do it from database triggers because my application is database independent. please help me how can I do it from django admin form? models.py: class BooksCopy(models.Model): book = models.ForeignKey(Book, on_delete=models.PROTECT) branch = models.ForeignKey(Branch, on_delete=models.PROTECT) no_of_copies = models.IntegerField('Stock') current_no_of_copies = models.IntegerField('Current Stock') admin.py: class BooksCopiesAdmin(admin.ModelAdmin): models.BooksCopy.current_no_of_copies = models.BooksCopy.no_of_copies exclude = ('current_no_of_copies',) list_display = ('branch', 'book', 'no_of_copies', 'current_no_of_copies',)