Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to load the uploaded image in the
In my database, the Banner table's url field value is like this:uploads/images/banner.jpg. So, in my template: {% for ban in data.banner %} <li><img src="{{ ban.img }}" alt="" ></li> {% endfor %} The result in browser is like below: <img src="uploads/images/banner.jpg" alt="" draggable="false"> So, it did not load the image under my project. How can I load the relative path images ? -
Running Native python scripts (with arguments) using Django & controlling the underlying system using Django
I need some help with python, django & an Windows Azure VM. I have some python scripts on a Windows Server 2012 R2 VM hosted on azure that are supposed to run daily at 5am (I currently run them manually via RDP). These scripts query a web API, then receive JSON which they parse and insert into various MYSQL tables. I would like to configure the Windows VM to run these python scripts daily at 5am (like a unix cron job) with arguments sourced from one of the MYSQL tables. These said arguments are used in querying the web API. How do I automate the scripts such that I must not log into the VM via RDP to run them? Also, I'd like to access the underlying database via django and use the same django web app to run the said repetitive scripts on demand (plus supply the arguments through the Django web app), monitor the progress of the native python scripts and log errors, as well as control the system in entirety, edit the data on the database, etc. The Django web app will be hosted on the VM's local server. I'd like to be able to access this … -
Creating an Oauth2 application when an instance of another model is created
I'm new with Django and oauth2 provider, I have a model Store , I want to create an Oauth2 application automatically when I create an instance of a store , is that possible ? Thank you -
SelectMultiple fails to display saved choices for a MultipleChoiceField with dynamic choices
I'm doing an admin form with a SelectMultiple with dynamically populated choices in Django 1.10 This is the model: class HelpRequest(models.Model): name = models.CharField(max_length=32) groups = models.TextField(blank=True) This is my form: class AdminHelpRequestForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['groups'] = forms.MultipleChoiceField(choices=groups_from_ldap, widget=SelectMultiple(attrs={'class': 'chosen'})) class Meta: model = HelpRequest fields = ('name', 'groups') The form gets used in Admin: @admin.register(HelpRequest) class HelpRequestAdmin(admin.ModelAdmin): form = AdminHelpRequestForm The SelectMultiple saves the choices fine into the model >>> ar = HelpRequest.objects.get(pk=1) >>> print(ar.groups) ['mygroup', 'othergroup', 'yetanothergroup'] But will not display the saved choices from the model instance in the widget. What's wrong here? -
git link to a submodule file import problems
I added a file to my project which is a symlink to a file in another git project. I followed the steps in this answer https://stackoverflow.com/a/27770463/3573182 to add the other project as a submodule in my project. Now the link I added to the file has some broken imports. Let's say my project A's structure is like this (including the structure of the submodule from project B): Project A: - package1: -- link.py - submodule-of-project-B -- package1: --- linked_file.py -- package2 -- package3 Now the 'linked_file.py' has some imports from 'package2' which is a package inside project B. But because project A doesn't have that package so the imports inside the link are broken and I cannot run project A. I know I can change the imports from import package2 to import submodule.package2. But because this is a link, I think this will change the import line in the original file in project B which will make it broken there. I used a link because in the future I need any update in the original file from its developers to be immediately reflected in my project. -
Django view objects filter with timezone.now().date or timezone.now().time-> expected string or bytes-like object
Hi i have some Django 11 project, my model look like class Event(models.Model): name = models.CharField(max_length=100, unique=True) title = models.CharField(max_length=100) info = models.CharField(max_length=100) image = models.ImageField(upload_to='events/%Y/%m/%d') start_date = models.DateField(default=timezone.now) start_time = models.TimeField(default=timezone.now) stop_date = models.DateField(default=timezone.now) stop_time = models.TimeField(default=timezone.now) place = models.ForeignKey('places.Place', on_delete=models.CASCADE) company = models.ForeignKey('companies.Company', on_delete=models.CASCADE) and my view look like def place_website(request, place_id): place_template = get_template('room.html') place_obj = Place.objects.filter(id=place_id) # filter for event obejts only for requested place, filtered for now and next events place_event_now = Event.objects.filter(place=place_id, start_date=timezone.now().date, stop_date__gte=timezone.now().date) place_events_next = Event.objects.filter(place=place_id, start_date=timezone.now(), stop_date__gte=timezone.now()).order_by('start_time') place_context = { 'place_obj': place_obj, 'place_event_now': place_event_now, 'place_events_next': place_events_next, } return HttpResponse(place_template.render(place_context)) the thing i want to manage is to pass to template the list of filtered Event objects based on time. Lets pick this line place_event_now = Event.objects.filter(place=place_id, start_date=timezone.now().date, stop_date__gte=timezone.now().date) it couse error "expected string or bytes-like object" but when i remove ".date" from "timezone.now()" error disappear (then filter do nothing) but i want to compare date to date and time to time. How to do this properly ? This approach to filter objects in view rather than in template is proper? -
Relational Object doesn't exist error in django python
I am a fresher in python-django. I am trying to save a model from admin.py. I have 3 tables auth_user (generates user id as id) general_userprofile (One-To-One relationship with auth_user and user_id is a foreignkey) account_emailaddress (One-To-One relationship with auth_user and user_id is a foreignkey) Contents of admin.py from django.contrib import admin from django.contrib.auth import admin as upstream from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import Group, User from django.utils.translation import ugettext, ugettext_lazy as _ from .models import EmailAddress,UserProfile class CustomUserAdmin(UserAdmin): list_display = ('email', 'first_name', 'last_name', 'is_staff') list_select_related = ( 'profile', ) #exclude = ('username',) fieldsets = ( ('Personal information', {'fields': ('first_name', 'last_name', 'username', 'email', 'password')}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( ('None', { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2')} ), ) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) def get_ordering(self, request): return ['-date_joined'] def save_model(self, request, obj, form, change): obj.address.save() obj.save admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) From models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from django.db.models.signals import post_save from django.dispatch import receiver from ciasroot.util import HashedPk from phonenumber_field.modelfields … -
Localized string collator in Django
Is there any simple way how to get a string collator for the current set language in Django (1.11)? I need to use it to sort accented strings. In theory this should be working: import locale from django.utils.translation import to_locale, get_language locale.setlocale(locale.LC_ALL, to_locale(get_language())) sorted(..., cmp=locale.strcoll) But it doesn't. to_locale does not return the correct formatted locale, e.g. for Czech language it returns cs, whereas the system locale is called cs_CZ. Moreover it looks kinda unpythonic and undjangoish to me. Considering how easy it is to do internationalization in Django, I would suspect there should be something like from django.utils.translation import get_strcoll, but apparently it is not. Can you help me out? Thank you. -
django custom 404 not found page
I want to create custom not found page. But, I can see only default django not found template. What I'm doing wrong ? notFound.html {% extends "account/base.html" %} {% load crispy_forms_tags %} {% load i18n %} {% load account socialaccount %} {% block head_title %}{% trans "Page not found" %}{% endblock %} {% block content %} <div class="col-md-4 col-md-offset-4"> <div class="jumbotron" style="margin-top:50px;opacity:0.90"> <h1 class="text-center" style="color:#A12830">4+800:2</h1> <h3 class="text-center">Web page not found</h3> <div style="text-align: center"> <a href="{% url 'home' %}">Main menu</a> </div> </div> {% endblock %} urls.py from django.conf.urls import (handler400, handler403, handler404, handler500) -
How to call an element which I need in django massive?
I have such code {% for x in list %} <div class="col-md-4"> <h3>{{ x.title }}</h3> <span>{{ x.category }}</span> </div> {% endfor %} I need a certain element from this massive in different divs. For example {% for x in list %} <div class="col-md-4"> <h3>{{ 3.title }}</h3> <span>{{ 1.category }}</span> </div> <div class="col-md-6"> <h3>{{ 4.title }}</h3> <span>{{ 3.category }}</span> </div> {% endfor %} I need such grid in one loop How can I do it? http://blog.eney.solutions/wp-content/uploads/sites/3/2014/12/737781.png1 -
How to retrieve the field which triggerd a hit for a elasticsearch query
Running a wagtail site (1.11) with elasticsearch (5.5) as search backend and indexing multiple fields, e.g.: search_fields = Page.search_fields + [ index.SearchField('body'), index.SearchField('get_post_type_display'), index.SearchField('document_excerpt', boost=2), index.SearchField('get_dark_data_full_text'), ] I would like to indicate in which field the search lands a 'hit' in my search results template (or even better display a snippet of the hit, but that seems to be another question). This question seem to address my issue, but I don't know how to integrate this in my wagtail site. Any tips how to get this information and how to integrate this in wagtail search? -
How to rewrite FBV to CBV in Django?
Can someone help me to rewrite this function based view to class based view. I'm a little confused. views.py: def book_delete(request, pk): book = get_object_or_404(Book, pk=pk) data = dict() if request.method == 'POST': book.delete() data['form_is_valid'] = True books = Book.objects.all() data['html_book_list'] = render_to_string('book_list.html', { 'books': books }) else: context = {'book': book} data['html_form'] = render_to_string('book_delete.html', context, request=request, ) return JsonResponse(data) -
Django url from a huge list of words from a file
I have a file with 60,000 words, I need the url to be valid only when it contains any of the words in that file url(r'^site/KEYWORD/$', 'mysite.views.home') so basically I need KEYWORD to be one of the words present in that file. I know that we can use the pipe for multiple words but the list too large to do that -
Django - pdf response has wrong encoding - xhtml2pdf
I'm working on an invoice PDF generator on my Django website. I use xhtml2pdf. It seems to be working but encodings is not correct. There are wrong signs/characters when I use diacritics. This is a view: def render_to_pdf(template_src, context_dict): template = get_template("pdf/pdf.html") context = context_dict html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode('utf-8'), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf; encoding="utf-8"') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) And this is the html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>title</title> </head> <body> <p>Č š ž Ž x y ľ ĺ ó</p> </body> </html> This is the generated pdf: Do you know how to make it work correctly? -
Create a query to database from the data in form
My code #model.py class Personal(models.Model): name = models.CharField(db_column='FIO', max_length=255, blank=True, null=True) history_contract = models.CharField(max_length=255, blank=True, null=True) category = models.CharField(max_length=255, blank=True, null=True) #form.py class NameForm(forms.Form): name = forms.CharField(label='Name', max_length=100) history_contract = forms.CharField(label='History', max_length=100) category = forms.CharField(label='Category', max_length=100) #view def get_personal(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): name = form.cleaned_data['name']#data from form history = form.cleaned_data['history_contract']#data from form category = form.cleaned_data['category']#//data from form query = Sotrudniki.objects.filter(fio__contain=name, history_contract__contain=history, category__contain=category)#The part I want to accomplish else: form = NameForm() return render(request, 'personal.html', {'form': form, 'query': query}) I need to check the data that I entered into the form. After making a request to the database and returning only the data that I indicated in the form. I got an error at the end "local variable 'query' referenced before assignment", maybe I have a wrong approach to the task. How can I implement the idea? -
Why mock model method failed when run full suite
I have to change .clean() which has deep logic behind the scene. Since it is not directly related to my feature I decided to mock it out and cut the complicate logic. Then I can use mommy.make to fulfill the testing objects. Here is my code. https://gist.github.com/elcolie/cfeadfbb29996823abfb998447cfe822 If I run them individually it works. But fail when run full suite. I had follow these: why would a django test fail only when the full test suite is run? Django unit tests failing when run with other test cases But does not work. My errors: 2 last test cases fail Failure Traceback (most recent call last): File "/Users/el/.pyenv/versions/3.6.0/lib/python3.6/unittest/mock.py", line 1179, in patched return func(*args, **keywargs) File "/Users/el/Code/eneos-pos-web/eneos/apps/mail_logs/mail_data_tests.py", line 194, in test_user_change_status_13July_query_all_false self.assertDictEqual(expected_obj, summary) AssertionError: {'tod[71 chars] 0, 'today_active_email_true': 0, 'today_active_email_none': 1} != {'tod[71 chars] 0, 'today_active_email_true': 0, 'today_active_email_none': 0} {'today_active_email': 1, 'today_active_email_false': 0, - 'today_active_email_none': 1, ? ^ + 'today_active_email_none': 0, ? ^ 'today_active_email_true': 0, 'today_all_orders': 1} Failure Traceback (most recent call last): File "/Users/el/.pyenv/versions/3.6.0/lib/python3.6/unittest/mock.py", line 1179, in patched return func(*args, **keywargs) File "/Users/el/Code/eneos-pos-web/eneos/apps/mail_logs/mail_data_tests.py", line 231, in test_user_change_status_16July self.assertDictEqual(expected_obj, summary) AssertionError: {'today_active_email': 1, 'today_active_email_fals[84 chars]': 1} != {'today_all_orders': 1, 'today_active_email': 1, '[84 chars]': 0} {'today_active_email': 1, 'today_active_email_false': 0, - 'today_active_email_none': 1, … -
Django runserver UnicodeDecodeError
I am trying use create Django Server in Windows and when type command "python manage.py runserver" it pop out these error message C:\Users\USER\Desktop\VENV\Scripts\testproject>python manage.py runserver Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\core\management\commands\runserver.py", line 62, in execute super(Command, self).execute(*args, **options) File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\core\management\commands\runserver.py", line 101, in handle self.run(**options) File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\core\management\commands\runserver.py", line 110, in run autoreload.main(self.inner_run, None, options) File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\utils\autoreload.py", line 341, in main reloader(wrapped_main_func, args, kwargs) File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\utils\autoreload.py", line 312, in python_reloader exit_code = restart_with_reloader() File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\utils\autoreload.py", line 294, in restart_with_reloader str_value = force_bytes(new_environ[key], encoding=encoding) File "C:\Users\USER\Desktop\VENV\lib\site-packages\django\utils\encoding.py", line 124, in force_bytes return s.decode('utf-8', errors).encode(encoding, errors) File "C:\Users\USER\Desktop\VENV\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode byte 0xb6 in position 0: invalid start byte I don't what going on and how to slove this -
Can't install on Mac using pip or easy_install in terminal
I am very new to Mac. This is my first time to switch from Windows to Mac. In windows, I didn't have any problems using the commands below in a cmd: pip install django Now, when I tried to install it on my Mac using the same command in the terminal, I get this error13: Permission denied. Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/django' Thank you in advance! -
How to pre-populate field from ForeignKey on Django via decorator?
Suppose I have 3 classes on my model in Django 1.11 & Python3.5: Class 1: class Country(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name Class 2: class City(models.Model): country = models.ForeignKey(Country) name = models.CharField(max_length=255) latitude = models.DecimalField(max_digits=15, decimal_places=10) longitude = models.DecimalField(max_digits=15, decimal_places=10) def __str__(self): return self.name Class 3: class Profile(AbstractUser): username = models.ForeignKey(User, max_length=100, blank=False, unique=True) address = models.CharField(max_length=255, blank=False) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="city_set", max_length=100, blank=False, null=True) country = models.CharField(max_length=255, blank=False) birthplace = models.ForeignKey(City, on_delete=models.CASCADE, related_name="birthplace_set", max_length=100, blank=False, null=True) latitude = models.DecimalField(max_digits=15, decimal_places=10) longitude = models.DecimalField(max_digits=15, decimal_places=10) def __str__(self): return self.username @property def country(self): if not self.city: return False else: negara = City.objects.get(name=self) return negara.country @property def latitude(self): if not self.birthplace: return False else: lat = City.objects.get(latitude=self) return lat.latitude @property def longitude(self): if not self.birthplace: return False else: lnt = City.objects.get(longitude=self) return lnt.longitude My questions are: How to get and autofill/pre-populate country's attribute at Profile's class from city's attribute (which's a ForeignKey from City's class)? I've tried to get it by using @property decorator but I get None value only. Can I use same class (from City's class) for ForeignKey fields in one class (on Profile's class) together twice? In this case is city & birthplace attribute, and then … -
django - adding isnull=False filter on ManyToMany inflates the results count
I have the following queries: full_page_events = FeatureApiEvent.objects.filter(site=monitor.site, created_time__range=[start_date, end_date], feature=feature) full_page_count = full_page_events.count() full_page_success_count = full_page_events.filter(server_suggested_items_unordered__isnull=False).count() As you can see I take all FeatureApiEvent for specific site, feature and dates range, and count them. This works fine. Then I add to that queryset another filter and count it: full_page_events.filter(server_suggested_items_unordered__isnull=False).count() Now here's the weird part - the second filter, which is the first queryset + additional WHERE condition, return more results than the first counter. Even if I add distinct the results are the same. I looked at the SQL queries and they look like this: >>> a = (site=monitor.site, created_time__range=[start_date, end_date], feature=feature) >>> print a.query SELECT "features_analytics_featureapievent"."id", "features_analytics_featureapievent"."site_id", "features_analytics_featureapievent"."feature_id", "features_analytics_featureapievent"."category_id", "features_analytics_featureapievent"."user_id", "features_analytics_featureapievent"."from_page_id", "features_analytics_featureapievent"."created_time", "features_analytics_featureapievent"."server_start_timestamp", "features_analytics_featureapievent"."server_end_timestamp" FROM "features_analytics_featureapievent" WHERE ("features_analytics_featureapievent"."site_id" = 19881 AND "features_analytics_featureapievent"."created_time" BETWEEN 2017-08-08 07:41:28.715422 AND 2017-08-09 07:41:28.715422 AND "features_analytics_featureapievent"."feature_id" = 19) >>> b = a.filter(server_suggested_items_unordered__isnull=False) >>> print b.query SELECT "features_analytics_featureapievent"."id", "features_analytics_featureapievent"."site_id", "features_analytics_featureapievent"."feature_id", "features_analytics_featureapievent"."category_id", "features_analytics_featureapievent"."user_id", "features_analytics_featureapievent"."from_page_id", "features_analytics_featureapievent"."created_time", "features_analytics_featureapievent"."server_start_timestamp", "features_analytics_featureapievent"."server_end_timestamp" FROM "features_analytics_featureapievent" INNER JOIN "features_analytics__featureapieventitemsrelationship" ON ("features_analytics_featureapievent"."id" = "features_analytics__featureapieventitemsrelationship"."event_id") WHERE ("features_analytics_featureapievent"."site_id" = 19881 AND "features_analytics_featureapievent"."created_time" BETWEEN 2017-08-08 07:41:28.715422 AND 2017-08-09 07:41:28.715422 AND "features_analytics_featureapievent"."feature_id" = 19 AND "features_analytics__featureapieventitemsrelationship"."item_id" IS NOT NULL) The WHERE part seems to be OK, the second query contains all the first query conditions + AND "features_analytics__featureapieventitemsrelationship"."item_id" … -
Creating a simple chat bot framework (state machine) in Django
I need to create a bot framework inside of my django project. All that it needs to do now is ask a question from some user on a platform like workchat and then wait for an answer. Once it gets the answer it will go back to the previous state before asking another question. The solution that I have thought of as of yet is: Have a model 'Conversation' that stores the 'state' of every conversation that bot has going on with the users so that it knows what to reply to whom Have a class of bot which gets the incoming message and the associated conversation model object, calculates the state shift, stores the new conversation state back, and then replies. The class of bot needs a representation in terms of state, transitions, conditions and actions since this way it allows me to edit my bot without ever touching the code that makes it work since I can just change the states, transitions, conditions and actions. I referred to the dropbox's securitybot code but realised that in it the state-machine is calculated from normal dictionaries and loaded once for every user which is possible since the code is enclosed … -
django locale can't translate depend on accept-language
Here is my settings LANGUAGES = ( ('zh_CN', u'简体中文'), ('en-us', u'English'), ) LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # "django.middleware.cache.CacheMiddleware", "django.middleware.transaction.TransactionMiddleware", ) Here is some print ('django_language', '') ('COOKIES', '') ('ACCEPT_LANGUAGE', 'zh_CN') ('LANGUAGE_CODE', 'en-us') My django version is 1.5.4 If i set request.session['django_language'] = 'zh_CN', I will get translation next time. What's wrong with it? -
Django form -Fill in duration field when 2 DateField were selected
I have a form for employee to apply leaves, how can I make by selecting the start date and end date field in the form it will calculate the duration in days. How can I do the calculation in view.py? Any help is much appreciated Below is my code : model.py : class Leave(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='+') start_date = models.DateField() end_date = models.DateField() duration = models.FloatField() form.py : class LeavesDetailForm(forms.ModelForm): class Meta: model = Leave fields = ('employee','start_date', 'end_date', 'duration',) widgets = {'start_date': forms.DateInput(attrs={'type': 'date'}), 'end_date': forms.DateInput(attrs={'type': 'date'}), 'employee': forms.HiddenInput()} view.py : def my_leaves_view(request): form = LeavesDetailForm(request.POST or None) leaves_log = Leave.objects.all().filter(employee=request.user.profile.employee.id) for annual_field in leaves_log: annual_duration = annual_field.end_date - annual_field.start_date print(annual_duration) if form.is_valid(): inst = form.save(commit=False) inst.save() return HttpResponseRedirect('my_leaves_content.html') context = {'form': form} return render(request, 'hrm/my_leaves/my_leaves_content.html', context) -
Insert DOM element into React component
I am using django as backend and most of it as frontend as well, the exception is one form that is made in reactjs. To speed up loading of this form I would like to load it's data by grabing it from html instead of using request. Django would send the data and form on loading the page and another request would not be neccessary. I managed to grab the data, which is html, but I am running in to following error: Uncaught (in promise) Error: Objects are not valid as a React child (found: [object HTMLOptionElement]). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method For testing purposes I am grabing html from another form that looks like this: <select name="tz" border="solid 1px #F6892D" id="id_tz"> <option value="Africa/Abidjan">Africa/Abidjan</option> (...) <option value="" selected=""></option> </select> It happens after the component mounted: componentDidMount = () => { document.addEventListener("DOMContentLoaded", (event) => { var tz_options = document.getElementById('id_tz'); this.setState({tz:Array.from(tz_options)}); }); } I also tried to solve the error by adding toArray function and installing the createFragment addon, but it didn't help: function toArray(obj) { var array = []; … -
Can't get Data from json object
First of all I would like to say that I've tryied some of the Questions that may already have your answer and i couldn't answer it I have this script <script type="text/javascript"> function requestimg(username){ $.ajax({ url: '{% url "image" %}', data: { 'username': username }, dataType: 'json', success: function (data) { if (data) { //Printing the whole data console.log(data); //Printing to see where I am console.log("Name: "); //Trying to rint the name console.log(data[0].nombre); }else { alert("May Day"); } } }); } I have a problem reading the properties in the json object When i print the data I get this: {json: "[{"model": "polls.imagen", "pk": 17, "fields": {"n…"36", "imagen": "polls/static/pictures/dr.jpg"}}]"}json: "[{"model": "polls.imagen", "pk": 17, "fields": {"nombre": "55", "pub_date": "2017-08-08T05:52:38Z", "tecninca": "yyyy", "tamano": "yyyyyyyy", "precio": "yyyyy", "size": "36", "imagen": "polls/static/pictures/dr.jpg"}}]" And when i print the data as I have it on the code i get: Uncaught TypeError: Cannot read property 'nombre' of undefined I have tryied writing it like data.nombre but i just get undefined I have also tryied this console.log(data[0].fields); , data[0].model, data.model IMPORTANT I want to clarify that i wont know why there are 2 json objects im supposed to get just one and even if i try to put …