Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get matplotlib image from python called from Javascript
I have a Django web app which will be a dashboard to track the location of ISS using data from (http://api.open-notify.org/iss-now.json). I am having trouble looping the javascript to get the new image and update the src in the tag every 5 seconds. you can see the javascript is using setInterval to loop every 5 seconds. can someone help how i can call python function plot to get the uri to pass to the src in place of the dummy function urls.py from django.urls import path from . import views app_name = "appdjando" urlpatterns = [ path("", views.index, name="index"), path("plot", views.plot, name="plot") ] views.py where the returned uri variable is basically a base64 encoded buffer image saved from matplotlib PNG file. calling the plot function again or (a=TrackerISS(), def plot(request): home_name = 'Modena' a = TrackerISS() b = BasemapPlot(home_name, home_lat, home_lon) uri = b.plot_location(a.get_speed_iss_pos()) return render(request, "helloiss/plot.html", {'data':uri}) plot.html {% extends "helloiss/layout.html" %} {% block body %} <script type="text/javascript"> setInterval(function(){ document.getElementById("getMapImage").src = dummyFunction(); }, 5000); </script> <section id="two"> <div class="inner"> <h1 align="center">ISS location</h1> <p><br>Python chart here</p> <img id="getMapImage" src="data:image/png;base64,{{ data }}" alt="" height="400", width="700"> </div> </section> {% endblock %} -
Configure two virtual hosts with django and apache
Im trying to modify my existing stack to allow users to access two different versions of django app on one host. Due to internal DNS issues i can only work with domain corpnet.com/abc/ I tried to add two virtual hosts in abc.conf <VirtualHost *:443> WSGIScriptAlias /abc/prod /var/www/abc/abc-django/abc/wsgi.py ServerName corpnet.com/abc/prod DocumentRoot /var/www/abc/abc-django/abc ... </VirtualHost> <VirtualHost *:443> WSGIScriptAlias /abc/test /var/www/abc/abc-django-test/abc/wsgi.py ServerName corpnet.com/abc/test DocumentRoot /var/www/abc/abc-django-test/abc ... </VirtualHost> Apache seems to understand this configuration as apache2ctl -S returns: *:443 is a NameVirtualHost default server corpnet.com/abc/prod (/etc/apache2/sites-enabled/abc.conf:7) port 443 namevhost corpnet.com/abc/prod (/etc/apache2/sites-enabled/abc.conf:7) port 443 namevhost corpnet.com/abc/test (/etc/apache2/sites-enabled/abc.conf:43) ServerRoot: "/etc/apache2" Main DocumentRoot: "/var/www/html" Main ErrorLog: "/var/log/apache2/error.log" Mutex watchdog-callback: using_defaults Mutex rewrite-map: using_defaults Mutex ssl-stapling-refresh: using_defaults Mutex ssl-stapling: using_defaults Mutex ssl-cache: using_defaults Mutex default: dir="/var/run/apache2/" mechanism=default PidFile: "/var/run/apache2/apache2.pid" Define: DUMP_VHOSTS Define: DUMP_RUN_CFG User: name="www-data" id=33 Group: name="www-data" id=33 Yet /abc/prod path works, while /abc/test returns 404 What am i missing? -
Does the UserCreationForm in Django automatically update itself to fit the custom user model or do you have to create a custom forms.py form
So my project has a complicated User-base setup which I'm hoping will work well using Django's custom user model but I'm curious whether or not I can use Django's built in UserCreationForm to render the custom fields in my custom user model or if I need to create a form in forms.py to render the new fields out myself. -
Check for unique constraint inside the save method
I have a model on which the unique_together parameter is not working. The reason is that most of the times the "client_repr" variable is set on the save() method. If someone creates a task with the same ('client_repr', 'task_type'... ) combination the model won't detect it because the "client_repr" value is null until the end of the save() method. How can i call for a unique constraint verification inside the save() method? class Task(models.Model): client = models.ForeignKey(Client, related_name = 'tasks', on_delete = models.CASCADE) b_client = models.ForeignKey(BClient, related_name = 'tasks', on_delete = models.CASCADE, null = True, blank = True) client_repr = models.CharField(max_length = 100, null = True, blank = True) task_type = models.CharField(max_length = 100) task_description = models.CharField(max_length = 100) department = models.ForeignKey(Department, related_name = 'tasks', on_delete = models.CASCADE) extra_fields = models.ManyToManyField(ExtraField, blank = True) spot = models.BooleanField(default = False) class Meta: unique_together = (('client_repr', 'task_type', 'task_description', 'department'), ) def __str__(self): return ' | '.join([f'{self.client_repr}', f'{self.task_description}', f'{self.task_type}']) def save(self, *args, **kwargs): if not self.b_client: self.client_repr = str(self.client) else: self.client_repr = str(self.b_client) super().save(*args, **kwargs) I know i could just make a search (ex: if Task.objects.get(...): ) but is it the most django-pythonic way? -
how to loop through a list of strings and print in Tabula form
am practicing python I have this issue here, I have a list of three teams,teams = ['manu','spurs','roma'] just looping through the index 0 i was able to print the outcome teams = ['manu','spurs','roma'] for m in teams[0]: print(m,'\t') ` but can I print all the teams in a tabula form like help out -
How to configure Editor js in Django?
I am currently making a blogging site in python and django and for blog editing a saw many text editing plugins for django like ckeditor but the one. I liked is Editor.js Can anyone tell me how to can I put the editor.js in Django the safest method possible? -
How to write manager class which use filter field as computed field not as a part of model fields?
have a model Student with manager StudentManager as given below. As property gives the last date by adding college_duration in join_date. But when I execute this property computation is working well, but for StudentManager it gives an error. How to write manager class which on the fly computes some field using model fields and which is used to filter records. The computed field is not in model fields. still, I want that as filter criteria. class StudentManager(models.Manager): def passed_students(self): return self.filter(college_end_date__lt=timezone.now()) class Student(models.Model): join_date = models.DateTimeField(auto_now_add=True) college_duration = models.IntegerField(default=4) objects = StudentManager() @property def college_end_date(self): last_date = self.join_date + timezone.timedelta(days=self.college_duration) return last_date Error Django gives. django.core.exceptions.FieldError: Cannot resolve keyword 'college_end_date' into field. Choices are: join_date, college_duration -
ImageField > height and width field type as PositiveIntegerField?
I am currently creating an ImageField and wonder what's the right type for image_height & image_width. I chose models.PositiveIntegerField(). Is that a good choice? I couldn't find any recommendations online yet. image = models.ImageField( verbose_name=_("Image"), height_field="image_height", width_field="image_width" ) image_height = models.PositiveIntegerField() image_width = models.PositiveIntegerField() -
Openedx mobile rest
Can anyone help with How can I set up open edx ios app I have followed the offical documentaion but I get only edx.org app what files should I change -
How download image from URL to django?
enter image description here I want to load an image by URL, but only the URL itself is saved to the model, how can I specify the path to save to the media folder, and how do I save it at all? -
django channles base64 encoded pdf too large, how to handle
async def receive(self, text_data): pdf_base64 = text_data['message'] ... I encoded pdf to base64 and uploaded to server, but the file is too large, how to read the text_data as a stream and I could decode the data using iterator in server side, thanks! -
Can BaseRenderers be cached?
I am returning huge CSV and PDF files with DRF (https://www.django-rest-framework.org/api-guide/renderers/). Is it possible to cache the responses? I have already @method_decorator(cache_page(60 * 60 * 24)) on dispatch method of the viewset, but it does not cache renderers. What can I do? -
Why does Django recreate the DB tables on each docker-container restart?
I am running Django with PostgreSQL in a docker-compose setup for development. Each time I restart the application container, the database is empty, even though I do neither restart the DBMS container nor do I drop the DBMS's data volume. It seems that Django is dropping all tables upon restart. Why? My setup closely follows the description here. That is, my compose file looks as follows (simplified): version: '3.8' services: db: image: postgres environment: - POSTGRES_DB=db_dev - POSTGRES_USER=dev - POSTGRES_PASSWORD=postgres volumes: - type: volume source: app-data target: /var/lib/postgresql/data app: build: . command: python manage.py runserver 0.0.0.0:8888 container_name: app environment: - DATABASE_URL - PYTHONDONTWRITEBYTECODE=1 - PYTHONUNBUFFERED=1 volumes: # Mount the local source code folder for quick iterations. # See: https://www.docker.com/blog/containerized-python-development-part-3/ - type: bind source: . target: /code ports: - target: 8888 published: 8888 depends_on: - db env_file: - ./dev.env volumes: app-data: external: true The Django application is started by means of an entrypoint.sh: #! /bin/sh if [ "$DATABASE" = "postgresql" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi doMigrate=${DB_MIGRATE:-false} if [ "$doMigrate" = true ] ; then python manage.py flush --no-input python manage.py migrate fi exec "$@" In the … -
Is there a way to make a django template variable variable into a for loop
I have this in my model: tank0 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank0') tank0MQTT = models.BooleanField(default = False) tank1 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank1') tank1MQTT = models.BooleanField(default = False) tank2 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank2') tank2MQTT = models.BooleanField(default = False) tank3 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank3') tank3MQTT = models.BooleanField(default = False) tank4 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank4') tank4MQTT = models.BooleanField(default = False) tank5 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank5') tank5MQTT = models.BooleanField(default = False) tank6 = models.ForeignKey(nb200V1, on_delete=models.SET_NULL, null=True, blank=True, related_name='pmp300Tank6') tank6MQTT = models.BooleanField(default = False) I would like in my template to make a for loop to generate the html and set the variable with the i in the for loop like this: {% for i in "0123456" %} <div class="row" style="margin-top:10px"> <div class="col-sm-12"> <div class="card"> <div class="card-header"> Tank # {{forloop.counter}} </div> <div class="card-body"> <div class="row"> <div class="col-lg-2 col-md-3 col-sm-4 align-self-center"> <label><b>Serial:</b></label> <a href="#" id="{{obj.serial}}_tank{{i}}">{{obj.tank{{i}}.serial}}</a> <small id="{{obj.tank{{i}}.serial}}_serial_ts" class="form-text text-muted">{{obj.tank{{i}}.timeStamp}}</small> </div> </div> </div> </div> </div> </div> {% endfor %} Is there anyway way to do this ? -
How To Create Dynamic Routes in Django Rest Framework Based off a Model Column?
I am trying to create dynamic routes for django rest framework that filters based off a model's specific column value. There are different chefs who all have a specialty. I am trying to make it so I can go to localhost:8000/chef/< specialty >/ and it will only have chefs with that specialty listed. I've tried searching but I can't find any answers or even questions related to this. I've tried following the tutorial here on rest framework's website as well. I keep getting 404 errors or AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute. models.py: class Chef(models.model) name = models.CharField(max_length=200) specialty = models.CharField(max_length=200) urls.py router = routers.DefaultRouter() router.register('chef/(?<specialty>.+)/$', views.ChiefModelViewSet()) url_patterns = [ path('', include(router.urls)), ] views.py class ChefModelViewSet(viewsets.ReadOnlyModelView): # it is ReadOnly because I only want it to be read only serializer_class = ChefModelSerializer def get_queryset(self): specialty = self.kwargs['specialty'] return Chef.objects.filter(specialty=specialty) -
Django Model.objects.get(...) case-insensitivity
I am developing a dictionary application and I have an Expression model defined as follows: class Expression(models.Model): expression = models.CharField(max_length=64, unique=True) In one of my views, I am using Expression.objects.get_or_create(expression=expression) to either get an Expression with expression "expression" or create it if it does not exist. Importantly, I want the comparison between "expression" and all existing Expression objects in my database to be case-insensitive. In other words, even though this is not valid syntax, I would like the logic of my search to be: Expression.objects.get_or_create(expression.lower()=expression.lower()) How can I achieve that? -
Django-rest-auth and allauth registration
I am self-learning Django auth and had a question about the django-rest-auth package. In the demo app of this package, both the endpoints /account/signup/ and /rest-auth/registration/ provide the same functionality (allow new users to sign up). Is there a way to only enable /rest-auth/registration/ and disable signing up via the /account/signup endpoint. I cannot completely get rid of the /account/ related urls because /rest-auth/registration/ uses the /account/confirm-email/Mw:1kQVfP:MxaGSypA88IVpvtwhFGHalSMUoO1Px4fJ5tBGpJVppk/ for email verification when I set the email verification related variables in the settings file. ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_REQUIRED = True -
TypeError: '<=' not supported between instances of 'decimal.Decimal' and 'dict'
I'm not sure how to resolve this issue. I tried to convert highest_bid to a float: highest_bid = float(Bid.objects.filter(id=bid_item.id).aggregate(Max('bid_input'))) but that also produced an error because a dict cannot be converted to a float in that way. So I'm not sure how to resolve this. I'm trying to build an auctions site and I would like the bid that a user places to be rejected if it is less than the listing start price and less than the highest of all the bids that have been placed. error Internal Server Error: /listing/2/bid Traceback (most recent call last): File "C:\Python\Python385\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python\Python385\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sarah\Desktop\commerce\auctions\views.py", line 157, in placebid if bidform.cleaned_data['bid_input'] < listing.start_price and bidform.cleaned_data['bid_input'] <= highest_bid: TypeError: '<=' not supported between instances of 'decimal.Decimal' and 'dict' [08/Oct/2020 13:59:48] "POST /listing/2/bid HTTP/1.1" 500 62598 views.py def placebid(request, id): listing_bid = get_object_or_404(Listing, id=id) highest_bid = Bid.objects.filter(id=id).aggregate(Max('bid_input')) listing = Listing.objects.get(pk=id) if request.method == "POST": bidform = BidForm(request.POST) if bidform.is_valid(): if bidform.cleaned_data['bid_input'] < listing.start_price and bidform.cleaned_data['bid_input'] <= highest_bid: return render(request, "auctions/listingPage.html", { "listing": listing, "error": "Make sure your bid is greater than the start price and current highest bid" … -
Django+Bootstrap4 raise Error: "mysqlclient 1.4.0 or newer is required; you have 0.10.0."
I Use Django 3.1.2 with MySQL, and it worked normal with database. But affter i've installed Botstrap 4 (pip install bootstrap4) and load it in my Tamplate {% load bootstrap4 %} i get Error: django.core.exceptions.ImproperlyConfigured: mysqlclient 1.4.0 or newer is required; you have 0.10.0. raised by bootstrap as you can see bellow. But in my venv i have installed module mysqlclient version 2.0.1 (not 0.10.0). (As PyCharm show me.) I don`t understend it. And how css/js library like bootstrap even apply to Database engine? How to solve it? "C:\Program Files\JetBrains\PyCharm 2019.3.3\bin\runnerw64.exe" C:\MyProject\venv\Scripts\python.exe C:/MyProgect/MySite/manage.py runserver 8000 Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\User\Anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\User\Anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\User\ITResearch\all_gid_2\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\User\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line … -
ERROR: Failed building wheel for cryptography
Hey guys I was installing "channels" "pip install channels" but I received this Error. Failed building wheel for cryptography Running setup.py clean for cryptography Failed to build cryptography Could not build wheels for cryptography which use PEP 517 and cannot be installed directly What should I do now? -
how to update with a foreign key field that also has a foreign key field
I have three sample models below: Class User(Model): ...some other fields receiving_info = OnetoOneField('ReceivingInfo') Class ReceivingInfo(Model): ...other fields receiving_address = OnetoOneField('Address') Class Address(Model): street = CharField(max_length=100) house_number = CharField(max_length=100) city = CharField(max_length=200) I am trying to update them below using this: address = Address( street='new st', house_number='new number', city='new city' ) user = User.objects.get(id=id) user.receiving_info.receiving_address = address user.save() but somehow it doesn't work, any ideas how to make it work? -
How to retrieve user id from token?
There is a Plan model that has a user field and I want to fill the user field with user's token so that user can not send user id to create the model for another user and just send post request for themself, here is my model: class Plan(models.Model): """Plan object""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) and my view is: class PlanViewSets(viewsets.ModelViewSet): """A viewset for non-admin user see list and admin can curd plan model""" model = Plan queryset = Plan.objects.all().order_by('-id') serializer_class = serializers.PlanSerializer permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) def get_queryset(self): """retrieve plan just for its own user who is authenticated already""" return self.queryset.filter(user=self.request.user) How to create Plan just for user without getting user field by request body? -
django-haystack not removing stale record when used with django-safedelete
I use django-haystack 2.5 with Django 1.11 and elasticsearch 2.3. I have some indexed models that use django-safedelete. This means that rather than deleting the object, I mark them as deleted with a flag on the object. In my haystack search index, I have specified the queryset to exclude the "deleted" items, of course. However, if I update_index --remove, the stale records are not deleted, so they are returned in search results as they were indexed before they got deleted. Any suggestions on how to solve this issue? Thanks! -
how to get the slug from object name in django
hey i want to get the slug from my product name automaticlly forexamle if my product name is (product number one) i want the slug be(product_number_one) how can i do thaat? here is my code : models.py class Product (models.Model): name = models.CharField(max_length=100) price = models.FloatField(default=0) description = models.TextField(null=True, blank=True) color = models.ForeignKey(Color , on_delete=models.DO_NOTHING) material = models.ForeignKey(Material, on_delete=models.DO_NOTHING) image = models.ManyToManyField(Image) category = models.ForeignKey(Category,on_delete=models.DO_NOTHING , default=0) slug=models.SlugField(max_length=300 , allow_unicode=True , blank=True , null=True , unique=True,) view = models.IntegerField(default=0) def __str__(self): return self.name -
How to write JS that will count date and change table color?
i need a JavaScript that counts date between an input and another input. If result is smaller then 24 hours, table row needs to be colorized as red. I'll give some codes below; class Campaigns(models.Model): start_date = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Starting Date") end_date = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Ending Date") broadcast = models.CharField(choices=BROADCAST_STATUS, blank=False, verbose_name="Broadcast Situtation", max_length=10) This is my table rows : {% for campaign in campaigns %} <tr> <td class="text-center">{{ campaign.agency }}</td> <td class="text-center">{{ campaign.brand }}</td> <td class="text-center">{{ campaign.channel }}</td> <td class="text-center">{{ campaign.target_group }}</td> <td class="text-center">{{ campaign.start_date }}</td> <td class="text-center">{{ campaign.end_date }}</td> <td class="text-center">{{ campaign.date_to_take_place }}</td> <td class="text-center">{{ campaign.day_part }}</td> <td class="text-center">{{ campaign.impression }}</td> <td class="text-center">{{ campaign.broadcast }}</td> </tr> {% endfor %} So what i need as mathematic is : campaign.start_date - campaign.end_date = result , if result < 24 hours , table row color becomes red. Thanks for any tip/solution!