Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing values to constructor of custom HTMLElement
I have a custom HTMLElement that's working as intended, but I cannot find a way to pass arguments to the constructor; instead I'm accessing passing the values in my custom tag, but then I have to set the values in connectedCallback(), which I'm not satisfied with. Here's a stripped down version of what I'm doing now: class TrackingPreview extends HTMLElement { constructor() { super(); const video = document.createElement('video'); video.setAttribute('controls', ''); video.setAttribute('width', '1920'); video.setAttribute('height', '1080'); shadow.appendChild(video); this.video = video; } connectedCallback() { const videoId = this.getAttribute('video-id'); this.video.id = videoId; } } I'd rather pass the videoId directly to the constructor, something like this (which is NOT working): JS: class TrackingPreview extends HTMLElement { constructor(videoId) { super(); const video = document.createElement('video'); video.setAttribute('id', videoId); video.setAttribute('controls', ''); video.setAttribute('width', '1920'); video.setAttribute('height', '1080'); shadow.appendChild(video); } connectedCallback() { } } JS Script on HTML Page: $(document).ready(function(){ const tracking_preview = document.createElement('tracking-preview','{{video_id}}'); tracking_preview.videoId = '{{video_id}}'; document.body.append(tracking_preview); }); Is there a way to pass values to a custom constructor? The docs imply it is possible but aren't very helpful for how to do it. -
How to initialize a postgres container with data using .dump instead of .sql?
i've seen in the docs and many solution to initialize a postgres container with a database using an init.sql as mentioned in this question: COPY init.sql /docker-entrypoint-initdb.d/10-init.sql The problem is that my database data in .sql is to large(8GB). This makes the dump process to long and the file to heavy. I was trying to make something similar to this approach generating a .dump file with (540mb). I have 2 containers to run my django project. A Dockerfile for my python environment and postgres image. My docker files are shown in the end of this question. So far i've managed to run the dump in my container with these steps: I add my .dump file to my container in docker-compose build my containers Go inside my postgres container and execute a pg_restore command to dump my database. Then go to my python/django container to execute a migrate command. And finally run server. This works but its not automated. How can i automate this problem in my docker files so i don't need to execute these commands manually? Bellow are my files and the commands i required to run my .dump file on postgres container: generate and add ./project-dump/latest.dump to my … -
How Django find correct Template variable from TemplateView
I have this pieces of code: # newspaper_project/urls.py from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('admin/', admin.site.urls), path('users/', include('users.urls')) path('users/', include('django.contrib.auth.urls')), ] # users/urls.py from django.urls import path from . import views urlpatterns = [ path('signup/', views.SignUp.as_view(), name='signup'), ] # users/views.py from django.urls import reverse_lazy from django.views import generic from .forms import CustomUserCreationForm class SignUp(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' <!-- templates/home.html --> {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! <p><a href="{% url 'logout' %}">logout</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> | <a href="{% url 'signup' %}">signup</a> {% endif %} {% endblock %} And my question is: How Django know what model is used in home.html template? (how Django know about "username"?) In TemplateView i don't specify Model (in this case CustomUser). When we want to access and render database data, we need specify Model class (or in this case Form) in view. And from here Django accesses for template variable. Isn't it? -
how to logout from django with a custom usermodel?
I made an app and extended the AbstractUser to add some fields to my User model. after done that... everything works as expected (login, create user, reset password...) but when i try to logout using default django.contrib.auth.LogoutView or include('django.contrib.auth.urls') it will simply ignore the logout. when i go back to the restricted page i can enter and see the content and my user is actually loggen in!. i created a custom logout view like this def custom_logout(request): print('Loggin out {}'.format(request.user)) auth.logout(request) print(request.user) return HttpResponseRedirect('/restrictedpage') on the restrictedpage i have a print to show the user print("User logged: {}".format(request.user)) When i click logout this is what shows up in the console: "GET /restrictedpage HTTP/1.1" 200 19820 User logged: ceterre ----- This is where i click logout ------ Loggin out AnonymousUser AnonymousUser "GET /accounts/logout/ HTTP/1.1" 302 0 ----- this redirects me to /restrictedpage User logged: ceterre "GET /restrictedpage HTTP/1.1" 200 19820 -
How to send a tar file from django to react client side and download it
I have a django view that downloads a bunch of files from an s3 bucket and then tarballs them together. I would like to be able to send that tarballed file to the client side and then download it on the client side. I've been trying to open it up with a blob, but the tarball file always says it has a fatal error when I try to open it up. Django side tar_name = "Inspection{}{}.tar.gz".format(inspection.id,first_file_name) tar_path = "{}/{}".format(os.path.join(os.path.expanduser('~'), 'Downloads'), tar_name) self.download_tar(files,tar_path) tarred = tarfile.open(tar_path,'r:bz') response = HttpResponse(tarred,content_type='application/x-gzip') response['Content-Disposition'] = "attachment; filename={0}".format('test_worked.tar.gz') response['Content-Encoding'] = 'tar' return response React side. We use a program called transcrypt that turns python into react. def download(self,url): data = __new__(Blob([url], {type: 'application/x-gzi'})) csvURL = window.URL.createObjectURL(data) tempLink = document.createElement('a') tempLink.href = csvURL tempLink.setAttribute('download', 'hello.tar') tempLink.click() Expected Result: Tarball is downloaded on client side. Actual Result: Tarball is downloaded on client side, but cannot be opened. Says An error occurred while loading the archive. Fatal Error -
How to display 3 posts in a row in pyhton with html and css? It now displays every post under the last one
I want to display like col-md-4 but it displays every post under the last one. Ive tried to set the class of the conatiner to col-md-4 but it didnt worked for me. Can i define it directly into the container like I've tried or should I define it into CSS? I would be grateful if you can help me! Regards, My code of my container is: <div class="content container"> <div class="row"> <div class="col-md-4"> {% block content %} {% for post in posts %} <div class="post"> <div class="date"> {{ post.published_date }} </div> <h1>{{ post.title }}</h1> <p>{{ post.text|linebreaksbr | truncatewords:50 }}</p> <a href="{% url 'post_detail' pk=post.pk %}" class="btn btn-default">Weiterlesen</a> </div> {% endfor %} {% endblock %} i have also an base.py {% load static %} <html> <head> <title>Code Reminder</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> </head> <body> <div class="page-header"> <h1><a href="/">Code Reminder</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </body> </html> my css looks like this, maybe i should define it into css? blog.css .page-header { background-color: black; margin-top: 0; padding: 20px 20px 20px 40px; } .page-header h1, .page-header h1 a, … -
self.create() store data separated from the parent model
The problem that I have is my UserProfileModel has a nested SubscriptionModel, when I call the self.create() method it stores SubscriptionModel outside the parent model "UserProfileModel ". The script stores the user perfectly in both of the User model and in the UserProfileModel too with no peoblem but when it comes to the SubscriptionModel, it stores it but not in the perent model "UserProfileModel ". class SubscriptionModel(models.Model): subscription_name = models.CharField(_('subscription name'), max_length=50, choices=SUBSCRIPTION, default='F') def __str__(self): return self.subscription_name def save(self, *args, **kwargs): super().save(*args, **kwargs) # The parent model. class UserProfileModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='', related_name='user_instance') subscription = models.OneToOneField(SubscriptionModel, related_name='user_subscription', on_delete=models.CASCADE, blank=True, null=True) # Other fields.... objects = UserProfileManager() # The UserProfileManager() functions. @transaction.atomic def create_user_profile(self, user, subscription): password = user.pop('password') user = User(**user) user.set_password(password) user.save() subscription = SubscriptionModel(**subscription).save() self.create(user=user, subscription=subscription) return user # The UserRegistrationSerializer. class UserRegistrationSerializer(serializers.Serializer): subscription_name = serializers.ChoiceField(choices=SubscriptionModel.SUBSCRIPTION, default='F') # Other fields... def get_cleaned_data(self): return { 'username': self.validated_data.get('username', None), 'first_name': self.validated_data.get('first_name', None), 'last_name': self.validated_data.get('last_name', None), 'email': self.validated_data.get('email', None), 'password': self.validated_data.get('password', None) } def get_subscription_cleaned_data(self): return { 'subscription_name': self.validated_data.get('subscription_name', None) } def save(self, request): print(request.data) cleaned_data = self.get_cleaned_data() subscription = self.get_subscription_cleaned_data() user = UserProfileModel.objects.create_user_profile(user=cleaned_data, subscription=subscription) return user -
What is the purpose of Django's phone2numeric method in the utils library?
Django has the following function phone2numeric(phone) defined below: def phone2numeric(phone): """Convert a phone number with letters into its numeric equivalent.""" char2number = { 'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9', } return ''.join(char2number.get(c, c) for c in phone.lower()) From the looks of it it basically takes a number e.g. 1-800 GALAXY and turns the GALAXY part to 425299 so it becomes 1-800 425299. I'm just wondering why Django has implemented such a specific function. I'd imagine the utils.text library would hold general purpose functions like e.g. slugify or capfirst but why phone2numeric? Wouldn't that be something that is defined if you're writing a web app that is related to number management because what other use case is there? -
Adding a variable passed from views.py into a static file in a template
I have 4 pdfs files with names such as "lesson-1, lesson-2, lesson-3" etc. I want each of them to render when the path for each one is accessed. How can I pass the variable from views.py into the static link from the template? I've tried {% static 'lectii/lectie-' | add:{lectie}.pdf %} {% static 'lectii/lectie-{lectie}.pdf %} and none worked. Here's the template: {% extends 'base.html' %} {% load static %} {% block content %} </div> <div id="middle-section" class="container-fluid container-fluid-margin"> <div class="row content-block"> <div class="col-md-12"> <embed src="{% static 'lectii/lectie-{lectie}.pdf %}" style="width: 100%; height: 100vh;"></embed> </div> </div> <div class="row content-block"> <iframe width="100%" height="750" src="https://www.youtube.com/embed/I6dQXpJKlPk" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> {% endblock %} views.py from django.shortcuts import render from django.shortcuts import get_object_or_404 from .models import Lectie def lectii(req): return render(req, '../templates/pagini/lectii-selector.html') def lectie(req, lectie_id): lectie2 = get_object_or_404(Lectie, pk=lectie_id) context = { 'lectie': lectie2 } return render(req, '../templates/pagini/lectii.html', context) (lectie = lesson) So how can I include the variable into that static path? Thanks. -
Existe alguma forma de ofuscar o javascript de um sistema desenvolvido, frondend e backend em Django?
Boa Tarde, você sabe se existe alguma forma de ofuscar o javascript de um sistema desenvolvido, frondend e backend em Django? Preciso criptografar -
how do I Include partial html files into index.html?
I'm using python & django and tying to include html files in my index.html file but cant seem to get it to work - any help will be appreciated. I'll add some context.. I've downloaded a theme via Keentheme and want to use it in my project. The getting started tutorial (https://www.youtube.com/watch?v=ApO_obOK_00) at around 14:20 instructs me to change all html files to php files and to use This doesn't work. The html files contain numerous instructions like the following: '''[html-partial:include:{"file":"partials/_mobile-header-base.html"}]/''' The file location for the above is as follows: ./partials/_mobile-header-base.html The tutorial only walks through the php include method - can anyone help? -
Sum of fields values is not returning the correct value after saving a object
I'm trying to pass the result from a sum aggregation function to another object after saving it. However, every time I change the value save the object, the sum aggregation queryset result is not correct. How do I properly do this? class Team(models.Model): total = models.PositiveSmallIntegerField(default=0) class Player(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) score = models.PositiveSmallIntegerField(default=0) def save(self, *args, **kwargs) super(Player, self).save(*args, **kwargs) # new_total value does not get updated. new_total = Player.objects.filter(team=self.team).aggregate(Sum('score')).get('score__sum') Team.objects.filter(id=self.team.id).update(total=new_total) @receiver(post_save, sender=Player) def sum(sender, instance, **kwargs): # new_total_attempt_two value does not get updated either. new_total_attempt_two = sender.objects.filter(squad=instance.squad).aggregate(Sum('score')).get('score__sum') If I have an existing object with score 10 and change it to 15, I expect the total on Team model to get updated to 15 but it is still 10. I'm using python 3.6, django 2.1.7. I also tried using post_save signals but had no success either. -
Django-filter: How do I determine the current language inside an OrderingFilter?
I have a django_filter FilterSet which contains an OrderingFilter as follows: from django.utils.translation import get_language import django_filters class geographicEntityFilter(django_filters.FilterSet): ordering = django_filters.OrderingFilter( fields = ( ('displayedNames__' + get_language()[0:2],'name'), ) ) I use that Filter with a class-based view: class GeographicEntityListView(FilterView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) f = geographicEntityFilter(self.request.GET, queryset=self.get_queryset()) ... What I want to do is to set the field name depending on the currently selected language by the user. The get_language() method always returns "en" no matter what language the site is on. I assume I need to access the language via the request, but I can't find any documentation on that. That works in other parts of my code with other FilterSets e.g. when I define a callable for the QuerySet of a ModelChoiceFilter, where the request is available. But according to the documentation, the fields argument "accepts the ‘list of two-tuples’ syntax ...fields may also just be an iterable of strings". No mention about a callable. So, any help is appreciated. -
Post to an UpdateView without actually displaying the template for submission?
I've got a screen that displays objects a user has entered. On this template form, there is a button next to the object - when the user clicks the button, it should update that object (mark it as 'done', a Boolean) Can I post to this 'UpdateView' without actually having to create a template for the UpdateView? I suppose I could just post to a function-based view, but I'm trying to use ClassBasedViews to simplify things. I've got a CreateView method that works without issue. class TaskForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.task_location = kwargs.pop('task_location', None) super(TaskNeededForm, self).__init__(*args, **kwargs) self.fields['task'].queryset = Task.objects.filter( id__in=[task_item.task_id for task_item in TaskReference.objects.filter( task_location_id=self.task_location, ) ] ) class Meta: model = TaskNeed fields = ['task', 'task_percent', 'task_status'] My UpdateView looks like this: class TaskNeededUpdate(SuccessMessageMixin, UpdateView): model = TaskNeeded fields = ['task', 'task_percent', 'task_status'] success_message = 'Task has been successfully updated.' template_name = 'tasks/task_needed_form.html' #same form as CreateView def post(self, request, *args, **kwargs): self.object = self.get_object() self.object.task_status = True self.object.save() return super().post(request, *args, **kwargs) The form template looks like this: <form id="update-form" class="" action="" method="post"> {% csrf_token %} <button class="btn bg-danger text-white" type="submit" name="button">Task Complete</button> </form> The task pk is passed in via the URL: path('<int:location_id>/task-needed/update/<int:pk>/', views.TaskNeededUpdate.as_view(), name='update_task'), -
App rendering blank template in multi app django project
I have a simple CRUD app that renders all its templates when i test it as the only app in a project. It shows me a blank template however, for the same templates, when i add it to a project with a login/ out app (so that there are two apps all together) I am sure its something i am overlooking but i cant work it out. help! All works with the templates in a template folder and is the default app in a project. I use a standard settings.py and the templates section is below. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates',], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] The Url is also straight forward as below from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^conform/', include('conform.urls')), ] The templates are located in the apps/templates folder Consequently, i am able to call the pages thus /conform/conform/view_name/ and it works fine. However, if i create a new project and add a login/logout app as well as the conform app. In the login app, i present the authenticated user with a nav bar with menu links to … -
When is the correct time to use a choice field over another model?
First, I'm not super experienced at all. If I have a model, for say a single instance of a business, what would be the correct method to build a "profile" around it? I would want to limit some of the choices to specific things. I was thinking of setting it similar to below. (this isn't the code I just through it together.) class Dimensions(models.Model): weight = models.IntegerField() length = models.IntergerField() height = models.IntegerField() class Business(models.Model): Name = models.Charfield(max_length=100) # Dimensions would be a predetermined list of ~20 choices that will grow dimensions = models.ForeignKey(Dimensions, on_delete=models.CASCADE) # About 7 other foreign key fields would also be added onto this model It would be a total of about 8 models set up similar to the Dimensions model. This seems like it is not ideal for an efficient database set up. Am I wrong? Should I just be using a choices field instead? -
InvalidSchema(“No connection adapters were found for '%s'” % url)
I'm trying to run my scraper, but there is a problem with urls. They are looking like this: //ocdn.eu/pul... Error message: raise InvalidSchema("No connection adapters were found for '%s'" % url) requests.exceptions.InvalidSchema: No connection adapters were found for '/http:///http://... Error raise at r = session.get line. Thanks for help! for post in posts: title = post.find('span', {'class': 'title'}).get_text() link = post.find("a")['href'] image_source = post.find('img')['src'] image_source_solved = "http://".join(image_source) # stackoverflow solution media_root = '/Users/mat/Desktop/jspython/just django/dashboard/media_root' if not image_source.startswith(("data:image", "javascript")): local_filename = image_source.split('/')[-1].split("?")[0] r = session.get(image_source_solved, stream=True, verify=False) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): f.write(chunk) current_image_absolute_path = os.path.abspath(local_filename) shutil.move(current_image_absolute_path, media_root) -
Django function based view with url parameter to class based ListView
I'm trying to transform my function based view to ListView. From what I've read, I need to use self.kwargs, also I'm using the simple example from Django docs here (the Dynamic filtering section). This is my function view (I'm using type for the header on the page): def product_list(request, product_type): type = 'type1' if product_type=='a1' else 'type2' if product_type == 'a2' else \ 'type3' if product_type == 'a3' else 'type4' if product_type == 'a4' else 'type5' \ if product_type == 'a5' else 'type6' if product_type == 'a6' else 'type7' if \ product_type == 'a7' else '' context = { 'products': Product.objects.all().filter(type=product_type).order_by('name'), 'types': type } return render(request, 'main/productList.html', context) Here's my model: class Product(models.Model): name = models.CharField(max_length=50, default="Name") description = models.TextField(blank=True, null=True) producer = models.CharField(max_length=100, blank=True, null=True) type = models.CharField(max_length=50, default="") price = models.CharField(max_length=10, blank=True, null=True) And url pattern for this view: path('<str:product_type>/', views.product_list, name='product-list') And a link in a template: <a href="{% url 'product-list' 'a1' %}">A1 products</a></li> Now, as mentioned above, I'm trying to use the example from Django docs, so I wrote this: class ProductsListView(ListView): model = Product template_name = 'main/productsList.html' context_object_name = 'products' def get_queryset(self): self.type = get_object_or_404(Product, type = self.kwargs['type']) typeHeader = 'type1' if product_type=='a1' else 'type2' … -
Django cache.clear() not working (LocMemCache, AWS)
Background I have a website running Django 2.0 on AWS ElasticBeanstalk. I have a couple views on my website that take some time to calculate, so I thought I'd look into some simple caching. I decided on LocMemCache because it looked like the quickest to set up that would meet my needs. (I'm using AWS, so using Memcached apparently requires ElastiCache, which adds cost and is additional setup overhead that I wanted to avoid.) The views do not change often, and the site is not high-traffic, so I put long timeouts on the caches. There are three views where I have enabled caching: A report generated inside a template – uses Template Fragment caching A list of locations requested by AJAX and used in a JS library – uses per-view caching A dynamically-generated binary file download – uses per-view caching The caching is set up and works great. The data that goes into these views is added and edited by other staff at my company, that are used to their changes appearing immediately. So in order to address questions such as, "I updated this data, why has the webpage not updated?" I wanted to create a "Clear Server Cache" button, … -
How to display just for example 100 words of an post in python?
I have made something like this. If the reader clicks on "Weiterlesen" then it should display the whole tekst. But first i want to display an range of words (for example 100) Can i set range[:100] into {{ post.text|linebreaksbr }} ?? Thanks for your answers {% block content %} {% for post in posts %} <div class="post"> <div class="date"> {{ post.published_date }} </div> <h1>{{ post.title }}</h1> <p>{{ post.text|linebreaksbr }}</p> <a href="{% url 'post_detail' pk=post.pk %}" class="btn btn-default">Weiterlesen</a> </div> {% endfor %} {% endblock %} -
I want to insert the data into database using python
! I Want to insert the html table data into database using python. And am completely new to python also i attached the image follow and suggest some code to me and also i tried but i couldnt find the solution please help me to solve this problem! -
How to have a Form from another Model inside a DetailView in Django?
I'm working with Django and what I want to do is to have a DetailView of Posts, and inside that detail view I want a comments section with a form for posts comments. When I load the detail view it doesn't show me the form of Comments I'm using Class Based Views for the Detail of the form. My models.py looks like this: class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length = 200) text = models.TextField() created_date = models.DateTimeField(default = timezone.now) likes = models.IntegerField(default=0) tags = models.CharField(max_length = 50, default = '' ) def get_absolute_url(self): return reverse('blog:post_list') def __str__(self): return self.title class Comments(models.Model): post = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.CASCADE) text = models.TextField() created_date = models.DateTimeField(default = timezone.now) The views.py looks like this: class PostDetailView(DetailView): form_class = CommentsForm model = Post The form looks like this: class CommentsForm(forms.ModelForm): class Meta: model = Comments fields = ('text',) widgets = { 'text' : forms.Textarea(attrs={'class':'comment-textarea'}) } And the comments_form.html looks like this: <div class="container"> <div class="row"> <div class="col"> <h1>Estoy siendo insertado</h1> <form action="" method="POST"> {%csrf_token%} {{ form.as_p }} <input type="submit" class="btn mt-2 btn-comments" value="Comment"> </form> </div> </div> </div> -
How to fix 'ctypes.ArgumentError: argument 1: <class 'TypeError'>: expected LP_c_ulong instance instead of LP_SECURITY_ATTRIBUTES'
I'm trying to open Ipython shell by running the command python manage.py shell for django project but I'm not getting the expected output. Instead, I'm getting some weird output. Please help me solve this problem. I tried running twice but the same thing is happening again and again. D:\Django\airlines>python manage.py shell 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 "c:\users\khyati\django\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "c:\users\khyati\django\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\khyati\django\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\khyati\django\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "c:\users\khyati\django\django\core\management\commands\shell.py", line 99, in handle return getattr(self, shell)(options) File "c:\users\khyati\django\django\core\management\commands\shell.py", line 36, in ipython start_ipython(argv=[]) File "C:\Users\khyati\Anaconda3\lib\site-packages\IPython\__init__.py", line 125, in start_ipython return launch_new_instance(argv=argv, **kwargs) File "C:\Users\khyati\Anaconda3\lib\site-packages\traitlets\config\application.py", line 657, in launch_instance app.initialize(argv) File "<decorator-gen-113>", line 2, in initialize File "C:\Users\khyati\Anaconda3\lib\site-packages\traitlets\config\application.py", line 87, in catch_config_error return method(app, *args, **kwargs) File "C:\Users\khyati\Anaconda3\lib\site-packages\IPython\terminal\ipapp.py", line 317, in initialize self.init_shell() File "C:\Users\khyati\Anaconda3\lib\site-packages\IPython\terminal\ipapp.py", line 333, in init_shell ipython_dir=self.ipython_dir, user_ns=self.user_ns) File "C:\Users\khyati\Anaconda3\lib\site-packages\traitlets\config\configurable.py", line 412, in instance inst = cls(*args, **kwargs) File "C:\Users\khyati\Anaconda3\lib\site-packages\IPython\terminal\interactiveshell.py", line 431, in __init__ self.init_prompt_toolkit_cli() File "C:\Users\khyati\Anaconda3\lib\site-packages\IPython\terminal\interactiveshell.py", line 281, in init_prompt_toolkit_cli self._eventloop = create_eventloop(self.inputhook) File "C:\Users\khyati\Anaconda3\lib\site-packages\prompt_toolkit\shortcuts.py", line 95, in create_eventloop return Loop(inputhook=inputhook, recognize_paste=recognize_win32_paste) … -
Is there an easy way to optimize this query?
I have two models: class Bar(models.Model): tick = CharField(max_length=10) @property def foos(self): foos = [] for pk in [x['associated_thing__pk'] for x in self._foos.all().values('associated_thing__pk').distinct()]: foos.append( {pk: self._foos.filter(associated_thing__pk=pk)} ) return foos class Foo(models.Model): associated_bar = models.ForeignKey(Bar, on_delete=models.SET_NULL, related_name=_foos) associated_thing = models.ForeignKey(Thing, on_delete=models.CASCADE) name = CharField(max_length=10) So what I'm doing here is returning a list of dictionaries. Each dictionary has one key, which is the pk of all Things that some group of Foos are associated to. The value is a queryset of these Foos. (That is, multiple Foos can be associated to a single Thing, and multiple Foos are associated to a single Bar. bar.foos returns all associated Foos, but split up according to the Thing pks they've in common). When I bar.foos, the query takes about 2 seconds. This seems somewhat long, and is leading me to believe that there's some terrible, optimizable thing going on. Is there something I'm doing terribly wrong? -
How to add a Python module to a docker container?
I created a Boilerplate project from the Divio Django project template: (Python 3.6, Django CMS, HTML 5) Checking out the repository returns a couple of files, among which are a docker-compose and a dockerfile. Docker-compose: version: "2" services: web: build: "." links: - "db:postgres" ports: - "8000:80" volumes: - ".:/app:rw" - "./data:/data:rw" command: python manage.py runserver 0.0.0.0:80 env_file: .env-local db: image: postgres:9.6-alpine environment: POSTGRES_DB: "db" volumes: - ".:/app:rw" So locally I try to run docker-compose run web to startup a local Django CMS instance. However, I run into the following error: Starting ale_db_1 ... done /app/addons/aldryn-django/aldryn_config.py:137: RuntimeWarning: no cache configured. Falling back to CACHE_URL=locmem:// RuntimeWarning, /app/addons/aldryn-django/aldryn_config.py:137: RuntimeWarning: no cache configured. Falling back to CACHE_URL=locmem:// RuntimeWarning, Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f42a18c4950> Traceback (most recent call last): File "/virtualenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/virtualenv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/virtualenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/virtualenv/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/virtualenv/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/virtualenv/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/virtualenv/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/virtualenv/lib/python3.6/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/virtualenv/lib/python3.6/importlib/__init__.py", line 126, in import_module return …