Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'datetime.date' object has no attribute 'days' error while using timedelta
Here I am writing property method to display the remaining leave days and total leave days.The total leave days are working fine but def leave_remaining_days(self) this is not working. I go this error 'datetime.date' object has no attribute 'days' Here the problem is while returning the no.of days return leave_remaining.days but when i return return leave_remaining just then it works. How can I calculate the remaining leave days here ? Only if leave.is_accepted True then i want to calculate remaining days. models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff') sub = models.CharField(max_length=300) msg = models.TextField() start_day = models.DateField() end_day = models.DateField() is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) @property def leave_days(self): diff = self.end_day - self.start_day return diff.days @property def leave_remaining_days(self): if self.is_accepted: leave_remaining = self.end_day - datetime.timedelta(days=1) return leave_remaining.days -
How to add a column in table from frontend in django
I want to add columns to my Django app from frontend. For this, I have created a separate table for table fields but I don't know how can I add a field so that it automatically becomes a column in Contact table. Thanks in advance. class Contact(models.Model): fname = models.CharField(max_length=200) lname = models.CharField(max_length=200) email = models.CharField(max_length=100) mobile = models.CharField(max_length=12) address = models.CharField(max_length=200,default=None) pincode = models.CharField(max_length=10) created_date = models.DateField(auto_now=True) class Field(models.Model): field_name = models.CharField(max_length=100) field_type = models.CharField(max_length=50) is_required = models.BooleanField() -
Invalid argument for include_parents
Invalid argument for include_parents getting error when I use inplace_edit in django 2.3 v {% inplace_edit "object.title" %} -
Django UpdateView and ModelForm for file upload is not working
issue Whenever I am trying to submit form without uploading a new file, I am getting error due to form clean method. How will one submit update form with same file. error - AttributeError: 'FieldFile' object has no attribute 'content_type' views.py class DocUpdate(UpdateView): model = Document form_class = CreateDocForm template_name = 'mydoc/doc_update.html' success_url = reverse_lazy('mydoc:doc_list') context_object_name = 'document' def get_form_kwargs(self): kwargs = super(DocUpdate, self).get_form_kwargs() kwargs['request'] = self.request return kwargs forms.py class CreateDocForm(forms.ModelForm): file = forms.FileField(label='Select a file', help_text='only img/jpg/jpeg, pdf, doc/docx, xls/xlsx files are ' 'allowed with max. 50 megabytes size.') def __init__(self, *args, **kwargs): self.extension = '' self.size = '' self.password = '' self.name = '' self.request = kwargs.pop("request") super(CreateDocForm, self).__init__(*args, **kwargs) class Meta: model = Document fields = ['file', 'description'] def clean(self): # validate mime type of file file = self.cleaned_data['file'] self.name, self.extension = os.path.splitext(file.name) if self.extension not in settings.VALID_FILE_EXTENSIONS: raise forms.ValidationError("Invalid file extension.") mime = file.content_type self.size = int(file.size) if mime not in settings.VALID_FILE_MIME_TYPES: raise forms.ValidationError("Invalid file content.") if self.size > settings.MAX_UPLOAD_SIZE: raise forms.ValidationError("File size exceeded.") return self.cleaned_data def save(self, *args, **kwargs): self.instance.extension = self.extension self.instance.size = self.size self.instance.password = self.password self.instance.user = self.request.user file_instance = super(CreateDocForm, self).save(*args, **kwargs) return file_instance doc_update.html <form id="createDocForm" method="post" enctype="multipart/form-data"> {% … -
Is there any way in python to seperate meaningful words from paragraph?
Using python I want my paragraph breaks into meaningful phrases for Example I have a paragraph format like this: Input: interpreted high-levelGeneral-purpose programming languageCreated by GUIDO VAN ROSSUMFirst released in 1991 Output: interpreted high-level, General-purpose programming language, Created by GUIDO VAN ROSSUM, First released in 1991, Note: There is no space between two phrases in Input, So by using this input I want the output and mentioned above. -
Is it possible and how get all users from LDAP using python and django?
Env: python - 3.6.6 django - 2.x.x django-auth-ldap - 2.0.0 python-ldap - 3.2.0 Code: import ldap from django_auth_ldap.backend import LDAPBackend, _LDAPUser, LDAPSearch user = _LDAPUser(LDAPBackend(), "any") # just for getting root connection to LDAP search = LDAPSearch( "ou=Some,dc=some,dc=some,dc=some", ldap.SCOPE_SUBTREE, "???? what should be here ???" # criteria, I guess ) # list of users is expected, or at least user's names result = search.execute(user.connection) Question: How to construct correct criteria(or how it should be called correctly) for getting list of users? (links would be great) Is it possible at all? -
ValueError: too many values to unpack (expected 3) in url config
I have a django project with django-rest-framework named MyProject in which I have created an app accounts. I have the following code inside MyProject/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('accounts.urls', namespace='accounts')), path('admin/', admin.site.urls), ] Inside MyProject/accounts/urls.py, I have: from django.contrib import admin from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register('accounts', views.UserView) urlpatterns = [ path('', router.urls) ] Inside MyProject/accounts/views.py: import sys from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from rest_framework import viewsets from .serializers import UserSerializer class UserView(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer I am getting the error: > File > "C:\Users\user\PycharmProjects\MyProject\accounts\urls.py", > line 10, in <module> > path('', router.urls) File "C:\Users\user\PycharmProjects\MyProject\venv\lib\site-packages\django\urls\conf.py", > line 61, in _path > urlconf_module, app_name, namespace = view ValueError: too many values to unpack (expected 3) -
Can someone please explain adding custom Permissions? (Django)
I am using Django 1.9 and I am trying to add a permission for a group to only be able to view certain models in the admin panel. I have found this in the Django Documentation: https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#custom-permissions But I don't understand how it works if Django 1.9 does not include support for a view only permission. How does it know what view_task is supposed to do? How would I go about implementing this? Do I need to write code elsewhere to define what a view permission is? class Task(models.Model): ... class Meta: permissions = ( ("view_task", "Can see available tasks"), ("change_task_status", "Can change the status of tasks"), ("close_task", "Can remove a task by setting its status as closed"), ) -
Django SimpleHistoryAdmin How to Change Custom Column Name
In Django SimpleHistoryAdmin List View are 5 default columns (OBJECT, DATE/TIME, COMMENT, CHANGE_BY, CHANGE_REASON). I may add another column adding it to the history_list_display but name of this additional column is displayed as it's name in code, for example first_name. Is there an easy way to display it as First Name? -
Lateral Join in django queryset (in order to use jsonb_to_recordset postgresql function)
I have a model "myModel" saving some data in a (postgresql) jsonField named "json", The typical structure of the json data is: {key:[{"a":1, "b":2}, {"a":3, "b":4}]}. I would like to filter myModel queryset according to the values of "a" or "b". I may also want to aggregate over "a" or "b" So "unnesting" the (json -> key) array would be very appreciated, but I can't figure out how to do this with django api. I have try to perform the "unnesting" straight in postgresql via the following SQL query. SELECT * FROM "myModel" join lateral jsonb_to_recordset("myModel"."json" -> 'key') as r("a" int, "b" int) on true LIMIT 5 We can even make it more compact using shortcut notation for the lateral join SELECT * FROM "myModel", jsonb_to_recordset("myModel"."json" -> 'key') as r("a" int, "b" int) LIMIT 5 But I have no idea how to do something equivalent using the django API. I've tried a few things with annotate and RawSQL, but not of them seems to act on the "FROM" clause. Which is the place where I should actually add the 'jsonb_to_recordset' statement. I could probably use the raw function to place my raw SQL, but that would mean I can't "filter" … -
Websorl returns error " unknown field 'django_ct' " when building schema.xml
Our website runs with Python 3.6.5 and: django==1.11.20 django-haystack==2.8.1 certifi==0.0.8 urllib3<1.25,>=1.21.1 pysolr==3.8.1 I generated schema.xml with django-haystack (python manage.py build_solr_schema > schema.xml) and pasted it in websolr (heroku version). When I run below command: heroku run python manage.py rebuild_index --app terradiem I get the following error : Failed to add documents to Solr: Solr responded with an error (HTTP 400): [Reason: ERROR: [doc=naturalearth.naturalearthmerged.12001] unknown field 'django_ct'] Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/haystack/backends/solr_backend.py", line 72, in update self.conn.add(docs, commit=commit, boost=index.get_field_weights()) File "/app/.heroku/python/lib/python3.6/site-packages/pysolr.py", line 918, in add overwrite=overwrite, handler=handler) File "/app/.heroku/python/lib/python3.6/site-packages/pysolr.py", line 500, in _update return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'}) File "/app/.heroku/python/lib/python3.6/site-packages/pysolr.py", line 412, in _send_request raise SolrError(error_message % (resp.status_code, solr_message)) pysolr.SolrError: Solr responded with an error (HTTP 400): [Reason: ERROR: [doc=naturalearth.naturalearthmerged.12001] unknown field 'django_ct'] I guess it is related to the following lines in schema.xml : <field name="id" type="string" indexed="true" stored="true" multiValued="false" required="true"/> <field name="django_ct" type="string" indexed="true" stored="true" multiValued="false"/> <field name="django_id" type="string" indexed="true" stored="true" multiValued="false"/> Any clue ? -
UserCreationForm remains invalid - but no errors show up
I use a UserCreationForm to add users without the admin panel. I added the form, but the validation fails without throwing errors. This is for a small Django app where users should be able to sign up themselves. I tried giving access to the admin panel, which is not a suitable approach. forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms import formset_factory class KAP_add(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254,required=True) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) views.py def kundenAdminPanel(request): formAdd = KAP_add() if request.method == 'POST': print(request.POST) print(formAdd.errors) print(formAdd.non_field_errors) if formAdd.is_valid(): formAdd.save() print("Save") else: print(formAdd.errors) context = { 'add':formAdd, } return render(request,'visDat/kundenAdminPanel.html',context) kundenadminpanel.html <form method="POST" name="add" id = "add" > {% csrf_token %} {% bootstrap_form add %} <button type="submit" class="btn btn-secondary" id="tabl">Submit</button> </form> It should add a user to the database, or throw an error. Whatever I do, the form remains invalid, thus the save command is never executed. Any ideas why this might be the case? The errors section remains empty. -
Getting a value error while trying to view a product without logging in
Created an analytics model to track the user data and get the IP address. But it only works for the logged in user. A guest user when tries to view a object it throws an error. Product - views.py class ProductDetailSlugView(ObjectViewedMixin, DetailView): def get_context_data(self, *args, **kwargs): context = super(ProductDetailSlugView, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj return context Accounts - views.py class LoginView(FormView): if user is not None: login(request, user) user_logged_in.send(user.__class__, instance=user, request=request) try: del request.session['guest_id'] except: pass Analytics - mixin.py from .signals import object_viewed_signal class ObjectViewedMixin(object): def get_context_data(self, *args, **kwargs): context = super(ObjectViewedMixin, self).get_context_data(*args, **kwargs) request = self.request #instance = context['object'] instance = context.get('object') if instance: object_viewed_signal.send(instance.__class__, instance=instance, request=request) return context Analytics - signals.py from django.dispatch import Signal object_viewed_signal = Signal(providing_args=['instance', 'request']) Analytics - utils.py def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR', None) return ip Analytics - models.py def object_viewed_reciver(sender, instance, request, *args, **kwargs): _type = ContentType.objects.get_for_model(sender) # instance.__class__ print(sender) print(instance) print(request) print(request.user) ip_address = None try: ip_address = get_client_ip(request) except: pass new_view_obj = ObjectViewed.objects.create( user = request.user, content_type = _type, object_id = instance.id, ip_address = ip_address # TODO: parsing the ip address to get the location ) object_viewed_signal.connect(object_viewed_reciver) class … -
Advanced Web Mapping Dashboard: Which back-end to choose?
I have been using Leaflet, DC-js, D3-JS, Crossfilter, etc. to create some Web map applications like on the picture below. As you can see, I am displaying some shapefiles and tabular data which is interacting with the map. For now, my application is "working well" if I don't display too much data. But I would like to develop more "sub-applications which will be connected to more data in my Postgresql database. Ex: Connect the sales of stores of my PostgreSQL and create a dashboard based on geographic delimitations. I saw some examples over the web like https://github.com/mjfoster83/web-map-workshop. Its NodeJS/Express is still good back-end? What type of backend(django, react, ...) API, MapServer, I should consider using for having fast queries and creating complex Geospatial Dashboards with an important volume of data to process? -
Django Pass Parameter to Form Object Filtering Queryset
The scenario ; We got a from with fields and inside form there is a combobox it fills with items. We have tenancy and every user got TenantID so when A1 user(tenantid 1) calls create form we need to filter that combobox to filter only A1 UserItems with using Query Filtering. When User B7 (tenantid 77)login and call create form and only items which has tenantid:77 gonna be listed.How can I pass that dynamic tenantid. Btw for every user tenantid stored in abstracted class django core USER- added new field tenantid. Any advice Im open for it , thank you for your attention. Forms.py class ItemForm(forms.ModelForm): class Meta: model = Items fields = ('id', 'item', 'start', 'end') widgets = { 'start': DateTimePickerInput(format='%Y-%m-%d %H:%M'), 'end': DateTimePickerInput(format='%Y-%m-%d %H:%M'), } def __init__(self, *args, **kwargs): super(ItemForm, self).__init__(*args, **kwargs) self.fields['item'].queryset = Items.objects.filter(tenantid=int(User.tenantid)) views.py @login_required() def create_item_record(request): if request.method == 'POST': form = ItemForm(request.POST) if request.method == 'GET': tenantidX = request.user.tenantid form = ItemForm() return save_item_form(request, form, 'items_create_partial.html') -
How to access to database objects in django custom save method?
I have to check if the django model save method is for create new object or update it, because i have to update status of the child objects from parent if is updated. class Categoria(Entidad): ESTADO = (("Activo", "Activo"), ("Inactivo", "Inactivo")) estado = models.CharField(verbose_name=_("Estado"), max_length=20, choices=ESTADO, default=1) categoria_padre = models.ForeignKey('self', verbose_name=_("Categoría Padre"), related_name='parent_category', related_query_name='child_category', null=True, blank=True, on_delete=models.CASCADE) def save(self, *args, **kwargs): from django.db import connection # first option does not work because i can access to django model manager old = self.objects.get(id=self.id) # second option throughs 500 error when create new objects cursor = connection.cursor() response = cursor.execute("SELECT * FROM cms_categoria WHERE id = '" + str(self.id) + "'") set = response.fetchall() connection.commit() cursor.close() connection.close() The second options works on local development but not when push it to heroku with postgres. Anybody could help me please ? Thanks, Regards. -
ModelForm Showing DropDown instead of New Form
I am using Modelforms And my model is like class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) RestaurantName = models.CharField(max_length=50, null=False, blank=False) My forms.py is like class RestaurantForm(ModelForm): class Meta: model = Restaurant fields = '__all__' On Admin side On user field It letting me add a new user by opening a new form in popup but In model form its giving just drop down of existing users. Can I use same functionality of admin? -
How can I use input data from form by using TemplateView
I am trying to create a simulation site which shows the results of calculation and graph by inputing figures. Because I need to integrate a graph created by plotly, my views.py looks like this: views.py: from django.shortcuts import render from django.contrib.auth.models import User from django.http.response import HttpResponse from django.contrib.auth import authenticate, login from django.shortcuts import redirect import pandas as pd from django.views.generic import TemplateView from . import plots class ScatterView(TemplateView): template_name='simulator.html' def get_context_data(self, **kwargs): context = super(ScatterView, self).get_context_data(**kwargs) context['scatter'] = plots.get_scatter() return context The graph can successfully be shown now, but how can I use data input from the form of simulator.html? There are many explanations on web but they are mostly function based like if request.method == 'POST': but how can I do that by class based? simulator.html: the data to be used are for example 'Century', 2019 <form method='POST' action=''>{% csrf_token %} <div class="form-group"> <label for='input_model_name' class="control-label">Name of Model</label> <select name='model_name' placeholder='model_name' class="form-control"> <option>------</option> <option>Century</option> </select> </div> <div class="form-group"> <label for='input_model_year' class="control-label">Model_Year</label> <input type='integer' name='model_year' placeholder="model_year" class="form-control"> </div> <button class="btn btn-secondary" type="submit" name="calculation">calculate</button> <p></p> <div class="form-group"> </form> What I finally want to do is assign the input data to below 'submit_model_name' and 'submit_model_year', so that further calculation can … -
select2.js not showing results as in example with Django
I would like to have Select2.js working with Django. There's django-select2 available for this but for the things I am doing, the author advises that I use native Select2. I was referring to basic code example here https://select2.org/getting-started/basic-usage <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <!--Select2.js--> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script> <select class="js-example-basic-multiple" multiple="multiple" name="lv0"> <option value="US">US</option> <option value="UK">UK</option> </select> <script type="text/javascript"> $(document).ready(function() { $('.js-example-basic-multiple').select2({ placeholder: 'Select an Lv0' }); }); </script> However, I only get below. What am I missing here? Thanks. -
Inlineformset missing management form
4 models, where two ("DataModel", "ImageModel") are in play with this inlineformset factory. The parent contain data and the child should contain uploaded pictures for that data. After the POST, or getting the values, iv got the error title. Seems like im missing some instance when i try to put the post to formset. I try different ways in the template, using the {{ formset.management_form }}, and also trying different ways to make instance out of the Data model but without success. For now i have the following code: def insert(request): ImageFormSet = inlineformset_factory(DataModel, ImageModel, form=ImageForm, extra=1, can_delete=False) if request.method == "POST": model1 = othermodel1(reqeust.POST) model2 = othermodel2(reqeust.POST) datamod = DataModel(request.POST) imgformset = ImageFormSet(request.FILES or None) if model1.is_valid() and model2.is_valid() and datamod.is_valid() and imgformset.is_valid(): ..... save() ..... So the whole idea is to have enter data for model1,2 datamodel and multiple images for the given datamodel. Also storing history for the given data and models. For example: Model1 have this model2, datamod and imgformset . Any ideas why im getting this error even before im get to the if request.method == "POST". And is there a better way to validate all this models. -
How to define default attributes for objects that can be created ini Factory using factory-boy?
Whenever an object is created using a factory there are certain attributes to be set before using it in any unit test. How to achieve this? For example "Employee" has "Division" attribute and I want it to be set to "APAC" for all employees created using EmployeeFactory. class EmployeeFactory(factory.DjangoModelFactory): class Meta: model = employee company = factory.SubFactory() -
How to add one hour in django {% now %} template tag?
I want to add one hour in current time using django {% now %} tag? How can i do it. {% now 'h:i A' %} -
datetime.timdelta not working properly in django?
Here I am writing property method to display the remaining leave days and total leave days.The total leave days are working fine but def leave_remaining_days(self) this is not working as I wanted. For example if the total_leave day is 4 days then this property returns leave_remaining.days return 5 days.It is increasing by 1 instead of decreasing ? How can I calculate the remaining leave days here ? models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff') sub = models.CharField(max_length=300) msg = models.TextField() start_day = models.DateField() end_day = models.DateField() is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) @property def leave_days(self): diff = self.end_day - self.start_day return diff.days @property def leave_remaining_days(self): leave_complete_date = self.start_day + datetime.timedelta(days=(self.end_day - self.start_day).days) if self.is_accepted: leave_remaining = leave_complete_date - datetime.date.today() return leave_remaining.days -
Why django is not completing it's installation?
After setting up an environment and activate the environment, when I run the following command to install the django: pip install django It's run the installation but didn't complete it and stop the process without showing any error! (venv) C:\Users\rakib\Desktop\python\PythonDjangoDevToDeployment\btre_project>pip install django Collecting django Using cached https://files.pythonhosted.org/packages/94/9f/a56f7893b1280e5019482260e246ab944d54a9a633a01ed04683d9ce5078/Django-2.2.5-py3-none-any.whl Collecting sqlparse (from django) I am a windows user. I think I followed the proper way of installation. But I don't understand why it's not complete the installation! -
How do you know the presence of schools in the neighborhood near
How do you know the presence of schools in the neighborhood near your home by way of coordinates lat and lng and accept my sincere greetings