Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run behave-django features in PyCharm?
Background I have a Django project ("api") with unittest tests and behave features. Relevant parts of its structure are code/ # i.e. the Django root is not the root of the project manage.py api/ settings.py # and other Django stuff app/ # Django app stuff features/ environment.py steps/ foo.feature virtualenv/ I use behave-django. python manage.py behave works. I use PyCharm. It's configured to use the project's virtualenv. Its Django support is configured thus: Running Django and running unittest tests inside PyCharm works. The problem When I attempt to run a behave feature in PyCharm (by hitting control-shift-R when editing the feature file and choosing the behave run context configuration) I get /Users/dave/data/projects/api/code/virtualenv/bin/python2.7 "/Applications/PyCharm 2016.3.app/Contents/helpers/pycharm/behave_runner.py" Testing started at 04:31 ... Traceback (most recent call last): File "/Applications/PyCharm 2016.3.app/Contents/helpers/pycharm/behave_runner.py", line 294, in <module> _BehaveRunner(my_config, base_dir).run() File "/Applications/PyCharm 2016.3.app/Contents/helpers/pycharm/_bdd_utils.py", line 91, in run number_of_tests = self._get_number_of_tests() File "/Applications/PyCharm 2016.3.app/Contents/helpers/pycharm/_bdd_utils.py", line 211, in _get_number_of_tests for feature in self._get_features_to_run(): File "/Applications/PyCharm 2016.3.app/Contents/helpers/pycharm/behave_runner.py", line 231, in _get_features_to_run self.__real_runner.run() File "/Users/dave/data/projects/api/code/virtualenv/lib/python2.7/site-packages/behave/runner.py", line 672, in run return self.run_with_paths() File "/Users/dave/data/projects/api/code/virtualenv/lib/python2.7/site-packages/behave/runner.py", line 678, in run_with_paths self.load_step_definitions() File "/Users/dave/data/projects/api/code/virtualenv/lib/python2.7/site-packages/behave/runner.py", line 658, in load_step_definitions exec_file(os.path.join(path, name), step_module_globals) File "/Users/dave/data/projects/api/code/virtualenv/lib/python2.7/site-packages/behave/runner.py", line 304, in exec_file exec(code, globals, locals) File "code/features/steps/common.py", line 5, in β¦ -
Python reliable project setup: write data from a serial port to a database in a certain time interval
The application should read data from a serial port every 15 minutes (using the Modbus Protocol) and put them into a database. The data can then be viewed and manipulated in a web interface. I'm using Windows (no server) with a RAID system to prevent data loss. My current setup looks like this: using pyserial and minimalmodbus for reading the data and putting them into a MySQL database setting a cron job to run the script every 15 minutes (alternatives?) using Django in order to have a neat interface where one can view stats and download the data as a *.csv file My questions are: Does this setup makes sense concerning reliability; do you have any improvements? How can i detect if the system has experienced a shutdown and i lost some data? -
OperationalError at /admin/login/ no such table: auth_user
I am getting this error even after running syncdb multiple times and i am using django 1.7.4 and i have also tried doing migration of my installed apps manually and still it doesn't solve the problem. Environment: Request Method: POST Request URL: https://myapp.herokuapp.com/admin/login/?next=/admin/ Django Version: 1.7.4 Python Version: 2.7.12 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core') Installed Middleware: ('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 "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 52. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/sites.py" in login 361. return login(request, **defaults) File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 105. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 52. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/views.py" in login 37. if form.is_valid(): File "/app/.heroku/python/lib/python2.7/site-packages/django/forms/forms.py" in is_valid 162. return self.is_bound and not bool(self.errors) File "/app/.heroku/python/lib/python2.7/site-packages/django/forms/forms.py" in errors 154. self.full_clean() File "/app/.heroku/python/lib/python2.7/site-packages/django/forms/forms.py" in full_clean 354. self._clean_form() File "/app/.heroku/python/lib/python2.7/site-packages/django/forms/forms.py" in _clean_form 378. cleaned_data = self.clean() File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/forms.py" in clean 192. password=password) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/__init__.py" in authenticate 60. user = backend.authenticate(**credentials) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/backends.py" in authenticate 16. user = UserModel._default_manager.get_by_natural_key(username) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/models.py" in get_by_natural_key 159. return self.get(**{self.model.USERNAME_FIELD: username}) File "/app/.heroku/python/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method 92. return getattr(self.get_queryset(), name)(*args, β¦ -
Gunicorn settings for virtualenvwrapper
I am trying to deploy a test site which made using Django and virtualenvwrapper. I want to use nginx for requests.I used Taskbuster's tutorial. So my project layer is similar as below : --abctasarim **main folder --manage.py **django manage file ----/yogavidya ** project folder ----/yogavidya/wsgi.py **wsgi file ----/yogavidya/settings/base.py ***settings I prepared a script to use with gunicorn. I addressed virtualenv to virtualenvwrapper envs #!/bin/bash NAME="yogavidya" #Name of the application (*) DJANGODIR=/home/ytsejam/public_html/abctasarim # Django project directory (*) SOCKFILE=/home/ytsejam/public_html/abctasarim/run/gunicorn.sock # we will communicate using this unix socket (*) USER=ytsejam # the user to run as (*) GROUP=webdata # the group to run as (*) NUM_WORKERS=1 # how many worker processes should Gunicorn spawn (*) DJANGO_SETTINGS_MODULE=yogavidya.settings.base # which settings file should Django use (*) DJANGO_WSGI_MODULE=yogavidya.wsgi # WSGI module name (*) echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/ytsejam/.virtualenvs/yv_dev/bin/activate #export /home/ytsejam/.virtualenvs/yv_dev/bin/postactivate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec /home/ytsejam/public_html/abctasarim/gunicorn \ --name $NAME \ --workers $NUM_WORKERS \ --env DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE \ --pythonpath $DJANGODIR β¦ -
Django - python: real time check of data without reloading page
The task: i have a Chart that feeds of some data which is continuosly updated throughout the day. Specifically, the data is extracted from the web, it's written in the database and such database is read by a django view and later visualized in the aforementioned Chart. The problem: I want the user to see the new data without reloading the page. Looking online, using Django, i think I have to link it to a rest api, the problem is that in practice i have no cliente how to set it up. The question: is this the best way to do it? If so, could you point me to some tutorials that make this happen? -
Gunicorn and SystemΠ² not started
I have web server for this configuration: - site/ - env/ - src/ - PROJECT - setting.py - wsgi.py - ... - manage.py - static_content/ - static/ It's systemd gunicorn.service: [Unit] Description=gunicorn daemon After=network.target [Service] User=USERNAME Group=USERNAME WorkingDirectory=/home/USERNAME/site/ ExecStart=/home/USERNAME/site/env/bin/gunicorn --workers 3 --bind unix:/home/USERNAME/site/src/PROJECT.sock PROJECT.wsgi:application [Install] WantedBy=multi-user.target And this's log "sudo systemctl status gunicorn.service": * gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Sun 2016-12-18 14:48:11 MSK; 44s ago Main PID: 853 (code=exited, status=217/USER) Dec 18 14:48:11 amper systemd[1]: Started gunicorn daemon. Dec 18 14:48:11 amper systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Dec 18 14:48:11 amper systemd[1]: gunicorn.service: Unit entered failed state. Dec 18 14:48:11 amper systemd[1]: gunicorn.service: Failed with result 'exit-code'. Why? -
Django: How do I get my website/app online?
I have started with Django. The problem I have is: I own a domain. I have one on hostgator and another on g domains. I would like to use g domains to host, but how on earth do you connect your django webapps to the domain? I have looked all over for resources on this topic, with no luck. So to be clear, I have a domain name, hosted by G domains. I have a great django webapp. How do I get that webapp online, using my domain name? Thanks. -
Artificial delay before sending a response
For the purpose of throttling users that aren't using the site in a way that it was intended to be used (brute-force attackers, crawlers [search engines exempt], etc), I'd like to find a way to delay the response in a way that: Won't have any performance impact for other users Won't require more computing resources Is this possible with the stack outlined in the tags of this question? At which layer should it be implemented? From what I understand, if this kind of behavior were to be implemented in Django, the delayed request would block the next requests for the duration of the delay. In other words: Given a server that can handle 100 requests per second, I'd like to find a way to artificially delay 10000 requests from a bad user (the bad user would see 10000 loading screens), and still process nearly 100 requests per second from legitimate users. -
assign foreign key with request.user but i get error django
I am getting the following error:UNIQUE constraint failed: user_profile_credit.customer_id I trying to assign the id of the current user to a model models.py class Credit(models.Model): WALLET=( ('1','first choice'), ('2','second choice') ) customer=models.OneToOneField(User) wallet=models.CharField(max_length=2, choices= WALLET) and my form.py class CreditForm(forms.ModelForm): class Meta: model=Credit fields=['wallet'] widgets = { 'wallet': forms.RadioSelect(), } finaly my views.py: def CreditView(request): if request.method == "POST": form = CreditForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.customer=request.user #:(( post.save() return redirect('user_profile:index') else: form = CreditForm() return render(request, 'user_profile/credit.html', {'form': form}) i even change: post.customer=request.user to: post.customer=User.objects.filter(id= request.user.id)[0] and currentuser=request.user post.customer=currentuser.id but i get error Cannot assign "5": "Credit.customer" must be a "User" instance. -
Django splitting URLConf across multiple applications
I know it's feels like elementary, and yet I can't come up with a clean solution based on doc only. I have the following project structure (I omit files like models.py, forms.py for the purpose of keeping the question concise) hello_world hellow_world urls.py app_2 urls.py app_3 urls.py urls.py settings.py As you see, my goal is to have a separate urls.py file for each app, and then assemble them into root urls.py (depicted at the same level as settings.py in the list above). The problem is that my root urls.py is EMPTY (!!!) now, and the site still loads the home page !!! What am I doing wrong ??? See the details below: settings.py: ROOT_URLCONF = 'urls' hellow_world urls.py: urlpatterns = [ url(r'^$', views.home , name = 'home'), ] root urls.py - empty ! -
Django 1.10 redirect view not working
My redirect to another view is not working in django 1.10 Views.py from django.shortcuts import render, redirect # Create your views here. from forms import DocumentForm from models import Document from django.apps import apps myapp = apps.get_app_config('django_celery_results') myapp.models.TASK_MODEL = myapp.models['taskresult'] def tasks_view(request): tasks = TASK_MODEL.objects.all() return render(request, 'saved.html', {'tasks': tasks}) def SaveDocument(request): saved = False if request.method == "POST": #Get the posted form MyDocumentForm = DocumentForm(request.POST, request.FILES) if MyDocumentForm.is_valid(): print 'It enters here' document = Document() document.name = MyDocumentForm.cleaned_data["name"] document.doc = request.FILES["document"] print document.doc print document.name print 'request type', request.method document.save() saved = True return redirect('tasks_view') else: print 'Fails' else: MyDocumentForm = DocumentForm() return render(request, 'saved.html', locals()) urls.py from django.conf.urls import url from django.views.generic import TemplateView from core.views import * urlpatterns = [ url(r'profile/',TemplateView.as_view( template_name = 'profile.html')), url(r'saved/', SaveDocument, name = 'SaveDocument'), url(r'check/', tasks_view, name = 'tasks_view,') ] I do not understand why do i always get this exception in Reverse for 'tasks_view' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] The url redirects to NoReverseMatch at /my_app/saved/. Why doesnt it redirect to the tasks view and goes to /my_app/check/ instead? -
Django project structure in Eclipse (3 layers)
Eclipse: Neon Release (4.6.0) Django: 1.10.4 (though, not important). I start a new Django project in Eclipse. File -> New -> Project -> PyDev Django Project. And now I get a three-layer structure. For example (with an application "home" already added): michael@ThinkPad:~/workspace/MyProject$ tree . βββ MyProject βββ home β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ tests.py β βββ views.py βββ manage.py βββ MyProject βββ __init__.py βββ __pycache__ β βββ __init__.cpython-35.pyc β βββ settings.cpython-35.pyc βββ settings.py βββ urls.py βββ wsgi.py Look: MyProject / MyProject / MyProject. I haven't used Eclipse for some years. If I'm not mistaken, in bygone days Eclipse organized a two-layer structure. If I wanted a three-layer structure, I first created the project in terminal through "django-admin startproject". Then imported the project. And I changed Pythonpath in Eclipse (String Substitution Variables). I understand that the top layer is for control version system. What I can't understand: why Eclipse organizes it for me. Whether they decided that this is the best practice and now they follow it? Then why PyCharm creates a two-layer structure. Why django-admin itself creates a two-layer structure. I would say, Eclipse β¦ -
Bootstrap Modal not closing in Safari
I have an issue with bootstrap where Modals are not closing upon form submission in Safari but it is fine in Chrome. Note this is a Django project but I don't think that is the issue. Also I am using using this upload progress bar for the uploads but I am getting the issue both with this and without. Here is my HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>VideoOrganiser</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> {% load static %} <link href="{% static 'mfo/base_style.css' %}" rel="stylesheet" type="text/css"> <script src="{% static 'scripts/index.js' %}" type="text/javascript"></script> <script src="{% static 'scripts/bootstrap-uploadprogress.js' %}" type="text/javascript"> </script> </head> <body data-spy="spyscroll"> <nav class="navbar navbar-custom"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="/" style="font-size: 200%">VideoOrganiser</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li style="padding-top: 11px"> <!-- Trigger the modal β¦ -
Overriding methods for defining custom model field in django
I have been trying to define custom django model field in python. I referred the django docs at following location https://docs.djangoproject.com/en/1.10/howto/custom-model-fields/. However, I am confused over the following methods(which I have divided into groups as per my understanding) :- Group 1 (Methods in this group are inter-related as per docs) __init__() deconstruct() Group 2 db_type() rel_db_type() get_internal_type() Group 3 from_db_value() to_python() get_prep_value() get_db_prep_value() get_db_prep_save() value_from_object() value_to_string() Group 4 formfield I am having following questions :- When deconstruct() is used ? Docs says that, it's useful during migration, but it's not clearly explained. Difference between db_type() and get_internal_type() Difference between get_prep_value() and get_db_prep_value() Difference between value_from_object() and value_to_string(). value_from_object() is not given in docs. Both from_db_value(), value_to_string() and to_python() gives python object from string. Then, why these different methods are exists ? I know, I have asked a bit lengthy question. But couldn't find any other way to better ask this question. Thanks in advance. -
HTTP_422_UNPROCESSABLE_ENTITY doesn't work with django rest framework
Its strange whenever i try to return HTTP_422_UNPROCESSABLE_ENTITY from my django rest api it instead throws 500 with below error whereas same code works when i return 404. Any limitation on this. [Sun Dec 18 05:37:45.314796 2016] [:error] [pid 24535] <rest_framework.request.Request object at 0x7f96cb0a6710> 422 ['profile', 'sig', 'email'] [Sun Dec 18 05:37:45.315550 2016] [:error] [pid 24535] Internal Server Error: /v3/users/signup/ [Sun Dec 18 05:37:45.315561 2016] [:error] [pid 24535] Traceback (most recent call last): [Sun Dec 18 05:37:45.315564 2016] [:error] [pid 24535] File "/usr/lib64/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response [Sun Dec 18 05:37:45.315567 2016] [:error] [pid 24535] response = self.process_exception_by_middleware(e, request) [Sun Dec 18 05:37:45.315570 2016] [:error] [pid 24535] File "/usr/lib64/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response [Sun Dec 18 05:37:45.315572 2016] [:error] [pid 24535] response = wrapped_callback(request, *callback_args, **callback_kwargs) [Sun Dec 18 05:37:45.315575 2016] [:error] [pid 24535] File "/usr/lib64/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view [Sun Dec 18 05:37:45.315577 2016] [:error] [pid 24535] return view_func(*args, **kwargs) [Sun Dec 18 05:37:45.315579 2016] [:error] [pid 24535] File "/usr/lib64/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view [Sun Dec 18 05:37:45.315582 2016] [:error] [pid 24535] return view_func(*args, **kwargs) [Sun Dec 18 05:37:45.315584 2016] [:error] [pid 24535] File "/usr/lib64/python2.7/site-packages/django/views/generic/base.py", line 68, in view [Sun Dec 18 05:37:45.315586 2016] [:error] [pid 24535] return self.dispatch(request, β¦ -
Python generated S3 signature returning SignatureDoesNotMatch
I have tried nearly everything to create a proper signature so that a user can upload a file straight to my s3 bucket, but am overwhelmed by the process, and cant get my signature to be accepted. I am not sure how to even troubleshoot, as Amazon's response provides no detail, and the signature creation process requires many moving parts. My signature is created in views: def sign(key, msg): return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() def getSignatureKey(key, dateStamp, regionName, serviceName): kDate = sign(("AWS4" + key).encode("utf-8"), dateStamp) kRegion = sign(kDate, regionName) kService = sign(kRegion, serviceName) kSigning = sign(kService, "aws4_request") return kSigning signature = base64.b64encode(getSignatureKey(settings.AWS_SECRET_ACCESS_KEY, '20161217', 'us-east-1', 's3')) And passed to my form in templates <form action="https://videoresume.s3.amazonaws.com" method="post" enctype="multipart/form-data"> <input type="hidden" name="key" value="media/uploads/"> <input type="hidden" name="AWSAccessKeyId" value="AKIAIC2JUPOFASWQXOHQ"> <input type="hidden" name="acl" value="public-read"> <input type="hidden" name="success_action_redirect" value="http://example.com"> <input type="hidden" name="policy" value="{{policy}}"> <input type="hidden" name="signature" value="{{signature}}"> File to upload to S3: <input name="file" type="file"> <br> <input type="submit" value="Upload File to S3"> </form> The response I receive back from amazon is: <Error> <Code>SignatureDoesNotMatch</Code> <Message> The request signature we calculated does not match the signature you provided. Check your key and signing method. </Message> <AWSAccessKeyId>AKIAIC2JUPOFASWQXOHQ</AWSAccessKeyId> <StringToSign/> <SignatureProvided>eJxuGd8rvrVezRapplFZukeg9psmAC44a11Hk2HgAO0= </SignatureProvided> <StringToSignBytes/> <RequestId>942408ABD414D18F</RequestId> <HostId> h2NTQhWJsTkPZs6SvfvgenVqe/zsHSmmFtPs6lzbj++pxVA+wQBCZP11EQ/dz0GXf/UJdjSr35k= </HostId> </Error> ( function(){ window.SIG_EXT = {}; β¦ -
can't change default many to many widget in django form
Hi I have a many to many field: class Seeking(models.Model): entity = models.OneToOneField(Entity) company_type = models.ManyToManyField(CompanyTypeChoice) I have this form that uses field: class SeekingForm(forms.ModelForm): class Meta: model = Seeking widgets = {'m2m_field': forms.CheckboxSelectMultiple} exclude = ( 'entity', ) def __init__(self, *args, **kwargs): super(SeekingForm, self).__init__(*args, **kwargs) self.fields["company_type"].widget = forms.CheckboxSelectMultiple() The widget still renders as a multi select box. I am using django 10. What am I doing wrong? -
How to activate the process queue in "django-background-tasks"
I am new to django and django-background-tasks package. I am facing an issue that I couldn't do/start background task unless i forcefully run the command process_tasks , that is python manage.py process_tasks. I wanna do/start background task without run the process_tasks command. Please help me with the solution.. Sorry for my bad language :-( settings.py MAX_ATTEMPTS=1 BACKGROUND_TASK_RUN_ASYNC = True tasks.py from background_task import background #included necessary packages for SMTP @background(schedule=5) def test(): #send mail to some ids views.py def index(request): test(schedule=5) return HttpResponse("Hello, world. ") Ignore my logic. -
Can't override CSS in bootstrap
Like the title says, my custom CSS isn't overriding the core CSS in bootstrap. I'm following this tutorial and trying to add a larger margin beneath the navbar with no luck. I'm also using Django, here's my html file: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Bootstrap 101 Template</title> <!-- Bootstrap --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" href="{% static 'css/bootstrap-override.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-theme.css' %}"> <script src="{% static 'jquery/3.1.1/jquery.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> </head> <body> <nav class="navbar navbar-inverse navbar-static-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Client Sign-In</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">About</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Services<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Design</a></li> <li><a href="#">Development</a></li> <li><a href="#">Consulting</a></li> </ul> </li> <li><a href="#">Contact</a></li> </ul> </div> </div> </nav> <h1>Enter ID</h1> <form method="POST" class= "post-form"> {% csrf_token %} {{ form.as_p }} <button type='submit' class="save btn-default">Save</button> </form> {% β¦ -
cursor.copy_from failed with psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0x8a
Project setup: PostgreSQL 9.5.5, Python 3.5.2, Django==1.10.4, psycopg2==2.6.2 In the code below, I am trying to convert hex string into bytearray for insertion into PostgreSQL bytea column. This returns the error below. Is this possible with copy_from? Error: Traceback (most recent call last): File "./insert.py", line 40, in <module> insert_rows(table, columns, rows) File "./insert.py", line 27, in insert_rows columns=columns) psycopg2.DataError: invalid byte sequence for encoding "UTF8": 0x8a CONTEXT: COPY app_testtable, line 1: ""bytearray(b""A\x04g\x8a\xfd\xb0\xfeUH\'\x19g\xf1\xa6q0\xb7\x10\\\xd6\xa8(\xe09\t\xa6yb\xe0\xea\x1fa..." Database table: db=# \dS project_testtable; Table "app.project_testtable" Column | Type | Modifiers --------+---------+---------------------------------------------------------------- id | integer | not null default nextval('project_testtable_id_seq'::regclass) bin | bytea | Indexes: "project_testtable_pkey" PRIMARY KEY, btree (id) models.py: class TestTable(models.Model): bin = models.BinaryField(blank=True, null=True) Code: #!/usr/bin/env python3 # -*- coding: utf-8 -*- from io import StringIO import binascii import csv import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') import django django.setup() from django.db import connection from project.app.models import TestTable def insert_rows(table, columns, rows): stream = StringIO() writer = csv.writer(stream, delimiter='\t') for row in rows: writer.writerow(row) stream.seek(0) with connection.cursor() as cursor: cursor.copy_from( file=stream, table=table, sep='\t', columns=columns) TestTable.objects.all().delete() table = 'app_testtable' columns = ('bin', ) bin_value = '4104678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5fac' rows = [(bytearray(binascii.unhexlify(bin_value)), ),] insert_rows(table, columns, rows) -
Use cycle value to compare with list
I've faced some problems with compare value in list Let's say I have list of values such as [u'1', u'2', u'3'] And If I write it in template like this: {% if "3" in selected_list %} Checked {% else %} {% endif %} Then It works well But If I try to use it in cycle like: {% for item in items %} {% if item.id in selected_list %} Checked {% else %} {% endif %} {% endfor %} Then it fails, it doesn't compare them together -
How i can use variable of one function to another function in django
I'm writing a program to edit student details(not as a admin). I have to different def's that hold the variables that contain the username. in first one i am trying to get username and in another def that actually applying the edit functionality. but it needs the variable that contains the username. How can I call the variables from the first one? Sorry for the weird wording. I don't know how else to say it :P Thanks! def get_username(): #the code to open up a input fields that gets the username username = input def edit_student(): #the code to open up a pre populated form with the instance of the same student which i get from get_username() -
Rewrite PostgreSQL to Django ORM
if this possible to rewrite this PostgreSQL query to Django ORM with no raw SQL, i tried it by myself but i haven't succeeded. select * from finance_fund order by((select price from finance_nav where date='2016-11-08' and fund_id=finance_fund.id)/(select price from finance_nav where date='2016-11-07' and fund_id=finance_fund.id)) So basically i need to order by division result of two simple queries of backward relations of Foreign key Thanks in advance ! -
Django render function gives error dict expected at most 1 arguments, got 3
def home(request): """Renders the home page.""" assert isinstance(request, HttpRequest) return render( request, 'app/index.html', context = RequestContext(request, { 'title':'Home Page' }) ) I am getting an error at dictionary object. dict expected at most 1 arguments, got 3 -
If I change ImageFIeld.upload_to parameter, should it move previously uploaded files upon migration?
I have a Django model with ... image = models.ImageField(default=None, upload_to=settings.PHOTO_UPLOAD_TO) ... I have changed the value of settings.PHOTO_UPLOAD_TO, but the files have remained where they were, and the database entries also don't seem to have changed. A newly added image is placed in the correct new location, but not the old ones. Is it an expected behaviour? Is there a way to migrate the image locations? I would like to slightly change the directory/URL structure of my project.