Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Error while using function name as a variable in Pycharm, Python, Django: local variable 'processed' referenced before assignment
I use Pycharm Professional 2019.2, Python 3.7.4, Django 2.2.5. As I know, function names are global variables in modules. But I have a function that denies that. def processed(request): if request.method == 'post': text = request.post['text'] processed = text.upper() return HttpResponse(processed) The browser shows the following error: UnboundLocalError at /process/ local variable 'processed' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/process/ Django Version: 2.2.5 Exception Type: UnboundLocalError Exception Value: local variable 'processed' referenced before assignment -
Get a url parameter with Django Rest Framework
I'm Using django rest framework and I would like to achieve an endpoint like so : http://127.0.0.1:8000/posts//like This endpoint will allow a user to like a certain post. But the problem is that I have no ideas about writing the view for that purpose. I think that I have to get the current id of the post, which I can only access with grabbing the "" from the URL. Here is how my view looks like : class PostList(generics.ListCreateAPIView): serializer_class = PostSerializer queryset = Post.objects.all() permission_classes = [isAuthenticatedOrReadOnly] #Get Post Details : delete / update / get the post class PostDetail(generics.RetrieveUpdateDestroyAPIView): serializer_class = PostSerializer queryset = Post.objects.all() #Get my posts : List class MyPostList(generics.ListCreateAPIView): serializer_class = PostSerializer permission_classes = [isAuthenticatedOrReadOnly] def get_queryset(self): return Post.objects.filter(user = self.request.user) class PostLike(generics.ListCreateAPIView): serializer_class = ActivitySerializer permission_classes = [isAuthenticatedOrReadOnly] def get_queryset(self): return Vote.objects.filter(activity_type='L', content_object=self.id, object_id=self.id) As you can see, I'm completely lost with the PostLike view. The goal of this view is to : Display likes of the current post id, create a like instance that target this post id Thank you ! -
How to make date formatting in Django template?
I apologize for my English already. I did some research, but none of them worked for me. But no data is shown. It appears if I don't type "date:" D d M y ". Example: {% for row in activities %} <tr> <td style="width:30%" class="ads-details-td"> <div> <p><strong> Date: </strong> {{ row.dateStart|date:"D d M Y" }} </p> </div> </td> </tr> {% endfor %} Incoming start date format 'dateStart': '2019-02-05 05:45:00' I will be glad if you help me. -
How to get unique values in django from database
So this is my query and it displays only file name but I want 'id' also. filenames=Upload.objects.values('file').distinct().filter(created_by=request.user).all() this will generate only unique files as dict. But I want 'id' of those files also and if use 'id' inside that 'values' it will not give unique file names. So this is my issue. I'm okay with other methods as well. -
Django Custom Tag Filtering
Need a little help. I have a news site, and what I'm trying to do is make a custom tag (it has to be a custom tag, part of my task) that will display the latest 3 news in a category. So let's say I click on a "health" article, the article opens, and my custom tag renders the latest 3 news from the health category next to the article. I hope I didnt confuse you, I'm still learning. My tag : from django import template from news.models import Article register = template.Library() @register.inclusion_tag("news/categories.html") def show_results(category=None): article = Article.objects.all() if category: article = article.filter(category=category) return {'article': article[:3]} My models: class Category(models.Model): category_title = models.CharField(max_length=200, default="") def __str__(self): return self.category_title class Article(models.Model): title = models.CharField('title', max_length=200, blank=True) slug = AutoSlugField(populate_from='title', default="", always_update=True, unique=True) author = models.CharField('Author', max_length=200, default="") description = models.TextField('Description', default="") is_published = models.BooleanField(default=False) article_text = models.TextField('Article text', default="") pub_date = models.DateTimeField(default=datetime.now, blank=True) article_image = models.ImageField('Article Image') article_category = models.ForeignKey(Category, on_delete="models.CASCADE", default="") img2 = models.ImageField('Article Image 2', default="", blank=True) img3 = models.ImageField('Article Image 3', default="", blank=True) img4 = models.ImageField('Article Image 4', default="", blank=True) img5 = models.ImageField('Article Image 5', default="", blank=True) img6 = models.ImageField('Article Image 6', default="", blank=True) def __str__(self): return … -
Need to add employee search function in googlesite
I have google sheet which store all employee details (name,email,employee number, etc.) and I need a suggestion for create local web with Flask/Django, add search function and then upload it to googlesite intranet. I'm python user but never do something like this before This is for all employee, I need to add something in googlesite like employee search function. So everyone in the company can find colleagues email, name, etc. via googlesite I dont have any code yet, but I think I can use Flask for Backend and ReactJS for Frontend design. I don't have the database, and don't want anyone to add the employee data. So I gonna update the data via google sheet and need to retrieve the data from it the step I thinking about is 1. we normally update the data via google sheet 2. create webpage with search function (which retrieve the data from google sheet) and mayb we use 127.0.0.5000 first 3. then use google api / heroku to deploy 4. embed url in the googlesite 5. when employee go to this webpage, they can search name, email, etc. from here and shows the employee result I learn some in the web and did … -
Converting Django project from Python 2 to Python 3: pip3 install django_comments NameError unicode
System info: 64-bit OS-X, Python 3.7 I am converting a Django website from Python 2 to Python 3. To do this, I ran 2to3 on the whole project. I then installed all of the required modules in INSTALL_APPS in settings.py - except one: django_comments. (env) user:languages user$ pip3 install django_comments Collecting django_comments Using cached https://files.pythonhosted.org/packages/c7/df/3a752f3e393b470087304dd47be6a4bad9867e7ec33963ff022d32143700/django-comments-1.0.0.b.tar.bz2 ERROR: Command errored out with exit status 1: command: /Users/user/.../env/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/setup.py'"'"'; __file__='"'"'/private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: /private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/setup.py", line 12, in <module> version = get_version(), File "/private/var/folders/tb/vbtzyvv92hz6262qv7x8r8jh0000gn/T/pip-install-xjv_0ird/django-comments/django_comments/__init__.py", line 4, in get_version return u'.'.join(map(unicode, VERSION)) NameError: name 'unicode' is not defined ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I have found that this may be related to compatibility with Python 3 and that one potential fix is to replace unicode with str. However, this is a module that I would like to work in Python 3 since the Django project relies on this for comments currently. Is it deprecated essentially with no way to work outside …