Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
annotate Model Country field with country name
I want to filter a class (Region) and annotate it with Country name. class SearchInput(TextInput): input_type = "search" class RegionUniversalFilter(django_filters.FilterSet): query = django_filters.CharFilter( method="universal_search", label="", widget=SearchInput(attrs={"placeholder": "Search..."}), ) class Meta: model = Region fields = ['name','country'] def universal_search(self, queryset, name, value): AllRegionCountry = AllRegion.annotate(countryname=Value(dict(countries)[F('country')], output_field=CharField())) return AllRegionCountry.filter( Q(name__icontains=value) | Q(country__icontains=value) | Q(countryname__icontains=value) ) And i have an error : KeyError at /regions F(country) On the other hand : AllRegionCountry = AllRegion.annotate(countryname=Value(dict(countries)\["NZ"\], output_field=CharField())) WORK So, how to evaluate F('country') ? Regards -
Testing a split API route in django rest framework using pytest
I'm trying to create a split of routes, creating two APIs. My idea is that my application works in two modes: normal, custom. Here is an example of my directory structure: - config - urls.py - api - custom - v1 - urls.py - normal - v1 - urls.py For the modes, I'm using environment variables. In my main urls.py I put it like this: [...] router = DefaultRouter() NORMAL = "normal" CUSTOM = "custom" if config.settings.MODE == NORMAL: urlpatterns = [ path("normal/v1/", include("api.normal.v1.urls")), ] elif config.settings == CUSTOM: urlpatterns = [ path("custom/v1/", include("api.custom.v1.urls")), ] My urls.py (normal): [...] router = DefaultRouter() urlpatterns = [ re_path(r"^", include(router.urls)), path("normal-example/", normal.normal-example, name="normal-example/"), ] And my urls.py (custom): [...] router = DefaultRouter() urlpatterns = [ re_path(r"^", include(router.urls)), path("custom-example/", custom.custom-example, name="custom-example/"), ] Ok. When I run and change, by env, works. Both in normal and custom. My problem is how to test this with pytest. I tried like this: @pytest.fixture(autouse=True) def mode_custom(settings): settings.MODE = "custom" def test_custom-example(mode_custom, client): resp = client.get("/custom/v1/custom-example/") assert resp.status_code == 200 Or using override_settings decorator. But the result is the same: It always takes the normal route. It only works in the custom route if I change it in the … -
how can i trigger django channels consumer as background task
I have a consumer that written using django channels so i can get info from binance websockets, how i can parallel that and write data to database in background. So i need to get data from BinanceTradeMonitor on each instance that create user and pass it to consumer, so he can write data to BinanceNotification model. But cant undestend ho to this. import json import asyncio import uuid from datetime import datetime import websockets import numpy as np from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from apps.binance.services.connection import BinanceWebSocket class BinanceConsumer(AsyncWebsocketConsumer): close_prices = {} # Dictionary to store close prices async def disconnect(self, close_code): # Clean up when a WebSocket connection is closed pass async def subscribe_to_binance_websockets(self, id, symbol, interval, length, barlimit): try: candle_count = 0 websocket_url = f"wss://stream.binance.com:9443/ws/{symbol}@kline_{interval}" subscription_payload = { "method": "SUBSCRIBE", "params": [f"{symbol}@kline_{interval}"], "id": 1, } async with websockets.connect(websocket_url) as websocket: await websocket.send(json.dumps(subscription_payload)) while True: data = await websocket.recv() data_dict = json.loads(data) # Process received data as needed print(f"Received data from {symbol}@kline_{interval}: {data}") try: close_price = float(data_dict["k"]["c"]) except KeyError: print( f"Close price data ('k' or 'c') not found in the received JSON data for {symbol}@kline_{interval}." ) candle_count += 1 if candle_count >= barlimit: ma_value = await … -
Django Jinja include static file with path in variable
I need to do something like this: {% load static %} {% include {% static path %} %} I have a lot of files, and I give this path variable in context, and it also contains in static directory, so I cant just do {% include path %} Also I found that I cant just put function inside another function: {% %} inside {% %} I looked at the Jinja's documention to find how to deal with this inside functions, but that didnt help me. -
How to use pipeline method in django mainApp
I create an django project name is registration in this project I build an app name is mainApp so in this project I have to create sign in with google functionallity so this I have done it now I want this sign with google email-id is stored in my created custom model table So how can I do this I try it for the pipeline method but when I click on login with google it takes only reload not signin within the home page -
Django container with Celery and Redis
Django DiagramI was had 3 questions based on the diagram. Is this a realistic feasible approach. (learning/work project for growing users/data) Can the same Redis server act as the celery broker and API buffer Should I start building all the components first, or should i start piece by piece (meaning django and db first, then add the other components) I have a base Django project, but needs will start to grow for the data. -
where to find the filles in container registtry on Azure?
I have deployed a django docker container to the azure platform. And I created a container registry: crdierenwelzijn So I pushed two images to the container registry: docker push crdierenwelzijn.azurecr.io/dwl_backend_rachid-proxy:latest push crdierenwelzijn.azurecr.io/dwl_backend_rachid-web:latest And I also created a wepp app recource. And when I hit the url: https://dockerdierenwelzijn.azurewebsites.net/admin/login/?next=/admin/ I see the app. But I cannot login. If I enter the credentials. I get this error: Help Reason given for failure: Origin checking failed - https://dockerdierenwelzijn.azurewebsites.net does not match any trusted origins But I have declared that in settings.py file: SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = bool(int(os.environ.get('DEBUG',0))) ALLOWED_HOSTS = ['dockerdierenwelzijn.azurewebsites.net'] ALLOWED_HOSTS.extend( filter( None, os.environ.get('ALLOWED_HOSTS', '').split(" "), ) ) CSRF_TRUSTED_ORIGINS = ["https://dockerdierenwelzijn.azurewebsites.net"] And my docker-compose-deploy file looks like: version: "3.9" services: web: image: crdierenwelzijn.azurecr.io/dwl_backend_rachid-web build: context: ./ dockerfile: Dockerfile.prod restart: always command: gunicorn DierenWelzijn.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/media expose: - 8000 env_file: - ./.env.prod proxy: image: crdierenwelzijn.azurecr.io/dwl_backend_rachid-proxy build: context: ./proxy restart: always depends_on: - web ports: - 80:80 volumes: - static_volume:/home/app/staticfiles - media_volume:/home/app/media volumes: static_volume: media_volume: So I think maby it is an old version of that file that is stored in the container registry. But I am not sure. Question: how to find the files in the container registry on … -
ModuleNotFoundError: No module named '\\mysite\\settings'
I have read the previous questions and answers here, and tried the suggested solutions, however still getting ModuleNotFoundError: No module named '...\mysite\settings' The project is DosV3Master with a folder under it and the typical files under mysite, asgi.py, settings.py, wsgi.py and so forth. the venv folder is under the DosV3Master as is manage.py When I run "python manage.py check" I get... (venv) PS C:\Users\viter\DoseV3Master> python manage.py check Traceback (most recent call last): File "C:\Users\viter\DoseV3Master\venv\lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\viter\DoseV3Master\venv\lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) File "C:\Users\viter\DoseV3Master\venv\lib\site-packages\django\core\management\commands\check.py", line 76, in handle self.check( File "C:\Users\viter\DoseV3Master\venv\lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( File "C:\Users\viter\DoseV3Master\venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\viter\DoseV3Master\venv\lib\site-packages\django\core\checks\templates.py", line 39, in check_string_if_invalid_is_string for conf in settings.TEMPLATES: File "C:\Users\viter\DoseV3Master\venv\lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "C:\Users\viter\DoseV3Master\venv\lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "C:\Users\viter\DoseV3Master\venv\lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Program Files\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", … -
Update value from a django view
I'm looking to update a value in my template whenever a change is made in a form. Here's the relevant template code snippet: <div> <p style="text-align: right;">Object count: {{ object_count }}</p> </div> <form action="{% url 'list_objects' %}" method="post"> <div id="target" class="fieldWrapper"> {{ form.target.errors }} {{ form.target.label_tag }} {{ form.target }} </div> </form> I'm handling the change event using JavaScript, and when the "target" value changes, I'm sending the new value to the view. This is the view code: class MyView(LoginRequiredMixin, FormView): template_name = "my_template.html" form_class = MyForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) object_count = MyModel.objects.all().count() context['object_count'] = object_count return context def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) target_id = request.POST.get("target_id", None) target_obj = TargetModel.objects.filter(target_id=target_id).first() if target_id else None if target_obj: object_count = MyModel.objects.filter(club=target_obj).count() context["object_count"] = object_count return render(request, self.template_name, context) However, despite handling the target change, the counter for MyModel does not update as expected. Could you please advise on what I might need to fix to achieve the desired behavior? -
An inline formset of a model returns an error saying that the fields are required, even though they're filled
As mentioned, I'm trying to make a form on a model called SellerCardDetail. The model has a foreign key to another model (SellerAccount), which in turn, has another foreign key to the base user model. The model in question: class SellerCardDetail(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) card_name = models.TextField(default="CARDNAME") card_quality = models.CharField(max_length=16) card_price = models.DecimalField(max_digits=19, decimal_places=2) card_image = models.URLField(blank=True, null=True) card_url = models.URLField(blank=True, null=True) card_notes = models.TextField(blank=True, null=True) card_stock = models.IntegerField(default=1, blank=False) date_added = models.DateTimeField(auto_now_add=True) seller_details = models.ForeignKey(SellerAccount, on_delete=models.CASCADE) def __str__(self): return self.seller_details.user.username The form: class SellerCardBase(forms.BaseInlineFormSet): def clean(self): if not self.has_changed(): raise forms.ValidationError('I have no idea what went wrong, but I know this error is here') SellerCardFormSet = inlineformset_factory(SellerAccount, SellerCardDetail, fields=('card_name', 'card_quality', 'card_price', 'card_notes', 'card_stock'), formset=SellerCardBase) The view: @login_required(login_url="/account/") def add_seller_card(request): card_form = SellerCardFormSet user = SellerAccount.objects.get(user=request.user) # imported model if request.method == "POST": formset = card_form(request.POST, instance=user) if formset.is_valid(): formset.save() return redirect("/") else: print(formset.non_form_errors) print(formset.errors) # the helpful "debug" that got me here formset = card_form(instance=user) return render(request, 'account/profile/addcard.html', {"formset": formset}) else: return render(request, 'account/profile/addcard.html', {"formset": card_form(instance=user)}) And finally, the html: <form method="post"> {% csrf_token %} {{formset.management_form}} <h1 class="h3 mb-3 fw-normal">List a card</h1> <fieldset> <div class="container"> <div class="form-floating"> <input type="text" name="card_name" class="form-control" id="floatingInput"> <label for="floatingInput">Card name</label> </div> <div … -
How to run Powershell commands in Django Web App in Production. (Azure Web Apps)
i have a Django App that i want to deploy to Azure Web Apps. Some functions require interaction with Windows Powershell. Im using subprocess.Popen to execute specific commands directly in powershell and catch the output. Locally this is running fine but i am afraid these funtions will no longer work when deploying to Azure. Please see below a sample function. And yes i am planning to validate and sanitize inputs. Anybody had a comparable scenario and can help me out? def assign_mailbox_permission(tenant, user, mail_group): secret = get_secret(keeper_uids[tenant]['M365 Zentrale API Administrator']) username = secret['login'] password = secret['password'] if tenant == "einsnulleins Schloß Holte-Stukenbrock": mail_group = mail_group.replace("standort.", "") else: mail_group = mail_group.replace("standort", tenant.replace("ä", "ae").replace("ü", "ue").replace("ö", "oe").replace("ß", "ss").lower()) powershell_command = f'$UserCredential = New-Object System.Management.Automation.PSCredential -ArgumentList "{username}", (ConvertTo-SecureString "{password}" -AsPlainText -Force); Connect-ExchangeOnline -UserPrincipalName "{username}" -Credential $UserCredential; Add-MailboxPermission -Identity "{mail_group}" -User "{user}" -AccessRights FullAccess -InheritanceType All ' command_args = ["powershell.exe", "-Command", powershell_command] mailbox_error = "Ex6F9304" not_found_error = "Ex9BC9DD" counter = 0 while True: process = subprocess.Popen(command_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr= process.communicate() error = stderr.decode('utf-8', errors='replace') counter += 1 if error == '': result = { 'update': f'Benutzer Berechtigungen für {mail_group} erteilt', 'success': True } return result if mailbox_error in error: result = { 'update': f'Postfach … -
Missing 1 required positional argument: 'on_delete'?
So: I'm trying to implement Django CMS to my Django website and I'm facing the "OneToOneField.init() missing 1 required positional argument: 'on_delete'" in my models.py from Django. from django.db import models class Word(models.Model): word_name = models.CharField(max_length=50) word_about = models.TextField() word_resources = models.URLField() def __str__(self): return self.word_name class Meta: db_table = 'words' class Principle(models.Model): word = models.ForeignKey(Word, on_delete=models.CASCADE) principle_name = models.CharField(max_length=100) principle_description = models.TextField() class Meta: db_table = 'principles' class CodeSnippet(models.Model): raw_code = models.TextField() What I've tried: this, this + chatgpt so basically: word = models.OneToOneField(Word, on_delete=models.CASCADE), word = models.OneToOneField(Word, on_delete=models.CASCADE/PROTECT/DO_NOTHING/SET_DEFAULT) -
Django smart select doesn't work with Django CSP
I admit that I am truly a beginner in this area. I made a database driven website with django. Models.py: from django.db import models from smart_selects.db_fields import ChainedForeignKey # Create your models here. class Company(models.Model): ID = models.AutoField(primary_key=True, unique=True) soc_name = models.CharField(max_length=100) phone = models.CharField(max_length=100, blank=True) class Meta: ordering = ('soc_name',) def __str__(self): return self.soc_name class Plant(models.Model): ID = models.AutoField(primary_key=True) name = models.CharField(max_length=100) company_id = models.ForeignKey(company, on_delete=models.CASCADE) class Meta: ordering = ('name',) def __str__(self): return self.name class Interventions(models.Model): ID = models.AutoField(primary_key=True) start_date = models.DateField() description = models.TextField() company_id = models.ForeignKey(company, on_delete=models.CASCADE) plant_id = ChainedForeignKey( Installations, chained_field="Company_ID", chained_model_field="Company_ID", show_all=False, auto_choose=True, sort=True) def __str__(self): return str(f"{self.start_date}, {self.plant_ID}") I used Django-Smart-Selects so that in Interventions Form, when a Company is selected, the Combo Box of the Plants (which belong to the respective Companies) is automatically filtered. Here an image to make it easier to understand: Up to here everything works perfectly. So I tried adding Content Security Policies (CSP) to my site. To do this, I added these lines of code to the Settings.py file: MIDDLEWARE = [ [...] 'csp.middleware.CSPMiddleware', ] CSP_DEFAULT_SRC = ("'none'",) CSP_STYLE_SRC = ("'unsafe-inline'", "https:") CSP_SCRIPT_SRC = ("'self'",) CSP_FONT_SRC = ("'self'",) CSP_IMG_SRC = ("'self'",) The problem is that when I … -
Django template bracket notation with variable key does not work
I am trying to dynamically render a table based on a table model and it's columns. In the template, I loop over each item in the qeuryset and then over each column from a list of hard coded column names, but Django returns a Could not parse the remainder: '[column]' from 'table[column]' error. table.id renders the correct id value but table[column[0]] returns an error. Does Django not allow bracket notation fro variables? In this example table is a dict of a model class and columns is a list of the model's column names. <tbody> {% for table in query_set %} <tr> {% for column in columns %} <td>{{table[column]}}</td> {% endfor %} </tr> {% endfor %} </tbody> I have also tried using the .items method on the table dict: <tbody> {% for table in query_set %} <tr> {% for key, value in table.items %} <td>{{value}}</td> {% endfor %} </tr> {% endfor %} </tbody> but this renders nothing. table.items seems to be undefined -
{ "detail": "You do not have permission to perform this action." }
I am stuck for a few days with this, and nothing is working for me. So, my db is in Neo4j, and I am making API with Django DRF. These are the relevant files: # models.py class NeoUser(StructuredNode): uid = UniqueIdProperty() emp_id = StringProperty(unique_index=True) username = StringProperty() email = EmailProperty(unique_index=True) password = StringProperty() designation = StringProperty() department = StringProperty() pp = StringProperty(unique_index=True) dob = DateTimeProperty() phone = StringProperty(unique_index=True) ** settings.py ** REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { # 'JWT_SECRET_KEY': 'your-secret-key', 'JWT_ALGORITHM': 'HS256', 'JWT_ALLOW_REFRESH': True, 'ACCESS_TOKEN_LIFETIME': timedelta(days=30), 'REFRESH_TOKEN_LIFETIME': timedelta(days=90), 'JWT_AUTH_HEADER_PREFIX': 'Bearer ', "ROTATE_REFRESH_TOKENS": False, "BLACKLIST_AFTER_ROTATION": False, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "SIGNING_KEY": SECRET_KEY, # "VERIFYING_KEY": SECRET_KEY, "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, 'JWT_ALLOW_REFRESH': True, # 'AUTH_HEADER_TYPES': ('Bearer',), "AUTH_HEADER_NAME": "Authorization", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "JTI_CLAIM": "jti", # "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", # "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), # "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } serializer.py from rest_framework import serializers from .models import NeoUser from rest_framework.validators import UniqueValidator class Neo4jUserSerializer(serializers.Serializer): username = serializers.CharField() emp_id = serializers.CharField() email = serializers.CharField() phone = serializers.CharField() password = serializers.CharField() def validate(self, data): id … -
Which Django.forms.Form method should be overridden to use variables created in __init__() when creating form fields?
I need to get data access to variables in (init: dictionary), which Django method should be overridden for this? The dictionary variable is used as a label when creating form fields. Form code: class TrainingForm(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(TrainingForm, self).__init__(*args, **kwargs) self.dictionary = self.user.userdictionaries.dictionary word0 = forms.CharField(label=dictionary, widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) word1 = forms.CharField(label=dictionary, widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) word2 = forms.CharField(label=dictionary, widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) word3 = forms.CharField(label=dictionary widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) word4 = forms.CharField(label=dictionary, widget=forms.TextInput(attrs={ 'class': 'form-input', 'data-word-translate': ''})) View code: class Training(MixinDataParams, TemplateView): template_name = 'training.html' def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) form_training = TrainingForm(self.request.POST, user=self.request.user) c_def = self.get_user_context(title='Training', form=form_training) return dict(list(context.items()) + list(c_def.items())) I tried to change the required fields in the body of the view function (get_context_data), but this does not work reliably. -
Django MySQL ORM commented out 'use_index'. w
my command : qs = model.objects.force_index('idx_sensorid_id_accelerator').filter(sensor_id=dev['id']).order_by('-id').values(*cols) and my index (mysql) : STATISTICS Table Non_unique Key_name Seq_in_index Column_name Collation Cardinality Sub_part Packed Null Index_type Comment Index_comment Ignored sensor_accelerator 0 PRIMARY 1 id A 131673992 \N \N BTREE NO sensor_accelerator 1 sensor_accelerator_sensor_id_b0bf304a 1 sensor_id A 19720 \N \N BTREE NO sensor_accelerator 1 sensor_accelerator_added_c16fd96c 1 added A 131673992 \N \N BTREE NO sensor_accelerator 1 idx_sensorid_id_accelerator 1 sensor_id A 19714 \N \N BTREE NO sensor_accelerator 1 idx_sensorid_id_accelerator 2 id D 131673992 \N \N BTREE NO sensor_accelerator 1 idx_sensorid_added_accelerator 1 sensor_id A 15368 \N \N BTREE NO sensor_accelerator 1 idx_sensorid_added_accelerator 2 added D 131673992 \N \N BTREE NO but the query result is : SELECT `sensor_accelerator`.`sensor_id`, `sensor_accelerator`.`id`, `sensor_accelerator`.`x`, `sensor_accelerator`.`y`, `sensor_accelerator`.`z`, `sensor_accelerator`.`temp`, `sensor_accelerator`.`time`, `sensor_accelerator`.`added` FROM `sensor_accelerator` WHERE ((/*QueryRewrite':index=`sensor_accelerator` USE `sensor_accelerator_sensor_id_b0bf304a`*/1) AND `sensor_accelerator`.`sensor_id` = 'A0011') ORDER BY `sensor_accelerator`.`id` DESC LIMIT 1 what i expected is : SELECT `sensor_accelerator`.`sensor_id`, `sensor_accelerator`.`id`, `sensor_accelerator`.`x`, `sensor_accelerator`.`y`, `sensor_accelerator`.`z`, `sensor_accelerator`.`temp`, `sensor_accelerator`.`time`, `sensor_accelerator`.`added` FROM `sensor_accelerator` USE INDEX (idx_sensorid_id_accelerator) WHERE `sensor_accelerator`.`sensor_id` = 'A0011' ORDER BY `sensor_accelerator`.`id` DESC LIMIT 1 Why django orm commented out use_index phrase? -
How to change a value of the element without reloading after a button element is clicked
I am trying to implement a “Like” button for each post. I want to change the class of the button element based on whether the user has liked the post or not, and I want the change to be reflected in real-time without a full page reload. So far, the button can send data that is like or not to a function of Django using fetch however the change of the data isn’t reflected without reloading. To achieve this, what does it need to modify? Button element in html file <div id="{{ post.id }}"> {% if post.id in whoyouliked %} <button class="btn btn-secondary fa fa-thumbs-down" onclick="likeHandler(`{{ post.id }}`, `{{ whoyouliked }}`)"></button> {% else %} <button class="btn btn-info fa fa-thumbs-up" onclick="likeHandler(`{{ post.id }}`, `{{ whoyouliked }}`)"></button> {% endif %} </div> likeHandler function in script tag in the same html file function likeHandler(id, whoyouliked){ let btn = document.getElementById(`${id}`); btn.classList.remove('fa-thumbs-up') btn.classList.remove('fa-thumbs-down') if(whoyouliked.indexOf(id) >= 0){ var liked = true; } else{ var liked = false; } if(liked === true){ fetch(`remove_like/${id}`) .then(response => response.json) .then(result => { btn.classList.add('fa-thumbs-up') }) } else{ fetch(`add_like/${id}`) .then(response => response.json) .then(result => { btn.classList.add('fa-thumbs-down') }) } } I'm new to Javascript, so I'd appreciate any comment. -
Best Practice to Insert single text passages in Django (not from database)
I'm not a developer but do little Django projects for my business for several years now. I am wondering how to best implement longer text passages like e.g. directions, data protection/privacy rules or opening hours to my website. I don't like to hard code this in the template. In the last projects I've been using the database with a model "Information" and query for the "name" "directions", "privacy rules" or "opening hours". Then I can pipe it through markdown and insert it into the template. Is this the proper way or should I put the information in a file? The content of this is kind of static (at least for years). Thanks for ideas and help, Dirk -
Third test in Django with Pytest is failed because "django.template.exceptions.TemplateDoesNotExist"
I got 3 tests in django using pytest, the first two tests are alright untill third one which cannot find Template. Last 2 of 3 are working with same template but second one cannot find the template. FAILED app_wallet/accounts/tests/test_pytest.py::test_login_failed - django.template.exceptions.TemplateDoesNotExist: main_layout.html #test_pytest.py import pytest from django.urls import reverse from django.contrib.auth.models import User pytestmark = pytest.mark.django_db def test_create_account_success(client): client_url = reverse('accounts:create') data = { 'username': 'test', 'email': 'test@domain.pl', 'password1': 'myPassword123', 'password2': 'myPassword123', } response = client.post(path=client_url, data=data) user = User.objects.all().first() assert response.status_code == 302 # redirected to another page - valid data assert User.objects.all().count() == 1 assert user.username == data.get('username') assert user.email == data.get('email') def test_login_success(client): client_url = reverse('accounts:login') user = User.objects.create_user(username='test123', password='Password123', email='test@domain.pl') data = { 'username': 'test123', 'password': 'Password123' } response = client.post(path=client_url, data=data) assert response.status_code == 302 # redirected to another page - valid data assert User.objects.all().first().username == data.get('username') assert User.objects.all().first().email == 'test@domain.pl' def test_login_failed(client): client_url = reverse('accounts:login') user = User.objects.create_user(username='test123', password='Password123', email='test@domain.pl') data = { 'username': 'test123', 'password': 'Password12' } response = client.post(path=client_url, data=data) assert response.status_code == 200 assert User.objects.all().count() == 1 assert User.objects.all().first().username != data.get('username') #login.html {% extends 'main_layout.html' %} {% block head %} <title> Test 123 </title> {% endblock %} {% block main %} … -
Django application visible in the home network only if run by root
I have a web app on Django that I'm running with the internal server to make it see on my home network. If I run with my user with python manage.py runserver 0.0.0.0:8080 I can see it work but only within my host. If I try to reach on another PC on the same network I have connection refused. If I run the same command but with root user, so using sudo su, everything works and I can reach the server from any PC on the network. I'm using Python 3.10.12 and Ubuntu 22.04.3 LTS 6.2.0-26-GENERIC -
AttributeError: module 'django.db.models' has no attribute 'JSONField' in django 3.0.5
I am trying add a model in my app like this: class WarehouseTablePreferences(models.Model): owner = models.ForeignKey(User, on_delete=models.PROTECT) column_preferences = models.JSONField(default=dict) and in the app I have: Django==3.0.5 django-cors-headers==3.2.1 djangorestframework==3.11.0 but its still giving me the following error: File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend copy/users/models.py", line 407, in <module> class WarehouseTablePreferences(models.Model): File "/Users/rahulsharma/PycharmProjects/Trakkia-Backend copy/users/models.py", line 409, in WarehouseTablePreferences column_preferences = models.JSONField(default=dict) AttributeError: module 'django.db.models' has no attribute 'JSONField' -
why view inheritance in django does not work
django(i am new) view inheritance dont work <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>coding Django</title> </head> <body> <h1>Welcome to this shit show</h1> {% block content %} {% endblock content %} </body> </html> this is sub component and does not show inside base view i tried to include it in the base.html does not work either {% extends "base.html" %} {% block content %} <h1> this is from sub component <h1> {% endblock content %} -
How can i integrate salesforce to my Django Application
Previously I worked with ROR where I used Restforce Gem. I am new to this Django can someone suggest what are the best ways to be followed to integrate salesforce to my e-commerce application I am new to this Django is there any rest api calls that i need to make. What is the project structure i need to keep in my mind while implementing this in Django -
How to access the fields from other models in Django
I am trying to make a application where the data incoming is in this format { "author name": "J. K. Rowling", "books" : ["Harry potter 1" , "Harry potter 2"] } Now i made the models for author and books in the following format class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.ForeignKey(Author,on_delete=models.CASCADE) title = models.CharField(max_length=200) The seralizers are :- class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' class AuthorSerializer(serializers.ModelSerializer): books = BookSerializer(many=True, required=False) # Use the BookSerializer here class Meta: model = Author fields = '__all__' Views are: class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer Custom View:- class ImportDataViewSet(ViewSet): @action(methods=["POST"],detail=False) def import_data(self,request): data = request.data print(data) # deseralize the data and check book_seralizer = [BookSerializer(data = book_data) for book_data in data.get("books",[])] author_seralizer = AuthorSerializer(data = data.get("author")) if(author_seralizer.is_valid() and all(seralizer.is_valid() for seralizer in book_seralizer)): author_instance = author_seralizer.save() for book_instance in book_seralizer: book_instance.validated_data['author'] = author_instance print("hello ",book_instance.data) book_instance.save() return Response({"message","Data imported successfully"},status=200) else: author_errors = author_seralizer.errors if (author_seralizer.is_valid() == False) else {} book_errors = [serializer.errors for serializer in book_seralizer if(serializer.is_valid() == False)] errors = { "author_errors": author_errors, "book_errors": book_errors } return Response(errors,status=400) URLS:- router = DefaultRouter() router.register(r"authors",AuthorViewSet) router.register(r"books",BookViewSet) import_data_view …