Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IOError when trying to send email in Django app
I have a Django app running on a server with uWSGI and nginx. In my local_settings.py file I have this: ############### # EMAIL SETUP # ############### EMAIL_HOST = 'smtp.privateemail.com' EMAIL_HOST_USER = 'support@mydomain.com' EMAIL_HOST_PASSWORD = 'MY EMAIL PASSWORD' EMAIL_PORT = 587 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True ######################## # OTHER EMAIL SETTINGS # ######################## ADMIN_EMAIL = "admin@mydomain.com" SUPPORT_EMAIL = "support@mydomain.com" When I fill out the /password_reset/ template with an email and submit the form, the email I enter gets no email. I see these lines in my uwsgi.log file after I submit the password reset form. Fri May 11 17:48:10 2018 - SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /password_reset/ (ip 73.49.35.42) !!! Fri May 11 17:48:10 2018 - uwsgi_response_write_headers_do(): Broken pipe [core/writer.c line 248] during POST /password_reset/ (73.49.35.42) IOError: write error What error is this? Why won't the password reset email send? -
Not showing data in the template, Django=1.11
I've a simple model class Task(models.Model): author = models.ForeignKey('auth.User', on_delete=models.PROTECT, related_name='+') name_task = models.CharField(max_length=1000) label_task = models.ManyToManyField(LabelTask) executive_man = models.ManyToManyField(User) But in template not all data show me, for example code from views look like def task_detail(request, pk): task = get_object_or_404(Task, pk=pk) return render(request, 'task/task_detail.html', {'task': task}) And template look like <small>{{ task.author }}</small> <h1>{{ task.name_task }}</h1> <p>Label - {{ task.label_task }}</p> <p>Executive - {{ task.executive_man }}</p> But all data show good, but Label - task.LabelTask.None Executive - auth.User.None I do not right it. Label - instead of data is the task.LabelTask.None Executive - instead select users - auth.User.None But in my admin look all good. Hope you help me. Thank you very much. -
Ensure that urlpatterns is a list of path() and/or re_path() instances
What's wrong with my urlpatterns? urlpatterns = [ re_path(r'^dj-admin/', admin.site.urls), re_path(r'^admin/', include(wagtailadmin_urls)), re_path(r'^docs/', include(wagtaildocs_urls)), i18n_patterns( path(r'', include(wagtail_urls)), prefix_default_language = False ) ] ERRORS: ?: (urls.E004) Your URL pattern [ (None:None) ''>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. To my best understanding it is equivalent to the example in the docs: urlpatterns = [ path('sitemap.xml', sitemap, name='sitemap-xml'), ] urlpatterns += i18n_patterns( path('about/', about_views.main, name='about'), ) BTW: In [1]: import django In [2]: django.__version__ Out[2]: '2.0.5' -
How to enumerate elements for each foreign key
friends. I have 2 classes (part and data). To each element of class Part there are several elements of class Data (via foreign key). So, I have 2 tables in SQLite: Part and Data. The ID numbering in the Data table is continuous, that is, regardless of whether the foreign key has changed, the table ID is incremented. How to number the table for each foreign key independently (from 1 to the number of rows with one foreign key)? By the way, English is foreign language :) -
Django CSTF missing or Sessions middleware required
When trying to create a django 2 rest framework api, I keep getting this error. Forbidden (CSRF token missing or incorrect.): /login/ After doing some research the problem might be with sessions authentication which I dont really need since I will be replying on token based auth. When I try to remove some of the session auth from my settings I end up getting this. AssertionError: The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE setting to insert 'django.contrib.sessions.middleware.SessionMiddleware' before 'django.contrib.auth.middleware.AuthenticationMiddleware'. Settings.py snippet INSTALLED_APPS = [ # API (v1) 'apiV1.v1.accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Requirements 'corsheaders', 'rest_framework', 'rest_framework.authtoken', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', # 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'apiV1.urls' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.SessionAuthentication', ), } Views.py from django.contrib.auth import authenticate from django.shortcuts import get_object_or_404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from apiV1.v1.accounts.models.user import User from apiV1.v1.accounts.serializers.user import UserSerializerLogin # login class LoginView(APIView): authentication_classes = () permission_classes = () @staticmethod def post(request): """ Get user data and API token """ user = get_object_or_404(User, email=request.data.get('email')) user = authenticate(username=user.email, password=request.data.get('password')) if user: serializer = UserSerializerLogin(user) … -
Django 2 - How to register a user using email confirmation and CBVs?
This question specifically aims for a Django 2.0 answer as the registration module isn't available (yet) for it. More, this might seem to broad, but I often found myself in situations where I can't use any 3rd party module because ... oh well..policies. I'm sure many did. And I know that looking and putting together information taken from here or django docs was a headache. Workflow: Let's suppose we need the following flow: The user goes to the sign-up page and fills in the following fields: first_name, last_name and email (the email will be used as the username). The user submits the form and receives a confirmation email with an URL containing a unique token. When the user clicks on the received link, he's redirected to a page where he'll set his password. When done, he's logged in to the dashboard page. Extra-info: The user will later log in by using his email (which is actually his username) and password. Specific question: How will the models/views (using CBVs)/forms/urls look like? -
how to relate 'publishe_db' model with User() model to let username1 username2 ...create here publish in django
User() model this = from django.contrib.auth.models import User create class to add publication from the User class publishe_db(models.Model): title = models.CharField(max_length = 500) body = models.TextField(max_length = 5600) file = models.FileField() date = models.DateTimeField(auto_now_add = True) def __str__(self): return self.title -
Django database replication with Postgresql
In my Django application, I am planning to create two mirror database (maybe both R/W or one for write and both for read) + one backup only database(write only for disaster management) with Postgresql. Now I read the Django MultiDB documentation and Postgres mirroring but the part I don't understand is how do I configure those? Does Django MultiDB take care of synchronization between different databases? or what I think is, I need to write DB routers in Django for Django multiple databases R/W operation and setup mirroring functionality manually for Postgresql like by using Pgpool-II or similar. Can anyone PLEASE Guide me the Correct way for this? -
Can't create gunicorn_start in deployment process
I am trying my first deployment. Following this instructions. The problem is that those instructions are for python 2.7, while I am on 3+. So I have mixed it with some another instructions. I have created a virtual environment for python 3. Run python manage.py runserver 0.0.0.0:8000 also successfully. But stopped on the point of configurating Gunicorn. When I write vim bin/gunicorn_start - I come to vim redactor, I write some configuration, but next when I try save and exit with :wq - I get E212 error, which in brief says that I can't save that file, but I don't know the reason of that. Why does that happen? What am I doing wrong? Here is a structure of folders beginning from my_project_folder mowing to the top level folder, got with ls, may be that will help somehow (first in the row is folder where we come from).: ^ Cosmo | polo polo_env | environments | chiefir | home bin boot dev etc initrd.img lib lib64 lost+found media mnt opt proc root run sbin snap srv sys tmp usr var vmlinuzcd -
Error on OR on filter Django
i'm try create or on filter on django This is my little example : products=Products.objects.values('name', 'price').all().filter(status=1|0) The problem is that don't validate the two options (1|0) don't get a error on the print(products.query) only validate one option don't the 2 options..!! Please thanks !! -
Python - HTML to PDF with Jinja - the most secure option
In my project I get data like Name and Username from user using form based at Javascript(Axios). Data from form I want placed at HTML template and then from HTML file generate to .PDF document. I do not need save any file. I want to only generate some files without saving it inside my VM. In this case I have some ideas, but I don't know, which is the best. User give me some data, then inside template I got special prepared string and after opening the file (read file in Python) I want to use .replace() method to change them. For example: <p>USERNAME</p> The second option is to use Jinga template engine. But is it necessary? What is the best way to generate data to .PDF? Thanks in advance! -
Storing and querying a sequence in python
Let's say we're using Django with a Postgres database. I want to store a sequence of data like so: Record 1: 1, 2, 3, 4, 5 Record 2: 7, 8, 2, 3, 1, 9, 6 Record 3: 4, 4, 3, 2 A couple points to note: The sequence will always be one-dimensional. A sequence can have redundant values. A sequence can be of variable length. So first thing; I want to store this information in the database. There are lots of ways I can accomplish this, so let's look into my querying requirements. Let's say I have a query sequence 1, 2, 3. Now I want to identify the sequences that match this sequence. A match would meet one of the following cases: Case A: The sequence contains the query 1, 2, 3 in that order. In the example, Record 1 matches this. Case B: The sequence contains the components of the query 1, 2, 3 in any order. In the example, Record 1 and 2 match this. Case C: The sequence contains some of the components of the query 1, 2, 3 in any order. In the example, all records match this. In a perfect world I'd like the … -
how to apply complicated ORM query in django
I have 3 models. I am using billmanagment for date and customerproductbill table save record of product sale that how many products sale. I am using ORM django query and get record correctly but i need also those product which is not sale and in my customerproduct just save sale product record. I need sale and not sale product, because i am developing Ledger of inventory which shows all record. Here is my queriy: products = Product.objects.all().order_by('id') --------------------------------------------------- product_sale_history = BillManagement.objects.filter(Q(creation_date__gte=from_date) & Q(creation_date__lte=to_date) & Q(product__in=products) ).exclude( Q(customer_id=1248)).values('customerproductbill__product_id')\ .annotate(sale_quantity = Coalesce(Sum('customerproductbill__product_qty'), 0)).order_by('customerproductbill__product_id') class Product(models.Model): """ Represent an Inventory Product entity """ product_name = models.CharField(max_length=512, null=True, blank=True) reference_number = models.CharField(max_length=20, null=True, blank= True, unique=True) class Meta: verbose_name_plural = 'Inventory Products' def __unicode__(self): return self.product_name ------------------------------------------------------- class BillManagement(models.Model): """ Represent a Bill entity""" bill_number = models.CharField(max_length=250, null=True, blank=True) creation_date = models.DateField(auto_now_add=True) product = models.ManyToManyField(Product,through='CustomerProductBill', related_name='customer_product_bill') class Meta: verbose_name_plural = 'BillManagements' ordering = ['creation_date'] def __unicode__(self): return self.creation_date ------------------------------------------------ class CustomerProductBill(models.Model): """ Represent a CustomerProductBill entity """ bill = models.ForeignKey(BillManagement, null=True, blank=True) product = models.ForeignKey(Product, null=True, blank=True) product_qty = models.IntegerField(null=False, blank=False, default=0) class Meta: verbose_name_plural = 'CustomerProductBill' ordering = ['product'] def __unicode__(self): … -
Postgres and django. Restore data
I have dump of the database. And I have the table users, and there are many columns, but I want extract from the dump only id and status and update it in the production database. How can I do it? -
Django/Python: How to iterate through a list in a dictionary
I’m trying to set up migration files to load values into my tables. I am creating countries/states in my tables. I would like to set it up in a way that I can put each country in its own file, and then run through all the countries on migration. I successfully got all the names in separately, but I’m trying to make it easier. I think I want to make the country into a dictionary: # Country import_country = ['CAN', 'CANADA'] # State import_states = [ ['CAN', 'AB', 'ALBERTA'], ['CAN', 'BC', 'BRITISH COLUMBIA'], ['CAN', 'MB', 'MANITOBA'], ['CAN', 'NB', 'NEW BRUNSWICK'], ['CAN', 'NL', 'NEWFOUNLAND & LABRADOR'], ['CAN', 'NS', 'NOVA SCOTIA'], ['CAN', 'NT', 'NORTHWEST TERRITORIES'], ['CAN', 'NU', 'NUNAVUT'], ['CAN', 'ON', 'ONTARIO'], ['CAN', 'PE', 'PRINCE EDWARD ISLAND'], ['CAN', 'QC', 'QUEBEC'], ['CAN', 'SK', 'SASKATCHEWAN'], ['CAN', 'YT', 'YUKON'], ] canada = { country: import_country, states: import_states, } The country and states are two different models related by ForeignKey. Here’s the method that I used for the country part(state is very similar): def import_countries(apps, schema_editor): Country = apps.get_model('app', 'Country') for c in import_country: country = Country.objects.get_or_create( country_code=c[0], country_name=c[1] ) I want to iterate through all the countries: list_of_countries = [canada, usa, mexico] And then have it … -
Open tag issue when inserting model into forms in Django
I've a model in Django called "Bank". The bank model has an attribute called "currencies" which describes what type of currency they handle (e.g. USD, EUR etc). While creating a modelform to create a new bank, I wanted some specific formatting on my drop-down to select a currency and thus have the following code: <div class='form-group'> <label class="control-label col-md-3 col-sm-3 col-xs-12">Currency</label> <div class="col-md-6 col-sm-6 col-xs-12"> <select id="currency_id" class="form-control" required> <option value={{form.currency}} </select> </div> </div> This code works, however if I try to close the option tag by writing the following: <option value={{form.currency}}></option> The dropdown will show but with a ">" at the end of the dropdown. Why is this generated? I feel like there is some issue with my css when my HTML only works without me closing the tag. -
Python distributed tasks with multiple queues
So the project I am working on requires a distributed tasks system to process CPU intensive tasks. This is relatively straight forward, spin up celery and throw all the tasks in a queue and have celery do the rest. The issue I have is that every user needs their own queue, and items within each users queue must be processed synchronously. So it there is a task in a users queue already processing, wait until it is finished before allowing a worker to pick up the next. The closest I've come to something like this is having a fixed set of queues, and assigning them to users. Then having the users tasks picked off by celery workers fixed to a certain queue with a concurrency of 1. The problem with this system is that I can't scale my workers to process a backlog of user tasks. Is there a way I can configure celery to do what I want, or perhaps another task system exists that does what I want? -
Django - Unable to access css file in static under root folder. Error 404 in console
I am unable to access 'css' and 'js' files placed in 'static' folder under the root folder. The following error is displayed in the log - [11/May/2018 11:07:33] "GET /static/home.css HTTP/1.1" 404 1648 below is settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') Part my the html template: <head> <title>HomePage</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> {% load staticfiles %} <link rel="stylesheet" type="text/css" href={% static '/home.css' %}> <script type="text/javascript" src={% static '/home.js'%}></script> </head> urls.py urlpatterns = [ . . ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) When I try to access css manually by typing 'http://127.0.0.1:8000/static/home.css' in the browser I get Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/home.css Raised by: django.views.static.serve 'home.css' could not be found Also, I was thinking how I could have same css throughout my application? Aand, what if I add the css and js in my html template directly? Will it be a problem when I deploy in production? -
Django modelform field how to make disabled and prevent tampering?
There is this disabled attribute. But i am not able to apply it to the modelform fields. I am not sure how to. I can add it to forms.Form easily. But since I am using widgets I just dont know where to insert it. https://docs.djangoproject.com/en/2.0/ref/forms/fields/#disabled class TestForm(forms.ModelForm): class Meta: model = Test fields = ['date'] widgets = { 'date': forms.TextInput(attrs={'readonly': 'readonly'}), } -
Django Redirect - String Versus Slug
Not sure if I should be doing this or not..but here it goes. I have a url that looks like this: /deals/category/Apparel/ I changed it to category/Apparel to shorten it. but also notice the capitalized Apparel --as it is using the category name. So i added a slug to my Category model and I'm trying to redirect the deals/category/Apparel to category/apparel where the latter represents the slug in my deals app i have this URL: path('category/<str:category>', RedirectView.as_view(pattern_name='category', permanent=True)), and it is 'supposed to be' redirecting to this url: path('category/<slug:slug>', deals_by_category, name='category') my view for the `deals_by_category' looks like this: def deals_by_category(request,slug): category_deals = Deal.objects.filter(category__slug=slug).order_by('expired','-date_added') category = category_deals[0].category return render(request, 'deals/category.html', {'category_deals': category_deals, 'category':category}) so when i go to deals/category/Apparel it is redirecting to category/Apparel which is not what I want...and i get an error like this: IndexError at /category/Beauty list index out of range pointing at this line in my view category = category_deals[0].category can anyone advise on this? -
Autocomplete in Django
I have problems with the autocomplete in Django, Django recognize the autocomplete but it gets a 404 error when I try it this is the part of the template I'm using the autocomplete <table> <td class="input-group mb-3"><label for=" {{TeacherForm.teacher.id_for_label}}"> Teacher(es): <td> <div class="ui-widget"> {{TeacherForm.asesores}}</td> </div> </table> This is my model: class Teacher(models.Model): firstname=models.CharField(max_length=50) middlename=models.CharField(max_length=30) lastaname=models.CharField(max_length=30) This is my form: class TeacherForm(forms.Form): teacher=forms.CharField(widget=forms.Textarea) This is the script I'm using: <script> $(function() { $("#id_teacher").autocomplete({ source: "/api/get_teacher/", select: function (event, ui) { //item selected AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } </script> This is my url.py: urlpatterns = [ url(r'^api/get_teacher/', views.get_teacher, name='get_teacher'), ] And in my view.py I have: def get_teacher(request): if request.is_ajax(): q = request.GET.get('term', '') asesor = Asesor.objects.filter(lastname=q) results = [] for professor in teacher: teacher_json = {} teacher_json = professor.lastname+ " "+professor.firstname+" "+professor.middlename results.append(teacher_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) In my base_layout I'm calling: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script> <!-- jQuery UI !--> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> When I try it, i get this error GET http://localhost:8000/api/get_teacher/?term=Guerrer 404 (Not Found) How can I solve the error -
Running periodic task at time stored in database
Currently I have periodic tasks set up with a Job Scheduler on my Azure instance. These are triggering api (django) endpoints at fixed times. I want to make these times dynamic (which will not work with this solution). The plan is to fire these tasks directly from django. The schedule times will be stored in my database (MySQL) and be retrieved to create the scheduled job. When these values are changed the scheduler should also change accordingly. After looking at Celery it seems that using periodic tasks crontab schedules could work. Using this, is it possible to set my scheduled time based on values from my database? It looks like I will also need a Redis instance as well. Since I would only be using Celery for periodic tasks is it still the right approach? -
Disallowed host with Django, Kubernetes and a Load Balancer on Google Cloud Platform
I'm just getting started with GCP and Kubernetes Engine. So far I managed to start a Kubernetes cluster, run my app in a pod and connect it to a Cloud SQL instance. I also added a load balancer so now my app has a static IP and I should be able to connect to it from the outside. However, I just get a DisallowedHost error? Which IP should I allow? The IP of the pod that is completely random or the IP of the load balancer? -
Restructuring Table in Django Model
I'm building a Django web interface for legacy systems that currently use MS Access as a front end for an MSSQL database. We have two similar test stands that report similar data, but in two different ways. The older one puts all of the results in one table with a column for each step of the test, and the other one uses a related table, as it was designed to have different numbers of steps. My question is, can I create a model that turns the first table into a master and lookup table? Start Table: +-----+---------+--------+-----------+----------------+----------+----------------+----------------+----------+----------------+-------------+---------------+ | ID | PartNum | Serial | Pass/Fail | Test A 1 Upper | Test A 1 | Test A 1 Lower | Test A 2 Upper | Test A 2 | Test A 2 Lower | Test B Done | Test B Passed | +-----+---------+--------+-----------+----------------+----------+----------------+----------------+----------+----------------+-------------+---------------+ | 123 | 991 | 111 | T | 10.0 | 8 | 6 | 15 | 13 | 12 | T | T | | 124 | 991 | 112 | F | 10.0 | 9 | 6 | 15 | 16 | 12 | T | T | | 125 | 991 | 113 | … -
How to have a multi line statement in Django
I have an include statement with lots of variables being passed in. Was wondering if there was any way to make it multiline. Ex:{% include 'foo.html' with img_src='bar.jpg' img_text='baz' %} into {% include 'foo.html' with img_src='bar.jpg' img_text='baz' %}.