Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can I create a project with django?
i install python and Django on mac with pip , but when i want start project with Django by this command i have message error : macs-MacBook:desktop mac$ django-admin.py startproject blog pkg_resources.DistributionNotFound: The 'pytz' distribution was not found and is required by Django i try solve that with this command but i have same error : sudo pip install -U djangorestframework how can i solve that and create project ? -
Unexpected keyword 'import' in WebPack Django and Vue.js project
I have a simple project where I am using Django, Webpack and Vue.js. When I build a static bundle upon load it seems like my bundle is not compiled correctly. I get an error in JavaScript console: [Error] SyntaxError: Unexpected keyword 'import' (anonymous function) (main-dd2bbbf09bf9a252a3c7.js:47) I tried to keep my webpack.config.js really simple: var path = require("path"); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { context: __dirname, entry: './frontend/js/main', output: { path: path.resolve('./frontend/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], resolve: { extensions: ['', '.js', '.vue', '.json'], }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { } // other vue-loader options go here } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ], }, } .babelrc looks like this: { "presets": [ ["env", { "modules": false }] ] } main.js (which ultimately blows up) is simple: import Vue from 'vue' import App from './App.vue' new Vue({ el: '#app', render: h => h(App) }) -
Django: I want a Queryset as a list. How?
I need to get a Queryset in Django and make a copy of it as a variable in the form of a list of dictionaries. I thought this is what Querysets were, I guess I'm wrong. listA = User_Item.objects.filter(user=User.objects.get(id=1)) Gives me an error when I try to perform a simple algorithm with it. I don't want to interact with the database- I need to copy that Queryset as a list of dictionaries. How do I do this? (Trying to get a list of entries in this join table, which should be a list of dictionaries with dictionaries for some of the key values) -
Django: Cannot insert user profile data from model into the template
I am using Django's default auth for users and I have created a separate model to extend the user profile a bit. When I try to access the user profile info its not showing up on the page. In my view, I pass the Profile objects to the view's context but it still not working. When I try it in the shell, I get AttributeError: 'QuerySet' object has no attribute 'country' error when I do: profile = Profile.get.objects.all() country = profile.coutry country Below is my models.py: from pytz import common_timezones from django.db import models from django.contrib.auth.models import User from django_countries.fields import CountryField from django.db.models.signals import post_save from django.dispatch import receiver TIMEZONES = tuple(zip(common_timezones, common_timezones)) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) country = CountryField() timeZone = models.CharField(max_length=50, choices=TIMEZONES, default='US/Eastern') def __str__(self): return "{0} - {1} ({2})".format(self.user.username, self.country, self.timeZone) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Here is my views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from user.models import Profile @login_required() def home(request): profile = Profile.objects.all() return render(request, "user/home.html", {'profile': profile}) And finally the home.html file: {% extends "base.html" %} {% block title %} Account Home for {{ user.username }} … -
How can I repeatedly call a function from a views.py in Django?
How can I repeatedly call a function from a views.py in Django? urls.py urlpatterns = [ url(r'^$', views.index), url(r'^report/(?P<extension>\d+)/$', views.report), ] views.py def report(request, extension): """ I will do some logic here. I need the extension variable for database purposes. EX: my_array = Report.objects.fetching_reports(extension='3') """ return render(request, 'report.html’) If you notice in extension, I passed in 3. The idea is that each extension will have their own data. However, I want them to render on the same html template. I will begin rendering from extension 1, up to 12 then goes back to 1. Let’s say extension 4 is missing, it will be redirected to extension 5.These extension will come from my database. Example: …/report/1/ …/report/2/ …/report/3/ ## will skip 4 if not available …/report/5/ …/report/6/ ## and so on.. Each extension will render the same HMTL template. Right now, I can successfully render these reports if I type the URL patter directly to the browser. Is there a way to call report( ) continuously, let’s say every 15 seconds? Or should I have a different approach to this? Thank you very much for reading. -
Django DateInput default set by browser
In my Django project I have a regular looking forms.py which, for one form, specifies a certain field to use the DateInput widget. This works fine - when I browse to the page, I see an empty date field on which I can click and select a date from a calendar view. Now I'd like to auto-populate that for the user using the current date on their computer. So not a server-side default value, but probably browser-side set by Javascript or something. How can I do this? Essentially this is the template for my form: <form action="/new_case/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> -
django SelectDateWidget and bootstrap
I'm trying to render a SelectDateWidget with bootstrap, however when I add the class "form-control" it just appears vertically. If I don't add it it appears horizontal but unstyled. Is there a way to break down the widget so that I can customise it as needed? (Note I've used django widget tweaks to add the css class) <div class="form-group"> <label for="{{ form.move_in_date.id_for_label }}"> {{ form.move_in_date.label }} </label> {% render_field form.move_in_date.errors class="form-control" %} {% render_field form.move_in_date class="form-control" placeholder=form.move_in_date.label %} </div> -
Django Wagtail Jinja2 include_block tag not passing variables
I have the following very simple statement to render blocks in wagtail. {% for block in blocks %} {% include_block block %} {% endfor %} The for loop works and iterates over the blocks as does the template tag include_block. The variable 'block' however is not accessible in the template executed by include_block. {% set background_image = block.background_image.image %} The above statement called in the template called by include_block throws the following error. 'block' is undefined This does not really make sense since the documentation for Wagtail's include_block states that variables get passed down into the called template. http://docs.wagtail.io/en/v1.9/advanced_topics/jinja2.html#include-block I have the following statement in order to explicitly pass in variables but it still does not work, {% include_block block with context %} -
Django REST Framework - unittest client failing to resolve hyperlinks relation for POST
I have this test: class AttributeTest(APITestCase): def setUp(self): user1 = User.objects.create(pk=1, username='pepa', email='ads@asasd.cz', is_active=True, is_staff=True) user1.set_password('mypass') user1.save() self.c1 = Campaign.objects.create(pk=1, owner=user1, project_name='c1') def test(self): campaign_url = 'http://testserver/api/campaigns/{}/'.format(self.c1.pk) self.client.login(username='pepa', password='mypass') data = { "label": "something_here", "parent_campaign": campaign_url, } # campaign clearly exists (created in setUp) and GET retrieve it: assert self.client.get(campaign_url).json()['project_name'] == 'c1' # I can even try it myself using pdb # but this doesn't work - response return 400 Bad Request # complaining about the very same hyperlink I can GET above response = self.client.post('/api/keys', data, format="json") self.assertEqual(response.status_code, status.HTTP_201_CREATED) but when run, it fails with {'parent_campaign': ['Invalid hyperlink - No URL match.']}. When I try using curl or browsable API (outside the test environment), everything works as expected. Anyone knows what's going on? -
Django "apps" folder still relevant?
There was somewhere I read couple of years ago (Two scoops of Django 1.4?) suggested having an "apps" folder inside the Django project which hosts all the apps. Repo folder -- Project root folder -- apps -- app 1 -- app 2 -- settings etc But just had a quick read of "Two scoops of Django 1.8" there is no mention of the "apps" folder in the preferred project structure. Repo folder -- Project root folder -- app 1 -- app 2 -- settings etc What have I missed? And why did they remove this folder? -
Django & SET CONSTRAINTS ALL DEFERRED
What is the most repeatable way to update my db with unique constraints suspended during the update? Do I have to write the SQL query out every time I do a new one, or? -
Why Are my Nav-Pills and Carousel Slides Suddenly Not Working?
So I created my website for my company and when I had launched the site the functionality of various elements were working perfectly. On various pages of the website are carousel slides with slide timers and on one of the pages, https://ordinanceservices.com/services , I have nav nav-pills so that prospective customers could view the two elements of our services, one at a time; without needing to reload the page or visit a different page altogether. You guys get it. Upon revisiting my website after a while, I noticed that the carousel slides now no longer change and the nav nav-pills no longer change between "Identity Protection" and "Financial Planning". If I attempt to click on "Financial Planning" tab, it will reload the page but remain on the tab "Identity Protection". Since the markup is very lengthy and it is multiple elements that are no longer working, I will simply provide you all the URL to the page in question so that you all can view the source and play around on the webpage. If anyone has a solution or thinks they have found why this is happening please do let me know. As I have sank many hours into the … -
Preventing a file upload completely if file already exists in Django
I'm trying to make it so that when someone tries to upload a file that has already been uploaded before with a model form, the form will prevent it from submitting. Here is the relevant code: models.py class File(models.Model): file = models.FileField(upload_to='documents/') forms.py class FileForm(forms.ModelForm): file = forms.FileField() class Meta: model = File fields = ('file',) views.py def file_upload(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('list_files') else: logger.error(form.errors) else: form = FileForm() return render(request, 'files/file_upload.html', {'form': form}) Let's say someone uploaded a file called document_1.xlsx. The way this code is now, if someone tries to upload another file called document_1.xlsx, it will upload it and add some weird suffix to it before the dot. I don't want that. I want the form to not allow anyone upload a file that already exists period, without breaking the code. Apparently adding 'unique=True' to the file field in the model doesn't work. I've seen so many questions that ask how to rename a file if it already exists, but I don't want that. I want to stop it completely if that file name already exists. Thanks. -
Generate SQL query string from Django ORM
I need to use SET CONSTRAINTS ALL DEFERRED in order to persist new order values on a series of rows, where they have a unique constraint. Django does not have support for deferring constraints natively, and I don't want to have to rewrite the query every time I want to do something like this. Is there a way to have Django write some SQL for me, and then I can toss the SET CONSTRAINTS ALL DEFERRED into it before running raw_sql? -
How to reverse_lazy to a view/url with variable?
I've got a DeleteView I use for removing objects from a model. It is launched via a button in a table. It works fine. class DeleteAssignment(DeleteView): model = Assignment success_url = reverse_lazy('company') I just want to have it return to it's parent view on success. I currently have it redirecting to the parent's parent (company), as this view doesn't require a variable. This would be simple, but the parent view requires a variable farm_id to render, this is captured from the url like "/farm/18" url(r'^farm/(?P<farm_id>.+)', views.farm, name='farm'), I've solved this with forms on the page by having them redirect to the view farm with the variable farm_id. return redirect(farm, farm_id=farm_id) How could I do this with the success_url for my DeleteView? -
the view didn't return an HttpResponse object. It returned None instead.,nothing work
i am now working with Django in python. this is views.py class AddTeamView(View): def get(self, request): form = TeamForm() context={ 'form':form } def post(self, request): if request.method == "POST": form = TeamForm(request.post) if form.is_valid(): team = Mem() team.Your_Name = form.cleaned_data['Your_Name'] team.Your_Age = form.cleaned_data['Your_Age'] team.Your_Country = form.cleaned_data['Your_Country'] team.Your_Memories = form.cleaned_data['Your_Memories'] team.save() return redirect('/') return render(request, 'newmem.html', context) and this is the full error from terminal Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /new/ Traceback (most recent call last): File "C:\smile-env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\smile-env\lib\site-packages\django\core\handlers\base.py", line 198, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view web.views.AddTeamView didn't return an HttpResponse object. It returned None instead. [12/Sep/2017 21:32:39] "GET /new/ HTTP/1.1" 500 57308 i did search but nothing i don't know what's wrong i also added else in the end but same error -
Django model.save() Not Effecting New Instances of Same Model
I've hit this bug in an application I'm working on and have replicated it in a new django server instance to test. Here is the shell I ran: user@hostname:~/testproject$ sudo python3 manage.py shell Python 3.5.2 (default, Nov 17 2016, 17:05:23) Type 'copyright', 'credits' or 'license' for more information IPython 6.1.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from testapp.models import testmodel In [2]: a = testmodel.objects.first() In [3]: print(a.testvar1) 0 In [4]: a.testvar1 = 1 In [5]: print(a.testvar1) 1 In [6]: a.save() In [7]: b = testmodel.objects.first() In [8]: print(b.testvar1) 0 So could someone please explain why I can't adjust values of model instances and have those changes take effect when model.save() is run? I can't find any alternate way of modifying models in the Django documentation but any direction would be appreciated. Thanks! -
Mezzanine FileBrowser not allowing me to select an image
I am using mezzanine to deploy a simple blog website. Each part of the website has a header that needs to be easily changed by the blog team. My solution was to make a model with a FileField for the blog team to change a pages header on the admin page. I am using S3 bucket to store static and media files. Chief Complaint: When a user goes to upload a photo, the file gets uploaded to the S3 bucket, but I can't click the select button on the file that I am looking to use. Mezzanine file selector button. My implementation: I mainly used this tutorial to implement the backend for the file uploader (I only used S3). settings.py AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' MEDIA_ROOT = '' custom_storages.py from django.conf import settings from storages.backends.s3boto import S3BotoStorage from filebrowser_safe.storage import S3BotoStorageMixin class StaticStorage(S3BotoStorage, S3BotoStorageMixin): location = settings.STATICFILES_LOCATION class MediaStorage(S3BotoStorage, S3BotoStorageMixin): location = settings.MEDIAFILES_LOCATION models.py class Header(models.Model): file = FileField("File", max_length=200, format="Image", upload_to=upload_to("galleries.GalleryImage.file", "")) # other fields ... Error messages: FB_FileBrowseField.js:16 Uncaught TypeError: Cannot set property 'value' … -
Django / Postgres write-only database
For a specific security reason, a client has asked if we can integrate a 'write-only' DB into a Django web application. I have tried creating a DB then restricting access to one of its tables in psql via: REVOKE SELECT ON TABLE testapp_testmodel FROM writeonlyuser; But then trying to save a model in the Django shell... p = new TestModel(test_field="testvalue") p.save(using="writeonlydb") ...generates this error: ProgrammingError: permission denied for relation testapp_testmodel Which I assume is because the ORM generated SQL includes a return of the newly created object's id, which counts as a read: INSERT INTO "testapp_testmodel" ("test_field") VALUES ('testvalue') RETURNING "testapp_testmodel"."id" My question is therefore, is this basically impossible? Or is there perhaps some other way? -
django-windows-tools service not starting up
I am using django-windows-tools to start up a celery worker and beat service. I have followed the process given in the link. I have adjusted parameters to work for my settings and still fails to start up properly when I check the task manager. It shows I have a django-myapp-service created. Here is my services.ini file: [services] # Services to be run on all machines run=celeryworker clean=C:\inetpub\wwwroot\Django\BPTS\myapp\logs\celery.log [BEATSERVER] # There should be only one machine with the celerybeat service run=celeryworker celerybeat clean=C:\inetpub\wwwroot\Django\BPTS\myapp\logs\celerybeat.pid;C:\inetpub\wwwroot\Django\BPTS\myapp\logs\beat.log;C:\inetpub\wwwroot\Django\BPTS\myapp\logs\celery.log [celeryworker] command=celery worker parameters=--app=myapp.celery -f C:\inetpub\wwwroot\Django\BPTS\myapp\logs\celery.log -l info [celerybeat] command=celery beat parameters=--app=myapp.celery -f C:\inetpub\wwwroot\Django\BPTS\myapp\logs\beat.log -l info --pidfile=C:\inetpub\wwwroot\Django\BPTS\myapp\logs\celerybeat.pid [runserver] # Runs the debug server and listen on port 8000 # This one is just an example to show that any manage command can be used command=runserver parameters=--noreload --insecure 0.0.0.0:8000 [log] filename=C:\inetpub\wwwroot\Django\BPTS\myapp\logs\service.log level=INFO When I take the commands and arguments themselves they also do work. *It says commands will be run through python manage.py so here is what I do to run int manually. python manage.py celery worker --app=myapp.celery -f C:\inetpub\wwwroot\Django\BPTS\myapp\logs\celery.log -l info python manage.py celery beat --app=trackingsystem.celery -f C:\inetpub\wwwroot\Django\BPTS\trackingsystem\logs\beat.log -l info --pidfile=C:\inetpub\wwwroot\Django\BPTS\trackingsystem\logs\celerybeat.pid which works by the output in the terminal. -
Can we structure groups within a website using Django framework(groups like admin, moderators,helpers,users,etc)?
I am really-really badly stuck at choosing the backend language for web-development between php,python and ruby... especially i want to make myself clear among the respective frameworks like laravel/cakephp/CodeIgniter(php's framework), django(python's framework) and rails/sinatra(ruby's framework) ... i have once tried to do a small project using django. Now i am starting a new one where i want a website where i can divide the whole members into different categories like i already said admin,mods,helpers,users,etc. i thought of doing it with django since i have already used. So i went to django's official site and couldn't find any efficient result neither i could find any community support or forums so that i can discuss,so i have come here. Or please tell me how i can complete this task of structuring the site in this groups. I know php can do it but i really-really search the entire internet and found this and that blah...blah...blah.... i am just tired .Please help me out.Drop a very genuine and step by step thoughts for my ease.I know HTML,CSS and Bootstrap and a little django, now please tell me whether i should go with laravel,Rails or Django(Can Rails and Django do this task of structuring?). … -
graylog filters is not setup for django after configuration
I've set up a logging configuration as the dict below: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(levelname)s %(message)s' } }, 'filters': { 'fields': { 'env': 'test' } }, 'handlers': { 'graypy': { 'level': 'DEBUG', 'class': 'graypy.GELFHandler', 'host': 'graylog2.example.org', 'port': 12201, 'filters': ['fields'] } }, 'loggers': { 'testlogger': { 'handlers': ['graypy'], 'level': 'DEBUG', 'propagate': True } } } After I run the application phase through manage.py, I didn't see the filters, env:test popped up for on graylog GUI, so I checked the settings locally with python manage.py shell. In the console, I have the following check: l = logging.getLogger('testlogger') l.filters And it returns [], which expectedly should have env:test in the list. I've read a couple of tutorials of how to setup filters for GELFhandler in django, it seems like they all have similar format like my settings above, I don't know why only filters are not set for my logger. Because when I check the handlers, it returns [<GELFHandler (DEBUG)>] -
Django websocket app running alongside mod_wsgi app
i have a Django project/website that hold 3 chatting application two of them is using HTTp request as a chatbot the uses views.py to retrieve the replay from the DataBase , and the third on is using Django channels and websockets as a normal basic one-to0one chatting app, connecting and echoing the messages worked perfectly but the problem is that when i try to send a message using Group() function in consumer.py it doesn't work. So, i found out that the reason is that my websocket app doesn't seem to route correctly when running alongside my mod_wsgi app. So, the only solution is stopping my Apache,and then serving the whole app from your websockets port via the runserver command. When i did this the Group () worked, but the problem is i developed the whole website using Apache which it serves 2 of 3 apps in my Django website, the 3th one is using web sockets(and it took me a long time). I need both Apache and websockets in my Django project. this is my Apache config: ServerRoot "/home/mansard/webapps/gadgetron/apache2" LoadModule authz_core_module modules/mod_authz_core.so LoadModule dir_module modules/mod_dir.so LoadModule env_module modules/mod_env.so LoadModule log_config_module modules/mod_log_config.so LoadModule mime_module modules/mod_mime.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule setenvif_module modules/mod_setenvif.so … -
Authenticate username and password in my own login form in django
i have a class 'user' in my models.py...user has several attributes like userid,username,password,etc. this is a part of my login page login.html <form action="" method="post" enctype="multipart/form-data"> <h1>Login Form</h1> <div> <label><b>Username</b></label> <input type="text" id="username" placeholder="Enter username" required=""> </div> <div class="password"> <label id="labelp"><b>Password</b></label> <input type="text" required="" placeholder="Enter password" id="password"> </div> <div class="submitb"> <input type="submit" value="Log In"> </div> </div> i want to retrieve this username and password from here and want to authenticate it against the values i have in my user table(username and password) and then login the user. how do i do that? -
Issue with Django dbbackup and restore command
I have 2 Databases in my app : DATABASES = { MAIL_ACCOUNTS_DB_CONFIG: { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'rango', 'USER': 'rangoadmin', 'PASSWORD': 'rango@2017', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', 'OPTIONS': {'charset': 'utf8mb4'}, }, DEFAULT_DB_CONFIG: { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'rango', 'USER': 'rangoadmin', 'PASSWORD': 'rango@2017', 'HOST': 'localhost', 'PORT': '5432', 'CONN_MAX_AGE': 0, } } In setting.py, DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage' DBBACKUP_STORAGE_OPTIONS = {'location': '/home/shan/project_bkp'} DBBACKUP_GPG_RECIPIENT = 'XXXXXXXXXXXXXXX' When I run python manage.py dbbackup --encrypt --compress I can only see default-shan-desktop-2017-09-12-213553.psql.gz.gpg . Where is the backup of mysql DB` ? Question: How to know which database backup has been made ? When I fire python manage.py dbbackup --encrypt --compress --database MAIL_ACCOUNTS_DB_CONFIG I get `django.db.utils.ConnectionDoesNotExist: The connection MAIL_ACCOUNTS_DB_CONFIG doesn't exist How to backup each DB seperately ? How to restore it ? When restoring using python manage.py dbrestore --decrypt I get : CommandError: Because this project contains more than one database, you must specify the --database option. When I run : python manage.py dbrestore --decrypt --database MAIL_ACCOUNTS_DB_CONFIG I get: CommandError: Database MAIL_ACCOUNTS_DB_CONFIG does not exist.