Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python app with Tkinter to webapp
I have this little app deployed into windows that executes stored procedures for password reset. I created the whole GUI in tkinter with input box, buttons, popups, sends emails with new password and all. Now they want me to take the app into the web. What's the best way to do it? Django? And the easiest but fully functional ? CGI? Thanks for any recommendations, I'm a newbie with HTML and CSS. -
Vue.js 2.0 filters in text interpolations
I'm using vue.js 2.0 (standalone) build. HTML: <div id="app-8"> <p> ${ number | results_found } </p> </div> JS: <script> var app = new Vue({ delimiters: ['${', '}'], el: '#app', data: { number: 0, }, filters: { results_found: function(value) { console.log(value + " results found!"); return value + " results found!"; } } }) </script> I changed the delimiters (see above) so that they would not conflict with Django's templating syntax. When I run this I see in the console: 0 results found! Yet in the HTML all I see is: 0 What am I doing wrong? All new to Vue.js, by the way. -
Consume Dynamics CRM Web API directly into PostgreSQL database in Django web app
Microsoft Dynamics 365 CRM has most current client and company data and I need it for the internal database the frequently uses the data. Trying to replace duplicative databases where one is getting updated (CRM) and the other is not. Because it is Office 365 and hosted in the cloud, we don't have access to the database, just are able to use the Web API. The Web API is over an HTTPS connection and requires login credentials. One thought was to use a PostgreSQL FDW like www_fdw, which is great except it accepts no options for login credentials. There does not appear to be alternatives. So I am back to using Django, Python, and/or Javascript to get the JSON, de-serialize it, and import it into the database. I do not need to display it in a Django template. Really, it just needs to come from CRM and go directly into the database. I am just not sure the best way to handle it. For example, would the Django REST Framework make it easier than just using JavaScript and Python to request the Web API and de-serialize? From there, how is written to the database if it is bypassing Django? -
Python to Web Application
I've written a python application that pulls in some excel files, does some data analysis, then writes the result into an excel file where plots are created. Currently options are set using input arguments via argparse. I'm wondering if there's a good, low overhead way to make this a web application. Is a jupyter notebook published via jupyter.org a good idea? Would I need to do something with django? I'd need to read the files from a local path, allow the user to set options via some sort of web UI, and return the results in a new excel file. Any thoughts would be greatly appreciated. -
How can I set a frequency for some views on Django?
I am starting to develop with Django and I need help. I need to make some views work with a certain frequency. For instance: I need to call the view A at every 30 minutes, the view B once a day and the view C once a week. Any ideas how can I do that? Thank you very much. -
Django migration issue after database restore
I get issues anytime I make a backup / restore of my database since migrations files are no more compatible. Any techniques to solve such migrations incompatibilities ? -
trouble installing mysql python, mysqldb module not found in django
I'm using mysql with django for the first time. Both are installed, i can use mysql in the workbench or command prompt, however when i tried makemigrations in django, it can't find the mysqldb module, cut most of it out, see below: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\jerro\Desktop\djangoEnv\lib\site-packages\django\db\backends\mysql\base.py", line 28, in raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb So i've been trying to use pip install mysql-python and can't do it. I've installed mysql-connector, annaconda, and tried many other suggestions on this and google, not luck. It gives me the error below: running build_ext building '_mysql' extension creating build\temp.win-amd64-2.7 creating build\temp.win-amd64-2.7\Release C:\Users\jerro\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include" -IC:\Python27\include -Ic:\users\jerro\desktop\djangoenv\PC /Tc_mysql.c /Fobuild\temp.win-amd64-2.7\Release\_mysql.obj /Zl _mysql.c _mysql.c(42) : fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory error: command 'C:\\Users\\jerro\\AppData\\Local\\Programs\\Common\\Microsoft\\Visual C++ for Python\\9.0\\VC\\Bin\\amd64\\cl.exe' failed with exit status 2 ---------------------------------------- Command "c:\users\jerro\desktop\djangoenv\scripts\python.exe -u -c "import setuptools, tokenize;file='c:\users\jerro\appdata\local\temp\pip-build-_da1js\MySQL-python\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record c:\users\jerro\appdata\local\temp\pip-kqvwr3-record\install-record.txt --single-version-externally-managed --compile --install-headers c:\users\jerro\desktop\djangoenv\include\site\python2.7\MySQL-python" failed with error code 1 in c:\users\jerro\appdata\local\temp\pip-build-_da1js\MySQL-python\ Nothing i've done or … -
Collectstatic error on deploying django app
I am getting error when trying to deploy my django app (the download and installation of packages went fine): $ python manage.py collectstatic --noinput Traceback (most recent call last): execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in __getattr__ File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 98, in __init__ utility.execute() self._setup(name) File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup self._wrapped = Settings(settings_module) % (self.SETTINGS_MODULE, e) ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 This is my settings.py file: """ Django settings for mysite project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*****' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False TEMPLATE_DEBUG = False ALLOWED_HOSTS = ["aa@bm.net"] # Application definition … -
Arbitrary amount of fields in Modelform
At first let me excuse for my English, it's not my native language. I need to construct a table of, say, 1000 rows and 5 cells in each row, so i've decided to have Cell and Row models. models.py class Cell(models.Model): content = models.CharField(max_length=100) row = models.ForeignKey('Row') class Row(models.Model): pass The contents of the table cells is unimportant (at the current stage i'm filling it with random data). What i need is to be able to add a new rows. The form should have an input field (it's nature is absolutely inconsiderable) in each cell. I prefer to use a Modelform: forms.py class RowForm(forms.ModelForm): class Meta: model = Row fields = ??? <- problem here. How can i get a Modelform that supplies input fields for each cell (keeping in mind that the amount of the cells may change in future)? I hope i've expressed my needs quite clearly. Thanks a lot! -
Django - Python - Override AbstractBaseUser Model Email As Username Unique Condition With Unique Together
I am writing a Django web application which has two types of users. The user model is a custom one using the email field as the username. In order to differentiate users I have set up two Boolean_fields. I am currently facing a challenge with the uniqueness of the username (i.e. email in my case) as the fact that all users must live in the same model implies that there cannot be a user of Type1 with the same email address than a Type2 user. Ideally I would like a user to be able to have two accounts (one of each type) with the same email address if he/she desires so. I have thought of using the 'unique_together' attribute but using the email as the username constrains to have 'unique=True' as a parameter for email in the custom user model. Would anyone know a solution to this issue? Thanks. -
How to display nested model as list of its first field
I have two models with many-to-many relation. class MyModel(models.Model): value = models.CharField(max_length=255) tests = models.ManyToManyField(to='Test', null=True, related_name='models') class Test(models.Model): name = models.CharField(max_length=255) What I am trying to accomplish is to display 'MyModel' as a list of its 'value' field. Here are my serializers (pretty simple as well): class MyModelSerializer(serializers.Serializer): value = serializers.CharField() class Meta: model = models.MyModel fields = ('value',) class TestSerializer(serializers.ModelSerializer): models = MyModelSerializer(many=True, read_only=True) class Meta: model = models.Test fields = ('name','models') So far I get a list of objects: "name": "", "models": [ { "value": "question" } ] Is there a way to display 'value' fields as a list of strings not a list of objects? Important, I would like to avoid serialization methods or any methods in models. Is there any built-in way? -
Upload user file to google drive through django web application
I want to use Google Drive as storage for my Django project (in particular I need to store images taken by users). What I'm trying to achieve is the following: Users upload their images using a form. These files must be somehow routed through Django which redirects them to Google Drive using Google Drive API. The reason I do not send the files directly from the user's browser to Google Drive is that I should store on the client side the secrey key to access Google Drive API (which, of course, must not be directly accessible to the users). Once uploaded, I must be able to display them in a gallery on my site. So far I've read Google Drive API documentation and, in particular, I've managed to accomplish the quickstart using OAuth2 for server to server application, see here (the quickstart cover the case where files are uploaded to user's Google Drive folder so the is an intermediate step of user authentication that I do not need). SIDE QUESTIONS: Is there a way to access in a browsable way the list of files uploaded by the users to Google Drive through the API or the API is the only … -
Wrong SQL query rendering in Django Debug Toolbar
There's some issue with displaying SQL queries in Django Debug Toolbar. They look like: <strong>SELECT</strong> <a class="djDebugUncollapsed djDebugToggle" href="#">&#8226;&#8226;&#8226;</a> <a class="djDebugCollapsed djDebugToggle" href="#">COUNT(*) <strong>AS</strong> &quot;__count&quot;</a> <strong>FROM</strong> &quot;categories_category&quot;<strong>INNER JOIN</strong> &quot;categories_categorygroup&quot;<strong>ON</strong> (&quot;categories_category&quot;.&quot;category_group_id&quot;= &quot;categories_categorygroup&quot;.&quot;id&quot;) <strong>INNER JOIN</strong> &quot;categories_supercategorygroup&quot;<strong>ON</strong> (&quot;categories_categorygroup&quot;.&quot;super_category_group_id&quot;= &quot;categories_supercategorygroup&quot;.&quot;id&quot;) <strong>INNER JOIN</strong> &quot;categories_supercategorygroup_sites&quot;<strong>ON</strong> (&quot;categories_supercategorygroup&quot;.&quot;id&quot;= &quot;categories_supercategorygroup_sites&quot;.&quot;supercategorygroup_id&quot;) <strong>WHERE</strong> (&quot;categories_supercategorygroup_sites&quot;.&quot;site_id&quot;= 1 <strong>AND</strong> &quot;categories_category&quot;.&quot;is_urgent&quot;= <strong>true</strong>) -
Cookie sent from backend not being set on frontend
I have the following situation. Part I: localhost:3000 is frontend (React) localhost:8000 is backend (Django) I make a successful cross-domain GET (I'm using django-cors-headers package) Part of the response headers: Set-Cookie: csrftoken=token; expires=Fri, 16-Feb-2018 10:56:00 GMT; Max-Age=31449600; Path=/ the cookie csrftoken is not being set in the browser (if I'm right, it's due to the browser ignoring cookies from a different domain), although I have it set to allow third-party cookies and site data (in Chrome's settings) POST fails due to csrf cookie not being set Part II: I set the cookie manually everything works perfect This is my ajax request: jQuery.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); jQuery.ajax({ url: url, type: 'POST', data: {attr: value, csrfmiddlewaretoken: csrftoken}, crossDomain: true, xhrFields: { withCredentials: true } }) csrft token in the headers and in the body arrive to the backend, but without the cookie. My question is - is there a way to tell Django to check for csrf token in the headers only? Or is it a bad idea? If that is not an option, what is an option? Is there any way to include the cookie in my POST? -
Django Rest Framework global pagination and pagination_class are not working
My settings: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2 } My pagination Class: from rest_framework.pagination import PageNumberPagination class CustomNumberPagination(PageNumberPagination): page_size = 5 My Testing View Class: from rest_framework.pagination import PageNumberPagination from circulation.pagination import CustomNumberPagination class Testing(generics.GenericAPIView): queryset = Testing.objects.all() serializer_class = TestingSerializer pagination_class = CustomNumberPagination def get(self, request): print PageNumberPagination.page_size # 2 print self.pagination_class.page_size # 5 queryset = self.get_queryset() serializer = self.serializer_class(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) I can print out the page_size of PageNumberPagination and CustomNumberPagination in my console correctly. However, passing page as a parameter doesn't have any effect. I couldn't get either global paginations or pagination_class in each view to work. -
Custom sql in django migration doesn't work
I'm trying to run custom SQL in my migration. This is how it looks like: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunSQL( "SET timezone TO 'UTC'", ), ] When I run it with ./manage.py migrate helper I can see in the logs that SQL command was run: [17/Feb/2017 20:37:37] DEBUG [django.db.backends.schema:103] SET timezone TO 'UTC'; (params None) [17/Feb/2017 20:37:37] DEBUG [django.db.backends:90] (0.000) SET timezone TO 'UTC'; But when I go and check it in database it still says timezone is localtime: gdp=# show timezone; TimeZone ----------- localtime (1 row) If I run the same command manually it works OK: gdp=# SET timezone TO 'UTC'; SET gdp=# gdp=# show timezone; TimeZone ---------- UTC (1 row) Django version: 1.10.5 PostgreSQL version: 9.5.5 Full logs: [17/Feb/2017 20:37:37] DEBUG [django.db.backends:90] (0.591) CREATE EXTENSION IF NOT EXISTS postgis; args=None [17/Feb/2017 20:37:37] DEBUG [django.db.backends:90] (0.002) SELECT c.relname, c.relkind FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('r', 'v') AND n.nspname NOT IN ('pg_catalog', 'pg_toast') AND pg_catalog.pg_table_is_visible(c.oid); args=None [17/Feb/2017 20:37:37] DEBUG [django.db.backends.schema:103] CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMARY KEY, "app" varchar(255) NOT NULL, "name" varchar(255) NOT NULL, "applied" timestamp with time zone … -
Django can't connect to Postgres in Docker setup
I'm setting up an application in Docker that uses Django and Postgres. I'm unable to connect to Postgres from the app. When I run either: docker-compose run web python manage.py runserver docker-compose run web python manage.py migrate I get the following error: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Here's my Dockerfile: FROM python:2.7 ADD requirements.txt /app/requirements.txt WORKDIR /app/ RUN pip install -r requirements.txt My docker-compose.yml: version: '2' services: db: image: postgres:9.4 hostname: db environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres ports: - "5432:5432" web: build: context: . dockerfile: Dockerfile hostname: web volumes: - .:/app ports: - "8000:8000" links: - db depends_on: - db command: python manage.py runserver 0.0.0.0:8000 and the database settings in Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } docker ps -a shows: e9df7e1644ce web "python manage.py ..." About a minute ago Up About a minute 0.0.0.0:8000->8000/tcp web_1 60801d3256e4 postgres:9.4 "docker-entrypoint..." About a minute ago Up About a minute 0.0.0.0:5432->5432/tcp db_1 Django v1.10.5 Docker for Mac v1.13.1 docker-compose v 1.11.1 -
In template 'a href' adds domain to the url, making url like my_domain/my_url. How to avoid this behaviour?
I have a model like this: class Slide(models.Model): slideshow = models.ForeignKey(Slideshow, verbose_name=_('slideshow'), blank=False) title = models.CharField(_('title'), blank=False, max_length=255) image = FileBrowseField(_('image'), max_length=255, null=True, blank=True, default=None) url = models.CharField(_('url'), blank=True, max_length=255) And in template I do: {% for slide in slideshow_slides %} <a href="{{ slide.url }}"> -->> {{ slide.url }} </a> {% endfor %} As a result I have the text: -->> google.com and url: mydomain.com/google.com How to get a url just google.com without such addition as mydomain.com? -
Iterate through Django Inline Objects
I have a restaurant menu with 2 models. A Product model and a MenuSelection model. A product can belong to many menus. The MenuSelection is added to Product as in inline relationship. The challenge I am having is listing menu objects in ModelAdmin list_display. Do I need to create a ForeignKey relationship or create a @property that iterates through the Inline objects? I definitely hit another wall in my experience. Any help would be much appreciated. MenuSelection class MenuSelection(ClusterableModel): menu_section = models.CharField(default=None, max_length=100, choices=MENU_CHOICES, unique=True, verbose_name='Menu Section') menu = models.CharField(default=None, max_length=100, choices=MENU, unique=True, verbose_name='Menu') menu_price = models.DecimalField( blank=True, null=True, max_digits=5, decimal_places=2, verbose_name='Menu Price', help_text='Numbers only with 2 digital decimal. I.e. 25.00' ) panels = [ MultiFieldPanel( [ FieldPanel('menu'), FieldPanel('menu_section'), FieldPanel('menu_price'), ], heading="Menu & Prices", classname="collapsible" ), ] Product class ProductMenuPrices(Orderable, MenuSelection): page = ParentalKey('Product', related_name='menu_selection') @register_snippet class Product(ClusterableModel): product_title = models.CharField(max_length=255, verbose_name='Menu Item') product_description = models.TextField(verbose_name='Product Description', blank=True) panels = [ MultiFieldPanel( [ FieldPanel('product_title'), FieldPanel('product_description'), InlinePanel('menu_selection', label="Menu & Price Assignment", max_num=3), ], heading="Product Detail", classname="collapsible" ), ] class Meta: verbose_name = 'Menu Item' def __str__(self): return self.product_title ProductModelAdmin class ProductModelAdmin(ModelAdmin): model = Product menu_label = 'Menu' menu_icon = 'snippet' menu_order = 300 add_to_settings_menu = False exclude_from_explorer = False list_display = … -
PageNumberPagination and a queryset without fixed order
According to the documentation, nothing special is required to enable pagination when using a class inheriting from GenericAPIView. I've look in the code of django and django rest framework and the ViewSet queryset doesn't seem ordered. The pagination only adds the SQL keywords LIMIT and OFFSET to the query. What I don't understand is how is handled a queryset that doesn't have a deterministic order ? Why the documentation doesn't say to add a .order_by() statement at the end of the ViewSet queryset ? -
What is the difference between @login_required and @method_decorator(login_required) in django
I am new to django and i am confused What is the difference between @login_required and @method_decorator(login_required) in django, which one we should use. Thanks in advance. -
Read and print the database in django html&sqlite3
I'm just stuck. How can I print the database in html on Django? I have "jegy.html" where I wanna print the jegy table, but else I said, I'm stuck. views.py: from django.shortcuts import render, get_object_or_404, render_to_response def index(request): return render(request, 'jegyrendeles/index.html', {}) def reg(request): return render(request, 'jegyrendeles/reg.html', {}) def jegy(request): return render(request, 'jegyrendeles/jegy.html', {}) def belep(request): return render(request, 'jegyrendeles/belep.html', {}) models.py from django.db import models class Jegy(models.Model): j_id = models.IntegerField(primary_key=True, blank=True, null=False) j_nev = models.TextField(blank=True, null=False) j_place = models.TextField(blank=True, null=False) class Meta: managed = False db_table = 'jegy' class Rendeles(models.Model): r_id = models.IntegerField(primary_key=True, blank=True, null=False) j_id = models.IntegerField(blank=True, null=False) sz_id = models.IntegerField(blank=True, null=False) class Meta: managed = False db_table = 'rendeles' class Szemely(models.Model): sz_id = models.IntegerField(primary_key=True, blank=True, null=False) sz_nev = models.TextField(blank=True, null=False) sz_pw = models.TextField(blank=True, null=False) class Meta: managed = False db_table = 'szemely' -
python manage.py collectstatic : boto.exception.S3ResponseError: 400 Bad Request
Hello all, I want to use a S3 bucket in Franckfurt or in London(eu-west-2). I have an existing bucket in Oregon and create another in ireland. The django command "python manage.py collectstatic" work well. Collectstatic comes from Django==1.10.5 (January 4, 2017) running on "windows 10" python 2.7 But when executing "python manage.py collectstatic" on a London or Frankfurt S3 bucket, i got the error : boto.exception.S3ResponseError: S3ResponseError: 400 Bad Request. refering to : Using boto for AWS S3 Buckets for Signature V4 boto S3ResponseError: 400 Bad Request So i did the followings : I create a ~.boto file and add 1 line: [s3] use-sigv4 = True.....failed I create a ~.boto\config file. Add 1 line: [s3] use-sigv4 = True.....failed I modified ~.aws\config file with region = eu-west-2...failed Any suggestion ? Thank you -
Django print labels
I have a database full of families with addresses. I want to print out mailing labels for each family. I have various avery labels to use, is there an easy way to do this task? Is there a library or some tutorials you know of that others have used to accomplish this? I used a project that was ported to python 2.6 and used pyPDF to make a pdf with labels of specific dimensions, but I think it may be outdated. The labels printed don't line up. Do I just need to adjust these or is there an easier way to save the data and do a mail merge in Word? -
Issues with 'django.contrib.staticfiles',
I have a website that works fine on my 'production server' with the url being something akin to: https://mymain.site.com I have had my sys admins build a site out for development and that url is: https://mymain.site.com/development It is a different IP address, but I believe the URL is wrecking havoc on django routing. Mostly I notice it in the static section of it. If I goto the development server settings and change the static url to: /development/static/ instead of /static/ like it was on production None of my static files are found. Since the development server is a VM copy the root on the server for static files is the same. So if I run with the /development/static as the dev url it fails to load resources. If I run on my development server with the url being /static/ I am 90% sure it is grabbing the static files from the production server (at a different ip/url). Not totally sure what the fix is here? I am loking for any kind of ideas. I suspect if the url of my development server was something more akin to: https://mymain.site.for.development/ then this would work right out of the box from the code …