Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create detail path in Django
I want to create detail path in Django. I've create a categories and subcategories directory and after that I putting in subcategory the post. I want to create my path like localhost/category/subcategory/detail_page.html In that moment my app creating the path like localhost/detail_page.html How to do it? my views.py is: from django.shortcuts import render, get_object_or_404 from .models import Kategoria, Firma def strona_glowna(request): kategorie = Kategoria.objects.filter(parent=None).order_by('name') firmy = Firma.objects.all().order_by('publish')[:5] context = {'kategorie': kategorie, 'firmy': firmy} return render(request, 'ogloszenia/index.html', context=context) def detale_firmy(request, slug): detale_firmy = get_object_or_404(Firma, slug=slug) return render(request, 'ogloszenia/detale_firmy.html', {'detale_firmy':detale_firmy}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.strona_glowna, name='strona_glowna'), path('<slug>', views.detale_firmy, name='detale_firmy'), ] **index.html** {% for kategoria in kategorie %} <li> <b>{{kategoria.name}}</b> {% if kategoria.children.count > 0 %} <ul> {% for sub in kategoria.children.all %} <li>{{ sub.name }}</li> {% endfor %} </ul> {% endif %} </li> {% endfor %} </ul> </div> <div class="col-2"> Ostatio dodane:<br> {% for firma in firmy %} <strong>{{firma.title}}</strong><br> <a href="{% url 'detale_firmy' slug=firma.slug %}"><img src="http://free.pagepeeker.com/v2/thumbs.php?size=m&url={{firma.www}}"/><br></a> -
How to show math expressions retrieving from database in JQuery?
I have a math expression like this which I am storing to the mysql database: Test = 10.0 A = 12.0 B = 03.0 -------25.0 But when I retrieve it from the database and show it to my html template it looks broken. Like: Test = 10.0 A = 12.0 B = 03.0 -------25.0 How can I manage this situation? How to show them as like when I am giving input to the database??? Is there any way to manage it with JS or JQuery something??? -
Create a Custom History in Django showing specific field changes
Heyho, in Django i want to create a history view of my model 'application' which shows a table with the columns: Who (changed), When, which field, old Value, new Value I found the django-simple-history app which stores every version of a model instance in a new model. Actually excactly what i need, but i do not know, how to get the fields of a historical object and especially just the fields which changed comparing two sequenced historical objects. Has anybody an idea or maybe a complete new approach for that? Thanks a lot! -
Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'ServiceWorkerGlobalScope': 'only-if-cached' can be set only with 'same-origin' mode
I getting this error in my Service Worker. I have a page that changes dynamically with user usage. I do not want to cache my requests. Can someone help me to change my fetch event but still allow me to have a progressive webapp? sw.js {% load static from staticfiles %} 'use strict'; this.addEventListener('install', function(event) { event.waitUntil( caches.open('myapp-v1.0.0.2').then(function(cache) { return cache.addAll([ "/", ]); }) ); }); self.addEventListener('push', function(event) { var body_content = JSON.parse(event.data.text()); var title = body_content.title; var options = { body: body_content.text, icon: body_content.icon, badge: body_content.icon, data: { url: body_content.url } }; event.waitUntil(self.registration.showNotification(title, options)); }); self.addEventListener('notificationclick', function(event) { event.notification.close(); event.waitUntil( clients.openWindow(event.notification.data.url) ); }); self.addEventListener('fetch', function(event) { event.respondWith(fetch(event.request)); // or simply don't call event.respondWith, which // will result in default browser behaviour }); self.addEventListener('activate', function(event) { event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.filter(function(cacheName) { // Return true if you want to remove this cache, // but remember that caches are shared across // the whole origin }).map(function(cacheName) { return caches.delete(cacheName); }) ); }) ); }); -
Illegal instruction: 4 when running Django
I made clean install of Django v1.11.10 now. When I run python manage.py runserver everything works fine. But when I try connect to Postgres database, I install package pip install psycopg2, modify DATABASES varibale and after running runserver command it fails with Illegal instruction error: Performing system checks... System check identified no issues (0 silenced). Illegal instruction: 4 What is it? How to get log error? I use Mac OS 10.11.6, PostgresApp (tried on v9 and v10 server to check error source). Python 3.6.4 (via virtualenv). DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'sirjay', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } -
What's the best way to add custom HTML in the middle of a form with many fields?
I have a model with 40+ fields and a ModelForm for interacting with it. In my template I'm doing {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label }} {{ field }} </div> {% endfor %} I want to customize the final HTML - insert separators after some fields, a div after another and so on. What's the best way to do this? I thought of two ways and am wondering if I missed something more elegant: The obvious one - instead of iterating over fields in the form, manually put all fields and whatever HTML I desire between them. The downside is that this duplicates the work of listing all fields in the model and requires manual adjustments if I ever change the set of the fields I want. Do something like this: for field in form render field if field.name in fields_i_want_to_put_a_br_after <br> if field.name in fields_i_want_to_put_a_div_after <div> -
django rest framework- how can I pass query params to foreign key serializer?
For my application, I have Locations, and Events given by the following (simplified) models: class Location(models.Model): name = models.CharField(max_length=64) class Event(models.Model): location = models.ForeignKey(Location) date = models.DateField() In my API, I have an endpoint: /api/locations/ which returns all locations, and each location has its events embedded within it, e.g.: [ { 'id': 1, 'name': 'Location 1', 'events': [ {'id': 1, 'date': '2018-01-01'}, {'id': 2, 'date': '2018-01-14'} ] }, { 'id': 2, 'name': 'Location 2', 'events': [ {'id': 3, 'date': '2017-12-28'}, {'id': 4, 'date': '2018-01-10'} ] } ] my serializers look like: class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('id', 'date',) read_only_fields = ('id',) class LocationSerializer(serializers.ModelSerializer): events = EventSerializer(many=True) class Meta: model = Location fields = ('id', 'name', 'events',) read_only_fields = ('id',) Using ViewSets, I would like to add a filter to this call, with a max_date, and min_date parameter, e.g.: /api/locations/?min_date=2018-01-01&max_date=2018-01-15. Which should return only locations that have events between those two dates, AND should only return the events for each location between those two dates. In the example data above, both locations would return, Location 1 would have both events listed, but Location 2 would only have the second event in its list. In my ViewSet, I … -
Removing djcelery dependency from django project
I am Using django 1.10, celery 3.1.25 and django-celery==3.2.1, i want to remove django-celery from my project as now celery is compatible with django and it doesn't need djcelery. When i remove djcelery from Installed_apps in settings.py file and restart celery by supervisor restart celery command, it gives me error- "Unknown command celery". i have removed all the settings, what else do i require more to remove djcelery. with djcelery in settings celery is working fine. Thanks in advance. -
Filter dictionary list by text in string
I have a list of dictionaries and need to filter them by a list of strings. Right now I have this: projects = [{u'CustomerName': u'abc', u'Projectname': u'Contract A full'}, {u'CustomerName': u'bcd', u'Projectname': u'Contract A medium'}, {u'CustomerName': u'cde', u'Projectname': u'Contract B full'}, {u'CustomerName': u'def', u'Projectname': u'Contract B medium'}] filter = ['B', 'full'] return [p for p in projects if p['ProjectName'] in filter] The result I need is: [{u'CustomerName': u'abc', u'Projectname': u'Contract A full'}, {u'CustomerName': u'cde', u'Projectname': u'Contract B full'}] However it returns nothing. Only if I specify the entire string: filter = ['Contract A full', 'Contract B full'] Thank's for the help. -
Django DateTimeField can't validate ISO 8601 format
Django DateTimeField can't validate ISO 8601 format forms.py from django import forms class ImageForm(forms.Form): updatedAfter = forms.DateTimeField() createdAfter = forms.DateTimeField() views.py class ImageView(View) def get_form(self): return ImageForm(data=self.request.GET or None) def get(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): ... Here is my request: http://127.0.0.1:8001/images/?updatedAfter=2011-10-05T14:48:00.000Z&createdAfter=2011-10-05T14:48:00.000Z -
Django falsely claims "There is no unique constraint matching given keys for referenced table"
If I add the following class to my model, all works fine on migration. class BeursCheck(models.Model): order = models.IntegerField(default=None) painting = models.ForeignKey(Painting, related_name='beursCheck',primary_key=True) However, if I add this field.. mturk_assignment = models.ForeignKey( 'mturk.MtAssignment', null=True, blank=True, related_name='+', on_delete=models.SET_NULL, unique=True ) It fails with error django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "mturk_mtassignment" This field relates to MtAssignemnt, which has a unique key. This related answered even says so. class MtAssignment(MtModelBase): id = models.CharField(max_length=128, primary_key=True) -
how to autofll fields on run time in django
i want to create a salesorder model form ... model.py class Salesorder(models.Model): salesorderid=models.CharField(max_length=100, primary_key=True) distributororder=models.ForeignKey(Distributor) sales_representative=models.CharField("Sales Representative",max_length=50) discount=models.CharField("Discount",max_length=50) status=models.CharField(max_length=15,choices=sale_status, default='Un Paid') sub_total=models.PositiveIntegerField() paid=models.PositiveIntegerField() balance=models.PositiveIntegerField() productsale=models.ForeignKey('product.Product') date = models.DateField() view.py def salesorder_create(request, template_name='sales/salesorder_form.html'): form = SalesOrderForm(request.POST or None) if form.is_valid(): form.save() return redirect('index.html') return render(request, template_name, {'form':form}) template <div class="form-group"> <h3>salesorderid</h3> {{form.salesorderid}} <h3>distributororder</h3> {{form.distributororder}} <h3>sales_representative</h3> {{form.sales_representative}} <h3>discount</h3> {{form.discount}} <h3>status</h3> {{form.status}} <h3>sub_total</h3> {{form.sub_total}} <h3>paid</h3> {{form.paid}} <h3>balance</h3> {{form.balance}} <h3>productsale</h3> {{form.productsale}} <h3>date</h3> {{form.date}} </div> i want when user enter sub_total and paid field the balance field autofill like balance = total -paid please help how do that -
Django related online coding
I have a Django Project which already deployment on the server.Now I want to do some coding such add superuser. I am wondering how should I do it? When I download deployment file on my computer I cannot use runserver command. There are always some unfixed bug? Should I use virtual environment. And how do I do it? Thanks! -
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.