Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After configuring the aws xray getting AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF' in django
ROOT_URLCONF = 'apps.urls' XRAY_RECORDER = { 'AWS_XRAY_DAEMON_ADDRESS': '127.0.0.1:2000', 'AUTO_INSTRUMENT': True, # If turned on built-in database queries and template rendering will be recorded as subsegments 'AWS_XRAY_CONTEXT_MISSING': 'RUNTIME_ERROR', 'PLUGINS': (), 'SAMPLING': True, 'SAMPLING_RULES': 'Apps', 'AWS_XRAY_TRACING_NAME': 'apps', # the segment name for segments generated from incoming requests # 'DYNAMIC_NAMING': 'apps.urls', # defines a pattern that host names should match 'STREAMING_THRESHOLD': None, # defines when a segment starts to stream out its children subsegments } -
I'm unable to add another model in my django project and getting this error
WARNINGS: ?: (2_0.W001) Your URL pattern '^ckeditor/' has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to d jango.urls.path(). No changes detected Main Settings.py urlpatterns = [ path('admin/', admin.site.urls), path('',include('tutorial.urls')), re_path(r'^ckeditor/', include('ckeditor_uploader.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Convert the Django website to a progressive web App Django?
Convert the Django website to a progressive web application. Based on the title, would it work on mobile devices? What do I need, due to the loss of connection through Wifi, in a private network. I run Python with Django and postgresql, when I run: python3 manage.py runserver_plus 0.0.0.0:8000, within the same network I can connect with my mobile device, but I want to use the web application in offline mode, I was reading something from IndexdDB, It will work? Does anyone know of a video or manual where I can orient myself "Service Worker"? -
Django / Pandas - Create Excel file and serve as download
I am trying to create an Excel file using pandas and serving it to the user as a downloadable file via Django. I put together some different answers on the topic that I found on here and ended up with this code: collection = [{"title": "something", "price": 34, "quantity": 23}, {..}] output = BytesIO() df = pd.DataFrame(collection, columns=['title', 'price', 'quantity']) writer = pd.ExcelWriter(output, engine='xlsxwriter') df.to_excel(writer, sheet_name='Sheet1') writer.save() output.seek(0) workbook = output.getvalue() response = StreamingHttpResponse(workbook, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename={output_name}.xlsx' return response It all works well until I try to open the resulting file - I can an error saying that the file is damaged or that there is something wrong with the data-format. I suspect that it could have something to do with the data being binary? How can I resolve this issue? -
Passing context to django admin index page
I'm trying to create a table on django admin's index page, listing all users registered in a specific timeframe. I've managed to already edit the index page to include my table but I now want to populate the table. I tried declaring the extra_context variable but it still doesn't pass it to the template. I've been on this issue for days and still can't figure out what I'm doing wrong. This is my admin.py file from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin from .forms import SignUpForm, EditUserForm from .models import CustomUser from django.urls import path from datetime import datetime, timedelta from django.utils import timezone class CustomUserAdmin(UserAdmin): list_filter = ['created_at',] list_display = ['username', 'email', 'created_at', 'is_active'] # index_template = 'admin/my_index.html' def time_threshold(num): num = int(num) thresh = datetime.now(tz=timezone.utc) - timedelta(hours=num) return thresh print(time_threshold(30)) def get_urls(self): urls = super().get_urls() custom_urls = [ path("user_metrics/", self.user_metrics), ] return custom_urls + urls def user_metrics(self, request, extra_context=None): extra_context = extra_context or {} user_24 = CustomUser.objects.filter(created_at__gt=time_threshold(730)) extra_context['users_in_past_24_hours'] = CustomUser.objects.filter(created_at__gt=time_threshold(24)) extra_context['users_in_past_week'] = CustomUser.objects.filter(created_at__gt=time_threshold(168)) extra_context['users_in_past_month'] = CustomUser.objects.filter(created_at__gt=time_threshold(730)) print(user_24) return super(CustomUserAdmin, self).user_metrics(request, extra_context=extra_context) admin.site.register(CustomUser, CustomUserAdmin) admin.site.unregister(Group) admin.site.site_header = "Savests Custom Admin" And this is my index.html file I have inside template/admin folder {% extends "admin/base_site.html" … -
Django Rest Framwork with natural_key (unique_together fields)
I have an model that closely resemble the one from the doc: https://docs.djangoproject.com/en/3.1/topics/serialization/#natural-keys i.e.: from django.db import models class PersonManager(models.Manager): def get_by_natural_key(self, first_name, last_name): return self.get(first_name=first_name, last_name=last_name) class Person(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birthdate = models.DateField() objects = PersonManager() class Meta: unique_together = [['first_name', 'last_name']] def natural_key(self): return (self.first_name, self.last_name) The doc then shows how to serialize: >>> serializers.serialize('json', [book1, book2], indent=2, ... use_natural_foreign_keys=True, use_natural_primary_keys=True) However I can't figure out how should I use it in a DRF Serializer class. I know, if I had a single unique field, I could use a SlugRelatedField But in my case, it's a combination of two fields, and there seems to be no solution in the Relations DRF page referenced above. I there are way to use unique_together natural_keys in DRF Serialization? Can I override serialize method to include required natural_key options? If so, could you please show? May be another way? Or is this something fundamentally impossible? Thanks in advance! -
Path not accesible in Django
This is maybe a very silly doubt, but i can't seem to figure out the reason for my code not working. So this is my Django Project file directory structure. Now, my targeted HTML file (index.html) is in aboutme/templates/ folder. I want to render it from the view.py in my aboutme app. Now my css and js files are inside "assets" folder which will be used by my index.html. But when i run the server the CSS files are not taking any effect on my index.html page. I have added the static files path in my settings.py of my project and added the static path in my index.html while trying to refer to the CSS and JS files, but still the changes are not reflected in the html file. Below is the snippet of my settings.py file: And below is the snippet of the index.html file from where i am trying to access the CSS files. -
Multiple independent forms in a DetailView
I have these simplified models. One Order can have multiple OrderItems. The OrderItems have a status ("A", "B" or "C"). class OrderItem(models.Model): STATUS_CHOICES = ( ("A", "A"), ("B", "B"), ("C", "C"), ) name = CharField(max_length=100) status = models.CharField(choices=STATUS_CHOICES, blank=False, default="A", max_length=1) def __str__(self): return self.name class Order(models.Model): items = models.ManyToManyField(OrderItem) def __str__(self): return self.pk Currently i use a DetailView, that shows one Order and loop through the OrderItems. Each OrderItem has a link to an UpdateView, to update the status: views.py class DetailOrder(DetailView): model = Order template {% for orderitem in object.items.all %} {{orderitem}} <a href={% url 'some-updateview' orderitem.pk %}>Update Status</a> {% endfor %} Now to my question: how would I approach that for each orderitem an independent form is displayed to update the status directly in the DetailView instead of following a link to an UpdateView. Is that even possible? Something like this, just to show the idea: {% for orderitem in object.items.all %} {{orderitem}} {{form}} {% endfor %} -
Django Rest Framework - Edit related object set
I have a listing system in my Django project, with a Tag object that attaches a list of Tags to a Listing. Each object has its own standard Viewset which is passed to router.register(). The current way I'm editing or creating Tags is through a POST or PATCH to /tags/. Ideally, I'd do this by doing a PATCH /listings/[id]/ with a JSON body of {"tags": [{"type": "foo", "text": "bar"}]}. I've provided a slightly simplified version of my code below. serializers.py class NestedTagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ['text', 'type'] class ListingSerializer(serializers.ModelSerializer): tags = NestedTagSerializer(many=True, read_only=False) class Meta: model = Listing fields = ['tags', 'title', 'id'] models.py class Listing(models.Model): title = models.CharField(max_length=255) description = models.TextField() class Tag(models.Model): listing = models.ForeignKey(Listing, on_delete=CASCADE) text = models.CharField(max_length=255) type = models.CharField(max_length=255) Is there a nice way to do this with Django Rest Framework? -
How to append hardcoded data to a serializer?
I put together a Django API with a serializer, that returns a specific object, with one "feature" per row returned. Now, I want to append to that object a kind of metadata, a list. An example is worth a thousand words, so: My API returns: [ [{"id":43680,"type":"Feature","geometry":{"type":"Point","coordinates":[39.79839999999999,30.1316]}},"2017-05-02","2017-05-02T00:00:00","event type 1","sub event 35","This is a test"], [{"id":47444,"type":"Feature","geometry":{"type":"Point","coordinates":[39.79839999999999,30.1316]}},"2017-02-13","2017-02-13T00:00:00","event type 1","sub event 24","This is a test"] ] What I actually want is: [ [{"id":43680,"type":"Feature","geometry":{"type":"Point","coordinates":[39.79839999999999,30.1316]}},"2017-05-02","2017-05-02T00:00:00","event type 1","sub event 35","This is a test"], [{"id":47444,"type":"Feature","geometry":{"type":"Point","coordinates":[39.79839999999999,30.1316]}},"2017-02-13","2017-02-13T00:00:00","event type 1","sub event 24","This is a test"], "fields": [ {'name': 'location', 'type': 'geojson', 'analyzeType': 'GEOMETRY'}, {'name': 'event_date', 'type': 'date', 'analyzeType': 'DATE'}, {'name': 'event_time', 'type': 'time', 'analyzeType': 'DATETIME'}, {'name': 'event_type', 'type': 'string', 'analyzeType': 'STRING'}, {'name': 'sub_event_type', 'type': 'string', 'analyzeType': 'STRING'}, {'name': 'notes', 'type': 'string', 'analyzeType': 'STRING'} ] ] I have tried a few methods to add that additional data to my serializer. I tried a "def save(self)" in the serializer class but it is not being called. I tried a "perform_create(self, serializer)" in the views.py but again, not called. I tried to manually append to the serializer.data in the views, but got "TypeError: 'property' object is not iterable" in response when trying to do "list(serializer_class.data)" or "mydict.update(serializer_class.data)" wheer mydict had my additional row. … -
Django get the list of checked checkbox from and process in views.py
I have a checkbox in template and want to get the lit of value from checked checkbox for rendering to pdf in views.py. Do I need to create a form for it? No idea how to combine it. html: {% for order in orders %} <div class="mb-3"> {% for item in order.items.all %} <input type="checkbox" name="item_checkbox" value="{{ item.item.id }}" >{{ item.item.product_name }}<br> {% endfor %} </div> <a href="{% url 'generate_pdf' id=order.id %}" class="btn btn-primary" target="_blank">PDF</a> {% endfor %} How do I get the checkbox value and pass it to views.py? pdf redering in views.py def generate_to_pdf(request, id): order = get_object_or_404(Order, id=id) time_now = timezone.now() template = get_template('invoice.html') context = { 'order': order, 'time_now': time_now } template.render(context) pdf = render_to_pdf('invoice.html', context) return HttpResponse(pdf, content_type='application/pdf') Should I do the Form post method in below funcion for get the value from html? views.py for the above html: def order_admin(request): orders = Order.objects.all().order_by('-id') context = { 'orders': orders, } return render(request, 'product_admin.html', context) -
Gracefully stopping celery tasks
I am using celery for async processing along with Heroku. I would like to be able to determine when Heroku sends SIGTERM prior to shutting down (when we are deploying new code, setting env vars, etc) in specific tasks. This will allow us to do any clean up on long running tasks greater than 10 seconds. I understand that we should strive for short idempotent tasks, but the data we are dealing with is too large to get to that level. I have ran into the following doc: https://devcenter.heroku.com/articles/celery-heroku#using-remap_sigterm But the documentation is lacking, and without much context. If someone could give me an example of how to handle this, I would greatly appreciate it! -
Add dataEmptyMessage in FusionCharts Django
How can I display status and error messages that can be set for any chart in the Django FusionCharts constructor? -
Use of Django Serializers
I have this endpoint which return list of dictionaries. step 1 :- def db_data: return list(table_name.objects.all().values()) The same can be achieved by DRF serializers(Django Rest Framework) as follows. step 2 :- serializers.py from rest_framework import serializers from .models import table_name class IdMetricsSerializer(serializers.ModelSerializer): class Meta: model = table_name fields = '__all__' views.py from rest_framework import generics from models import table_name from serializers import IdMetricsSerializer class IdMetricsView(generics.ListAPIView): queryset = table_name.objects.all() serializer_class = IdMetricsSerializer If step1 and step2 gives the same result, what is the use of django serializers? -
is there any length function for the Django Model Objects?
I've hard coded this 3 in my loop range because I was unable to get the actual length. I tried listing the available features but didn't found any print(dir(Todo_Item.objects)). Maybe is there any other better way to iterate over the object and stop when it ends? This is my code with hard coded 3 in loop range. def home_view(request): display_list = [] for i in range(3): display_list.append(Todo_Item.objects.get(id=i+1).task) .......some code below as well....... My Todo app runs fine without any error but the only problem is this non-dynamic loop. -
Make isort recognize imports from Django apps as first-party imports
I'm working on a project with many different Django apps. I want to use isort on this project but the imports from Django apps (from myapp1.mymodule import myfunction) are seen by isort as third-party imports. How can I make isort recognize them as first-party imports? I could add in the isort configuration (in the .cfg): known_first_party=myapp1,myapp2... but I'll have to maintain this list. Is there a better way? -
order_with_respect_to a null ForeignKey causes expensive query
I have a model that looks like this: class CharacterSheetNode(models.Model): parent = models.ForeignKey('self', related_name='items', null=True, on_delete=models.CASCADE) # other fields class Meta: order_with_respect_to = 'parent' I have 30M+ instances of this model in my database. My problem is that when I create a new instance of it, the following Django code is ran: site-packages\django\db\models\base.py, line 876: if meta.order_with_respect_to: # If this is a model with an order_with_respect_to # autopopulate the _order field field = meta.order_with_respect_to filter_args = field.get_filter_kwargs_for_object(self) self._order = cls._base_manager.using(using).filter(**filter_args).aggregate( _order__max=Coalesce( ExpressionWrapper(Max('_order') + Value(1), output_field=IntegerField()), Value(0), ), )['_order__max'] This piece of code will go through all the CharacterSheetNode with no parent (there are probably 1M of them), and look for the Max('_order') value. As if they were all children of the same parent "None". The query itself takes 7 seconds to run. How can I avoid running this code if the parent is null? Or at least tell Django to only set the order_value if there is a parent? The whole method from which these lines were extracted: def _save_table(self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None): """ Do the heavy-lifting involved in saving. Update or insert the data for a single table. """ meta = cls._meta non_pks = [f for … -
Cannot Get Django & Celery to work to Upload Images
I'm working on a django app that allows the user to upload multiple images at the same time. The problem is when they upload more than a two or three images they're forced to wait for too long while they're processed. The more images they put in there the longer they have to wait, also if they upload a ton of images (15 ~3mb images seems to be the max) it crashes. I would like them to be able to upload as many images as they want at the same time and not have huge wait times or crashes. I researched and seems like Celery & Rabbitmq would be great solutions to solve this as they would upload in the background while the user could return to the app, so it solves the waiting issue and the timeout issue as they'd all be uploaded as separate tasks (I think) I have rabbitmq installed and open, celery 4.3 installed but I'm not able to get it to work. I'm getting this error when I submit the form Exception Type: EncodeError at /test_form/ Exception Value: Object of type InMemoryUploadedFile is not JSON serializable I've tried to force celery to use pickle (celery.py … -
unique_together = (("name", "added_by"),) in Django model gives IntergretyError at/admin instead of Validation Error
I want to show a validation message like "This Project already exists" in my django admin. I keep getting an IntegrityError at my Name. Isn't Django supposed to validate this and give an ValidationError if I use unique_together=((,)) in my model? Or do I have to Try and Catch the IntegrityError myself? Can anyone tell me a best practice for validating unique users inside a form/model. models.py class Project(models.Model): name = models.CharField(max_length=200) added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, default=None) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = (("name", "added_by"),) def __str__(self): return self.name -
How can I access related_name from a model inside another app in Django?
I am working with models from differents apps in Django. I have two apps. One is called partners and other contracts. In the app partners, inside the file models.py, I have this model defined: class Partner(models.Model): cpf = models.CharField(max_length=11, null=False, blank=True) In the app contracts, inside the file models.py, I have this model defined: from partners.models import Partner class Contrato(models.Model): ... indications = models.ManyToManyField(Partner, through='ContractIndication', related_name='indications') class ContractIndication(models.Model): contract = models.ForeignKey(Contract, on_delete=models.CASCADE) partner = models.ForeignKey(Partner, on_delete=models.CASCADE) payed = models.CharField(max_length=1, choices=YES_NO, null=False, blank=True, default='N') However, in the file views.py from partners app, I cannot access all the contracts that a partner is linked, using this: partner = Partner.objects.get(...) indications = partner.indications.all() I am already using the related_name attribute from Contract. What am I doing wrong? -
Pass in variable to tag django
is there a way to pass in a variable in a tag in django templating? For example, <a href="{% url '{{ url_path }}' %}">Click here</a>, as you can see, I want to pass the url_path variable into the url tag, but when I do this, django treats {{ url_path }} as the string itself, not the variable url_path. Is there a way to pass in that variable in the url tag? Thanks in advance! -
Django make migrations error, fields clashes
I am doing a Django Web Application and I have a problem when I try to import the models with: python manage.py makemigrations ERROR SystemCheckError: System check identified some issues: ERRORS: beers.Beer.company: (models.E006) The field 'company' clashes with the field 'company' from model 'core.commoninfo'. CLASS BEERS.BERR Path: my_project/beers/models.py class Beer(CommonInfo): COLOR_YELLOW = 1 COLOR_BLACK = 2 COLOR_AMBER = 3 COLOR_BROWN = 4 COLORS_CHOICE = ( (COLOR_YELLOW, 'Yellow'), (COLOR_BLACK, 'Balck'), (COLOR_AMBER, 'Amber'), (COLOR_BROWN, 'Brown'), ) name = models.CharField('Name', max_length=50) abv = models.DecimalField('Alcohol By Volume', decimal_places=2, max_digits=5, default=0) color = models.PositiveSmallIntegerField('Color', choices=COLORS_CHOICE, default=COLOR_YELLOW) is_filtered = models.BooleanField('Is filtered?',default=False) creation_date = models.DateField('Creation Date', auto_now_add=True) image = models.ImageField('Image', blank=True, null=True, upload_to=beer_image_upload_location) company = models.ForeignKey(Company, related_name='beers', on_delete=models.CASCADE) class Meta: verbose_name = "Beer" verbose_name_plural = "Beers" ordering = ['name'] def __str__(self): return self.name @property def is_alcoholic(self): return self.abv > 0 def more_alcohol_than(self, alcohol): return self.abv > alcohol FATHER CLASS CORE.COMMONINFO Path: my_project/core/models.py For some reason I had to add core to my settings.py INSTALLED_APPS, but this isn't an app. class CommonInfo(models.Model): created_at = models.DateTimeField('Created at', blank=True, default=now) last_modified_at = models.DateTimeField('Modified at', blank=True, default=now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='Created by', blank=True, null=True, related_name="%(app_label)s_%(class)s_created", on_delete=models.DO_NOTHING) last_modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='Modified by', blank=True, null=True, related_name="%(app_label)s_%(class)s_lastmodified", on_delete=models.CASCADE) def save(self, *args, **kwargs): if not … -
direction on how to update page for multiple users
I've created a django app that deals with company vehicles. A user enters the site and is able to see a list of vehicles. Then the user can click and check out a vehicle which then grays out the vehicle. The user can also click the gray and select the vehicle as being free for someone else to use. Question I have is what's the best way in handling if there was multiple users on the page? how do I update the page for user A when user B selected vehicle X. I've read about django-channels and also signals. I'm not sure what's the best fit. -
xhtml2pdf - Problem with displaying table rows using django forloop tag
What I am trying to do is to create an invoice pdf file with several table rows. Table rows would be created using for loop in Django. The problem is data inside for loop tag is not visible on the pdf file. You can check the screenshots below. Django properly renders invoice.html template so the code is valid, but the pdf file contains empty frame without any table rows. To render pdf from html I am using xhtml2pdf. how django render the invoice.html template how pdf file looks like invoice.html <html> <head> {% load static %} <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta charset="UTF-8"> <style> @font-face { font-family: Roboto; src: url('{% static 'fonts/Roboto-Regular.ttf' %}'); } @font-face { font-family: Roboto-bold; src: url('{% static 'fonts/Roboto-Bold.ttf' %}'); font-weight: bold; } @page { size: a4 portrait; @frame header_frame { /* Static Frame */ -pdf-frame-content: frame_header_left; left: 50pt; width: 245pt; top: 30pt; height: 150pt; } @frame header_frame { /* Static Frame */ -pdf-frame-content: frame_header_right; left: 300pt; width: 245pt; top: 50pt; height: 150pt; } @frame content_frame { /* Content Frame */ -pdf-frame-content: frame_invoice_number; left: 50pt; width: 512pt; top: 170pt; height: 30pt; } @frame col1 { -pdf-frame-content: frame_col1; left: 50pt; width: 245pt; top: 220pt; height: 130pt; } @frame … -
Model validation and intengrity errors
When my model need special validations i usually think first of db constraints to ensure the integrity of my database completely but i found some problem with this approach. I usually use UniqueConstraints like: models.UniqueConstraint( fields=('author', 'title'), name='valid_unique_author_title', ), and they work well because the forms and serializers catch the error and show a error like Post with this Author and Title already exists. but what happen with UniqueConstraint have a condition like models.UniqueConstraint( fields=('author', 'title'), condition=models.Q(title='title1'), name='valid_unique_title1_author_title', ), Contrary to expected they throw a integrity error which is not captured by the form and serializers (DRF), that cause a http response with 500 as status code, only just by adding a condition the error is no longer captured. The first question, I must modified all the forms and serializers that have check constraints or unique constraints with condition for catch Integrity errors? Finally the same happens with CheckConstraints like: models.CheckConstraint( check=~models.Q(title='forbidden_title'), name='valid_forbidden_title' ), The aboves examples are differents, i found two cases of constraints: No susceptible for race conditions. The check constraint that verified if the title is different for forbidden_title. Susceptible for race conditions. The second UniqueConstraint that verified if the author have other post with the same …