Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to open xml file in Django python using open()
I am trying to open and .xml file using open() and then convert it into dictionary. I am using it in django application File is also located at correct location.. Problem is "\" is getting replaced with "\\" and file extension ".xml" with ".xmlf" and no such file directory is error as in snapshot Filepath is changing can be seen into image. code for reading file is how to resolve the error in django server -
Extend Behavior of models.Model
In django, I am trying to extend the behavior of the models.Model class. I want to execute code as the model inits, as well as using the default init. Here is the code I so far which looks like what im wanting to do but the behavior is incorrect. class DirtyModel(models.Model): def __init__(self, *args, **kwargs): super(DirtyModel, self).__init__(*args, **kwargs) print("extended") class Foo(DirtyModel): bar = models.TextField() This code tries to make a model called DirtyModel, which I understand why, but I don't suppose I know how to extend the Model class otherwise. How should I go about creating a custom models.Model class to use in my models? -
Django html page does not display a variable i passed in views
i am a beginner with Django and i encountered a problem. I wrote a code which allows me to add different products and categories from admin, and then display them on a html page. However, when i click on any of the displayed products i want my product description to be displayed in another html page. The first page is working just fine( product_list.html), however i am having trouble with the second one (product_detail.html). urls.py ( without the imports): urlpatterns = [ url(r'^category/(?P<categoryid>\d+)/$', views.product_list, name='product_list_by_category'), #url(r'^list/(?P<id>\d+)/$', views.product_detail, name='product_detail'), re_path('^$', views.product_list, name = 'product_list'), url(r'^list/(?P<id>\d+)/$', views.product_detail, name='product_detail'), ] views.py def product_list(request, categoryid = 1): *this one is working* categories = Category.objects.all() products = Product.objects.all().filter(category_id=categoryid) context = {'categories': categories, 'products': products } return render(request, 'shop/product_list.html', context) def product_detail(request, id=1): *this one is not displaying anything* productt = Product.objects.all().filter(id = id) return render(request, 'shop/product_detail.html', {'product': productt}) product_detail.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="http://localhost:8000/shop/list/{{product.id}}/">{{product.description}}</a> </body> </html> Do you have any idea why the page rendered by product_detail does not display anything? -
models not showing in django admin page
My models in my admin page are not sowing up. I checked to see if my user was a super user, checked if my directories were good, and checked if my code was written wrong. As far as I know, all of these are correct. However I get this error when I add 'main.templates.admin.InfoAdmin' in settings.py. ...django\apps\registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Without that line there's no error, but the models don't show up on the admin page. admin.py from django.contrib import admin from .models import * class InfoAdmin(admin.ModelAdmin): fields = [ 'site_title', 'site_content', 'site_published' ] class DocumentAdmin(admin.ModelAdmin): fields = [ 'title', 'description', 'document', 'uploaded_at', 'creator' ] admin.site.register(models.Info, InfoAdmin) admin.site.register(models.Document, DocumentAdmin) models.py from django.db import models from datetime import datetime from django.contrib.auth.models import User from django.conf import settings # Create your models here. class Info(models.Model): site_title = models.CharField(max_length=200) site_content = models.TextField() site_published = models.DateTimeField("date published") likes= models.IntegerField(default=0) dislikes= models.IntegerField(default=0) def __str__(self): return self.site_title class Document(models.Model): title = models.CharField(max_length=100, default='NoTitle') description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) creator = models.ForeignKey('auth.User', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title urls.py from django.urls import path from . import views from . import … -
How to sync a Many to many relationship on Django
I want to know if there is a function I can call in Django ORM to update the intermediate table by passing an array of IDs Im used to work with Laravel, and that framework has a very useful method called sync. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table is there something like that in Django? I was looking through the documentation but I can't find it. If there isn't, what's the best way to do it? -
Why is my django exception handling not working
I want to make my django app as user friendly as possible and I want to handle appropriate exception handling cases and have it push out an error message sort of like an alert in javascript. I want to do this when there's no file uploaded in this case "POST" == request.method is emtpy. So when the upload button is pressed and nothing have been uploaded there would be an alert message sent out. But so far the code that I have keeps pushing out an error message that says "The view uploadpage.views.upload didn't return an HttpResponse object. It returned None instead." def upload(request): try: if "Post" == request.method: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) # getting a particular sheet by name out of many sheets worksheet = wb['Summary'] # iterating over the rows and # getting value from each cell in row seller_info = [] for cells in worksheet.iter_rows(min_col=2, max_col=2, min_row=1, max_row=5): for cell in cells: seller_info.append(str(cell.value)) return render(request, 'uploadpage/upload.html', {"excel_data": seller_info}) except: if "POST" == None: messages.error(request, 'Need upload file') return render(request, 'uploadpage/upload.html') MYAPP {% if messages %} {% for message in messages %} {{ message … -
What difference it makes when using ' /<int:id>' instead of '/<slug>' in url-patterns(Django)? Which method is more preferable?
I want to use URL-pattern to fetch product view from my products list. But I came across two methods and a bit confused about which to select. 1)<slug> 2) <int:id> -
Which is best? PHP or ASP or Django
From a long time I wanted to know Which is Good? Php or Asp or Django. I have used PHP more than Asp and Django. I would greatly thank the person who answers this. Regards, Dereck Smith Elijah -
How to solve __init__() takes 1 positional argument but 2 were given
views.py from django.views.generic import ListView from django.contrib.auth.models import User class UserListView(ListView): model = User template_name = 'infinitescroll/articles.html' context_object_name = 'users' paginate_by = 10 queryset = User.objects.all() urls.py from django.contrib import admin from django.urls import path from infinitescroll.views import UserListView urlpatterns = [ path('admin/', admin.site.urls), path('home/',UserListView, name='home'), ] articles.html <table class="table table-bordered"> <thead> <tr> <th>Username</th> <th>First name</th> <th>Email</th> </tr> </thead> <tbody> {% for user in users %} <tr> <td>{{ user.username }}</td> <td>{{ user.first_name }}</td> <td>{{ user.email }}</td> </tr> {% endfor %} </tbody> </table> I don't know what causes an error it gives error locations in Exception Location: C:\xampp\htdocs\8moviesdb\infinite\pal\lib\site-packages\django\core\handlers\base.py in _get_response, line 113 -
How to get all log levels in django celery to ELK(logstash) or write to a file
I want to get all logs from Django and celery and send them to logstash or write to a file when an error occurs in celery task it shows in the console but not writing to a file -
How can i give limit in django?
I'm making a project and want to use limit for fetch data how can i use limit if there are any function or any way i can give limit to my fetching data i expect the output of (2019, 12, 27)(2019, 6, 30) to be (2019, 12, 27) but it fetching all records def maintenancefunction(request): #maintenance page function if 'user' not in request.session: return redirect('/login') else: if request.session.has_key('user'): abc=request.session['user'] today = date(2019,1,1) # today= date.today.().strftime('%d/%m/%Y') next_date=today.strftime('%Y-%m-%d') lastdate= today + timedelta(days=180) new_date= lastdate.strftime('%Y-%m-%d') duedate=maintanance_table.objects.values_list('maintanance_todate').filter(user_email=abc).order_by('maintanance_todate').reverse() # # newduedate=duedate.strftime('%Y-%m-%d') print("DueDate:",duedate) checkstatus=maintanance_table.objects.filter(user_email=abc).filter(maintanance_status="PAID").order_by('maintanance_todate').reverse() if checkstatus: lastdate = lastdate + timedelta(days=180) new_date = lastdate.strftime('%Y-%m-%d') else: lastdate=lastdate new_date= lastdate.strftime('%Y-%m-%d') return render(request,"maintenance.html", {'abc':abc,'new_date':new_date}) else: return render(request,"login.html") return render(request,"maintenance.html") -
Django ORM sum prices from 3 level nested
I have these models and managers: class ItemManager(models.Manager): use_for_related_fields = True def get_queryset(self): qs = super().get_queryset() return qs.annotate(total_price=ExpressionWrapper( F('gross_price') * F('qty'), output_field=models.DecimalField()) ) class OrderManager(models.Manager): use_for_related_fields = True def get_queryset(self): qs = super().get_queryset() return qs.annotate(total_price=Sum(items__total_price)) # this doesnt work class Order(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length='50') class Item(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) price = models.DecimalField(max_digits=14, decimal_places=2) qty = models.IntegerField() order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) objects = ItemManager() I want to get Sum price of the order, like this: for sale in Order.objects.all(): print(sale.total_price) Error: django.core.exceptions.FieldError: Unsupported lookup 'total_price' for UUIDField or join on the field not permitted. I can get total_price for each item, and I want to use that total_price to get Sum of all items. I need in this way because I will use that sale total_price in a model that have multiple orders as child elements. -
Deploying django app on shared IIS - Script processor could not be found
I am trying to deploy my django app on a shared aws IIS server. First tried on my local machine following this blog:https://www.youtube.com/watch?v=CpFU16KrJcQ and was able to run successfully. However, I cannot install the dependencies on my server machine using pip as I did for my local IIS. So as a workaround I tried to copy all my project files along with the virtual env and other dependent packages files to my server but it did not work. I get the error <handler> scriptProcessor could not be found in <fastCGI> application configuration I guess this error occurs if IIS is not able to find the python/wfastcgi script, but this is only coming for my copied project directory and not the original one. I have updated the paths in web.config for copied proj directory as well though. Do we need to reinstall all the packages in the virtual environment if we just copy the directory? Or is there any easier way to just replicate a virtual env with all its dependencies installed to a different machine? Here is my project directory structure: project_folder -app1 -app2 -static manage.py -virtual_env_folder -lib -site-packages -scripts activate Many thanks in advance! -
Django filter question - How to delete a single item with the most recent date?
I have 1 db, Master that effectively has a composite primary key, of ID and date, My system allows deletion from this db for some users. What I am trying to do is have them enter an ID, and then it deletes the row with that ID, but only the most recent date. I have tried filtering for the ID, and then chaining the latest method, I have also tried using the order by and selecting the first entry. toDelete = Master.objects.filter(Identifier=id).latest('EffectiveDate') toDelete.delete() This statement, when I call delete, deletes all of the entries in the db which match the ID, I am trying to have it only delete the last one to occur. -
App accessible via port 3000 after deploy to server
I have a django app running in docker containers (please see docker compose and dockerfile below). I have removed port exposure from my docker-compose however when i deploy the code onto an ubuntu server, I can still access the app via port 3000. I am also using nginx to do the proxing (see nginx file below). services: rabbitmq: restart: always image: rabbitmq:3.7 ... db: restart: always image: mongo:4 ... cam_dash: restart: always build: . command: python3 manage.py runserver 0.0.0.0:3000 ... celery: restart: always build: . command: celery -A dashboard worker -l INFO -c 200 ... celery_beat: restart: always build: . command: celery beat -A dashboard -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler ... FROM python:3.7 COPY requirements.txt / RUN pip3 install -r /requirements.txt ADD ./ /dashboard WORKDIR /dashboard COPY ./docker-entrypoint.sh /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh ENTRYPOINT ["/docker-entrypoint.sh"] EXPOSE 3000 server { listen 80 default_server; listen [::]:80 default_server; server_name _; return 301 https://$host$request_uri; root /var/www/html; index index.html; } server { listen 443; server_name camonitor.uct.ac.za; ssl on; ssl_certificate /etc/ssl/certs/wildcard.crt; ssl_certificate_key /etc/ssl/private/wildcard.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; location / { root /var/www/html; index index.html; } location /dash/ { proxy_pass http://127.0.0.1:3000/dash/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; } ... I am expecting that if I … -
Why has this needed folder become a submodule?
I have a folder which has all the main code in it but its been created on Github as a submodule and I don't know how to change it or why it was created that way by Git? Also I'm making new branches and pushing them and every time I do the same "branch" (it seems) is being pushed so the folder is staying the same. git branch new git add . git commit -m "blah" git remote add origin new I take it that this code is wrong to make a completely new branch commit? I've tried numerous ways and seem to be going down a dead end constantly. Is there something wrong with my commits or adds? -
How to get the requested user id from slack workspace via a python app?
I`m creating a slack application. This application creates a separate channel and puts some links inside this channel to view some web pages. Those web pages created from this app. Slack workspace members can click those links and view the web pages. Currently, these pages can access anyone. I want to give access to view web pages only for the slack workspace members. How can I do this? I am going to authorize users by the following logic Get all the workspace members from the slack API. Get the user id of the link clicked user. (How can I do this?) Then check whether is that user in the slack workspace. -
Django Rest Framework: MultipleObjectsReturned
It´s a requirement of the project to start from an existing database. In which there are tables with compound keys. When generating the models from this database, a field was left as the primary key, and a constraint unique with both fields that previously formed the composite key. An example follows: models.py class Preciosventalista(models.Model): idlistaprecio = models.OneToOneField(Listasprecios, models.DO_NOTHING, db_column='idlistaprecio', primary_key=True) idarticu = models.ForeignKey(Articulos, models.DO_NOTHING, db_column='idarticu') porcendescue = models.DecimalField(max_digits=6, decimal_places=2) cohefi = models.DecimalField(max_digits=10, decimal_places=4) precioneto = models.DecimalField(max_digits=10, decimal_places=4) precioventa = models.DecimalField(max_digits=10, decimal_places=2) class Meta: managed = True db_table = 'preciosventalista' unique_together = (('idlistaprecio', 'idarticu'),) serializers.py class ArticulosSerializer(serializers.ModelSerializer): class Meta: model = Articulos fields='__all__' class PreciosVentaListaSerializer(serializers.ModelSerializer): articulo = ArticulosSerializer(source='idarticu', read_only=True) class Meta: model = Preciosventalista fields='__all__' apiviews.py class PreciosVentaListaList(generics.ListCreateAPIView): queryset = Preciosventalista.objects.all() serializer_class = PreciosVentaListaSerializer class PreciosVentaListaDetalle(generics.RetrieveDestroyAPIView): queryset = Preciosventalista.objects.all() serializer_class = PreciosVentaListaSerializer urls.py urlpatterns = [ path('v1/preciosventalista/', PreciosVentaListaList.as_view(), name='preciosventalista_list'), path('v1/preciosventalista/<int:pk>', PreciosVentaListaDetalle.as_view(), name='preciosventalista_detalle') ] The error when calling the service ( /api/v1/preciosventalista/1 ) from postman is: MultipleObjectsReturned at /api/v1/preciosventalista/1 get() returned more than one Preciosventalista -- it returned 75! I couldn´t get my service to return a set of instances or to be able to filter through both fields (idlistaprice, idarticu) to return a single instance. I have tried the following without … -
wkhtmltopdf - Exit with code 1 due to network error: ContentNotFoundError
I am trying to build a PDF file out of the HTML file. When I run the command to convert the HTML file the response was Counting pages (2/6) Resolving links (4/6) Loading headers and footers (5/6) Printing pages (6/6) Done Exit with code 1 due to network error: ContentNotFoundError -
Running both websocket client and server using django
I'm trying to create a Django project that will consume data from an external websocket (django as a websocket client) and when there is update from this external websocket (onMessage()) I will want to publish this data out as a websocket server (using Channels). My question is: Where could I place the websocket-client code within a Django project? Do I need to use like Celery to run the websocket-client as a async task? Kindly please help and point me to a good direction, thanks. -
Error importing devserver module devserver.modules.sql: "cannot import name util"
Just upgraded from django 1.8 to 1.9 and getting this error while migrating: Error importing devserver module devserver.modules.sql: "cannot import name util" Although they say it is fixed it here: https://github.com/dcramer/django-devserver/issues/131 [localhost] local: python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 324, in execute django.setup() File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/halit/project_folder./venv/local/lib/python2.7/site-packages/devserver/models.py", line 40, in <module> load_modules() File "/home/halit/project_folder/.venv/local/lib/python2.7/site-packages/devserver/models.py", line 25, in load_modules raise exceptions.ImproperlyConfigured, 'Error importing devserver module %s: "%s"' % (name, e) django.core.exceptions.ImproperlyConfigured: Error importing devserver module devserver.modules.sql: "cannot import name util" Fatal error: local() encountered an error (return code 1) while executing 'python manage.py migrate' Aborting. -
JQuery: Retrieve the input value by its name, which is within a div with an id
I'm trying to get the input value as the user types into the text field, using the div's id="search" and the name="vehicle" within the div. What I have currently done returns search_text as an empty string. I've simplified the code into help prove my issue: HTML <div id="search"> <input type="text" name="vehicle"> </div> JQUERY $(document).ready( function(){ $('#search').keyup(function() { $.ajax({ type: "POST", url: "http://localhost:8000/overview", data: { 'search_text': $('#search).Children("input[name=vehicle]") }, success: searchSuccess, dataType: 'html' }); }); }); function searchSuccess(data, textStatus, jqXHR) { $('#search-results').html(data); } I've tried the following: 'search_text': $('#search input") and 'search_text': $('#search).Children("input[name=vehicle]") Thanks -
ValueError at /register: The given username must be set
ValueError at /register/ The given username must be set Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 1.11.4 Exception Type: ValueError Exception Value: The given username must be set here's the views.py def register_page(request): form = RegisterForm(request.POST or None) context = { "form": form } if form.is_valid(): print(form.cleaned_data) username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = User.objects.create_user(username,email,password) print(username) return render(request, "auth/register.html", context) This is sending None as a username and i dont know why? user = User.objects.create_user(username,email,password) How to resolve this issue? It is not getting the username with POST method or there is some other mistake? -
Python3/Django. Separate project directory from environment directory
Is it possible to have django projects(python3) directory outside of the environment directory? e.g I want to have my projects under /Users/me/Documents/dev/myDjangoProject and environment under /Users/me/Documents/env/myCustomEnvironment and somehow link them together. Thanks in advance -
Deploy different version of django application in same server
I'm using Apache & mod_wsgi to deploy a django application on my server. I am using Daemon mode of wsgi for running django application on server. Now my goal is that I can have two or more version of my django application on the same server (with each its own settings, databases, etc). For example: https://test-server.com/ https://test-server.com/dev I have updated apache configuration file located at /etc/apache2/sites-available. Here is my config file:- <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin xyz@gmail.com ServerName test-server.com ServerAlias www.test-server.com #DocumentRoot /var/www/html Alias /static /var/www/html/Smart_chat_share/smart_chat_share/static // This should accesible via https://test-server.com/ which is working <Directory /var/www/html/Smart_chat_share/smart_chat_share/static> Require all granted </Directory> WSGIDaemonProcess smart_chat_share python-home=/var/www/html/Smart_chat_share/smart_chat_share/virtual_env python-path=/var/www/html/Smart_chat_share/smart_chat_share WSGIProcessGroup smart_chat_share WSGIScriptAlias / /var/www/html/Smart_chat_share/smart_chat_share/smart_chat_share/wsgi.py process-group=smart_chat_share application-group=%{GLOBAL} <Directory /var/www/html/Smart_chat_share/smart_chat_share/smart_chat_share> <Files wsgi.py> Require all granted </Files> </Directory> Alias /dev/static /var/www/html/dev/smart_chat_share/static // This should accesible via https://test-server.com/dev which is not working. <Directory /var/www/html/dev/smart_chat_share/static> Require all granted </Directory> WSGIDaemonProcess dev python-home=/var/www/html/dev/smart_chat_share/virtual_env python-path=/var/www/html/dev/smart_chat_share WSGIProcessGroup dev WSGIScriptAlias /dev /var/www/html/dev/smart_chat_share/smart_chat_share/wsgi.py process-group=smart_chat_share application-group=%{GLOBAL} <Directory /var/www/html/dev/smart_chat_share/smart_chat_share> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLCertificateFile /etc/letsencrypt/live/scss.identixweb.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/scss.identixweb.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> https://test-server.com/ this is working version but https://test-server.com/dev this second version i am not able to access and test.I'm often lost when it comes to Apache configuration. Your …