Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0.2 - Many To Many Relation - Can't get IDs
I've been trying to develop a webapplication with Django 2.0.2 including Full Calendar and Bitnami Stack. I seem to not comprehend the Many-to-Many relationship in Django. Currently I am attempting to match all fitting resourceIds with each corresponding event (called termin in this case): views.py: def events(request): terminList = Termin.objects.all() termine = [] for termin in terminList: termine.append({'title': termin.beschreibung, 'start': termin.startzeit, 'end': termin.endzeit, 'resourceId': str(termin.teilnehmer_betreuer.all()) ## Trying to get a Resource ID here ## }) return HttpResponse(json.dumps(termine, cls=DjangoJSONEncoder), content_type='application/json') models.py: class Termin(models.Model): GRUEN = 'GR' GELB = 'GE' ROT = 'RO' UEBERSCHREIBBARKEIT_AUSWAHL = ( (GRUEN, 'Überschreibbar'), (GELB, 'Auf Anfrage'), (ROT, 'Nicht Überschreibbar'), ) startzeit = models.DateTimeField(default=datetime.datetime.today) endzeit = models.DateTimeField(default=datetime.datetime.today) beschreibung = models.TextField(max_length=400) teilnehmer_patient = models.ManyToManyField(Patient) teilnehmer_betreuer = models.ManyToManyField(Benutzer) ueberschreibarkeit = models.CharField( max_length=25, choices=UEBERSCHREIBBARKEIT_AUSWAHL, default=GRUEN, ) raum = models.ForeignKey(Raum, on_delete=models.SET_NULL, null=True) def __str__(self): return self.beschreibung The json I get: [{"title": "Test", "start": "2018-02-09T06:57:23Z", "end": "2018-02-09T07:20:00Z", "resourceId": "<QuerySet []>"}, {"title": "Test", "start": "2018-02-09T13:05:59Z", "end": "2018-02-09T13:05:59Z", "resourceId": "<QuerySet [<Benutzer: doktor>, <Benutzer: joschmidl>, <Benutzer: skywalker>, <Benutzer: qsdasdsada>]>"}, {"title": "Taesaed123", "start": "2018-02-09T13:06:21Z", "end": "2018-02-09T13:06:21Z", "resourceId": "<QuerySet [<Benutzer: doktor>, <Benutzer: joschmidl>, <Benutzer: skywalker>, <Benutzer: qsdasdsada>]>"}] This is the extra table, which is not in my models.py, that Django creates after migrating my database. id,termin_id,benutzer_id 7,2,2 8,2,4 … -
django-rest-social-auth partial pipeline how to use?
I want to use partial pipeline with django-rest-social-auth and ask user for an email before create_user pipeline, change the email according to the users choice and then resume to stopped pipeline. I've created partial pipeline function, which redirect to change email function, but after resume to pipeline (when I go to /complete/) it redirect to SOCIAL_AUTH_LOGIN_REDIRECT_URL and I can't resume to stopped pipeline. -
get value of related model
I had the following model class Events(models.Model): nis = models.ForeignKey(Taxonomy, related_name='Taxonomy') group = models.ForeignKey(Ecofunctional) origin = models.ForeignKey(Origin) status = models.ForeignKey(Status) class Taxonomy(models.Model): SpeciesName = models.CharField() class Distributions(models.Model): species = models.ForeignKey(Events, verbose_name=u"Non-Indeginous Species", related_name='event',) country = models.ForeignKey(Country,) seas = models.ForeignKey(regionalseas) I would like to get the following View class NisDetail(generic.DetailView): """ Get a entry detail view """ try: events = Events.objects.select_related('Taxonomy').all() event = Events.objects.prefetch_related('event') model = Events template_name = "mamias/nisdetail.html" except Events.DoesNotExist:<br> raise Http404("The Species does not exist")<br> I can get the taxonomy field values but not the one concerning distribution related to events Any help thanks -
'str' object has no attribute 'META' error while creating a ModelForm in django 2
Request Method: GET Request URL: http://localhost:8000/addapp/add?t1=200&t2=500 Django Version: 2.0.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'META' Exception Location: C:\Users\bceha_000\PycharmProjects\project1\venv\lib\site-packages\django\template\context_processors.py in debug, line 40 Python Executable: C:\Users\bceha_000\PycharmProjects\project1\venv\Scripts\python.exe Python Version: 3.6.4 views.py file from django.http import HttpResponse from django.shortcuts import render def input(request): return render(request,"input.html") def add(request): x=int(input(request.GET['t1'])) y=int(input(request.GET['t2'])) z=x+y return HttpResponse("<html><body bgcolor = yellow> Sum is: "+str(z)+" </body></html>") input.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Addition</title> </head> <body bgcolor="aqua"> <form action="../addapp/add" method="GET"> F.N<input type="text" name="t1"><br> S.N<input type="text" name="t2"><br> <input type="submit" value="Add"> </form> </body> </html> urls.py from django.conf.urls import url from addapp import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^addapp$',views.input,name='input'), url(r'^addapp/add$',views.add,name='add'), ] -
TypeError: Error when calling the metaclass bases in django application
I get a these logs below when I try to run: python manage.py syncdb --settings=accounting.settings.local TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases logs in detail Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line utility.execute() File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 261, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 69, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/south/management/commands/__init__.py", line 10, in <module> import django.template.loaders.app_directories File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/django/template/loaders/app_directories.py", line 21, in <module> mod = import_module(app) File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/constance/__init__.py", line 3, in <module> config = Config() File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/constance/config.py", line 10, in __init__ utils.import_module_attr(settings.BACKEND)()) File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/constance/backends/database/__init__.py", line 22, in __init__ from constance.backends.database.models import Constance File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/constance/backends/database/models.py", line 7, in <module> from picklefield import PickledObjectField File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/picklefield/__init__.py", line 5, in <module> from picklefield.fields import PickledObjectField # reexport File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/picklefield/fields.py", line 79, in <module> class PickledObjectField(_get_subfield_superclass()): File "/home/aphya1/projects/AcornAccounting/acornaccounting/local/lib/python2.7/site-packages/django/db/models/fields/subclassing.py", line 15, in __new__ new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs) TypeError: Error when calling the metaclass bases … -
How to filter categories in Django
I have a little problem. I want to create something like a webpages directory. In my model I've create a class Kategorie, and class Firma. Class Kategoria creating main categories and subcategories. In class Firma I can define in witch category and subcategory the new record will be belong. My question is: How to display in html on main page main categories and little lower the subcategories like in this picture Here is my code models.py from django.db import models from django.contrib.auth.models import User class Kategoria(models.Model): name = models.CharField(max_length=250, verbose_name='Kategoria') slug = models.SlugField(unique=True,verbose_name='Adres SEO') parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name = 'Kategoria' verbose_name_plural = 'Kategorie' def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' / '.join(full_path[::-1]) class Firma(models.Model): user = models.ForeignKey(User, default=1, verbose_name='Użytkownik', on_delete=models.CASCADE) title = models.CharField(max_length=250, verbose_name='Nazwa firmy') slug = models.SlugField(unique=True, verbose_name='Adres SEO') category = models.ForeignKey('Kategoria', null=True, blank=True, verbose_name='Kategoria', on_delete=models.CASCADE) content = models.TextField(verbose_name='Opis') draft = models.BooleanField(default=False, verbose_name='Szablon') publish = models.DateField(auto_now=False, auto_now_add=False) class Meta: verbose_name='Firma' verbose_name_plural='Firmy' def __str__(self): return self.title views.py from django.shortcuts import render, get_object_or_404 from .models import Kategoria, Firma def widok_kategorii(request): kategorie = Kategoria.objects.filter().order_by('name') context = {'kategorie': kategorie} return render(request, … -
Validar estado de una tarea celery [on hold]
tengo un inconveniente, tengo unas tareas de celery que necesito saber en que momento termina para poder ejecutar otra tarea y asi evitar duplicados -
How to show some pages only when someone login through OAuth in Django?
I currently merged OAuth with one of my projects. What can I do, so that pages are not accessible for users who are not logged in? -
Django ASGI New Relic CORS Error Heroku
I am running a Django Application using Django channels and a daphne server (ASGI) instead of the typical gunicorn (WSGI) server. So I had to modify my application to this: # asgi.py import os import django from channels.routing import get_default_application from asgiref.wsgi import WsgiToAsgi from django.core.wsgi import get_wsgi_application from newrelic import agent os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") django.setup() application = agent.WSGIApplicationWrapper(get_wsgi_application()) application = WsgiToAsgi(application) To my surprise this actually works. When I access my django api from a browser or postman it works properly and the data shows up in New Relic. However, I also have a client-side Angular web app which makes REST API calls to the django server and I am getting CORS errors. Please note that this is not a regular CORS issue as when I remove the new relic wrapper I am able to access my API properly from Angular. Failed to load https://my-app.herokuapp.com/api/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin https://frontend.com is therefore not allowed access. -
how to get history of an object in django?
I use django 1.11 and I have a book model: class Book(models.Model): user_borrowed = models.ForeignKey(User, null=True) name = models.CharField(max_length=100) description = models.TextField() author = models.CharField(max_length=30) isbn = models.CharField(max_length=80) def borrow_book(self, user): if self.user_borrowed is not None: return False self.user_borrowed = user self.save() def return_book(self): self.user_borrowed = None self.save() it's like a library system. all I want to do is to know which users borrowed a special book. in fact all users. for example I want to get this result: [ { "username": "user_name_1", "date": "2018-02-08T14:13:22.142497"}, ] this means that user_name_1 borrowed this book at the above time. so how to do this ? thank you. -
How to prevent my frontend to make favicon request?
I am using next Js for my frontend and django rest framework in the backend. I'm facing an issue when i do a request between them : My frontend actually make two requests. The normal request as expected but also a strange favicon.ico request and this generating multiple errors. I could handled it by asking my server to ignore all request with favicon value, however, when i make a redirect from the frontend (next.js), getinitialprops only send favicon.ico and impossible to get the expected params from my request. I get a network error and I have to manually refresh the page. I created a favicon directory both in nextjs and django, i verified the path url is okay i don't understand. Any solution ? -
Django - Unsupported operand type(s) for decimal and method
I'm trying to add two values (one from a method and one from a field) in my Django models.py. class Object(models.Model): value = models.DecimalField() def scaled_value(self): scaled_val = float(self.value) * 3 return scaled_val def add_val_and_scaled_val(self): sum = self.scaled_value + self.value return sum When I try to get the value of the sum from the 'add_val_and_scaled_val' method in my template like this {% Object.add_val_and_scaled_val %} then I get the TypeError... TypeError at /objects/detail/object-12345678/ unsupported operand type(s) for +: 'instancemethod' and 'Decimal' The instancemethod which the error refers to (self.scaled_value) should return a decimal value should it not? What am I doing wrong? Thanks. -
Django 2.0 | include multiple urls conf namespace
This "problem" is quite related to : django 2.0 url.py include namespace="xyz" The previous dev used Django 1.9 (or maybe even before) but we are now migrating to Django 2.0. We got 3 sites on the same project, all with only 1 specific URLS Conf ### MAIN PROJECT REFERENCING ALL SITES ### ### Nothing changed here ### from django.conf import settings from django.conf.urls import url, include from django.contrib import admin from django.conf.urls.static import static from django.urls import path from frontend import urls as frontend_urls from search import urls as search_urls from international import urls as international_urls # Customisation admin admin.site.site_header = 'INT - ADMIN' temppatterns = [ # Admin Sites url(r'^admin/', admin.site.urls), # Organisation Sites url(r'^frontend/', include(frontend_urls)), # 1st Platform url(r'^search/', include(search_urls)), # 2nd Platform url(r'^international/', include(international_urls)), ] urlpatterns = temppatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is the previous frontend URLs CONF FRONTEND_PATTERNS = [ url(r'^conseiller$', views.GuidanceView.as_view(), name='guidance'), ....... url(r'^contact$', views.ContactView.as_view(), name='contact'), url(r'^$', views.HomeView.as_view(), name='home'), ] COMPANY_PATTERNS = [ url(r'^companydetail/(?P<slug>[-\w]+)/$', views.MemberLgView.as_view(), name='lg-detail'), url(r'^asso/orga/(?P<slug>[-\w]+)/$', views.MemberOrgView.as_view(), name='org-detail'), ] CONTENT_PATTERNS = [ ....... ] EVENT_PATTERNS = [ ....... ] REDIRECT_PATTERNS = [ url(r'^actualite/(?P<pk>\d+)/(?P<slug>[-\w]+)/$', views.OldBlogRedirectView.as_view(), name='blog-redirect'), ....... url(r'^ressources$', RedirectView.as_view( url=reverse_lazy('frontend:doc'), permanent=True)), ] urlpatterns = [ url(r'^', include(FRONTEND_PATTERNS, namespace='frontend')), url(r'^', include(COMPANY_PATTERNS, namespace='companies')), url(r'^', include(CONTENT_PATTERNS, namespace='contents')), url(r'^', … -
jQuery adding extra variables to url
I think this is problem on frontend, and I am not familiar with frontend. So, this might not be the best method, suggestions are most welcome. I need to get some data from a rest api developed via django-rest-framework and put it into the input field on a form. So, this is the code, function getcharmids(){ var get_url = "http://localhost:8000/get_charm_ids/" + name; # name I am declaring in the django template console.log('clicked'); $.ajax({ type: 'GET', dataType: "json", url: get_url, contentType: "application/x-www-form-urlencoded;charset=UTF-8", accept: "application/json", success: function(data){ var charm_input = document.getElementById('id_charm_ids'); console.log(charm_input.value); charm_input.value = data.charm_ids; }, }); }; So, it does call the URL, but with extra parameters. It should call http://localhost:8000/get_charm_ids/Kasam09 But it calls with /get_charm_ids/Shakti_02?callback=jQuery111009547658997639622_1518179689207&_=1518179689208 So, due to extra parameters, my backend cannot process this request. What is the workaround to this problem? What is the correct way to call apis via jquery? Or is there any another good method? -
Concatenate Django urls with parameters as href
I got a template where i send a queryset of this model: Id Item Url 1 Sales "{% shop:sales product.id %}" 2 Payroll "{% shop:payroll area.id type.id %}" . . . And so on... In that template i need to iterate this model items setting each item url as a href, as you can see each url it's different and receive a diferent ammount of parameters, so, i defined the url field in the model as a string and try it: <table class="table table-condensed"> {% for item in items %} <tr> <td>{{ item.name }}</td> <td><a href="{{ item.url }}">Go</a></td> </tr> {% endfor %} </table> Of course, i send product, area and type via context from the view too. But it doesn't work, already tried also: href={{ item.url }} -- with no "" And concatenating the url removing the parameters from the string in the model field to use it like this then: href= "{{ item.url }} + product.id" Any idea ?, thanks in advance. -
Write test for a Django model with many-to-many relation
I want to write a test for Django model with many-to-many relation but I got this error: ValueError: "" needs to have a value for field "id" before this many-to-many relationship can be used. My test: class ModelTestCase(TestCase): def setUp(self): self.mock_file = mock.MagicMock(File) self.mock_file.name = 'MockFile' self.before_count = Tour.objects.count() self.tour_agency = TourAgency.objects.create( name='agency', username='agency') self.tour_category = TourCategory.objects.create(name='category') self.tour_equipment = TourEquipment.objects.create(name='equipment') self.tour_leader = TourLeader.objects.create( name='leader', email='leader@sample.com', username='leader', bio='sample text',) self.tour_tag = TourTag.objects.create(name='tag') def test_model_can_create_tour(self): self.tour = Tour.objects.create( name='tour', description='description', summary='summary', agency=self.tour_agency, equipment=self.tour_equipment, category=self.tour_category, tags=self.tour_tag, activity_type='activity type', date=datetime.now, photo=self.mock_file) self.tour.save() self.tour.save_m2m() count = Tour.objects.count() self.assertNotEqual(self.before_count, count) I'll try to save objects with .save() but it doesn't work. -
Django bower - use was s3 as storage?
im using Django bower (http://django-bower.readthedocs.io/en/latest/installation.html) to manage my jquery plugins. my settings is currently as such, whereby all media and static go to S3, currently bower goes to root/compomnents. Im not sure on how I could send bower to go to functions.py class StaticStorage(S3BotoStorage): location = settings.STATICFILES_LOCATION class MediaStorage(S3BotoStorage): location = settings.MEDIAFILES_LOCATION settings.py AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'itapp.functions.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, STATICFILES_LOCATION) MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'itapp.functions.MediaStorage' DOCUMENT_ROOT = '/documents/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'djangobower.finders.BowerFinder', ) BOWER_COMPONENTS_ROOT = os.path.join(BASE_DIR, 'components') BOWER_INSTALLED_APPS = ( 'jquery', 'jquery-ui', 'chosen', ) -
Django Multiple File Upload uploads last file twice
I want to use the multiple file upload via one FileField. If the files are being uploaded the last file of the list is uploaded twice. Same if I only upload one file. My model: class UltrasoundImages(models.Model): Ultrasound = models.ForeignKey(Ultrasound, on_delete=models.CASCADE) image = models.FileField(upload_to='UltrasoundImages/%Y/%m/%d/') My view (something wrong in here!): class UltrasoundImagesCreate(LoginRequiredMixin, generic.CreateView): model = UltrasoundImages form_class = UploadForm login_url = 'member:login' def get_initial(self): ultrasound = get_object_or_404(Ultrasound, pk=self.kwargs.get('ves')) return { 'Ultrasound': ultrasound, } def get_context_data(self, **kwargs): context = super(UltrasoundImagesCreate, self).get_context_data(**kwargs) context['patientID'] = self.kwargs.get('id') return context def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('image') if form.is_valid(): for f in files: if not UltrasoundImages.objects.filter(Ultrasound=get_object_or_404(Ultrasound, pk=self.kwargs.get('ves')), image=f): UltrasoundImages.objects.create(Ultrasound=get_object_or_404(Ultrasound, pk=self.kwargs.get('ves')), image=f) return self.form_valid(form) else: return self.form_invalid(form) I appreciate every help. -
Django count do not show zeros
I write a complex query which count fields in one day. Unfortunately if the conditions are not met the Django do not show zero. My QuerySet: query=Table.objects.all() .filter(time_stamp__range=(before_now_week, now)). .filter(field__gt=0.02) .filter(field__lte=0.03) .annotate(day=TruncDay('time_stamp')) .values('day') .annotate(time=Count('time_stamp')) .annotate(field_count=Count('ipi')) .values('day','field_count') .order_by('-day') My result: 2018-01-17 00:00:00+01:00 2 2018-01-16 00:00:00+01:00 6 2018-01-14 00:00:00+01:00 2 2018-01-13 00:00:00+01:00 4 There is a gap (2018-01-15) where the result do not show 0. Is there any way to show 0 as well despite the conditions are not met? -
Django: make comma separated list based on day name from querySet
How can I make a dictionary efficiently from a queryset. I have days and each day has times associated with it like Day1 - Time1 Day1 - Time2 Day1 - Time3 Day2 - Time1 I would like to make a list of dictionary like [{"day":'Day1', "time":'Time1, Time2, Time3'}, ...] This join listof = ",".join(str([ab.day.day, str(ab.time)]) for ab in vqs.clinicDoctor_dayShift.all().order_by('day__id')) gives me string like ['Sunday', '15:01:00'],['Sunday', '16:02:00'],['Monday', '09:01:00'],['Monday', '15:01:00'],['Monday', '16:02:00'],['Tuesday', '09:01:00'],['Tuesday', '16:02:00'] I would like to have a list like this [{'day':'Sunday', 'time':'15:01:00, 16:02:00, 09:01:00'},{'day':'Monday', 'time':'15:01:00, 16:02:00'},{'day':'Tuesday', 'time':'09:01:00, 16:02:00'}] Can anyone please help me with this. Thank you. -
How to send argument to error function of ajax?
I have one question. How to send argument to error function of ajax? Is it possible? Right now I tried yo use next code: $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', error: function (xhr, ajaxOptions, thrownError, data) { if(xhr.status==403) { location.href = '/documents/'+data.current_category+'/'; } }, }); In browser console I see next error: TypeError: data is undefined That data attribute I create in views.py file of my Django project: class DocumentCreate(PermissionRequiredMixin, CreateView): permission_required = ('documents.add_document',) raise_exception = True def get(self, request, *args, **kwargs): data = dict() # Some other code data['current_category'] = self.kwargs.get('category') return JsonResponse(data) -
Initiate scrapy spider from different django project using Django API
I have a scrappy and Django project in the same directory. I want to write an API from Django that calls the scrappy spider and returns the output to Django side. Can anyone provide me an idea for implementing this? -
Dynamic colors are not showing in print preview
I am beginner in python and doing my first django project (student score calculation), based on the score i need to set the bgcolor in html page. The problem is unable to print the html page with dynamic bgcolors views.py context = { 'scores' : scores, 'scoreColors' : scoreColors, } return render(request, 'assessment/studentAssessmentReport.html', context) HTML template <div id="printable" class="section"> {% if context %} <table class="table"> <tbody> {% for title in context %} <tr> <td>{{ title.name }}</td> {% for score in title.scores %} <td style="text-align:center;" bgColor="{{score.color}}">{{score.score}}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> {% else %}{{title.midColor}}, <p>No tests taken.</p> {% endif %} </div> I am trying the print the div printable with dynamic bgcolor based on the score with css properties. But unable to print and tried with changing stylesheet with media="print, all". Also googled lot. Sorry for poor english Any help would be praised. -
How to display categories seperated from subcategories Django
I've create a model.py from django.db import models from django.contrib.auth.models import User class Kategoria(models.Model): name = models.CharField(max_length=250, verbose_name='Kategoria') slug = models.SlugField(unique=True,verbose_name='Adres SEO') parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.CASCADE) class Meta: unique_together = ('slug', 'parent',) verbose_name = 'Kategoria' verbose_name_plural = 'Kategorie' def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' / '.join(full_path[::-1]) class Firma(models.Model): user = models.ForeignKey(User, default=1, verbose_name='Użytkownik', on_delete=models.CASCADE) title = models.CharField(max_length=250, verbose_name='Nazwa firmy') slug = models.SlugField(unique=True, verbose_name='Adres SEO') category = models.ForeignKey('Kategoria', null=True, blank=True, verbose_name='Kategoria', on_delete=models.CASCADE) content = models.TextField(verbose_name='Opis') draft = models.BooleanField(default=False, verbose_name='Szablon') publish = models.DateField(auto_now=False, auto_now_add=False) class Meta: verbose_name='Firma' verbose_name_plural='Firmy' def __str__(self): return self.title This model create a categories as parent and subcategories as children. After that I can create a post in Firma class and connect with subcategory or category. In my view.py I have: from django.shortcuts import render, get_object_or_404 from .models import Kategoria, Firma def widok_kategorii(request): kategorie = Kategoria.objects.all() context = {'kategorie': kategorie} return render(request, 'ogloszenia/index.html', context=context) and on the end in html file: {% for kategoria in kategorie %} {{kategoria.name}}<br> {% endfor %} In this case I have in browser all records belongs to Kategoria class(category and subcategory are together). How to write a def … -
Docker migrations errors with Django but works locally?
I'm trying to "Dockerize" my Django application to enable continous deployment but I keep having errors regarding the migration process that I've implemented with a Docker entrypoint file. This is my docker-compose.yml file: version: '2' services: db: image: postgres container_name: postgres_1 env_file: - ./env/database.env ports: - "5432:5432" volumes: - postgres-db-volume:/var/lib/postgresql/data api: build: ./buzzbomb.io container_name: buzzbomb_api depends_on: - db env_file: - ./env/buzzbomb.env volumes: - .:/buzzbomb ports: - "8000:8000" front-end: build: ./buzzbomb.io/vue.js-buzzbomb container_name: buzzbomb_front_end ports: - "8080:8080" elasticsearch: build: ./elasticsearch container_name: elasticsearch_1 environment: - cluster.name=docker-cluster - bootstrap.memory_lock=true - xpack.security.enabled=false - "ES_JAVA_OPTS=-Xms512m -Xmx512m" ulimits: memlock: soft: -1 hard: -1 mem_limit: 1g volumes: - esdata1:/usr/share/elasticsearch/data ports: - 9200:9200 volumes: postgres-db-volume: esdata1: Here is my Dockerfile for API: ############################################################ # Dockerfile to run a Django-based web application # Based on an Alpine Image ############################################################ # Set the base image to use to Alpine FROM alpine:3.6 ENV BUILD_DEPS="postgresql-dev gcc python3-dev musl-dev jpeg-dev zlib-dev py-pyldap libffi-dev make" ENV RUNTIME_DEPS="python3 bash" RUN apk add --no-cache $RUNTIME_DEPS $BUILD_DEPS && \ python3 -m ensurepip && \ rm -r /usr/lib/python*/ensurepip && \ pip3 install --upgrade pip setuptools && \ if [ ! -e /usr/bin/pip ]; then ln -s pip3 /usr/bin/pip ; fi && \ rm -r /root/.cache # Local directory with …