Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to display custom fields for inlines?
How do I display custom fields in my admin interface? Specifically, I have a function that is used to display images, and I would like that to show beside the name. Here is my code. models.py class Photo(models.Model): file = models.ImageField(upload_to='media/images') ... def __str__(self): return f"{self.title}" class Album(models.Model): photos = models.ManyToManyField(Photo,related_name="photos",blank=True,through="Photo") admin.py from django.contrib import admin from adminsortable2.admin import SortableInlineAdminMixin from .models import Photo, Album class PhotoInline(SortableInlineAdminMixin, admin.TabularInline): model = Album.photos.through extra = 2 class AlbumAdmin(admin.ModelAdmin): list_display = ("title","published") inlines = [PhotoInline] ... admin.site.register(Album, AlbumAdmin) Right now, in my admin interface, I only see the titles of each model. -
HEROKU DJANGO PYTHON APP crashing with application error
I am having difficulty with my first deploy of a heroku app to DJANGO. I have loaded the application and it worked, but did not load all css. It also did not size images properly and appeared to be missing a template and bootstrap style sheets. It also deleted images loaded into the application on restart of dyno. I have upgraded to the hobby plan. I have made the changes noted by heroku to include the following : First Commit : #BASE_DIR = Path(file).resolve().parent.parent Second Commit: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) I am using whitenoise for img handling. TRACEBACK 2021-05-06T23:38:58.920990+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2021-05-06T23:38:58.921004+00:00 app[web.1]: worker.init_process() 2021-05-06T23:38:58.921005+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 134, in init_process 2021-05-06T23:38:58.921005+00:00 app[web.1]: self.load_wsgi() 2021-05-06T23:38:58.921005+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2021-05-06T23:38:58.921006+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-05-06T23:38:58.921014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-05-06T23:38:58.921014+00:00 app[web.1]: self.callable = self.load() 2021-05-06T23:38:58.921014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2021-05-06T23:38:58.921014+00:00 app[web.1]: return self.load_wsgiapp() 2021-05-06T23:38:58.921015+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2021-05-06T23:38:58.921015+00:00 app[web.1]: return util.import_app(self.app_uri) 2021-05-06T23:38:58.921015+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app 2021-05-06T23:38:58.921016+00:00 app[web.1]: mod = importlib.import_module(module) 2021-05-06T23:38:58.921016+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-05-06T23:38:58.921017+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-05-06T23:38:58.921017+00:00 app[web.1]: File "<frozen … -
Django Tables - Conditional Formatting (Display certain data)
Is there a way to display specific data using Django-tables2? I'm trying to use a Primary Key in my current Database to see if it matches the email of the user that is logged in. Once the user navigates to the page where the database is shown, it will only show data that is related to the user that is signed in. I've been looking up on Django-Tables2 Conditional Formatting but I am unsure on how to start. Some additional info: I am using Microsoft Graph API to sign in the users. -
'dict' object has no attribute 'user'
i am sending a post request from my frontend when i check it on my browser the successfully sent request looks like this user:"username" but when i try to print it in my views.py i get dict object has no attribute 'user' views.py @api_view(['POST']) def sendmail(request): print(request.data.user) note that request.data looks like this {'user': 'username'}, what am i doing wrong? -
ForeignKey between Shared and Tenants Applications, error
I'm using Django / Django-Tenants , i i would like to do a foreignKey between a shared Application and a Tenant one but i'm getting an error : from django.db import models from users.models import CustomUser from customer.models import Client from apps.contacts.models import Contact # Create your models here. class ContactCenter(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE, null=True, blank=False) contact_source = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=False) shared_with = models.ForeignKey(CustomUser, related_name="contact_y", on_delete=models.CASCADE, null=True, blank=False) Error Message : django.db.utils.ProgrammingError: relation "contacts_contact" does not exist NB: Contact is a Tenant Applciation not a shared one -
Django custom ManyToMany relation name
Consider the following 2 models: class Tag(models.Model): name = models.CharField(max_length=30) class Exercise(models.Model): name = name = models.CharField(max_length=30) tags = models.ManyToManyField(Tag, related_name='exercises') In admin.py: admin.site.register(Tag) When deleting a tag from the admin panel, a warning with relation object names are displayed which is not really informative. # Are you sure you want to delete tag3 ? The following elements will be deleted too. Tag: tag3 Relation exercise-tag: Exercise_tags object (3) Relation exercise-tag: Exercise_tags object (6) Relation exercise-tag: Exercise_tags object (9) How can one make a more informative message by displaying the actual exercise name instead of the relation name e.g Exercise_tags object (3) ? For instance: # Are you sure you want to delete tag3 ? The following elements will be deleted too. Tag: tag3 Relation exercise-tag: Advanced exercise 5 Relation exercise-tag: Introductory exercise on programming Relation exercise-tag: My exercise 2 -
Django doesn't recognize/can't find post_save edited field?
I'm trying to create a unique SlugField using a post_save model signal. If the SlugField already exists, a number should be appended to the slug to make it unique. However, Django does not seem to to recognize when the SlugField already exists. I'm using a single-tabled inherited MPTT model: class Text(MPTTModel): type = models.CharField(max_length=255, blank=False) # for STI. Essentially returns the class name. title = models.CharField(max_length=255, blank=True) slug = models.SlugField(max_length=255, blank=True) slug_order = models.CharField(max_length=255, blank=True) def __init__(self, *args, **kwargs): super(Text, self).__init__(*args, **kwargs) # If we don't have a subclass at all, then we need the type attribute to match # our current class. if not self.__class__.__subclasses__(): self.type = self.__class__.__name__.lower() else: subclass = [ x for x in self.__class__.__subclasses__() if x.__name__.lower() == self.type ] if subclass: self.__class__ = subclass[0] else: self.type = self.__class__.__name__.lower() class Book(Text): objects = BookManager() class Meta: proxy = True @receiver(post_save, sender=Book, dispatch_uid="create_book_slug") def create_book_slug(sender, instance, **kwargs): slug = slugify(instance.title) slug_exists = Book.objects.filter(slug=slug).exists() # This always seems to be False counter = 1 while slug_exists: counter += 1 new_slug = f"{slug}-{counter}" slug_exists = Book.objects.filter(slug=new_slug).exists() if counter > 1: slug = f"{slug}-{counter}" instance.slug = slug My test: b1 = Book.objects.create(title="book book") b2 = Book.objects.create(title="book book") self.assertEqual(b1.slug, "book-book") # True … -
Stop webpage from waiting for cancelled XHR requests
I'm working on a Django project and the Javascript for one of my pages makes some XHR requests that can take a while to complete. If the user goes to this page, they have to wait for these requests to finish before the site lets them go to another page. I've been trying to have the page cancels these requests when clicking to another page, but even if the requests cancel the page still waits quite a while before changing URLs. This is how my requests are structured. const controller = new AbortController() const signal = controller.signal let get_salesperson_sales = async() => { return await fetch(`/reports/salesperson-sales/${fromDate && toDate ? `from_date=${fromDate}&to_date=${toDate}` : ''}`, { signal }) .then(response => response.json()) .then(response => { document.getElementById('total_rep_sales').innerText = '$'+Number(response.total_sales.toFixed(2)).toLocaleString() return response }) .catch(error => { if (error.name === 'AbortError') console.log('Salesperson sales fetch was aborted.') else errorMessage.innerHTML += '<p>Error getting sales by rep: '+error.responseJSON ? error.responseJSON.details : 'Unexpected error'+'</p>' }) } There are 4 of these functions in total that I call with Promise.allSettled(). At the bottom of the page, I bind a couple functions to abort the requests. $('#date-filter').submit(() => { // Stop loading current report before submitting controller.abort() return true }) $(window).bind('beforeunload', () => … -
Is there code generator for Django like Gii?
I use Gii code generator with Yii2 framework for more that 3 years ago. Now I want to change to Django but I need a similar code generator. -
how to run some lines at the initialization of my django api in production?
I build an API in django, it worked perfectly until I tried to deploy it with gunicorn and nginx. I initiate some constants at the beginning of my views.py. So my code looks like this before defining all my views. from ... import... x = do_big_stuff() y = do_big_stuff2() z = do_big_stuff3() I do this to init x, y and z at the launching of the api (so when I enter python manage.py runserver) I use x, y and z in all my views after this. This init takes approximately 15 seconds then a request will take less than 1 second. It's not a problem But since I deployed this API with gunicorn and nginx I meet an issue : it looks like this lines are ran at EACH request. So it takes so much time and user always get "502 bad gateway" and I can see in my logs [CRITICAL] WORKER TIMEOUT (pid:23605) So i commented these lines and just add a print("hello world") to check and realised that hello world was printed at each request ... That was not the case during development. I assume my method is not good, but could anyone advice me please ? -
Django User registration/auth with Neo4j
i need a clear way to use Neo4j as default database and model of User registration and login in Django. i try many ways and I've done a lot of searching but cant find a clear way. Can anyone give me a practical example? -
Getting data from JSON to JS
In the django function, I send data to JS via JSON startdate = datetime.strptime(request.POST['startdate'], '%d.%m.%Y') enddate = datetime.strptime(request.POST['enddate'], '%d.%m.%Y') paymentparking = paidparking.objects.filter(expirationdate__range = (startdate, enddate)).values('expirationdate', 'price') return JsonResponse(dict(paymentparking)) How do I get price and expirationdate separately in JS? $.ajax({ type: "POST", url: "statistics", data: { 'startdate': finalDateStrStart,'enddate': finalDateStrEnd, }, dataType: "json", cache: false, success:function (data) { } }); This is what I get in the django function before sending the JSON: <QuerySet [{'expirationdate': datetime.date(2021, 4, 30), 'price': 300.0}, {'expirationdate': datetime.date(2021, 5, 5), 'price': 750.0}]> If success: function (data) { console.log(data) } As a result, I get: I need to get the price and expirationdate separately. How can this be done? -
ModuleNotFoundError: No module named 'scraper.items' when running django server
I am getting a weird error in a django scrapy web application. I am going to show my files structure first. | db.sqlite3 | manage.py | output.doc | +---accounts | | admin.py | | apps.py | | decorators.py | | forms.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | | __init__.py | | | | | \---__pycache__ | | __init__.cpython-39.pyc | | | +---templates | | \---accounts | | company_register.html | | login.html | | user_register.html | | | \---__pycache__ | admin.cpython-39.pyc | apps.cpython-39.pyc | decorators.cpython-39.pyc | forms.cpython-39.pyc | models.cpython-39.pyc | urls.cpython-39.pyc | views.cpython-39.pyc | __init__.cpython-39.pyc | +---products | | admin.py | | apps.py | | models.py | | tests.py | | urls.py | | views.py | | __init__.py | | | +---migrations | | | 0001_initial.py | | | __init__.py | | | | | \---__pycache__ | | 0001_initial.cpython-39.pyc | | __init__.cpython-39.pyc | | | +---templates | | \---products | | get_products.html | | | \---__pycache__ | admin.cpython-39.pyc | apps.cpython-39.pyc | models.cpython-39.pyc | urls.cpython-39.pyc | views.cpython-39.pyc | __init__.cpython-39.pyc | +---produp | | asgi.py | | settings.py | | urls.py | | views.py | | wsgi.py | … -
Is there an API to interract with porjects?
I'm developing a workflow-based application in Django. The purpose of this application is to grab some data about projects, and to create a project in a scheduler application. My corporate is testing "ONLYOFFICE Projects" for scheduling / projects managements. I've to import some Trello based projects, and add some projects from my django-based application. Is it possible to call an API entry point to create a project, manage users, groups... in ONLYOFFICE ? I've not seen anything in the docs... Thanks ! -
Django urls.py config gives page 404
I have a very simple Django installation with one app, but I cannot get the urls.py configured correctly. It's strange, because I have the same config in another application, which works perfectly. urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('subscribe/', include('newsletter.urls')), path('subscription-confirmation/<str:key>/', include('newsletter.urls')), path('admin/', admin.site.urls), ] APP urls.py from django.urls import path from newsletter.views import subscribe, subscription_conf urlpatterns = [ path('subscribe/', subscribe), path('subscription-confirmation/<str:key>/', subscription_conf), ] Error in browser: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/subscribe/ Using the URLconf defined in backoffice.urls, Django tried these URL patterns, in this order: 1. subscribe/ subscribe/ 2. subscribe/ subscription-confirmation/<str:key>/ 3. subscription-confirmation/<str:key>/ 4. admin/ The current path, subscribe/, didn’t match any of these. I'm pulling my hair out with this, what am I doing wrong? Thanks in advance. -
Trouble with Django annotation with multiple ForeignKey references
I'm struggling with annotations and haven't found examples that help me understand. Here are relevant parts of my models: class Team(models.Model): team_name = models.CharField(max_length=50) class Match(models.Model): match_time = models.DateTimeField() team1 = models.ForeignKey( Team, on_delete=models.CASCADE, related_name='match_team1') team2 = models.ForeignKey( Team, on_delete=models.CASCADE, related_name='match_team2') team1_points = models.IntegerField(null=True) team2_points = models.IntegerField(null=True) What I'd like to end up with is an annotation on the Teams objects that would give me each team's total points. Sometimes, a team is match.team1 (so their points are in match.team1_points) and sometimes they are match.team2, with their points stored in match.team2_points. This is as close as I've gotten, in maybe a hundred or so tries: teams = Team.objects.annotate(total_points = Value( (Match.objects.filter(team1=21).aggregate(total=Sum(F('team1_points'))))['total'] or 0 + (Match.objects.filter(team2=21).aggregate(total=Sum(F('team2_points'))))['total'] or 0, output_field=IntegerField()) ) This works great, but (of course) annotates the total_points for the team with pk=21 to every team in the queryset. If there's a better approach for all this, I'd love to see it, but short of that, if you can show me how to turn those '21' values into a reference to the outer team's pk, I think that will work? -
Transmitting JSON Django
I have a request for a model paymentparking = paidparking.objects.filter(expirationdate__range=(startdate, enddate)) I need to take 2 fields from the request and pass them to JS I send it via return JsonResponse({'price': paymentparking.price,'expirationdate':paymentparking.expirationdate}) But I get an error АttributeError: 'QuerySet' object has no attribute 'price' -
How to change HTTP to HTTPS in sitemaps.xml of django website?
Its show only http not https. But my sites is secured https. sitemaps doesnot shows https. Links are indexed in google console but not submitted in sitemap. Help me -
Django doesn't see urls.py
I'm new to Django and I'm following this tutorial: https://www.django-rest-framework.org/tutorial/1-serialization/ When I run the server with python manage.py runserver, it seems to work fine showing me no errors. However when I visit http://127.0.0.1:8000/snippets/ it gives me the following error: Using the URLconf defined in tutorial.urls, Django tried these URL patterns, in this order: admin/ The current path, snippets/, didn’t match any of these. Here's my urls.py located in the tutorial folder: from django.urls import path, include urlpatterns = [ path('', include('snippets.urls')), ] I don't understand what's going on, how come it only checks admin/ if I'm wiring the root urlconf to snippets.urls? On a related note, when I modify urls.py and add gibberish the server won't give me an error, however if I were to modify models.py then it'll start complaining, that's why I'm getting the feeling it doesn't even check my urls.py and maybe instead some default one... Any tips are very appreciated! -
Can I compare two datetime.datetime fields in Django?
I am having two-time fields - one from the database and one is the current time. I want to check if the current time is greater than the database time field or lesser. How to do that? if expiration_date < datetime.now() item_info['expired'] = True The above does not work. Syntax error. -
reading uploaded file before saving them to database in django
I want to validate the uploaded files before saving them to database. My validator is something like this def validate(size, file_name): valid_types = ["ffd8ff"] valid = 0 infile = open(f"{file_name}", 'rb') # here header = infile.read(24) header = str(binascii.hexlify(header))[2:-1] if header[0:6] in valid_types: valid = 1 else: valid = 0 return valid Im able to pass the size and file_name as arguments but how do I read the file without saving it. If the validator returns 1 then the my views.py saves the file else no. Thank you! -
How to fix nginx: [emerg] "proxy_cache" zone "django_cache" is unknown in /etc/nginx/nginx.conf:63
when I try to use error-check command in nginx using the command: sudo nginx –t this error has been raised: nginx: [emerg] "proxy_cache" zone "django_cache" is unknown in /etc/nginx/nginx.conf:63 I want to use nginx for my django server app but I stopped here! I searched about it but no result even in google I watched videos and read blogs but no one talk about this problem anyone knows about it thank you! -
Implement similar products in the Django framework
I want when the user enters the page of a product, that page displays the products whose first name is the same as this product. In fact, I want to implement similar products. Each time a user enters a page, the products whose first name was the same as the product the user entered are identified as similar products. I do this as follows but it does not recognize any products. What is the reason for this? my model: class Product(models.Model): name = models.CharField(max_length=200) .... my view: def product_details(request, id): products = get_object_or_404(Product, id=id) related_products = Product.objects.filter(name__startswith=products.name) ... -
django DRF with Firebase needs access to request._request
I have a mobile app talking to backend server (Django+drf). Auth is handled via Firebase. On the django side, I'm using custom DRF auth and session auth. The Custom DRF(firebase) auth kicks in for the first time and subsequently, after the jwt is validated and the user is created if needed, the session auth will kick in for as long as the session is alive. In order for the Session auth to kick in, I ofcourse need to auth.login(request, user) the user. However, the Request is the wrapped DRF request and not a Django Request. Questions: Is the above described pattern (DRFCustomAuthFirebase + SessionAuth) an acceptable approach Is the only way to login the user by accessing protected _request request._request or is there another way ? Basically, how do I get DRF Custom auth to intersect Django auth (aside from doing login(request_request, user) in order to effectively use DRF Session Auth. -
Django: Custom router for read-replica raises OperationalError on save (with related models)
I'm testing out a custom database router for a Django project to support read replicas (based on the Django docs on multiple database) and when I create model instances containing references to other models, the save method tries to use the read-replica, for some reason. I've registered the following router in the DATABASE_ROUTERS settings: class PrimaryReplicaRouter: def db_for_read(self, model, **hints): return "replica" This should only route read operations to the replica, but for some reason, save operations (on models with related models) seem to trigger use of the replica: In [1]: from django.contrib.auth import User In [2]: from myapp.models import BlogPost In [3]: user = User.objects.first() In [4]: post = BlogPost(user=user) In [5]: post.save() # ... <traceback> OperationalError: (1142, "INSERT command denied to user 'readonly'@'localhost' for table 'myapp_blogpost'") Using create on the queryset (e.g. BlogPost.objects.create(user=user)), on the other hand, works fine, and so does saving objects that don't have FK references to related models. This is a simplified version of my models, but the model I'm using only has a reference to the User model and some primitive fields and there are no custom save methods on the models. Am I doing something wrong or is this behavior documented somewhere? …