Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
vscode keeps asking for debug config
vscode asks me for my debug config file everytime I run the server, how can I get it to see it? here is my current config that keeps being ignored. { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload" ], "django": true } ] } I'm using Anaconda 4.7.12 mac running mohave python3.7 django2.2 -
Django 2.x filter and sort calculated boolean field
I am trying to figure out how to enable sorting by a calculated boolean field. I have seen some other related posts, but I cannot figure them out. I tried to add a custom manager for Files, but it did not work. I want to be able to sort and filter values according to calculated fields like exists. class File(models.Model): archive = models.ForeignKey("Archive", on_delete=models.CASCADE) file_name = models.CharField(max_length=2000, unique=False, validators=[validate_is_file]) comment = RichTextField() title = models.CharField(max_length=2000, default='') def __str__(self): return basename(self.file_name) def save(self, *args, **kwargs): self.title = basename(self.file_name) super(File, self).save(*args, **kwargs) def preview(self): return bs4(self.comment).get_text() def exists(self): return isfile(self.file_name) exists.boolean = True def size(self): return getsize(self.file_name) def created(self): return convert_ctime(time.ctime(getctime(self.file_name))) def modified(self): return convert_ctime(time.ctime(getmtime(self.file_name))) class FileAdmin(admin.ModelAdmin): readonly_fields = ['file_name', 'archive'] formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'style': 'width: 90%;'})}, } fieldsets = [ (None, {'fields': ['title', 'comment', 'file_name', 'archive']}) ] list_display = ['exists', 'file_name', 'size', 'created', 'modified', 'title', 'preview',] search_fields = ['title', 'file_name', 'comment', 'created', 'modified'] list_filter = ['exists'] # This does not work admin.site.register(Archive, ArchiveAdmin) admin.site.register(File, FileAdmin) -
Django: Improve page load time by executing complex queries automatically over night and saving result in small lookup table
I am building a dashboard-like webapp in Django and my view takes forever to load due to a relatively large database (a single table with 60.000 rows...and growing), the complexity of the queries and quiet a lot of number crunching and data manipulation in python, according to django debug toolbar the page needs 12 seconds to load. To speed up the page loading time I thought about the following solution: Build a view that is called automatically every night, completeles all the complex queries, number crunching and data manipulation and saves the results in a small lookup table in the database Build a second view that is returning the dashbaord but retrieves the data from the small lookup table via a very simple query and hence loads much faster Since the queries from the first view are executed every night, the data is always up-to-date in the lookup table My questions: Does my idea make sense, and if yes does anyone have any exerience with such an approach? How can I write a view that gets called automatically every night? I also read about caching but with caching the first loading of the page after a database update would still … -
Can we use django with pybuilder efficiently
I want to add a tool in my django project which will run test cases and create an alert if code coverage is less on newer commit. To handle this issue, one way is to use a test runner with a coverage tool in Django or I can use pybuilder. But, it didn't get much about pybuilder combination with django over the net. -
models.CharField Is being removed when I'm trying to add models.DateTimeField(auto_now=True) in a new migration
When I migrate this Search model it is migrated successfully and CharField is created against search field search = models.CharField(max_length=20, default="ping pong"), and can be seen in admin panel. class Search(models.Model): search = models.CharField(max_length=20, default="ping pong") def __str__(self): return '{}'.format(self.search) class Meta: verbose_name_plural = 'Searches' But the question is when I add a DateTimeField to this Search model class see the code class Search(models.Model): search = models.CharField(max_length=20, default="ping pong"), created = models.DateTimeField(auto_now=True) def __str__(self): return '{}'.format(self.search) class Meta: verbose_name_plural = 'Searches' so when I migrate again for the second field to update changes in database, it says - Remove field search from search - Add field created to search And the CharField of search that I was able to see in admin panel is no longer visable. Actually I want to store the search text and the time of that search in my database. -
Creating a django form that collects data and post in in the admin
I really am not posting any code here because this question is somewhat strait to the point... I need to create a form that collects phone numbers from users and post them in the admin....thanks anyone -
how to import all django models and more in a script?
I've put the following code at the top of my script file os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'momsite.conf.local.settings') django.setup() Now I can import my django apps and run small snippets (to mainly test stuff) I'd like to import all the models registered through settings.INSTALLED_APPS I know https://github.com/django-extensions/django-extensions does this when running manage.py shell_plus it automatically imports all the models and more. I'm looking at their code. not sure if I'll make sense out of it. https://github.com/django-extensions/django-extensions/blob/3355332238910f3f30a3921e604641562c79a0a8/django_extensions/management/commands/shell_plus.py#L137 -
Django. How to count the number of queries in a queryset that has been filtered and append that number as an attribute to another model?
I'm new with Python and Django. I have three models Post, Vote and VoteModel: class Post(VoteModel, models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=150) description = models.TextField(max_length=3000) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Vote(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE) post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) vote_choice = models.PositiveSmallIntegerField(default=0) #0 - none, 1 - yes, 2 - no date = models.DateTimeField(auto_now_add=True) class VoteModel(models.Model): num_vote_yes = models.IntegerField(default=0, db_index=True) num_vote_no = models.IntegerField(default=0, db_index=True) class Meta: abstract = True Now, I want to calculate the total number of yes and no votes for each post. I do it like this: yes_votes = Vote.objects.filter(post=post_instance, vote_choice=1).count() I want to save the yes_votes number in the abstract VoteModel class num_vote_yes attribute. How? I want to access num_vote_yes and num_vote_no by post_instance.num_vote_yes and post_instance.num_vote_no. Certainly, everytime I create a new instance of a Vote class I want the num_vote_yes and num_vote_no to be automatically updated. How? Been struggling for a long time now but I learned a lot! The time has come to outreach! Thanks! -
Document path parameters in REST API documentation
I am using REST's inbuilt API documentation tool and I can't figure out how to document the path parameters that I pass in my URLs. I think an image explains best what I mean: When I send data with a post method I can fill the description field by adding help_text in my mode or in my Serializer. But has anyone an idea how to document these path parameters? I can't find anything in the scarce documentation. Thanks in advance! Very much appreciated! Docs are created like this: from rest_framework.documentation import include_docs_urls from rest_framework.permissions import IsAdminUser API_TITLE = "..." API_DESCRIPTION = "..." urlpatterns = [ path('docs/', include_docs_urls( title=API_TITLE, description=API_DESCRIPTION, permission_classes=[IsAdminUser]) ), -
celery logging to django site page
What's the best practice of logging celery tasks into django's page. I have a django project and some periodic tasks powered by celery. Those tasks are located in tasks.py. I want to have a page on my site, named something like ".../tasks" where all the celery logs are being stored. So every time a periodic task was called by celery, the log information about the status of this task would show on mentioned page. Sorry for repeating myself, just want to make my question clear. Right now I have a default celery logger. Hope you'd help me. -
getting all products from parent category django rest
I have products related to child category for example: I have category like that Toys, Toys -> ChildToys, Toys -> ChildToys -> Cars I have related products to Toys -> ChildToys -> Cars and I can get all products by Cars but How can I get the products by filtering Toys category. What I have done so far class Category(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, blank=True, unique=True) icon = models.ImageField(upload_to='category_icons', null=True, blank=True) parent = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='children', null=True, blank=True) class Product(models.Model): category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) class ProductList(generics.ListAPIView): serializer_class = ProductSerializer def get_queryset(self): slug = self.request.query_params.get('slug', None) parent_id = Category.objects.get(slug=slug) cats = Category.objects.filter(parent_id=parent_id) qs = Product.objects.filter(category_id__in=parent_id) print(qs) return qs -
how to capture the number of downloads of a specific file in django
i have been working on a project that involves downloading files. i have been tasked to create a report of how many downloads per file. here is my code reports.py def dataset_download(request): download = DataSet.objects.annotate(numdownload=Count('name'),) return render(request, "my_admin/dataset_download.html", {"download":download}) my models.py class DataSet(models.Model): name = models.CharField(max_length=255) description = models.TextField() purpose = models.TextField() temporal_scope = models.TextField() taxonomic_scope = models.TextField() my urls.py path('dataset_download/', reports.dataset_download, name='dataset_download'), and finally my html {% for d in download %} {% if d.name != "" %} <tr> <td>{{ d.name }}</td> <td>{{ d.numdownload }}</td> <td> <a href="/dataset/?name={{ d.name }}" class="btn btn-primary btn-xs"> <i class="fa fa-eye"></i> View Details </a> </td> </tr> {% endif %} {% endfor %} -
DRF: can you deserialize one JSON key:value pair into multiple fields
In my API I have a module, which collects JSON objects obtained via POST request. JSON objects I'm receiving look more or less like this: { "id": "bec7426d-c5c3-4341-9df2-a0b2c54ab8da", "data": { "temperature": -2.4, // some other stuff is here as well ... } } The problem is requirement that I have to save both: records from data dictionary and whole data dictionary as a JSONField. My ORM model looks like this: class Report(BaseModel): id = models.BigAutoField(primary_key=True) data = JSONField(verbose_name=_("Data"), encoder=DjangoJSONEncoder, blank=True, null=True) temperature = models.DecimalField( max_digits=3, decimal_places=1, ) # other properties Is there any neat way to get both properties in one attempt to deserialize JSON object? Currently I use nested serializers formed like this: class DataSerializer(serializers.ModelSerializer): temperature = serializers.DecimalField( source="temperature", write_only=True, max_digits=3, decimal_places=1 ) class Meta: model = Report fields = ("temperature") class ReportSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source="uuid", read_only=True) data = DataSerializer(source="*") class Meta: model = Report fields = ("id", "data") which obviously does not pass whole data dictionary to validated_data, which means I have to update the JSON field elsewhere (not good since I would like to have both data and temperature at null=False in ORM model). Any good ideas on how to fix this using DRF serializers would be … -
How can I create a model that adds objects from other models to it
I am using Django 2.2 and am trying to create a model that takes information from another model. I am aware of ForeignKey however this doesn't add all of the object attributes such as title, price etc for me to call upon from my templates. I am selling a product. This product can be for women, or it can be for men. I have a category selection within the model that allows me to select for men or for women. If the category selection is 'for women' then I would then like this product to become available as an object to be added to my 'for women' model. Here are my models: product, and, for women. TOY_CATEGORY_CHOICES = ( ('FW', 'For Women'), ('FM', 'For Men') ) class Product(models.Model): slug = models.SlugField(max_length=40) image = models.ImageField(upload_to='media') title = models.CharField(max_length=150) description = models.TextField() price = models.DecimalField(max_digits=5, decimal_places=2) stock_quantity = models.PositiveIntegerField() in_stock = models.BooleanField(default=True) category = models.CharField(choices=TOY_CATEGORY_CHOICES, max_length=2, default='FW') brand = models.CharField(choices=TOY_BRAND_CHOICES, max_length=2, default='NB') on_sale = models.BooleanField(default=False) def __str__(self): return self.title class ForWomen(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) Here are my views: def WomenOnlyView(request): obj = ForWomen.objects.all() context = { 'object':obj } return render (request, 'products/forwomen.html') This is my URL file: urlpatterns = [ path('products/for-women/', … -
Django Custom Widget for Materialize can't find Template
We are using Django 3 and Materialize CSS in our project and when rendering a form checkboxes don't show up. This is because Materialize needs to style them a special way (reference) and our Django model form doesn't play ball. As we don't want any dependencies for a simple checkbox but we need to do this over and over again in different forms, we thought it would be a good idea to create a custom widget, just using a separate template for rendering the checkboxes: class MaterializeSwitch(forms.widgets.CheckboxInput): template_name = os.path.join(STATICFILES_DIRS[0], 'widgets', 'cb_materialize.html') def __init__(self, attrs={}, *args, **kwargs): super().__init__(attrs) If I understood correctly this is how it is done in Django internally and I just replaced the default template_name with our custom one: <div class="switch"><label>On<input type="{{ widget.type }}" name="{{ widget.name }}" {% if widget.value != None %}value="{{ widget.value|stringformat:'s' }}"{% endif %}>Off</label></div> When using one field with this widget the error message: TemplateDoesNotExist at [...] comes up. This is a pretty long question already I didn't want to spam it with more paths and information. If there is any more info needed to solve this I will add it on request. -
ValueError: Field 'id' expected a number but got 'Processing'
I'm going to deploy my django application on DigitalOcean. Everything gone well, except following error, and my question is: where can I find source of this error, actually in which file ? ValueError: invalid literal for int() with base 10: 'Processing' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/progbash/ccproject/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/progbash/ccproject/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) ... File "/home/progbash/ccproject/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2361, in get_db_prep_value value = self.get_prep_value(value) File "/home/progbash/ccproject/env/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1772, in get_prep_value ) from e ValueError: Field 'id' expected a number but got 'Processing'. -
Django ORM - Cast and filter a queryset
I would like to cast a related column to integer and then filter a queryset, but I can not get it to work. These are my models class Author(models.Model): name = models.CharField(max_length=255) ... class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(Author, on_delete=models.CASCADE) ... class MetricType(models.Model): label = models.CharField(max_length=255) class Metrics(models.Model): book = models.ForeignKey(Job, on_delete=models.CASCADE, related_name="metrics") metric_type = models.ForeignKey(MetricType, on_delete=models.CASCADE) value = models.CharField(max_length=255) For simplicity, let's suppose I have the following data Author: - Name: Miguel de Cervantes - Name: William Shakespeare Book: - Title: Don Quixote, Author: Miguel de Cervantes - Title: Hamlet, Author: William Shakespeare MetricType: - Label: Pages Metrics: - Book: Don Quixote, MetricType: Pages, value: 100 - Book: Hamlet, MetricType: Pages, value: 40 Now, the only thing I want to do is get all the books that have more than N pages. This would be really easy to do in normal circumstances but in this case I need to cast the value of the metrics and then do the filter. I have tried the following: from django.db.models import IntegerField from django.db.models.functions import Cast from . import models value = 50 pages_metric = models.MetricType.objects.get(label='Pages') models.Book.objects.annotate( pages=Cast('metrics__value', IntegerField() ).filter( metrics__metric_type=pages_metric, pages__gte=value ) I'd like to get one book, but … -
How to add settings for admin to change edit some variables?
I want to give admin access for some variables like changing the message text or changing the Index page text. How could i do that? -
Can't modify files created in docker container
I got a container with django application running in it and I sometimes go into the shell of the container and run ./manage makemigrations to create migrations for my app. Files are created successfully and synchronized between host and container. However in my host machine I am not able to modify any file created in container. This is my Dockerfile LABEL maintainer="Marek Czaplicki <marek.czaplicki@dlabs.pl>" WORKDIR /app COPY ./requirements.txt ./requirements.txt RUN set -ex; \ apk update; \ apk upgrade; \ apk add libpq libc-dev gcc g++ libffi-dev linux-headers python3-dev musl-dev pcre-dev postgresql-dev postgresql-client swig tzdata; \ apk add --virtual .build-deps build-base linux-headers; \ apk del .build-deps; \ pip install pip -U; \ pip --no-cache-dir install -r requirements.txt; \ rm -rf /var/cache/apk/*; \ adduser -h /app -D -u 1000 -H uwsgi_user ENV PYTHONUNBUFFERED=TRUE COPY . . ENTRYPOINT ["sh", "./entrypoint.sh"] CMD ["sh", "./run_backend.sh"] and run_backend.sh ./manage.py collectstatic --noinput ./manage.py migrate && exec uwsgi --strict uwsgi.ini what can I do to be able to modify these files in my host machine? I don't want to chmod every file or directory every time I create it. For some reason there is one project in which files created in container are editable by host machine, but … -
Mocking a celery task call
I have a celery task that needs to be mocked. It is being called as:- def trigger_task(id): task_name(id).delay() I tried using this but because I am passing a parameter it is not getting mocked properly. @patch('domain.tasks.tasks.task_name.delay') def test_abc: pass How can i Mock it? -
Django Coalesce returns null if no rows are found
I'm using the Coalesce function to prevent an aggregate Sum from returning None Coalesce(Sum('ext_price'), 0) The problem is that if no rows are found it still returns null. Is there a way to modify the function so it returns zero if no rows are found? class Coalesce(Func): """Return, from left to right, the first non-null expression.""" function = 'COALESCE' def __init__(self, *expressions, **extra): if len(expressions) < 2: raise ValueError('Coalesce must take at least two expressions') super().__init__(*expressions, **extra) -
Execute a python function without response - Django
I'm working with Django in a project and I need to execute some functions depending on what user's want to do. If this action has to return and show new values I know how to do it, but when I just want to execute a function in my views.py that I don't need any response and don't know how to do it. Now what I'm doing is return something and don't use it, but I'm sure it is possible do it without returning anything. My code that returns a response is: $('#import_btn').click(function(){ updateData() }); function updateData(filt){ console.log('Hello'); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ url: '/../../updateBBDD/', type: 'POST', headers:{"X-CSRFToken": csrftoken}, data: { 'Filt': filt, }, dataType: "json", cache: true, success: function(response) { var cols = response.Cols; } }); } How I have to do it in my js to execute a python function with no response?? Thank you very much. -
Bootstrap distance between buttons in navbar
I have a problem with bootstrap. I tried to do simple site in django, I created navbar from bootstrap with some buttons depends of user. It's looks that: And as U can see, the distance between buttons is zero. I tried a margin css as internet say, and even something stupid like adding 'space'. But usually nothing changes. For sure I just do something wrong. So I decide to ask here. My CSS is basic, I want to learn it but first it I want to end django tutorial, and I stuck here. My actual code: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/heroes/">SNP list <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="/heroes-new">New SNP</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> {% if user.is_authenticated %} <a> Witaj {{ user.username }} </a> {% if request.user.is_staff %} <a role="button" class="btn btn-outline-success btn-sm my-2 my-sm-0" href='/admin/'> Panel admina </a> {% endif %} <a role="button" class="btn btn-outline-success btn-sm my-2 my-sm-0" href='/logout/'> Logout </a> {% else %} <a role="button" class="btn btn-outline-success btn-sm my-2 my-sm-0" href='/login/'> Login </a> {% endif %} </form> </div> </nav> How can I handle it to make distance between that buttons? And... what should I know to handling … -
update an object in django model
I have a model in my app named foo class foo(models.Model): a = models.CharField(max_length=500, default=0,null=True) a_quantity = models.CharField(max_length=500, default=0, null=True) and I am updating this model from another form like this: def form_valid (self, form): product = form.save(commit=False) product.save() data = form.cleaned_data for i in range(1, 9): foo.objects.update_or_create(a=data["a" + str(i)], b=data["a_quantity" + str(i)]) But the problem here is that it creates a new entry if a is same but a_quantity. I want that when a is repeated its quantity should be summed to the existing quantity in the model. For eg id my input is this: bar 10 and the table is like this: a a_quantity nar 27 bar 15 lar 10 then when the function is called it should do this: a a_quantity nar 27 bar 15 lar 10 Currently it creates a new entry with the same name and different quantity. How can I do this ? -
How do I run a CGI script in python
I am trying to run a simple program of python when values are sent from html page. The html file is as follows: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css"> <title>Minimum Bootstrap HTML Skeleton</title> <!-- --> <style> </style> </head> <body> <div class="container"> <form action="search.py" method="post"> <input type="text" name="x_name"> <input type="submit" name="submit" value="submit"> </form> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.min.js"></script> <script> </script> </body> </html> And here is my search.py file import cgi import cgitb form = cgi.FieldStorage() name = form.getvalue('x_name') print "Content-type:text/html\r\n\r\n" print "<html>" print "<head>" print "<title>Hello - Second CGI Program</title>" print "</head>" print "<body>" print "<h2>Hello %s %s</h2>" % (name) print "</body>" print "</html>" Now, when I run the html file and enter name field and submit it, instead of processing the search.py file, it just displays the code written in search.py Like this: Check the output Any help regarding how to proceed further to run the files would be helpful. Thank you