Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nested relations in microservices
I have been exploring microservices architecture for some time now, and want to try it in real world app. But I have stumbled across problem and haven't found definitive answer. Imagine we are writing Tutorial app that connects tutors with students. We have user/accounts service that is responsible for governing stuff related to tutors and students. We also have tutorials service that manages everything related to scheduling a tutorial session. In pseudo-Django code it may look like this: user/accounts service entities: class Tutor(models.Model): name = models.CharField() avatar = models.ImageField() class Student(models.Model): dob = models.DateTimeField() name = models.CharField() tutorial service entities: class Tutorial(models.Model): tutor_id = models.IntegerField() # id of Tutor instance student_id = models.IntegerField() # id of Student instance datetime = models.DateTimeField() Now suppose we want to display: all tutorial sessions for given Tutor. It looks straight forward: fire an API request to tutorials service and you're done! But I want to display name and date of birth of each student. How should I handle this case? Two approaches I figured out are: Let tutorial service call user/accounts service and "nest" retrieved Student objects in response in student field of each Tutorial object From frontend app collect all id of students … -
How can I print my form errors in a proper way in Django and Jinga
I am trying to create a login page in Django. Now the page works fine but I can not print the errors in a proper way. For some reason, I am not using {{ form.as_p }} Here is the code <form method="POST" class="fcolumn fcenter login-form"> {% csrf_token %} <h1>LOGIN PANEL</h1><hr><br> <input type="text" placeholder="Username" required name="username"> <input type="password" placeholder="Password" required name="password"> <button type="submit">Login</button> {% if form.errors %} <p>{{ form.errors}}</p> {% else %} <p>New Here, <a href="{% url 'joinus' %}">Create an account</a></p> {% endif %} </form> Now this method printing the error in a ul, but I just want the error text Thanks in advance :) -
Django apache configuration with mod_wsgi module
From the Django documentation: WSGIDaemonProcess example.com python-home=/path/to/venv python-path=/path/to/mysite.com WSGIProcessGroup example.com where does 'python-home' point to ? where does 'python-path' point to ? where does 'example.com' point to ? -
CSV to PDF Convert in django
I want to be able to convert CSV to PDF files and have found several useful scripts but, being new to Python, I have a question: How could I convert CSV to PDF? import csv from fpdf import Template import os from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User as DjangoUser from django.http import HttpResponse def invoice_report(request): response = HttpResponse(content_type='"application/pdf"') response['Content-Disposition'] = 'attachment; filename="users.pdf"' #print response writer = csv.writer(response) writer.writerow( ['Creation Date', 'Bill Number', 'Name', 'Quantity', 'Product/Service Name', "Ref No", "Cost", "discounted Price", "Net Amount", "Costomer Name", "Commission Staff", "Commission Amount", "Patyment Type"]) commision_user = UserCommission.objects.filter(bill_id = bill.id, product_service_id=products_in_bill.product.id).first() name = "-" comm_amount = "-" if commision_user: name = commision_user.staff_user.user.first_name comm_amount = commision_user.commission_amount except: name = "-" comm_amount = "-" print(str(products_in_bill)+" | "+str(products_in_bill.product_qty) + name ) writer.writerow([ bill.creation_date,bill.bill_number,bill.staff.user.first_name+" "+bill.staff.user.last_name, products_in_bill, products_in_bill.product.reference_number, products_in_bill.product.cost, products_in_bill.discounted_price, products_in_bill.product.cost, customer_name, name, comm_amount, payment_type ]) file_name = "" file_name = 'reports/invoice_reports/' + timezone.now().strftime('%Y_%m_%d_%H_%M_%S.pdf') file_path = os.path.join(BASE_DIR, 'static/' + file_name) with open(file_path, 'wb') as f: f.write(response.content) return render(request, 'billing/report/invoices_report.html', { 'invoices':record_for_frontEnd, 'customers': Customers, 'cashiers': cashiers, 'file_name': file_name }) -
[wsgi:error]:No module named mysite.settings
I have deployed Django app in Wamp server which was working fine. Unfortunately after running pip install Wamp server stopped serving Django applicaiton and throwing below error mod_wsgi (pid=26240): Target WSGI script 'D:/testdeployment/mysite/mysite/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=26240): Exception occurred processing WSGI script 'D:/testdeployment/mysite/mysite/wsgi.py'. Traceback (most recent call last): File "D:/testdeployment/mysite/mysite/wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\core\\wsgi.py", line 13, in get_wsgi_application django.setup() File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\conf\\__init__.py", line 55, in __getattr__ self._setup(name) File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\conf\\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\\Python27\\lib\\site-packages\\django-1.9.4-py2.7.egg\\django\\conf\\__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\\Python27\\Lib\\importlib\\__init__.py", line 37, in import_module __import__(name) ImportError: No module named mysite.settings WSGI.PY import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() Wamp configuration: WSGIScriptAlias / "D:/testdeployment/mysite/mysite/wsgi.py" WSGIPythonPath "D:/testdeployment/mysite/mysite/" <Directory "D:/testdeployment/mysite/mysite/"> Order deny,allow Allow from all Require all granted </Directory> <Directory "D:/testdeployment/mysite/mysite/"> <Files wsgi.py> Require all granted </Files> SSLOptions +StdEnvVars Options Indexes FollowSymLinks MultiViews AllowOverride All Require local </Directory> Please let me know what is the issue here -
Do I need a many-to-many relationship for the leave approver of a company?
I have a: User and Company class User(AbstractBaseUser): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) company = models.ForeignKey( 'projects.Company', on_delete=models.PROTECT ) class Company(models.Model): '''Company model every user needs to be assigned to a company ''' name = models.CharField(max_length=255, unique=True) Now I need a to set a few leave approvers per company which will be Users. There can be a few and I want to set a priority for them. If it were a single LeaveApprover then I would simply add a one-to-one to the Company model with a foreign key to LeaveApprover. But In my case A company can have many approvers, an approver can only approve a single company. Do I need a many-to-many field? -
Shared image volume mount error in docker
I use docker-compose for running my containers in docker. I have two services - one of celerybeat and other the web (I have many others but considering only these services because they contain my problem). docker-compose.yml file looks like this: . . . celerybeat: image: web-image volumes: - /home/ubuntu/celerybeat:/code/celerybeat command: > /bin/ash -c "su -m celery -c 'celery -A <application_here> beat -s /code/celerybeat/celerybeat-schedule'" web: image: web-image volumes: - /home/ubuntu/celerybeat:/code/celerybeat command: > <some_command_to_run_server> In my Dockerfile I have added these commands for proper permissions RUN mkdir celerybeat RUN touch celerybeat/celerybeat-schedule RUN chown -R celery:celery celerybeat Note: In my compose file structure written above I have provided volume mounts for both containers (but actually I am using one at a time), for the ease of not writing the compose files again and again. The problem is actually here only. Technically the volume mount should be provided only in the celerybeat service. When I write volume mount for celerybeat-schedule in the celerybeat docker service I get permission denied. Whereas when I write the volume mount command in the web service celerybeat service starts happily. What is happening here can anyone explain me? I need a fix for this. -
send_mail works locally but not on production hosting
The following works locally but as I deployed it to production hosting at Digital Ocean, the email is not sending as I test on shell command (python manage.py shell) like below. The send_mail line just got stuck there and am getting error: [Errno 101] Network is unreachable after few minutes. How can I capture the error on the email sending? Please advise how can I troubleshoot this issue. from django.core.mail import send_mail send_mail('test email', 'hello world', 'xxxx@gmail.com', ['xxxx@gmail.com'],fail_silently=False) # Email settings EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'xxxx' #my gmail password EMAIL_HOST_USER = 'xxxx@gmail.com' #my gmail username EMAIL_PORT = 587 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
django quiz app model for multiple choice questions
I am creating quiz app in django, my django model for questions is like this, class Question(models.Model): questions = models.CharField(max_length=50, unique=True) choice1 = models.CharField(max_length=50, unique=True) choice2 = models.CharField(max_length=50, unique=True) choice3 = models.CharField(max_length=50, unique=True) choice4 = models.CharField(max_length=50, unique=True) correct_answer = models.CharField(max_length=50, unique=True) is this fine or save the four options in postgres array or save the choices in separate table. -
How can I separate text from a query result in html?
I'm trying to display the result of a query in a HTML page on django. I'm getting the result expected but I would like to separate the information from a cell in 5 cells. For example: enter image description here. Since this is a table, I would like to dispose this like 9030101 | 'Registo....' | 165.0 | \65.0 | None. Sorry if the question is silly but I can't fix this. -
Require Log in with AnonymousUser in Django Rest Framework
I have a viewset API which getting Notification of User who get authenticate with Django JWT but I got error. Please take a look! Viewset: from api.notifications.models import Notification from rest_framework.generics import ( ListAPIView ) from api.notifications.serializers import ( NotificationListSerializer ) from api.pagination import NewFeedPagination from rest_framework.permissions import AllowAny from api.permissions import IsOwnerOrReadOnly class NotificationListAPIView(ListAPIView): permission_classes = [AllowAny] serializer_class = NotificationListSerializer ordering_fields = 'date' def get_queryset(self, *args, **kwargs): queryset_list = Notification.objects.filter(to_user=self.request.user) return queryset_list When It doesn't logged in, it came to error: int() argument must be a string or a number, not 'AnonymousUser'. How can I set up with AnonymousUser, URL will come to login page: localhost:8000/admin? -
How to include images from Django staticfiles to <div style="background: url('image.jpg')">
I am having trouble on including image to from Django static/images/image.jpg -
Export all fields of functions in export function to generate xlsx
I have some functions in models.py class. Currently there are all fields mentioned in export class. I want to export all fields of function rather then mentioning every particular field which increases my line of code. Is there a way I could do it? Below is the code sample of export function def export_xlsx(self, request, queryset): list_dict = [] idx = 0 for q in queryset: list_dict += [{}] list_dict[idx]['name'] = q.name list_dict[idx]['place'] = q.place list_dict[idx]['time'] = q.time list_dict[idx]['date'] = q.date list_dict[idx]['country'] = q.country list_dict[idx]['city'] = q.city idx += 1 h = [ 'name', 'place', 'time', 'date', 'country', 'city'] gen_xlsx("export_file", h, list_dict, request) return request -
django rest_framework attribute error
Django serializing / deserializing two values to one model field """AttributeError: 'Profile' object has no attribute 'latitude'""" I am applying the same codes as mentioned in above link but in django 1.11, for me it shows error, is there anything to modify in models.py?,with the same serializer -
dajngo get date format in template
I am new to django. In my template I need the current date as date format, while the following code returns string: <p>{% now "Y-m-d" as date %}</p> where I want the date in format of 2018-12-17 as a date not string. Is there anyway to do that? thnaks -
How to register a custom ModelAdmin for FlatPage
I'm reading through the flatpages app documentation. And I was to make some edit to the flatpages admin.py, as discussed here: How to add, change and delete flatpages But forgive me, where exactly in my project do I create and add the admin.py file? Do I create a flatpages directory and place the admin.py in there? That was my first try, and I didn't work. -
How to route to a specific function in a view from django template?
For example I have the following situation where a delete button has to be routed different depending upon who has clicked it, like if he's an admin display a message else go to the delete view. I thought I will place the function to send a message in detail generic view but how to call that function directly from template? {% if user_detail.status == 0 %} <button class="btn clearfix"><i class="icon-trash"></i>Cannot Delete Admin</button> {% else %} <a href="{% url "members:delete" userid=user_detail.pk %}" class="btn clearfix"><i class="icon-trash"></i>Delete User</a> {% endif %} The delete generic view is directly linked to the template, is there to display message in delete view before loading the template? -
Django session wizard redirecting to skipped step when submit form
I am using a session wizard view to capture data from around 10 forms. Everything is working fine. But when I select the go to step which takes me to the last form and after I submit the form from the last page, it is redirecting to the step where I have selected the skip button rather than submitting the form. Usually it takes us to the particular form if there exist any validation error in that form. I have checked whether there is any validation error showing up or getting from the back-end but there exist no such validation error. This is happening in every form when I skip that particular form. It would be great if someone give a helping hand to figure out what is actually happening. -
Pass Django list of strings to JS as an array
Goal: I want to pass list of strings in Django to template JS as an array of strings and get index for each string in the array. Problem: Javascript indexOf() is counting each character (e.g. letters, single quotes and brackets). My tries below are based on this, this and this. Code 1: I tried escapejs and safe filters, but indexOf() is returning 2 for the first item in the array (should be 0). #views.py list = [#utf-8 encoded strings] return render(request, template, {'list': list}) #template JS $('#id').ready(function() { var array = "{{list|escapejs}}"; console.log(array.indexOf('{{obj}}')); #obj is item in list}); Code 2: Also tried json.dumps() with encode('utf8') or json.loads() but the problem persists. #views.py list = [#utf-8 encoded strings] list = json.dumps(list, ensure_ascii=False).encode('utf8') return render(request, template, {'list': list}) #template JS $('#id').ready(function() { var array = "{{list}}"; console.log(array.indexOf('{{obj}}')); #obj is item in list}); -
Why can't login after change password using django.contrib.auth.views?
here is the link to my project: https://github.com/MariuszKorotko/Twitter/tree/master/twitter I'm working on simple application like 'Twitter'. Everything looks like working ok, but after change password and logout, can't login again. New password and old password doesn't work. I was looking for solution of this problem but without success. Can I ask for your help? A I'm not sure, but maybe problem is beacause of custom User model. Thanks for any help. twitter/urls.py from django.contrib.auth import views as auth_views url(r'^$', IndexView.as_view(), name='index'), url(r'^login/', auth_views.LoginView.as_view( template_name='registration/login_form.html'), name='login'), url(r'^logout/', auth_views.LogoutView.as_view( template_name='registration/logged_out.html'), name='logout'), url(r'^password_change/$', auth_views.PasswordChangeView.as_view( template_name='registration/password_change_form.html', success_url=reverse_lazy('twitter:password_change_done')), name="password_change"), url(r'^password_change/done/$', auth_views.PasswordChangeDoneView.as_view( template_name='registration/password_change_done.html'), name="password_change_done"), twitter/models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set!') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a … -
Django. How can I edit JSONField (PostgreSQL 9.6) in standard Django admin?
My Django version is 1.11.8, Python 3.6.1 and PostgreSQL 9.6. I create Django model with JSONField(). For example, like this: from django.contrib.postgres.fields import JSONField from django.db import models class Dog(models.Model): name = models.CharField(max_length=200) data = JSONField() And put some data: >>> Dog.objects.create(name='Rufus', data={ ... 'breed': 'labrador', ... 'owner': { ... 'name': 'Bob', ... 'other_pets': [{ ... 'name': 'Fishy', ... }], ... }, ... }) But how I can edit this JSON data in admin page? I mean, something like transform all key: value data to normal fields into Django Admin. For example: 'breed': 'labrador' ---transforms---> CharField(name='breed', ...) with value 'labrador' Some use cases and useful comments are welcome. -
Django cannot find pattern name when redirecting
I am workign on django project, i have modified the default django user model to employee's model using AbstractUser model. Now On their first login, i need to redirect employee's to change password page the Url for which is defined in the EmployeeAdmin - get_urls method. Also to override the default login behaviour i had to override the default AdminSite as shown below: admin.py class MyAdminSite(AdminSite): login_form = AdminLoginForm admin_site = HRMSAdminSite(name='My-admin') @admin.register(Employee, site=admin_site) class EmployeeAdmin(admin.ModelAdmin): def get_urls(self): return [ path( '<id>/password/', self.admin_site.admin_view(self.user_change_password), name='auth_user_password_change', ), ] + super().get_urls() def user_change_password(self, request, id, form_url=''): pass And on my AdminLoginForm i check for the first login of user: forms.py class AdminLoginForm(AuthenticationForm): def confirm_login_allowed(self, user): # user.last_login is blank if this is first login for this user if not user.last_login: return redirect('auth_user_password_change') However, when running the above code i get below error: Reverse for 'auth_user_password_change' not found. 'auth_user_password_change' is not a valid view function or pattern name. I dont know why django cannot find the named url i.e defined inside EmployeeAdmin's get_urls() method. -
Django model formsets fields become none after save
I am trying to make a model formset to generate a form for each object that has 'completed' boolean field False. I managed to render it, but everytime i'm trying to save, the page will refresh and for a reason all field's values become None. Ex: From this to this models.py class TranslatorTest(models.Model): data = models.ForeignKey(TranslatorData) language = models.ForeignKey(Language) type = models.ForeignKey(TextType, blank=True, null=True, default=None) question = models.TextField(blank=True) answer = models.TextField(blank=True) completed = models.BooleanField(default=False) forms.py class BaseAuthorFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super(BaseAuthorFormSet, self).__init__(*args, **kwargs) self.queryset = TranslatorTest.objects.filter(completed=False) TranslatorTestFormSet = modelformset_factory( TranslatorTest, fields=['question', 'answer', 'language', 'type'], widgets={ 'language': forms.Select(attrs={'class': 'form-control m-bootstrap-select m_selectpicker', 'required': 'false'}), }, formset=BaseAuthorFormSet) views.py def translator_test(request): data = dict() if request.method == "POST": formset = TranslatorTestFormSet(request.POST) if formset.is_valid(): for form in formset.forms: form.save() return redirect(reverse_lazy('core:index')) else: formset = TranslatorTestFormSet() data['formset'] = formset return render(request, 'core/translator_test.html', data) translator_test.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="m-portlet__body"> {% for form in formset.forms %} {{ form.id }} {{ formset.management_form }} {% for field in form.visible_fields %} <div class="form-group m-form__group row"> {% if field.name == 'question' %} {{ field.label }} {{ field.value }} {% elif field.name == 'language' %} {{ field.label }} {{ field.value }} {% elif field.name == 'type' %} … -
'pipenv install -r' is not working
Excuted this : 'pipenv install -r requirements/local.txt' D:\doc\jaeeongram> pipenv install -r requirements/local.txt Requirements file provided! Importing into Pipfile… Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Nothing happens here. (After 5min, ...., 1hour) The following is my Pipfile. [[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [packages] Django = "==1.10.8" django-environ = "==0.4.4" django-crispy-forms = "==1.7.0" django-model-utils = "==3.0.0" Pillow = "==4.3.0" "argon2_cffi" = "==16.3.0" django-allauth = "==0.34.0" awesome-slugify = "==1.6.5" pytz = "==2017.3" django-redis = "==4.8.0" redis = ">=2.10.5" coverage = "==4.4.2" django_coverage_plugin = "==1.5.0" Sphinx = "==1.6.5" django-extensions = "==1.9.8" Werkzeug = "==0.13" django-test-plus = "==1.0.21" factory_boy = "==2.9.2" django-debug-toolbar = "==1.9.1" ipdb = "==0.10.3" pytest-django = "==3.1.2" pytest-sugar = "==0.9.0" [dev-packages] [requires] python_version = "3.6" pipenv shell -> django-admin not found... How to resolve this problem? -
Expand static tree sidebar menu in django template with jQuery when new pages loads
I have a python+django app and the sidebar menu is defined in the base.html, which is extended by other dynamic pages, so let's call the sidebar tree menu static. Now, when I click a link in the sidebar, as the new pages loads, the new page has the sidebar all items collapse, which is not desirable. I want to make the link corresponding to current page highlighted(with "class=active") and its parent item expanded. My site is based on a free webpage template called "AdminLTE": https://github.com/almasaeed2010/AdminLTE and it has some code to handle the toggle/expand/collapse event, but does not solve the "remain-link-active-and-menu-open" problem, because on every page, the sidebar part is repeated and each corresponding link and its parent have their states(active and expanded) hard-coded. I want the sidebar menu "remembers" the state, by passing some arg in between calls, etc. The sidebar tree code is below: /* Tree() * ====== * Converts a nested list into a multilevel * tree view menu. * * @Usage: $('.my-menu').tree(options) * or add [data-widget="tree"] to the ul element * Pass any option as data-option="value" */ +function ($) { 'use strict' var DataKey = 'lte.tree' var Default = { animationSpeed: 500, accordion : true, followLink …