Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test Django prohect that interacts with other components using Selenium?
I have a Django Project. I want to make end-to-end tests for it using Selenium. It interacts with Other components (usually run through docker-compose) API and functions properly. The Django Project and 'Other Components' are different repositories (obviously there are multiple 'other components') Testing of parts that don't involve API calls, have been tested. -
How to get current user field when creating an object in a model and save?
I'm creating a model name post and I have many users for the website but I need to create a field for the user who is adding the post. So, how to do it? -
Django request.method is "{}GET" when request from axios after built with vue-cli
I'm using axios with Vue in my project. While under development (npm run serve), it's worked correctly. But after built, any request after 'PUT' request will have "{}" in front of http method, such as "{}GET", "{}PUT". as I've tested, I've got this state diagram. // CASE 1 : OK axios.put('someurl') // HTTP_METHOD is 'PUT' axios.get('someurl') // HTTP_METHOD is 'PUT' // CASE 2 : HAS CURLY BRACKET IN METHOD axios.put('someurl', {}) // HTTP_METHOD is 'PUT' axios.put('someurl', {}) // HTTP_METHOD is '{}PUT' axios.post('someurl', {}) // HTTP_METHOD is '{}POST' axios.delete('someurl', {}) // HTTP_METHOD is '{}DELETE' axios.get('someurl', {}) // HTTP_METHOD is 'GET' this is some logs from django [28/May/2019 20:45:15] "GET /api/colla/comments/177/notify/ HTTP/1.1" 200 4 [28/May/2019 20:45:16] "PUT /api/colla/comments/177/notify/ HTTP/1.1" 200 5 [28/May/2019 20:45:19] "{}POST /api/colla/comments/177/notify/ HTTP/1.1" 405 43 [28/May/2019 20:45:25] "{}POST /api/colla/comments/177/notify/ HTTP/1.1" 405 43 [28/May/2019 20:45:30] "{}PUT /api/colla/comments/177/notify/ HTTP/1.1" 405 42 [28/May/2019 20:45:36] "{}DELETE /api/colla/comments/177/notify/ HTTP/1.1" 405 45 [28/May/2019 20:45:39] "DELETE /api/colla/comments/177/notify/ HTTP/1.1" 200 4 -
Saving Json datas into a ManytoMany relation in postgresql
I have set up a Jupyter Notebook for a Machine learning project using Ibm Watson-Studio and I'm trying to find a way to save my predictions which are in a Json format into a ManyToMany relationship in my Postgresql database. For better understanding the goal is to do this: Based on the description of a product, predict in which categories(which I call tags) this product should fit into and for each classes, if the confidence score is equal or higher than 0.30, save the classes as a tag into the ManytoMany table to his related product. ps; I use the Django-taggit module to generate this ManytoMany relation and to create the tags. I have a text classifier that is connected to my Postgresql database so that I can apply this model to my datas from the description column. I'm able to get accurate predictions for each descriptions that I have in a Json format as you can see below. My Notebook: from watson_developer_cloud import NaturalLanguageClassifierV1 import pandas as pd import psycopg2 import json # Connect to my Postgresql database conn_string = 'host={} port={} dbname={} user={} password={}'.format('151.201.17.226', 5432, 'dbsearch', 'locq', 'mysecretpass***') conn_cbedce9523454e8e9uyt455d4c1a52e = psycopg2.connect(conn_string) # Select the description column with the … -
DatabaseError: unable to open database file on django
I have a Django 1.5 application running on apache2 server and using sqlite database. The setting for the database is as follow DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/var/www/html/project/devdb', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } where devdb is the database file generated. When I run migration commands from the terminal console, it works fine and data is migrated to the database. But when I visit the application URL, it gives the error DatabaseError at /url_path/ attempt to write a readonly database Then I change the permission of file using sudo chown 777 devdb Then it starts giving the error DatabaseError at /url_path/ unable to open database file ls -la gives following output for the devdb file -rwxr-xr-x 1 ubuntu ubuntu 1036 May 11 2018 manage.py -rw-rw-r-- 1 ubuntu ubuntu 291840 May 28 09:31 devdb Getting user of the apache2 running using ps -ef | egrep '(httpd|apache2|apache)' | grep -v `whoami` | grep -v root | head -n1 | awk '{print $1}' gives www-data But changing owner of the file to www-data again gives unable to open database file. -
how can i populate a field with id while saving but id is not existing yet
I am building a helpdesk system and I would like to have a automated ticket designation based on the length of the ID. Example: The ID of a ticket is 47 so I would like to have a 5 Integer long designation -> #00047 or if ID 2021 designation should be #02021 my relevant code: My Model: class Ticket(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) designation = models.CharField(max_length=255, blank=True, null=True) I tried do populate the fields with a for loop in my views.py def Index(request): ticket = Ticket.objects.all() for t in ticket: id = len(str(t.id)) if id == 1: t.designation = "#" + str("0000") + str(t.id) elif id == 2: t.designation = "#" + str("000") + str(t.id) elif id == 3: t.designation = "#" + str("00") + str(t.id) elif id == 4: t.designation = "#" + str("0") + str(t.id) else: t.designation = "#" + str(t.id) context = {'ticket':ticket} return render(request, 'ticketsystem/index.html', context) and the output was correct, but I would like to have the population while creating the object i tried the following, by adding it to my Ticket model: class Ticket(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) ticketkennung = models.CharField(max_length=255, blank=True, null=True) def save(self): id = len(str(id)) if id == 1: … -
customize django admin page with terminal interface
I am trying to customize my admin site in django with a terminal looking template. 1. What is the action of the form to direct to admin home? 2. My since the page is terminal, pressing enter submits the form, how can I delay till I have the username and password before submitting? <!DOCTYPE html> <html> <head> <title></title> </head> <body> ... <!-- admin form --> <form name="adminform" method="POST" action="{% url '???' %}" > {% csrf_token %} <!-- {{ form.as_p }} --> <p class="search__form" > login: <input type="text" class="input search__input" id="username" placeholder="" name="search" {{form.username}} autofocus /> </p> </form> <!-- my javascript checks if input starts with a '$' sign then it is the username, if it begins with a '.' it is a password, I want to combine the two and send for admin authentication --> </body> </html> -
How to make a TabularInline orderable by user?
I created an admin view using the TabularInline class. With this view it is not possible to let the user order/sort the table to their liking, like within a standard ModelAdmin view. I would like to achieve this. I am using Django 2.2.1. What I tried I searched the Django docs, but besides hard coding 'ordering' within the admin.py file, I couldn't find anything on this topic. This is not what I want, I want the admin user to choose how to order. I tried to use adminsortable2, however I ran into some issues I couldn't resolve. This got me thinking: is it really not possible with the standard Django package. My code My model consists of TimeFrames, which are made up by TimeSlots. This is what my model.py looks like: from django.db import models class TimeFrame(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class TimeSlot(models.Model): DAY_CHOICES = ('work', 'Work'), ('weekend', 'Weekend') begin_time = models.TimeField() end_time = models.TimeField() reference = models.CharField(max_length=30) day = models.CharField(max_length=30, choices=DAY_CHOICES) timeframe = models.ForeignKey('TimeFrame', on_delete=models.CASCADE) I don't want to register a separate TimeSlot admin view, since the TimeSlots are always part of a TimeFrame. They don't exist on their own. from django.contrib import admin from .models … -
Is there a way to combine annotations and filtered aggregations in Django Querysets?
I have a complex query that, although it is easily done in python code, I'm trying to do through Django Querysets. Using the example models from https://docs.djangoproject.com/en/2.2/topics/db/aggregation/#aggregating-annotations, what I'm trying to do is to annotate each Publisher with the average of the total sales per author. However, the total sales per author should only include books from a given date range. Is there any way to do this in one query? Of course, doing two separate queries and joining the results using pure Python would work. However, in my specific use case, there is a large amount of overhead for each database connection/disconnection, so it would be preferable to combine them into one query. -
How to fix 'bool' object has no attribute 'get'
im new to python with django frame work and im developing three articles i have tried to debug but i have failed and im getting this error "bool object has no attribute 'get" this is my models.py from django.db import models # Create your models here. class Article(models.Model):# this new class articles inherits properties from models.model """docstring for Article""" title = models.CharField(max_length=255) body = models.TextField(max_length=255) pub_date = models.DateTimeField( 'date published') likes = models.IntegerField() def __unicode__(self): return self.get and in my urls i have from django.conf.urls import include, url from article.views import article #from django.shortcuts import redirect urlpatterns =[ url(r'^all/$', all, name='all'), url(r'^get/ (?P<article_id>\d+)/$', article, name='article'), ] i expect to have a list of articles and when i click on the articles im directed to another page but i get such an error System check identified no issues (0 silenced). May 28, 2019 - 15:38:06 Django version 2.2.1, using settings 'finalreading.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /articles/all/ Traceback (most recent call last): File "C:\code\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\code\lib\site-packages\django\utils\deprecation.py", line 96, in call response = self.process_response(request, response) File "C:\code\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: … -
Wkhtmltopdf to zip pdf files
is there any way to use wkhtmltopdf to download all pdf in a zip format in django? I used BaseZipView for the zipping or is it possible to combine it with PDFTemplateView? Thanks in advanced! -
Django DRF - Group by date
I need to group the result of a queryset by date on DRF """ Django model """ class Matches(models.Model): platform = models.CharField(max_length=100) mode = models.CharField(max_length=100) kills = models.IntegerField() date = models.DateTimeField() """ Serializer """ class v1SnapSerializer(serializers.ModelSerializer): class Meta: model = models.v1Snap fields = ('platform', 'mode', 'kills', 'date') Desired output (just an example): [ { 'date':'2019-01-01', 'data':[ { 'platform':'ps4', 'mode':'solo', 'kills':10, 'date':'2019-01-01 10:00:00' }, { 'platform':'ps4', 'mode':'duo', 'kills':10, 'date':'2019-01-01 12:00:00' }, { 'platform':'ps4', 'mode':'squad', 'kills':10, 'date':'2019-01-01 11:00:00' }, ] }, { 'date':'2019-01-02', 'data':[ { 'platform':'ps4', 'mode':'solo', 'kills':1, 'date':'2019-01-02 10:00:00' }, { 'platform':'ps4', 'mode':'duo', 'kills':2, 'date':'2019-01-02 12:00:00' }, { 'platform':'ps4', 'mode':'squad', 'kills':3, 'date':'2019-01-02 11:00:00' }, ] } ] For me, the easy solution is to make a raw querie on django and create a serializer, but it feels not so pythonic... So it appears that DRF has some beautiful way to make it look nice, maybe using to_representation... -
Element available for more groups than one
For example I have the button in my template that is available only for stuff: {% if request.user.is_staff %} <a href="{% url 'unosZanraKnjige' %}" class="button">Add new</a> {% endif %} I have group created in http://127.0.0.1:8000/admin/ called "Djelatnici". Is it possible to make some element (button in this case) available only for specific groups with "OR" (||) condition, something like: {% if request.user.is_staff %} || {% if request.user.is_djelatnici %} <a href="{% url 'unosZanraKnjige' %}" class="button">Add new</a> {% endif %} -
Django advice making views for ManyToMany model fields
i have 3 models having 2 manytomany relationship fields... and now i must to make the views.py function and the template. I want to do the template similary with what I have generated in django admin but i don t know how.. I will post models.py structure from app_name.models import Person, Admin from another_app.models import ListB, SchTrat, ListM class A(models.Model): data_create_a = models.DateTimeField(auto_now_add=True) data_modify_b = models.DateTimeField(auto_now=True) cant = models.CharField(max_length=100) days = models.CharField(max_length=100) mod = models.CharField(max_length=100, choices=MOD) sch = models.ForeignKey(SchTrat, on_delete=models.PROTECT) list_m = models.ForeignKey(ListM, on_delete=models.PROTECT) class B(models.Model): data_create_b = models.DateTimeField(auto_now_add=True) data_modify_b = models.DateTimeField(auto_now=True) type = models.CharField(max_length=100, choices=TYPE) list_b = models.ForeignKey(ListaB, on_delete=models.PROTECT) **med = models.ManyToManyField(A)** class C(models.Model): data_create_c = models.DateTimeField(auto_now_add=True) data_modify_c = models.DateTimeField(auto_now=True) simpt = models.CharField(max_length=100) tens = models.CharField(max_length=100) mm = models.CharField(max_length=100) temp = models.CharField(max_length=100) height = models.CharField(max_length=100) weight = models.CharField(max_length=100) glic = models.CharField(max_length=100) AV = models.CharField(max_length=100) **person = models.ForeignKey(Person, on_delete=models.CASCADE)** admin = models.ForeignKey(Admin, on_delete=models.PROTECT) **diag = models.ManyToManyField(B)** I want in my template to add a new C(models.Model) an to have posibility to insert multiple B(models.Model) and multiple A(models.Model) and to have posibiliy what i inserted in that new C(models.Model) before submit C(models.Model). Thanks! -
LDAP Authentication not working in Graphite
I have Installed Graphite in RHEL7 server. I have done the LDAP configuration in Graphite local_settings.py ## LDAP / ActiveDirectory authentication setup USE_LDAP_AUTH = True LDAP_SERVER = "ldap-proxy.de.pri.o2.com" LDAP_PORT = 389 #LDAP_USE_TLS = True ## Manual URI / query setup LDAP_URI = "ldap://ldap-proxy.de.pri.o2.com:389" LDAP_SEARCH_BASE = "ou=viaginterkom,dc=rqm" LDAP_BASE_USER = "uid=rqm,ou=globalusers,cn=config" LDAP_BASE_PASS = "WB6SruQ2" LDAP_USER_QUERY = "(sAMAccountName=%s)" #For Active Directory use "(sAMAccountName=%s)" # User DN template to use for binding (and authentication) against the # LDAP server. %(username) is replaced with the username supplied at # graphite login. LDAP_USER_DN_TEMPLATE = "cn=% (username),ou=viaginterkom,dc=rqm" # If you want to further customize the ldap connection options you should # directly use ldap.set_option to set the ldap module's global options. # For example: # #import ldap #ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) # Use #ldap.OPT_X_TLS_DEMAND to force TLS #ldap.set_option(ldap.OPT_REFERRALS, 0) # Enable for Active Directory #ldap.set_option(ldap.OPT_X_TLS_CACERTDIR, "/etc/ssl/ca") #ldap.set_option(ldap.OPT_X_TLS_CERTFILE, "/etc/ssl/mycert.pem") #ldap.set_option(ldap.OPT_X_TLS_KEYFILE, "/etc/ssl/mykey.pem") #ldap.set_option(ldap.OPT_DEBUG_LEVEL, 65535) # To enable verbose debugging # See http://www.python-ldap.org/ for further details on these options. I also restarted the graphite service by service uwsgi restart. When I tried to login , it throws "Authentication Attempt Failed,please make sure you entered your login and password correctly" In logs also I'm unable to find the error messages. How to fix … -
Django form can't send a form with a dash and spaces
I have simple form and > name, number in number input I use Javascript mask. Number it's phone. Try submit with value number > +7 (999) 999 99-99. I noticed that I can not pass validation because of the dash characters and spaces.How do I make my form validate with this value. order_create.html {% if form.errors %} <div class="error_message"> <strong><small>Something was wrong</small></strong> </div> {% endif %} <form action="{% url 'order:order_create' %}" method="POST"> {% csrf_token %} <label><span class="label_red">*</span> Name:</label> <input type="text" name="name" maxlength="80" placeholder="Name" required> <label><span class="label_red">*</span> Phone:</label> <input id="tel" type="tel" name="number" placeholder="+7 (xxx) xxx xx-xx" required> <button>Submit</button> </form> views.py def order_create(request): cart = Cart(request) if request.method == 'POST': order = Order.objects.order_by('id').last() form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create( order=order, product=item['product'], price=item['price'], quantity=item['quantity'] ) cart.clear_session() return redirect(reverse('order:order_success', kwargs={'pk':order.id})) else: return render(request, 'orders/order_create.html', {'form':form}) else: return render(request, 'orders/order_create.html', {'cart':cart}) forms.py from orders.models import Order from django import forms class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ['name', 'number'] javascript var input = document.querySelector("#tel"); input.addEventListener("input", mask, false); input.addEventListener("focus", mask, false); input.addEventListener("blur", mask, false); function setCursorPosition(pos, elem) { elem.focus(); if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd("character", pos); range.moveStart("character", … -
Is there a way to get an excel-like filtering with django?
I have simple filters for my django by I would like a improve them I have tried FilterSets but without getting expected result 31 class AnnonceFilter(django_filters.rest_framework.FilterSet): 32 class Meta: 33 model = Annonce S> 34 fields = ['advert_type', 'asset_type', 'sales_type', 'price', 'area', 'department', 'department_id', 'city', 'postal_code'] 52 class AnnonceMergedList(generics.ListAPIView): 53 authentication_classes = () 54 permission_classes = () 55 serializer_class = AnnonceMergedListSerializer 56 pagination_class = LargeResultsSetPagination 57 filter_backends = (DjangoFilterBackend,) 58 filter_class = AnnonceFilter S> 59 filterset_fields = ('advert_type', 'asset_type', 'sales_type', 'price', 'area', 'department', 'department_id', 'city', 'postal_code') S> 60 #search_fields = ('advert_type', 'asset_type', 'sales_type', 'price', 'area', 'department', 'department_id', 'city', 'postal_code', 'description') 61 # queryset = Annonce.objects.all() 62 63 def get_queryset(self): 64 # Make the querysets for each database S> 65 q1 = Annonce.objects.using('leboncoin').annotate(website_name=Value('leboncoin', output_field=CharField())).all() S> 66 q2 = Annonce.objects.using('pap').annotate(website_name=Value('pap', output_field=CharField())).all() 67 return q1 | q2 I would like to have a defined list of possible choices for each fields, maybe that choices would be returned by another route. I have no idea how to do that. -
Collectstatic produces inexplicable %20 (space) in static directory urls, so CSS doesn't load
My static files aren't being served correctly because there's a strange space in my folder structure. development folder structure static >css >lots of css files >js >img When I run collecstatic to serve them properly, collect static puts everything into a folder called staticfiles, here's my settings.py settings.py STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ STATIC_DIR ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles/static') # MEDIA file defaults MEDIA_ROOT = os.path.join(BASE_DIR,'staticfiles/media') MEDIA_URL = '/staticfiles/media/' I use it this way as this is how its configured on my live server. I now have (in my development env) a folder in the project called staticfiles/static, inside which I can find the a similar folder structure as above. staticfiles >img >media >static >css >admin >img >podcast >js However, once I've run the server, django thinks my CSS file 'static/%20css/front.css' and so it doesn't load. If I correct the URL to 'static/css/front.css' the css file loads perfectly...? Here's where it's trying to get the css from: http://127.0.0.1:8000/static/%20css/front.css Here's where it actually is: http://127.0.0.1:8000/static/css/front.css I've checked the folder name for 'css' on both my development static, and the staticfiles static, and it is correct. It seems to be something to do with the … -
How to duplication of task execution in celery? And how to assign an worker to an default queue
My task executes more than once with two minutes. but scheduled for once in celery_beat queue. Tried with restarting the celery with supervisorctl command as supervisorctl stop all and supervisorctl stop all app.autodiscover_tasks(settings.INSTALLED_APPS, related_name='tasks') app.conf.task_default_queue = 'default' app.conf.task_routes = {'cloudtemplates.tasks.get_metrics': {'queue': 'metrics'}} app.conf.beat_schedule = { 'load-softlyer-machine-images': { 'task': 'load_ibm_machine_images', 'schedule': crontab(0, 0, day_of_month='13'), 'args': '', 'options': {'queue': 'celery_beat'}, } } Expected to run the sheduled task only once for on 13 th of every month. -
Django admin export model with inlines to csv
I try to find a way to export a model with inlines to csv with a button or action in django admin. Has anyone done this before? I've already tried to export with django_import_export but i haven't found a way to get the content of the inlines. The goal of the export is to export a contract with n products and n subproducts. Thank you all for the help -
Django import export: Error encountered while trying to read file CSV
Hi I have a problem with django import export, Django==1.8 django-import-export==1.1.0 When I want to import a small csv (1 line) I have directly a blank page with the message Error encountered while trying to read file: XXX.csv I see in the network console a POST to http://localhost:8001/admin/XXX/XXX/import/ with a 200 response with this message. It is the same behavior whatever the model. -
How to implement multiple file upload in Django
How to implement multiple file upload in Django with two models? I have 1 form but two models that make two forms models.py class Ads(models.Model): title = models.CharField(max_length=85, blank=False) class Images(models.Model): ad = models.ForeignKey(Ads, related_name='images', on_delete=models.CASCADE) image = models.ImageField(blank=True, upload_to='') thumbnail = models.BooleanField(default=False) views.py class CreateAd(CreateView): model = Ads form_class = CreateAdForm success_url = reverse_lazy('index') forms.py class CreateAdForm(forms.ModelForm): class Meta: model = Ads fields = ('title',) class ImageForm(forms.ModelForm): class Meta: model = Images fields = ('image', ) -
how manipulate when view.py can be executed when there are multiple django app
I'm working on a project where i upload image, do some processing on it and then showing the original image with the processed one in addition to some statistics. i've set up 2 django apps 1 that just get the image from the user and save it and the other one is the one that process and show results of the processing. my problem is when i runserver the views.py of the seconde app runs without waiting for the image from the first app! any help ? -
Django how to create a nested serializer for a field that has possible null
I want to do a nested serializer to output something like this. In this example, division can be null, but if not null, it will have the exploded serializer using DivisionSerializer. "id" = 3 "username" = "hello", "first_name" = "mr", "last_name" = "hello" "division" = { "id" = 2, "name" = "finance" } models.py class Division(models.Model): company = models.ForeignKey(Company) name_of_division = models.CharField(max_length=30) class Employee(models.Model): username = models.CharField(max_length=30, blank=False) first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) division = models.ForeignKey(Division,null=True) serializers.py class DivisionSerializer(serializers.ModelSerializer): class Meta: model = Division fields = ("id", "name") class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ("id", "username", "first_name", "last_name", "division") -
Is it ok to update template in real time with jquery in django?
I have a script that makes an ajax request for every 2 seconds in my django template. This script is basically calling cpu_view function from views.py every 2 seconds and this function updates the data needed to populate my django table. Everything's working fine except that the page or specifically the html content of the page refreshes everytime including all the buttons which make the page looks kind of weird IMO. So I thought maybe there's a better way of doing this. Basically, what I'm trying to do here is to create a small monitoring application for my servers. Any advice or help is appreciated. <script type="text/javascript"> function executeQuery() { $.ajax({ type: 'GET', url: '/server/cpu', success: function(data) { $("html").html(data) } }); } setInterval(executeQuery, 2000); </script> views.py def cpu_view(request): output = [] listServers = Serveurs.objects.all() for x in get_proc_output(): pid = x.get('pid') for y in get_netstat_output(): if pid in y.values(): output.append({**x,**y}) for i in listServers: for j in output: if i.port in j.values(): j['type_server'] = i.type_du_serveur table = TableServeur(output) RequestConfig(request).configure(table) return render(request, 'server/table.html', {'table': table})