Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Nginx failing to load this diango/wagtail uwsgi socket?
I have created a virtual environment and installed wagtail as per these instructions. http://docs.wagtail.io/en/v1.9/getting_started/tutorial.html The server is setup to use uwsgi to connect to an existing application, so i would like to connect to the wagtail app in similar fashion (using uwsgi) The current Nginx config that handles the main traffic for the site (and passes it to a uwsgi socket) looks like this: - server { listen x.xx.xxx.xxx:80; server_name example.com www.example.com; access_log /var/customers/logs/webmaster-access.log combined; error_log /var/customers/logs/webmaster-error.log error; root /var/customers/webs/webmaster/; location / { uwsgi_pass unix:///opt/app/core.sock; include uwsgi_params; uwsgi_param UWSGI_SCHEME $scheme; uwsgi_param SERVER_SOFTWARE nginx/$nginx_version; } ... } This setup is working fine, for the existing non wagtail app. I have amended the entries above like so: server { listen x.xx.xxx.xxx:80; server_name example.com www.example.com; access_log /var/customers/logs/webmaster-access.log combined; error_log /var/customers/logs/webmaster-error.log error; root /var/customers/webs/webmaster/; location / { uwsgi_pass unix:///opt/rocker/core.sock; include uwsgi_params; uwsgi_param UWSGI_SCHEME $scheme; uwsgi_param SERVER_SOFTWARE nginx/$nginx_version; } ... } Simply changing the location of the socket to point to the wagtail app (which is in /opt/rocker/core.sock) instead of the existing socket. The Uwsgi log says everything is starting ok: *** Starting uWSGI 2.0.11.2 (64bit) on [Mon Mar 27 13:00:24 2017] *** compiled with version: 4.7.2 on 16 December 2015 01:49:08 os: Linux-3.2.0-4-amd64 #1 … -
Linking Django project to existing MySQL database in EC2 instance
So I've created an android app who's backend is stored in a AWS EC2 instance. I am now creating a website using Django and I would like them to share the same database, is this possible, if so how? I've been looking for the whole day and can't seem to find a solution, I've looked into deploying a Django application on AWS and it seems like I have to use Elastic Beanstalk which creates another EC2 instance and there doesn't seem to be a way to link it to my existing one. Any help would be greatly appreciated. Thank you -
CharField choice show human-readable value
I have little problem. I have models like Project and Member. Every project has members. In template I want to show user and his role in a specific project. It works but it shows me the number of role. I want to show human-readable value as "Business Analyst" e.t.c. How can I take that values? models.py: class Project(models.Model): members = models.ManyToManyField(User, through='Member', help_text=_('Members')) class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) role = models.CharField(max_length=20, choices=ROLE_CHOICES) ROLE_CHOICES = ( ('1', _('Manager')), ('2', _('Developer')), ('3', _('Business Analyst')), ('4', _('System Analyst')), ) template: {% for member in project.member_set.all %} <tr> <td class="text-center">{{ member.user }}</td> <-- Example: Mark <td class="text-center">{{ member.role }}</td> <-- Example: 3 but I need Business Analyst </tr> {% endfor %} -
module 'django.db.models' has no attribute 'Foreignkey'
I am new to Django and I just started learning it using Djaango by example but I am getting error messages. Here is my Traceback C:\Users\Harsley\shop>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 328, in execute django.setup() File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Harsley\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "C:\Users\Harsley\shop\shops\models.py", line 16, in <module> class Product(models.Model): File "C:\Users\Harsley\shop\shops\models.py", line 17, in Product category = models.Foreignkey(Category,related_name='products') AttributeError: module 'django.db.models' has no attribute 'Foreignkey' This is the model file and I have gone through it and it seems that I did not make any error. i from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique = True) class Meta: ordering … -
"prefetch_related" working on only side of One-Many relationship
I have two models with one-many relationship (Organization hasMany Locations) class Organizations(models.Model): name = models.CharField(max_length=40) class Location(models.Model): name = models.CharField(max_length=50) organization = models.ForeignKey(Organizations, to_field="name", db_column="organization_name", related_name='locations') class Meta: db_table = u'locations' Now, while trying to pre-fetch locations while retrieving "Organizations" I am getting this error. Organizations.objects.select_related('locations') FieldError: Invalid field name(s) given in select_related: 'locations'. Choices are: (none) However, if I preload the other way around it works fine. Location.objects.select_related('organization') Note: After pre-loading organizations from location model, the previous error does not occur anymore. I am using Django version: 1.8.6 -
Maintaining static files
In my django framework I collect user input from a form and create a matplotlib image. This image is displayed after a button push in a tagged field in an html file. After each button push this image is updated, changes and is newly displayed. This works well. Now I intend to introduce a second image at a second tag, that shows up and changes after pressing a different button. The problem that I have, is that after pushing the second button, the first image disappears and after pushing the first button, the second button disappears. Here is part of the html code: <form method=post action=""> {% csrf_token %} <table> {% for field in form %} <tr> <td>{{ field.label }}</td> <td>{{ field }}</td> <td></td> </tr> {% endfor %} </table> <br> <p><input type=submit name='button1' value='Create' class="btn btn-default" ></form></p> <p> {% if result != None %} {% load static %} <img src="{% get_static_prefix %}{{ result }}" width=1000> {% endif %} </p> <form method="post" class="topright"> {{form3}} {% csrf_token %} <p><input type=submit name='button2' value='Update' class="btn btn-default" default=1 ></p> </form> <form method=post action=""> {% csrf_token %} <table> {% for field in form4 %} <tr> <td>{{ field.label }}</td> <td>{{ field }}</td> <td></td> </tr> {% endfor %} … -
Can any one give me a clear breakdown on how to integrate Elm with an existing Django app?
I have an existing Django app that currently uses vanilla js, Ajax, and Jquery. I am looking to slowly moving our front-end over to the Elm programming language and the Elm architecture but there isn't any guidance on this topic. Is there anyone out there that can provide a brief walkthrough, what to watch out for, or at least where to start. Any help would be much appreciated. Thanks -
{{ form.empty_form }} __prefix__ not being replaced by django-dynamic-formset
I'm struggling with django-select2 and django-dynamic-formset, I'm following the examples given in django-dynamic-formset-select2-poc and works for one of my forms but not with the following code. I did some debugging and find that the '__prefix__' generated by the {{form.empty_form}} is not being replaced. below is a copy of my code. views.py def temp2(request): context_dict = {"user": request.user} expeseFormset = get_expenseproduct_formset(ExpenseProductForm, extra=1, can_delete=True) context_dict['formset'] = expeseFormset() return render(request, 'temp2.html', context_dict) models.py class ExpenseBill(models.Model): id = models.AutoField(primary_key=True) description = models.CharField(max_length=96) type = models.ForeignKey(to=ExpenseType) total = models.PositiveIntegerField(null=True) purchase_date = models.DateField(null=False) date_created = models.DateField(auto_now_add=True) class Expenses(models.Model): id = models.AutoField(primary_key=True) expense_description = models.CharField(max_length=96, null=True, blank=True) item = models.ForeignKey('Item', null=True, blank=True) unit = models.PositiveIntegerField() unit_price = models.PositiveIntegerField(blank=True,null=True) qty = models.PositiveIntegerField() subtotal = models.PositiveIntegerField() expense_bill = models.ForeignKey("ExpenseBill") date_created = models.DateField(auto_now_add=True) forms.py def get_expenseproduct_formset(form, formset=models.BaseInlineFormSet, **kwargs): return models.inlineformset_factory(ExpenseBill, Expenses, form, formset, **kwargs) class ItemWidget(ModelSelect2Widget): search_fields = ['item__icontains',] class ExpenseProductForm(forms.ModelForm): class Meta: model = Expenses fields = ['item', 'unit', 'unit_price', 'qty', 'subtotal'] widgets ={ # 'qty': Select(attrs={'class': 'form-control'}), 'item':ItemWidget(attrs={'class': 'full-width'}), } labels = { 'item':'Producto', 'qty': 'Cantidad', } temp2.html {{ formset.media.css }} <style type="text/css"> select { width: 200px; } </style><form method="post" action="{% url 'dashboard_add_expense_products'%}" novalidate> {% csrf_token %} <input type="hidden" name="type" id="type" value="{{ type }}"> <div class="box-body"> <div class="row"> … -
How to pass dictionary and image through ajax to views.py in Django
Hello I'm sorry because Im new to using django. I'm currently using ajax to send files to my views.py. My dilemma is I need to pass both a dictionary and a formData containing 2 images. How do I pass this to my view, and how do I access the images and the dictionary in my views.py? pls help The concepts I know so far to transfer data are ajax and FormData. As much as possible I'd like to keep using them for the solution jQuery and Ajax const form = new FormData(); form.append('tradeimage', extractPhoto(tradeimage)); form.append('receiveimage', extractPhoto(receiveimage)); data = { 'tradename': tradename, 'receivename': receivename, 'description': description }; generateCSRFToken(); $.ajax({ url: '/submit_post/', data: form, type: "POST", contentType: false, processData: false, success: function (data) { console.log("success") }, error: function (data) { console.log("somethings wrong with form") } }); views.py def submit_post(request): if request.method != 'POST': return redirect('/marketplace') post = Post() if 'tradeimage' and 'receiveimage' in request.FILES: post.author = request.user post.trade_item = request.FILES.get('tradeimage') post.receive_item = request.FILES.get('tradeimage') #HOW DO I GET DATA FROM DICTIONARY? -
Django getting all options values with SelectMultiple widget
When using SelectMultiple widget, selecting various or all options then deselecting a few I'm still getting all options selected initially and not only the checked ones. I tried with MultiSelectField and simply Charfield with no success. [Django 1.9 - Python 3.4.3] This is the code I'm using: models.py class OfferSeguro(models.Model): user = models.ForeignKey(User) tipo_seguros = MultiSelectField(choices=seguros.TIPO_SEGUROS) preferencias_seguros = models.CharField(max_length=150, default='') views.py def StepOneLanding(request, category_url_name): category = Category.objects.get(url_category_name=category_url_name) ... user_register = UserRegisterForm() seg_form = SegurosStep2Form() if request.method == "POST": if 'register_form' in request.POST: user_register = UserRegisterForm(request.POST) seg_form = SegurosStep2Form(request.POST) if user_register.is_valid() and seg_form.is_valid(): f = seg_form.save(commit=False) user_register.save(commit=False) User.objects.create_user( # various user_register.cleaned_data... ) user_create = authenticate( username=Username_Random, password=Password_Random) login(request, user_create) f.user = user_create f.tipo_seguros = seg_form.cleaned_data['tipo_seguros'] preferencias_seguros = dict(request.POST) count_seguros = len(preferencias_seguros['preferencias_seguros']) preferencias_seguros2 = '' for x in range(count_seguros): preferencias_seguros2 = preferencias_seguros2 + preferencias_seguros['preferencias_seguros'][x] + ',' f.preferencias_seguros = preferencias_seguros2 f.detalle = seg_form.cleaned_data['detalle'] f.save() forms.py class SegurosStep2Form(forms.ModelForm): preferencias_seguros = forms.MultipleChoiceField( choices=seguros.TIPO_SEGUROS, widget=forms.SelectMultiple(attrs={'required': 'True', 'class': 'validate', 'placerholder': ''})) class Meta: model = OfferSeguro fields = ( 'tipo_seguros', 'detalle', ) widgets = { 'tipo_seguros': forms.SelectMultiple(attrs={ 'required': 'True', 'placerholder': '' }), 'detalle': forms.Textarea(attrs={ 'class': 'validate materialize-textarea', 'required': 'True', }), } HTML <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} <div class="row input-field col s12 m12 s12"> {{ seg_form.tipo_seguros}} … -
how to serialize Chinese words with serializers.serialize in Django
I tried with the mentioned method to serialize some data to json. serializers.serialize('json', tbl_xxx.objects.all(), ensure_ascii=False). However, all Chinese words in the json are like '????'. May I know how to fix this? or I need to add something in the js code? -
NoReverseMatch at / Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I can access the admin area of the website but i cant get to homepage and other front end pages..following error pops up... Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.10.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Exception Location: C:\Python34\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 392 Python Executable: C:\Python34\python.exe Python Version: 3.4.4 Python Path: ['C:\\Users\\AAKANKSHA\\Desktop\\Bus_reservation\\src', 'C:\\WINDOWS\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages'] Error during template rendering In template C:\Users\DEEP\Desktop\Bus_reservation\src\templates\bus_resrv_system.html, error at line 49 Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] 39 40 <a name="about"></a> 41 <div class="content-section-a"> 42 43 <div class="container"> 44 <div class="row"> 45 <div class="col-lg-5 col-sm-6"> 46 <hr class="section-heading-spacer"> 47 <div class="clearfix"></div> 48 <h2 class="section-heading">Online ticket booking system:<br>No 'Line' on Online</h2> 49 <p class="lead">Bus Reservation System is designed to automate the online ticket purchasing through an easy online bus booking system.With the bus ticket reservation system you can manage reservations, clients data and passengers lists.</p> 50 </div> 51 <div class="col-lg-5 col-lg-offset-2 col-sm-6"> 52 <img class="img-responsive" src="{% static 'images/booking_page/abtus2.jpg' %}" alt=""> 53 </div> 54 </div> 55 56 </div> 57 <!-- /.container --> 58 59 </div> Here is TRACEBACK … -
Why are changes not getting saved to database table when editing objects using django modelform?
This is my first django app, and I am working with a modelform to update existing records in a table. I have been doing some testing and have not had any issues adding new records, but when it comes to editing existing records, my form seems to behave as expected (I get no errors), but the changes do not get saved. What am I missing? I've been struggling with this for a few days, any help would be most appreciated. models.py: class Mapindex(models.Model): COUNTY_CHOICES = ( ('ALA', 'Alameda'), ('CC', 'Contra Costa'), ('MRN', 'Marin'), ('NAP', 'Napa'), ('SCL', 'Santa Clara'), ('SF', 'San Francisco'), ('SM', 'San Mateo'), ('SOL', 'Solano'), ('SON', 'Sonoma'), ) ROUTE_CHOICES = ( ('1', '1'), ('4', '4'), ('8', '8'), ('9', '9'), ('12', '12'), ('13', '13'), ('14', '14'), ('17', '17'), ('21', '21'), ('24', '24'), ('25', '25'), ('29', '29'), ('32', '32'), ('35', '35'), ('37', '37'), ('49', '49'), ('52', '52'), ('61', '61'), ('77', '77'), ('80', '80'), ('82', '82'), ('84', '84'), ('85', '85'), ('87', '87'), ('92', '92'), ('93', '93'), ('100', '100'), ('101', '101'), ('102', '102'), ('104', '104'), ('112', '112'), ('113', '113'), ('114', '114'), ('116', '116'), ('117', '117'), ('121', '121'), ('123', '123'), ('128', '128'), ('130', '130'), ('131', '131'), ('141', '141'), ('152', '152'), ('156', '156'), ('160', '160'), … -
Django & nginx & uwsgi can not connect
it's my nginx.conf # nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///home/user/djangosite/project/project.sock; # server 127.0.0.1:8001; # for a web port socket } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name .example.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /home/user/djangosite/project/media; # your Django project's media files - amend as required } location /static { alias /home/user/djangosite/project/static; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/user/djangosite/project/uwsgi_params; # the uwsgi_params file you installed } } and it's my uwsgi.ini # introduction_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /home/user/djangosite/project # Django's wsgi file module = introduction.wsgi # the virtualenv (full path) home = /home/user/djangosite/django_virtual # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket … -
'**' is not a registered namespace
I am getting this error only in this specific app in django i am not getting why 1st url.py from django.conf.urls import url , include from . import views from Events import urls app_name = "Programme_Officer" urlpatterns=[ url(r'^$', view=views.index , name="index"), url(r'^logout/$', view=views.logout, name="logout"), url(r'^events/', include('Events.urls')), ] 2nd url.py from django.conf.urls import url , include from . import views app_name = "NS_Events" urlpatterns=[ url(r'^$',view=views.index,name='index'), url(r'bloodDonation/',view=views.bloodDonation , name='bloodDonation'), ] the form which is triggering error of 'NS_Events' is not a registered namespace template.html <form action="{% url 'NS_Events:index' %}" method="post"> when i replace action="{% url 'Programme_Officer:index' %}" it totally works. Why is this so ? -
Django - Checking datetime in an 'if' statement
I have a model very imaginatively called 'model' which has a field 'datefinish' in it; users can input a date here in the format MM/DD/YYYY. In my template I need some text displayed when said model has a datefinish (date) that is equal to the current day. HTML: {% if model.datefinish == datetime.today %} <h5>It ends today</h5> {% else %} <h5>It does not end today</h5> {% endif %} How might one achieve this? I'm using Django 1.10...thanks! -
Add checkbox objects to ListView in Django
I'd like to update a status for some objects at onece. As the following questions and answer said that I can add a checkbox for ListView, but when I submit the form to update, it shows the "Generic detail view ChiamataUpdateView must be called with either an object pk or a slug." error. error. Update selected objects from ListView in Django Could you tell me how to write the UpdateView please ? class ChiamataUpdateView(LoginRequiredMixin, UpdateView): model = Chiamata fileds = '__all__' template_name = "iija/daily_maintain/edit_form.html" success_url = "/" -
Hosting Django server on FTP space
I have built a Django project which I'd like to deploy now. I've already tried deploying it on pythonAnywhere which worked. But, my college wants to host it on their server and they have given me some server space and FTP credentials to upload files there. How can I get my Django website on to my college's server and host it from there? -
Models not visiable for stuff
I've added a Model to admin page with admin.site.register but it's being displayed only if superuser logs in. Even if i give all permissions to a stuff user the model does not show up there even though Groups and Users model does. How do i set this right? -
How to get Uwsgi working with wagtail (django)
I am trying to get up to speed with wagtail. I am running it on a remote server. I have installed a virtual environment, then I switched to the virtual environment and installed wagtail as per the steps here: http://docs.wagtail.io/en/v1.9/getting_started/tutorial.html pip install wagtail wagtail start rocker cd rocker pip install -r requirements.txt python manage.py migrate python manage.py createsuperuser The next step in the guide is to test the installation has worked by running: python manage.py runserver I can't do this as working with a remote server, and also there is already a Django app running on the server (using uwsgi). So I am now trying to connect to this wagtail app, via uwsgi. Using the string that starts the existing app as a template, I have modified it to bind a socket to the wagtail app: - uwsgi --chdir=/opt/rocker/rocker --module=rocker.wsgi:application --env DJANGO_SETTINGS_MODULE=rocker.settings --master --pidfile=/tmp/rocker.pid --socket=/opt/rocker/core.sock --processes=5 --uid=www-data --gid=www-data --harakiri=20 --max-requests=5000 --vacuum --home=/opt/rocker --daemonize=/var/log/uwsgi/rocker.logroot@caspium:/etc/init.d# However the app isn't starting... the error in the uwsgi log says the following: - *** Operational MODE: preforking *** Traceback (most recent call last): File "./rocker/wsgi.py", line 18, in <module> application = get_wsgi_application() File "/opt/rocker/local/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/opt/rocker/local/lib/python2.7/site-packages/django/__init__.py", line 22, in setup … -
Application with ExpressJS,-NodeJS/Django Python & MySQL
We are planning to build a website and hosting it on AWS. It has some data analysis algorithm written in Python. We were confused in what kind of stack should we use.. 1] NodeJS, Python & MySQL/MS SQL/MongoDB 2] Django, Python & MySQl/MS SQL/MongoDB We were interested in speed, level of integration of NodeJS/Django with Python algorithm and a suitable database which is fast in CRUD operations. Any help will be appreciated -
Template not rendering correctly Django
I made a template within Bootstrap studio and it renders exactly how I would like it. However when I transfer it over to the django template, the layout instantly changes. The footer has moved way up, the content is not in the write place. Can someone point out where my mistake is? Html generated from Boostrap Studio <div class="container-fluid"> <h1 class="text-center"><strong>Aircraft</strong> </h1></div> <div class="container"> <div class="btn-toolbar"> <div class="btn-group" role="group"> <button class="btn btn-default" type="button">Compare Selected Aircraft</button> <button class="btn btn-default" type="button">Reset Selected Aircraft</button> </div> </div> </div> Container for the items being listed <div class="team-boxed"> <div class="container"> <div class="row aircraft"> <div class="col-lg-offset-0 col-md-4 col-sm-3 item"> <div class="box"><img src="assets/img/images.jpg"> <h3 class="name">Boeing 777-300ER</h3> <h4><em>Range: 3535 NM</em></h4> <h4><em> Passengers: 324</em></h4> <h4><em> Speed: 532 Knots</em></h4> <div class="checkbox"> <label> <input type="checkbox">Add to Compare </label> </div> <button class="btn btn-default" type="button">Favourite </button> </div> </div> </div> </div> </div> Footer <div class="row"></div> <div class="footer-basic"> <footer> <ul class="list-inline"> <li><a href="#"><strong>Home</strong></a></li> <li><a href="#"><strong>Services</strong></a></li> <li><a href="#"><strong>About</strong></a></li> <li><a href="#"><strong>Terms</strong></a></li> <li><a href="#"><strong>Privacy Policy</strong></a></li> </ul> <p class="copyright"><strong>Excel Aviation© 2017</strong></p> </footer> </div> <script src="assets/js/jquery.min.js"></script> <script src="assets/bootstrap/js/bootstrap.min.js"></script> <script src="assets/js/bs-animation.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/aos/2.1.1/aos.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.9.0/js/lightbox-plus-jquery.min.js"></script> <script src="assets/js/search_bar_with_parameters.js"></script> </body> Base.html <!---------------- Main content will go between block tags ---------------> {% block content %} {% endblock content %} <!---------------- Footer ---------------> <div class="row"></div> <div … -
Django and python TypeError
I can access the admin area of the website but i cant get to homepage and other front end pages..following error pops up... > TypeError at / render_to_response() got an unexpected keyword argument > 'context_instance' Request Method: GET Request > URL: http://127.0.0.1:8000/ Django Version: 1.10.6 Exception > Type: TypeError Exception Value: render_to_response() got an > unexpected keyword argument 'context_instance' Exception > Location: C:\Users\DEEP\Desktop\Bus_reservation\src\bus\views.py in > index, line 10 Python Executable: C:\Python34\python.exe Python > Version: 3.4.4 Python Path: > ['C:\\Users\\DEEP\\Desktop\\Bus_reservation\\src', > 'C:\\WINDOWS\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', > 'C:\\Python34\\lib', 'C:\\Python34', > 'C:\\Python34\\lib\\site-packages'] Here is TRACEBACK > Environment: > > > Request Method: GET Request URL: http://127.0.0.1:8000/ > > Django Version: 1.10.6 Python Version: 3.4.4 Installed Applications: > ['bus.apps.BusConfig', 'bookTicket.apps.BookticketConfig', > 'account.apps.AccountConfig', 'django.contrib.admin', > 'django.contrib.auth', 'django.contrib.contenttypes', > 'django.contrib.sessions', 'django.contrib.messages', > 'django.contrib.staticfiles'] Installed Middleware: > ['django.middleware.security.SecurityMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware', > 'django.middleware.common.CommonMiddleware', > 'django.middleware.csrf.CsrfViewMiddleware', > 'django.contrib.auth.middleware.AuthenticationMiddleware', > 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', > 'django.contrib.messages.middleware.MessageMiddleware', > 'django.middleware.clickjacking.XFrameOptionsMiddleware'] > > > > Traceback: > > File "C:\Python34\lib\site-packages\django\core\handlers\exception.py" > in inner > 42. response = get_response(request) > > File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in > _legacy_get_response > 249. response = self._get_response(request) > > File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in > _get_response > 187. response = self.process_exception_by_middleware(e, request) > > File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in > _get_response > 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) > … -
Failed to order a list in TreeNodeMultipleChoiceField
I have a MTTP django model with a TreeNodeMultipleChoiceField. I try to orderby the list but it doesn't work. This is how the model looks: class Region(MPTTModel): objects = RegionManager() code = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=255) parent = TreeForeignKey('self', null=True, blank=True, related_name='children') def __unicode__(self): return self.name class MPTTMeta: order_insertion_by = ['name'] class Meta: ordering = ('name',) verbose_name_plural = 'Metadata Regions' And this is how the Form is: regions = TreeNodeMultipleChoiceField( required=False, queryset=Region.objects.all(), level_indicator=u'') regions.widget.attrs = {"size": 20} From the level_indicator I have removed all the underscores, so they all appear as one list. I have tried to use order_by but it doesn't return an ordered list. Any idea what I need to do? -
Change css of text and button separately with Django image upload field
I have the following field in one of my forms to allow the user to upload an image in Django: image = models.ImageField(upload_to=upload_location, null=True, blank=True) I display it as a field in my form table as follows: <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} <div style="overflow-x:auto;"> <table class="table-form" style='table-layout:fixed;'> <tr> <th>Image</th> <td>{{ form.image }}</td> </tr> ... And here is what the HTML looks like when I inspect the element with Chrome Developer Tools: <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} <div style="overflow-x:auto;"> <table class="table-form" style='table-layout:fixed;'> <tr> <th>Image</th> <td> <!-- IMAGE FIELD FROM DJANGO --> <input id="id_image" name="image" type="file"> </td> </tr> ... When there is no image uploaded, Django places the button alongside a piece of text saying "No file chosen". I want to be able to change this text, and the button text which says "Choose File" (shown below) independently. Currently I can only change both at once with the following in my css: #id_image { /* style */ } I want to make the "No file chosen" text size about 8px, and the "Choose File" text a bit bigger ~12px. Is this possible?...