Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Datepicker covers the input field within a modal
The datepicker element is not created correctly within a modal, it covers the input field and I can not visualize the data html: <div id="datepicker" class="input-append date col-md-12" > <input type="text" class="form-control"> <span class="add-on"> <span class="arrow"></span> <i class="fa fa-th"></i> </span> </div> js: <script src="{% static 'assets/plugins/bootstrapv3/js/bootstrap.min.js' %}" type="text/javascript"></script> $("#datepicker").datepicker({ format: "dd/mm/yyyy", startDate: "01-01-2015", endDate: "01-01-2020", todayBtn: "linked", autoclose: true, todayHighlight: true, container: '#myModal modal-body', zIndex: 2048, }); -
Difference between named urls in Django?
What is the difference between these two named urls in Django? re_path('articles/(?P<year>[0-9]{4})/', views.year_archive), path('articles/<int:year>/', views.year_archive), They appear to do the same? -
Django - getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
I am learning django framework from last 4 days. Today I was trying to retrieve a URL in HTML template by using {% url "music:fav" %} where I set the namespace in music/urls.py as app_name= "music" and also I have a function named fav(). Here is the codes: music/urls.py from django.urls import path from . import views app_name = 'music' urlpatterns = [ path("", views.index, name="index"), path("<album_id>/", views.detail, name="detail"), path("<album_id>/fav/", views.fav, name="fav"), ] music/views.py def fav(request): song = Song.objects.get(id=1) song.is_favorite = True return render(request, "detail.html") in detail.html I used {% url 'music:detail' %} But I dont know why this is showing this error: NoReverseMatch at /music/1/ Reverse for 'detail' with no arguments not found. 1 pattern(s) tried: ['music\/(?P[^/]+)\/$'] -
How to pass a date (year) parameter to my url?
This is a huge rookie mistake but I can't figure it out. This is what I wanna do: I have a page displaying a list a years where an objects is available. I want that, when I click on a year, it takes me to the corresponding YearArchiveView. I just don't succeed in passing the right parameter to the URL. Passing a template tag obviously doesnt work so what is the right way to do it ? I get this error: TemplateSyntaxError at /receipts/ Could not parse some characters: |{{y||date:"Y"}} My template: <ul> {% for y in years_available %} <li><a href="{% url 'receipt_year_archive' year={{y|date:"Y"}} %}">{{y|date:"Y"}}</a></li> {% empty %} <p>No Receipt Yet</p> {% endfor %} </ul> My view: class ReceiptListView(LoginRequiredMixin, ListView): model = Receipt template_name = 'receipts.html' def get_queryset(self): queryset = Receipt.objects.dates('date_created','year',order="DESC") return queryset def get_context_data(self, *args, **kwargs): context = super(ReceiptListView, self).get_context_data(**kwargs) context['years_available'] = Receipt.objects.dates('date_created', 'year', order="DESC") return context My urls.py: url(r'receipts/(?P<year>[0-9]{4}/$)',views.ReceiptYearArchiveView.as_view(), name='receipt_year_archive'), -
How to use Django Rest API in Django normal project for autocomplete using Select2?
In my project, I have a model named Product. The model consists of products which have following entities: name, id, price .... and so on. In my project, an admin can add a new/old product anytime. Now, for searching, I want to add autocomplete. I want to use Select2. So users don't have to memorize the name of the products. To do that I found out here in the Select2 doc that : Select2 comes with AJAX support built in, using jQuery's AJAX methods With this, I can search an API and fetch the data to show the users in autocomplete search field. My Question: Should I create a Django rest API and use that API to store products and fetch the data? 1.1 Would it be wise? 1.2 Is it possible to make a rest API within a normal Django project? If not then how to do that? Or should I just use a normal urls.py and querying the result from Select2 ajax function to that urls.py and to a custom query.py and fetch the data directly from the database? -
Searching for django_celery_beat alternative
I wasted a lot of time trying to install django_celery_beat with no results, with the following error: error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2 I'm searching for an alternative: package or do it myself if is not very complex and if I have a tutorial/start code. -
Django ForeignKey and OneToOneField query speed
I've seen this : https://groups.google.com/forum/#!topic/django-users/VEDZtuND2XM But on that answer, Ronaldo said just about convenience not the speed of query speed. Is there speed or performance difference between ForeignKey(unique=true) and OneToOneField? Or is there any other advantages on using OneToOneField than ForeignKey(unique=true) ? -
where to check for conditions in generic UpdateView in Django
I'm using Django 2.0 I have a model Note and using generic update view to update the note object. The URL configuration is like app_name = 'notes' urlpatterns = [ path('<int:pk>/', NoteUpdate.as_view(), name='update'), ] which is accessbile via it's namespace setup in app.urls /notes/<pk> I want to make some condition check in the view before loading the view or saving updated value. Since, a note can be shared with any user and there is single template to view and update the note. I want to check for whether the user is owner of the note or whether the note has been shared with the user and has write permission granted. class NoteUpdate(UpdateView): template_name = 'notes/new_note.html' model = Note fields = ['title', 'content', 'tags'] def get_context_data(self, **kwargs): context = super(NoteUpdate, self).get_context_data(**kwargs) """ check if note is shared or is owned by user """ note = Note.objects.get(pk=kwargs['pk']) if note and note.user is self.request.user: shared = False else: shared_note = Shared.objects.filter(user=self.request.user, note=note).first() if shared_note is not None: shared = True else: raise Http404 context['note_shared'] = shared_note context['shared'] = shared return context @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): return super(self.__class__, self).dispatch(request, *args, **kwargs) This is what I tried in get_context_data() but it is giving … -
After set Setting Cache Headers in NGINX, (django) all images disappeared, how to solve?
this is my cahe settings, when i delete this lines, image come back, if i set this, images are disappeared, help someone!) location ~* \.(?:jpg|css|js|html|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc)$ { expires 365d; access_log off; add_header Cache-Control "public"; } -
limit choices in drop downs in django rest browsable api
Is there a way to limit what fields are populated (such as in dropdown selectors or list selectors) in the DRF browsable API? It would be really useful if there was a way to link the objects populated in these fields to be set according to a get_queryset() function. This page seems to hint that it might be possible, I just can't find an example of how to do it: http://www.django-rest-framework.org/api-guide/filtering/ -
when i gave command "python manage.py startapp foodblog" does not work and give the error.Please share solution. Thank in advanced
enter image description hereError screenshot is showed below -
How to setup a simple Open EDX site in Django?
Hello I have searched for this, and found no answer. I recently downloaded: https://github.com/edx/edx-platform I want to setup django to use it. But I found no docs. What I found is this Bitnany Installer: https://bitnami.com/stack/edx +1 Gb And the docs does not appear to exits: https://openedx.atlassian.net/wiki/display/OpenOPS/Open+edX+Installation+Options But is there a simple way I can setup Opem EDX; without 1 Gb download, which I can not aford right now? Thank you in advance. Rodolfo -
Get status of all objects of model
models.py class Room(models.Model): # Default all rooms are Free number = models.ForeignKey(RoomNumber) class Reserved(models.Model): visitor = models.ForeignKey(Visitor, on_delete=models.PROTECT) room = models.OneToOneField(Room) reserved_date = models.DateTimeField() begin_date = models.DateTimeField() end_date = models.DateTimeField() How to get status of all Rooms in a List. In status of all rooms are in : Reserved Free Rooms Busy Rooms I myself tried to do this: ListView reserved = Reserved.objects\ .filter(room=OuterRef('pk'))\ .filter(begin_date=timezone.now())\ .values(count=Count('pk')) Room.objects.annotate(reserved=Subquery(reserved[:1])) but no result :( And how to get in template status of rooms? Through if else condition? Thanks you all in advance -
What should I learn to build a website that receives a file from user?
I am new to web design and I need to know what topics I should learn in order to build a website that receives a file from user, processes it and gives an output in a different page. I use python, so it would be nice if this was possible using Django. I would appreciate if someone guided me. -
relation does not exist(postgresql, django)
I'm using django with postgresql. But when I run the app, I get the following error: relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... I searched for this error, but the only situation people talked about was when the name of the table had mixed case characters. But the table name in my case is all in small letters so this shouldn't happen. What is wrong here? Thanks p.s. This is the project I'm working with. https://github.com/mirumee/saleor -
Deploying Web Application built with django(DRF) and Vue(Frontend) in aws
How to deploy an web application with Separate Frontend(Vue) and Backend(Django-DRF) Servers in AWS ? -
'ascii' codec can't encode... while uploading csv file
I've got class for uploading my csv files with holidays to my fullcalendar. It looks like this: class UploadVacationsView(APIView): def put(self, request, *args, **kwargs): try: # check file type mime = MimeTypes() url = urllib.pathname2url(request.FILES['file']._name) mime_type = mime.guess_type(url) if 'text/csv' not in mime_type: raise APIException(code=400, detail='File type must be CSV') vacations_list =[] csv_file = StringIO(request.data.get('file', None).read().decode('utf-8')) user_tz = pytz.timezone(request.user.common_settings.time_zone) schedule_file = ScheduleFile.objects.create(user=request.user) instance_hebcal = HebcalService() events = instance_hebcal.process_csv(csv_file, user_tz) And in the other class HebcalService, I've got a method that works with csv files: def process_csv(self, csv_file, user_tz): events = [] csv_input = csv.reader(csv_file.readlines(), dialect=csv.excel) curr_row = 1 start_date = None end_date = None start_name = None holiday_name = '' last_event = {'subject': '', 'date': '', } for row in list(csv_input)[1:]: subject, date, time, _, _, _, _ = row[:7] curr_row += 1 row = [unicode(cell.strip(), 'utf-8') for cell in row] if 'lighting' in subject and not start_date: start_date = user_tz.localize(format_datetime(date, time)) if date == last_event['date']: start_name = last_event['subject'] Everything is ok when working with english holiday's names but when I encounter hebrew names it shots an error: Traceback (most recent call last): File "/home/stas/work/vacation/vmode/apps/marketplaces/base/api/views.py", line 47, in put events = instance_hebcal.process_csv(csv_file, user_tz) File "/home/stas/work/vacation/vmode/apps/marketplaces/base/services/hebcal.py", line 106, in process_csv for … -
bootstrap link is not correct
My web site is not set bootstrap design correctly.I wrote in index.html, <html lang="ja"> <head> <meta charset="utf-8"> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="/static/index.css"> <link rel="stylesheet" href="/static/bootflat/css/bootflat.min.css"> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> </head> ・ ・ in settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'bootflat.github.io'), ] When I click href="/static/css/bootstrap.min.css",404 error happens. Directory structure is like -PythonServer -PythonServer -logic -static -index.css -templates -index.html -boolflat.github.io -bower_components I think I set STATIC_URL correctly so I do not know why bootstrap design is not set.What is wrong in my code?How should I fix this? -
('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'app_poll'. (208) (SQLExecDirectW)")
I am getting following while running python django app(using python-odbc-azure lib) on azure web app. ProgrammingError at / ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'app_poll'. (208) (SQLExecDirectW)") Method: GET Request URL: http://retailgenieredsky.azurewebsites.net/ Django Version: 1.11 Exception Type: ProgrammingError Exception Value: ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'app_poll'. (208) (SQLExecDirectW)") Exception Location: D:\home\python354x64\lib\site- packages\sql_server\pyodbc\base.py in execute, line 545 Python Executable: D:\home\python354x64\python.exe Python Version: 3.5.4 Python Path: ['.', 'D:\\home\\python354x64\\python35.zip', 'D:\\home\\python354x64\\DLLs', 'D:\\home\\python354x64\\lib', 'D:\\home\\python354x64', 'D:\\home\\python354x64\\lib\\site-packages', 'D:\\home\\site\\wwwroot'] Server time: Fri, 22 Dec 2017 13:10:47 +0000 Error during template rendering In template D:\home\site\wwwroot\app\templates\app\layout.html, error at line 5 42S02 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8" /> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>{{ title }} - Django Polls</title> 7 {% load staticfiles %} 8 <link rel="stylesheet" type="text/css" href="{% static 'app/content/bootstrap.min.css' %}" /> 9 <link rel="stylesheet" type="text/css" href="{% static 'app/content/site.css' %}" /> 10 <script src="{% static 'app/scripts/modernizr-2.6.2.js' %}"></script> 11 </head> 12 13 <body> 14 <div class="navbar navbar-inverse navbar-fixed-top"> 15 <div class="container"> I tried following ways. 1. Remove 5 But it given same error for next line. I tried to remove layout.html its still give same error This is deeper level of exception. chunked_fetch False … -
Django server not making changes to CSS
I'm pretty new to Django. I started an app, made template and static directories, add them to the project settings and ran the server by following this tutorial. Then I wanted to change some settings in my CSS file so I modified some lines. But when I ran the python manage.py runserver again(I ran on Windows), the changes did not take effect. The initial code of CSS is: body { position: relative; padding-bottom: 10px; min-height: 100%; background: #f7f7f7; } I changed the padding resulting like this: body { position: relative; padding-bottom: 50px; min-height: 100%; background: #f7f7f7; } When I ran the django server again, the new code was not taking effect. I checked the code with Chrome Dev Tools and found out the padding value was still 10px. I've been running the server again and again but with no change. Is there something I am missing with the settings? -
Show Django template with a camera stream
I'm trying to build a simple website in Python with Django. I want to load and show a template, and then show, on top of the template's background, the images acquired from the webcam for few seconds. Finally, the last image is saved on hard disk. The problem is that the template is loaded and showed only after the camera code finishes. This is the code: from django.shortcuts import render def takePicture(request): l = render(request,'pepper/picture.html') camstream() return l camstream() is the method that activates the stream from the camera, and it works as expected. It uses pygame, following this tutorial. Any suggestion? -
Django 1.9.2: Remove field from model very long
I have more than 2 million objects for the model. When I added a new field, the migration went fast I created another migration where I delete 4 fields - migration hangs for several hours How can I speed up the process? Does it depend on the number of objects? My migration for delete: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('multisession', '0008_add'), ] operations = [ migrations.RemoveField( model_name='mymodel', name='field1', ), migrations.RemoveField( model_name='mymodel', name='field2', ), migrations.RemoveField( model_name='mymodel', name='field3', ), migrations.RemoveField( model_name='mymodel', name='field4', ), ] -
Python decode unknown character
I'm trying to decode the following: UKLTD� For into utf-8 (or anything really) but I cannot workout how to do it and keep getting errors like 'ascii' codec can't decode byte 0xae in position 8: ordinal not in range(128) I'm reading from a csv and have the following: with open(path_to_file, 'rb') as f: reader = csv.reader(f) for row in reader: order = Order( ... product_name = row[11].encode('utf-8'), ... ) order.save() I would be happy right now to just ignore the character if I have keep the rest of the string. -
Django with nginx and gunicorn
I have deployed django with gunicorn and nginx, and it works fine, if the django app is served on the root url, with this configuration: server { listen 80; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:my_app.sock; } } However when I try to serve the django app on another url, it doesn't work. If I try to access http://domain/my_app/admin/ django tells me it cannot find the view. This is nginx config: server { listen 80; location = /favicon.ico { access_log off; log_not_found off; } location /my_app { include proxy_params; proxy_pass http://unix:/var/my_app/app.sock; } } How could I make this work? I was not able to find any solution to specify something like a "BASE_URL" so far. Thanks -
How should I add django import export on the User Model
I am trying to enable django import export on the django user model. I have tried defining a model admin class, unregistering the user model and then registering the new user admin class. But it doesn't work. my admin.py looks like this - from django.contrib.auth.admin import UserAdmin as BaseAdmin class UserResource(resources.ModelResource): model = User fields = ('first_name', 'last_name', 'email') class UserAdmin(BaseAdmin, ImportExportModelAdmin): resource_class = UserResource admin.site.unregister(User) admin.site.register(User, UserAdmin) I want to know how can I achieve this? Is there some other way I can apply django import export on the user model?