Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Build m2m relationship for parents to children and siblings
To describe my problem let's assume there is a model class Person: class Person(models.Model): name = models.CharField(max_length=100, unique=True) sex = models.CharField( max_length=1, choices=( ('F', 'female'), ('M', 'male') ) ) relatives = models.ManyToManyField('self', blank=True) def __str__(self): return self.name A person can have many (or none) relatives of these types: parents children siblings halfsiblings (maternal or paternal) In order to describe the relationship type we need another model class and the option through, which in this case will require also the option symmetrical=False. The relation parent-child is indeed asymmetrical, however the siblings relation is symmetrical. I'm looking for an elegant and clear solution to overcome the dilemma between the true symmetrical relation of siblings and the asymmetrical relation of parents and children. Adapting the field relatives and adding additional model class results in: class Person(models.Model): # ... relatives = models.ManyToManyField( 'self', through='Relatedness', symmetrical=False, blank=True ) class Relatedness(models.Model): RELATIONSHIPS = ( ('PA', 'parent'), ('SI', 'sibling'), ('MH', 'maternal halfsibling'), ('PH', 'paternal halfsibling'), ) source = models.ForeignKey('Person', related_name='source') target = models.ForeignKey('Person', related_name='target') relationship = models.CharField(max_length=2, choices=RELATIONSHIPS) class Meta: unique_together = ('source', 'target') What I need is: to show all relatives for a person to implement constraints that there are no weird combinations like if A … -
How to verify auth key of another API in my Api?
I have made an Django API(1), which calls another API(2) for data. Problem I am facing is that other API(2) use HMAC auth, so when logged in that API(2), I am getting the result but using the same app(1) in other browser { "message": "Unauthorized", "success": false } this message is coming. I know I need to put the auth key of API(2) somewhere in my views.py(1) file and currently I am doing this, def search(request): auth = HmacAuth('Username', 'mySEcretKey') response = requests.get('https://api(2).com/api/get_nearest', auth=auth, params=dict(token='imatinib')) print json.dumps(response.json(), indent=4) which is obviously not working. -
Django and multiple joins
I'm trying to do a quite long join, but it seems like django can't handle the last layer. Am I getting it wrong or is there any way around this? Models.py class A(models.Model): object_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) class B(models.Model): class_A_object = models.ForeignKey(A, on_delete=models.PROTECT) value = models.CharField(max_length=50) class C(models.Model): class_B_object = models.ForeignKey(B, on_delete=models.PROTECT) class D(models.Model): value= models.IntegerField(primary_key=True) class_C_object = models.ForeignKey(C, on_delete=models.PROTECT) I'm then trying to select the value in class D when the related class A object name = ABC. D.objects.filter(class_C_object__class_B_object__class_A_object__name='ABC') This fails, to begin with pycharm refuses the autocomplete it and if I run it i get a name not defined error. However, if i drop one layer it works. D.objects.filter(class_C_object__class_B_object__value='ABC') I haven't found any documentation mentioning a maximum number of joins, but it feels like there is a limitation here. Does anyone know if that's the case, and if so, what the best way would be to work around this? The database is external to me and can not be modified. The only working decent workaround i have at the moment is to use the cursor directly and write the sql by hand. However, this is not ideal for a lot of reasons. Any help would be … -
In Reportlab Using SimpleDocTemplate how to add image on top
How to use SimpleDocTemplate for add image on top in pdf. Becuase i try some solutions but not effect on pdf from PIL import Image from reportlab.pdfgen import canvas from reportlab.lib import colors from reportlab.lib.pagesizes import letter, A4, inch,landscape from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Table, TableStyle from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.pagesizes import A4 response = HttpResponse(content_type='"application/pdf"') response['Content-Disposition'] = 'attachment; filename=users.pdf' doc = SimpleDocTemplate(response, pagesize=(1600, 500),rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18) self.canv.drawImage(self.img, 0, 0, height = -2*inch, width=4*inch) # http://www.reportlab.com/apis/reportlab/2.4/pdfgen.html doc = SimpleDocTemplate(("report.pdf"),pagesize=letter, rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18) all_data = [] record_for_frontEnd = BillManagement.objects.filter(**kwargs) pdf_data = [['Creation Date', 'Bill Number', 'Name', 'Quantity', 'Product/Service Name', "Ref No", "Cost", "discounted Price", "Net Amount", "Costomer Name", "Commission Staff", "Commission Amount", "Patyment Type"]] -
Python/Django: How to display error messages on invalid login?
I'm trying to do the Login for my Django (2.0) website, so far I've got the login working for existing accounts. I'm using the built-in login function. Now I want to display an error message when you enter an invalid account, for example "Invalid username or password!". But I have no idea how to go about this. Right now it just refreshes the login page when your enter an invalid account. Any help is appreciated! Login.html {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} Login view def login(request): if request.method == 'POST': form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth_login(request, user) return redirect('index') else: form = AuthenticationForm() return render(request, 'todo/login.html', {'form': form}) -
How do I download a file from a FIleField in Django?
Using Django, I have uploaded files to a FileField. Is there a way to retrieve the file from this field, and download it in the original form back to my PC using a Python Script. This is the model for the item: class CatalogueItemData(VendorCustomerRestrictedPermissionMixin, OrnamentationBase, SoftDeleteObject): """ Represents Data belonging to an Item (CatalogueItem). """ url = models.FileField(upload_to=get_item_data_file_path, null=True, blank=True, validators=[validate_is_not_jpeg_extension], help_text='Disallowed format: .jpg') name = models.CharField(max_length=60) class Meta: verbose_name = 'Catalogue Item Data' verbose_name_plural = 'Catalogue Item Data' def __str__(self): return self.name def get_file_name(self): """ Returns the name of the uploaded file. """ name = self.raw.name return name.strip('category/item-data') I have the ID for the data, I want to download the file stored in the file field. I do not want to modify the model. -
djang - 404 error for only one css file
I have this in my base.html template: {%load staticfiles%} <link rel="stylesheet" type="text/css" href="{% static 'css/bulma.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/app.css' %}"> And this is what I get in console when navigating on the page. [21/Dec/2017 12:52:04] "GET / HTTP/1.1" 200 1134 [21/Dec/2017 12:52:04] "GET /static/css/bulma.css HTTP/1.1" 304 0 [21/Dec/2017 12:52:04] "GET /static/css/app.css HTTP/1.1" 404 1758 So the app.css doesn't load and I don't understand why because it is in the same folder ar bulma.css which as I see loads fine. urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings urlpatterns = [ path('', include('homepage.urls')), path(r'hap/', admin.site.urls), path(r'martor/', include('martor.urls')), ] urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) urlpatterns += staticfiles_urlpatterns() settings.py STATIC_URL = '/static/' STATIC_ROOT = './static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.FileSystemFinder', ) -
Apache Django app: ImportError: No module named django.core.wsgi
I installed mod_wsgi, and loaded it in apache. This is my apache virtual host: <VirtualHost *:80> ServerName mysite.localhost ServerAlias mysite.localhost Alias /static /var/www/mysite/static <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py </VirtualHost> When I go to mysite.localhost I get: ImportError: No module named django.core.wsgi I try to run it from python shell and everything goes well. I have django installed globally, not just in the virtualenv. Thanks. -
django-celery-beat not sending tasks to celery worker
I was using celery only in django first. This was my config, from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inventory.settings') app = Celery('inventory') app.config_from_object('django.conf:settings', namespace='CELERY') #app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.autodiscover_tasks() app.conf.beat_schedule = { 'send-report-every-single-minute': { 'task': 'db.tasks.send_daily_report', 'schedule': crontab(minute='*/1'), }, } And I ran celery worker and beat and the task worked. celery -A inventory worker -l info celery -A inventory beat -l info But now, I am using the package, django-celery-beat. I added the schedule in the django admin panel, and enabled the same task. But it does not send the task to the celery worker. The worker keeps on waiting. It is stuck on starting, Neither does it show the task scheduled when I run the beat manually, $ celery -A inventory beat -l debug [2017-12-21 16:10:48,471: INFO/MainProcess] beat: Starting... [2017-12-21 16:10:48,527: DEBUG/MainProcess] Current schedule: [2017-12-21 16:10:48,527: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes [2017-12-21 16:10:48,528: DEBUG/MainProcess] beat: Waking up in 5.00 minutes. See, below Current Schedule line, it shows nothing but an empty line. It happens only when I add task schedule through django admin panel. -
About django rest framework document, how custom the description of request params and add the field to post params?
In the auto-generate view by rest_framework.documentation,when I take the post test, there is no field to fill my params, and how to add the description of request params like the api of "delete>list"? I can not get the ideas from the document:Documenting your API Should I write some code at here? @api_view(['POST']) def Login(request): try: username=request.data['username'] password=request.data['password'] except Exception as error: return Response(str(error), status=status.HTTP_400_BAD_REQUEST) user = authenticate(username=username, password=password) if user is None: or : from django.conf.urls import url, include from django.contrib import admin from . import views from rest_framework.documentation import include_docs_urls urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^media/(?P<file_path>.*)', views.GetMediaFiles), url(r'^api/',include('api.urls')), url(r'^docs/', include_docs_urls(title='CLTools API Docs')), ] Thanks! -
Django Crispy Form doesn't render hidden fields in formsets
I'm using django crispy forms to create inline formsets using a model form and a helper class. In my template, If I do {% crispy entrance_formset entrance_helper %} everything works fine when I submit. But if I try to manually render each form in the entrance_formset like this: {{ entrance_formset.management_form|crispy }} {% for entrance_form in entrance_formset %} {% crispy entrance_form entrance_helper %} {% endfor %} I get the following error when submitting. django.utils.datastructures.MultiValueDictKeyError: "'entrances-0-id'" When I look at the html, I see that the hidden fields entrances-0-idand entrances-1-id are indeed missing. What am I doing wrong? form class: class EntranceForm(ModelForm): latitude = FloatField( min_value=-90, max_value=90, required=False, ) longitude = FloatField( min_value=-180, max_value=180, required=False, ) class Meta: fields = ['name', 'location', 'latitude', 'longitude', 'directions'] widgets = { 'location': HiddenInput, 'directions': Textarea(attrs={'rows': 5}) } def __init__(self, *args, **kwargs): super(EntranceForm, self).__init__(*args, **kwargs) coordinates = self.initial.get('location', None) if isinstance(coordinates, Point): self.initial['latitude'], self.initial['longitude'] = coordinates.tuple def clean(self): data = super(EntranceForm, self).clean() latitude = data.get('latitude') longitude = data.get('longitude') point = data.get('location') if latitude and longitude: data['location'] = Point(latitude, longitude) helper class: class EntranceFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(EntranceFormSetHelper, self).__init__(*args, **kwargs) self.layout = Layout( 'name', 'latitude', 'longitude', 'directions', ) self.form_class = 'form-horizontal' self.label_class = 'col-xs-4' self.field_class = … -
Running existing Django project
I am trying to locally run an existing Django project from my own github on a Mac. https://github.com/shanegibney/djangoForum.git Since posting to github over a year ago I've moved to a mac from linux, Fedora. I've been following instructions from, How to run cloned Django project? $ mkdir djangoForum $ cd djangoForum $ virtualenv $ git clone https://github.com/shanegibney/djangoForum.git $ source env/bin/activate $ cd djangoForum $ pip install -r requirements.txt This is where I get the following error, The error is the same whether I use pip or pip3. $ pip --version pip 9.0.1 from /Users/shanegibney/djangoForum/env/lib/python3.6/site-packages (python 3.6) $ python --version Python 3.6.3 The requirements.txt file is here, https://github.com/shanegibney/djangoForum/blob/master/requirements.txt Can anyone see why I get the error when trying to install requirements.txt? Thanks, -
How to mock media file directory in django with custom storage property?
django version: 1.11, python version: 3.6.3 According to this two blogs/articles: https://joeray.me/mocking-files-and-file-storage-for-testing-django-models.html https://www.caktusgroup.com/blog/2013/06/26/media-root-and-django-tests/ we would, ideally, use a temporary directory to upload the mock-files. Now, mocking the files is easy. But mocking the directory and using a temporary directory is not working with custom storage property in settings.py i have a protected root to upload non public images: MEDIA_URL = '/media/' MEDIA_ROOT=os.path.join(BASE_DIR, "cdn", "media") PROTECTED_ROOT = os.path.join(BASE_DIR, "cdn", "protected") in products/models.py i have: from django.conf import settings from django.db import models from django.core.files.storage import FileSystemStorage class Product(models.Model): media = models.ImageField( # custom storage property storage=FileSystemStorage(location=settings.PROTECTED_ROOT) ) and the test in products/tests/test_views.py: from django.test import TestCase from unittest import mock from products.models import Product from django.core.files import File class ProductViewSetup(TestCase): @classmethod def setUpTestData(cls): file_mock = mock.MagicMock(spec=File, name='FileMock') file_mock.name = 'test.jpg' cls.product = Product.objects.create( media=file_mock ) i thought i could just customize the code described in caktusgroup blog to: class TempMediaMixin(object): "Mixin to create MEDIA_ROOT in temp and tear down when complete." def setup_test_environment(self): "Create temp directory and update MEDIA_ROOT and default storage." super(TempMediaMixin, self).setup_test_environment() settings._original_media_root = settings.MEDIA_ROOT settings._original_file_storage = settings.DEFAULT_FILE_STORAGE settings._original_protected_root = settings.PROTECTED_ROOT self._temp_media = tempfile.mkdtemp() self._temp_protected = tempfile.mkdtemp() settings.MEDIA_ROOT = self._temp_media settings.PROTECTED_ROOT = self._temp_protected settings.DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage' def teardown_test_environment(self): "Delete … -
Django doesn't allow to add record to DB due to not table instance
I have a DB model: class building_list(models.Model): building_id = models.CharField(max_length=25, verbose_name="Building ID", unique=True) def __unicode__(self): return self.building_id class data(models.Model): oDate = models.DateField() building_id = models.ForeignKey( building_list, to_field = "building_id" ) content = models.CharField(max_length=25, verbose_name="Content") def __unicode__(self): return self.content There is no problem to add record via Admin Portal, I can choose building_id from SELECT list and everything is okay. But, there is a problem when I am trying to add record via view. Let me show you my code: url(r'^(?P<building_id>[\w-]+)/$', views.test, name='test'), def test( request, building_id ): if request.method == 'POST': oDate = request.POST.get('oDate', '') content = request.POST.get('content', '') row = data( oDate = oDate, building_id = building_id, content = content ) return True I see that Cannot assign "u'BrI9'": "data.building_id " must be a "building_list" instance. Can anyone explain what I am doing wrong ? -
Django database table missing columns
I am trying to implement my own custom token to have greater functionality with token-based authentication. I have created a custom token model in models.py, shown below. I followed this question and the rest_framework docs when creating it. Custom token: class ScrumScrumUserToken(models.Model): """A custom Token class. This implementation includes the client type for which the token is created. """ key = models.CharField(_("Key"), max_length=40, primary_key=True, default='0') user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='scrum_tokenr', on_delete=models.CASCADE, verbose_name=_("User"), default=-1 ) created_on = models.DateTimeField(_("Created"), auto_now=True) client = models.CharField(max_length=10) class Meta: verbose_name = _("Token") verbose_name_plural = _("Tokens") def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key() return super(ScrumScrumUserToken, self).save(*args, **kwargs) def generate_key(self): return binascii.hexlify(os.urandom(20)).decode() def __str__(self): return self.key To show that all fields are in the migration: migrations.CreateModel( name='ScrumScrumUserToken', fields=[ ('key', models.CharField(default='0', max_length=40, primary_key=True, serialize=False, verbose_name='Key')), ('created_on', models.DateTimeField(auto_now=True, verbose_name='Created')), ('client', models.CharField(max_length=10)), ('user', models.OneToOneField(default=-1, on_delete=django.db.models.deletion.CASCADE, related_name='scrum_tokenr', to=settings.AUTH_USER_MODEL, verbose_name='User')), ], options={ 'verbose_name': 'Token', 'verbose_name_plural': 'Tokens', }, ) The problem: MariaDB [(none)]> desc scrum_scrum.scrum_scrum_api_scrumscrumusertoken\G *************************** 1. row *************************** Field: client Type: varchar(10) Null: NO Key: Default: NULL Extra: 1 row in set (0.00 sec) MariaDB [(none)]> As you can see, only the client field shows up in the database. For the life of me I cannot figure out why the … -
Django tests apis model object does not exist
I have created 2 Django models, User and Account Model. In User model, i have all info and in account part, i have account details of that user. I have designed Views that when I create a user, respective account object also created. URLs: '/user/' will create new user and account object. but when I am writing tests to check APIs, I created a new user. User object is accessible but when I access account detail it throws models.object doesn't exist. class User(models.Model): user_name = models.CharField(max_length=35) first_name = models.CharField(max_length=35) last_name = models.CharField(max_length=35) email = models.EmailField(max_length=255) class Account(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) balance = models.IntegerField(default = 0) def post(self, request): received_json_data = json.loads(request.body.decode("utf-8")) user = User(user_name=received_json_data['user_name'], first_name=received_json_data['first_name'], last_name=received_json_data['last_name'], email=received_json_data['email']) user.save() account = Account(user=user); account.save(); class TestUser(TestCase): def setUp(self): self.c = Client() usercreate = User(user_name = 'saveuser', first_name = 'usersave', last_name = 'lastsave',email = 'save@gmail.com') usercreate.save() account = Account.objects.get(pk =1) -
django dynamic create models
I am stucking on the django dynamic create models.I have no any experience and ideas to do this. I want to create models and fields by html forms, My problem is: Is there any example? I need to customize the database and fields, how to do it? Thanks! -
Django context processor doesn't display new context values in template
I'm using Django 1.11 and this is my first time trying to use a custom context processor. The problem is that the context variable I'm supposed to be adding from the context processor does not return anything in the template. I don't receive any errors. I know the context processor file is being executed from some testing. So below {{ testcontext }} should return "IT WORKED!", but returns nothing. Every question I've read on the subject has something to do with the RequestObject not being included in the response, but from what I've read generic class based views are supposed to include RequestObject by default. settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'appname.context_processors.test_context', ], }, }, ] context_processors.py: def test_context(request): return {'testcontext': 'TEST WORKED!'} views.py: from django.views.generic import ListView from appname.models import MyModel class MyView(ListView): model = MyModel urls.py from django.conf.urls import url from appname.views import MyView urlpatterns = [ url(r'^$', MyView.as_view(), name="home"), ] template.html {{ testcontext }} -
Organize the checkout page with steps
I have developed a checkout page where a form(guest form and login form) is shown at first if user is not authenticated. When user fills the form, then only the user is redirected to the same checkout page where now he will be shown a shipping address form which when filled will redirect to the same page but now billing address form is shown and after completing that steps, a review is shown.Instead I want to show the steps like Login > Shipping > Billing > Review How can i organize the form or content based on the steps they are in? Here is the checkout view with template def checkout(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.furnitures.count() == 0: return redirect('carts') login_form = LoginForm(request=request) guest_form = GuestForm(request=request) address_form = AddressCheckoutForm() guest_email_id = request.session.get('guest_email_id') billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) if billing_profile is not None: order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj) context = { "order": order_obj, "login_form": login_form, "guest_form": guest_form, "address_form": address_form, "billing_profile": billing_profile } return render(request, "carts/checkout.html", context) {% block content %} <div class="checkout_area section_padding_100"> <div class="container"> <div class="row"> {% if not billing_profile %} <div class="col-sm-12"> <div class="checkout_details_area checkout-1 mt-50 clearfix"> <div class="row"> {% comment %} <!-- {% … -
Why models delete method not getting called?
I have a mapping model, and i am deleting its objects but delete method not getting called: My mapping model is: class StudentSeasonCourseMap(models.Model): student = models.ForeignKey('ProgrammeStudentMap', db_column='student_id', related_name='studentseasoncourses', null=True, blank=True, verbose_name=_('Student'), limit_choices_to={'status': 'A'}) """ Student can be mapped to the ProgrammeStudentMap model """ season_course = models.ForeignKey('SeasonCourseMap', db_column='season_course_id', related_name='studentseasoncourses', null=True, blank=True, limit_choices_to={'status': 'A'}, verbose_name=_('Course')) def delete(self, *args, **kwargs): super(StudentSeasonCourseMap, self).delete(*args, **kwargs) my view's post method is: class StudentUpdate(View): def post(self, request): StudentSeasonCourseMap.objects.filter(id__in=[1,2]).delete() There is no admin for this model. still models delete method for bulk operation not getting called. Does anyone know why? -
Django CMS 3.4 apphooks not "hooking"
I am trying to follow the tutorial here just with my own "app". It's called currencies. cms_apps.py is inside currencies directory and apparently it gets called since I can see the CurrenciesHook in the CMS admin later. However the custom view class is not executed and/or template is not displayed. All I get is a blank page with Django's toolbar at the top and navigation (i.e. what's in base.html template). @apphook_pool.register class CurrenciesHook(CMSApp): name = _("Currencies application") app_name = "currencies" def get_urls(self, page=None, language=None, **kwargs): return ["currencies.urls"] urls.py is also inside currencies dir: urlpatterns = i18n_patterns( url(r'^$', views.DesktopView.as_view(), name="desktop"), ) views.py in the currencies dir has a single class for testing: class DesktopView(generic.TemplateView): template_name = 'desktop.html' and finally template desktop.html inside currencies/templates is simply: {% extends "base.html" %} TEST The command line displays no errors. If you can't tell what may possibly be wrong from the info provided, I'd appreciate any suggestions how to debug this. I'm very new to Django and I last worked with python 5 years ago. -
Django many-to-many through query simplification?
I have a Project, User and a many-to-many through table called ProjectMembership: class Project(models.Model): '''Project model ''' name = models.CharField(max_length=255, unique=True) users = models.ManyToManyField( settings.AUTH_USER_MODEL, through='ProjectMembership' ) is_active = models.BooleanField( default=True, ) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) is_active = models.BooleanField( default=True, ) projects = models.ManyToManyField( Project, through=ProjectMembership ) class ProjectMembership(models.Model): '''Project Membership model ''' user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT ) project = models.ForeignKey(Project, on_delete=models.PROTECT) is_project_manager = models.BooleanField(default=False) Now I want a list of all the active project managers on all the active projects that a specific user is on. I have used the following query and loops below, but perhaps there is a way to do this without the loops? projects = self.leave_not_required_user.projects.filter(is_active=True) users = [] for project in projects: project_memberships = project.projectmembership_set.filter( is_project_manager=True, user__is_active=True ).all() for project_membership in project_memberships: users.append(project_membership.user) -
is django db able to have a secondary db set as back up? django
What I am trying to say is, I have two database and they are replicates. Is it possible for django to have settings that if first (primary db) is down / cannot be connected then connect to the second one until the first one is back up? I believe this can be done in server side, but I am wondering if it can be done with django easily instead of touching the db servers? -
Aligning text when converting from html to pdf in django
After following a tutorial, I successfully was able to convert html to pdf, however, when trying to align text on the same line (half of it to the left and the other half to the right) it would not convert properly. The html file looks as follow: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> <style type="text/css"> body { font-weight: 200; font-size: 14px; } .header { font-size: 20px; font-weight: 100; text-align: center; color: #007cae; } .title { font-size: 22px; font-weight: 100; padding: 10px 20px 0px 20px; } .title span { color: #007cae; } .details { padding: 10px 20px 0px 20px; text-align: left } .hrItem { border: none; height: 1px; color: #333; background-color: #fff; } </style> </head> <body> <div class='wrapper'> <div class='header'> <p class='title'>Invoice # </p> </div> <div> <div class='details'> Bill to: <span style="float:right">some text here</span> <br/> Amount: <br/> Date: <hr class='hrItem' /> </div> </div> </body> </html> The render_to_pdf function: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None The html file looks more than proper, but is not being converted properly in pdf. Aligning on separate lines does,however, convert normally to pdf … -
Running supervisord in AWS Environment
I'm working on adding Django Channels on my elastic beanstalk enviorment, but running into trouble configuring supervisord. Specifically, in /.ebextensions I have a file channels.config with this code: container_commands: 01_copy_supervisord_conf: command: "cp .ebextensions/supervisord/supervisord.conf /opt/python/etc/supervisord.conf" 02_reload_supervisord: command: "supervisorctl -c /opt/python/etc/supervisord.conf reload" This errors on the 2nd command with the following error message, through the elastic beanstalk CLI: Command failed on instance. Return code: 1 Output: error: <class 'FileNotFoundError'>, [Errno 2] No such file or directory: file: /opt/python/run/venv/local/lib/python3.4/site- packages/supervisor/xmlrpc.py line: 562. container_command 02_reload_supervisord in .ebextensions/channels.config failed. My guess would be supervisor didn't install correctly, but because command 1 copies the files without an error, that leads me to think supervisor is indeed installed and I have an issue with the container command. Has anyone implemented supervisor in an AWS environment and can see where I'm going wrong?