Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i make one static files that used in all apps?
Im using Django and i want to make a **static **file that can used in all apps templates this is the tree of my project C:. ├───AISystem │ ├───static │ │ ├───css │ │ ├───imgs │ │ │ ├───myfont │ │ │ └───result │ │ └───js │ └───__pycache__ ├───Text2imageApp │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───text2voiceApp │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ └───texttohandwriting ├───migrations │ └───__pycache__ ├───templates └───__pycache__ as you can see i put my css file in the (../AISystem/static/css/main_style.css) and i want to use it in other apps templates. my setting.py file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'AISystem\static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') template file in this dir : (Text2imageApp/templates/main.html) {% load static %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>IntelliHub</title> <link rel="main_style" href="i dont know what to write here"> how i can link main.html with the main_style.css? -
Being a Developer is hard...lets talk about it [closed]
What do you do when you're frustrated? I know its not a coding question, but we're so into the computer we forget sometimes that we're humans sitting down and typing for hours. What do you do when you just have so much to do in your project and the first thing on that long list is giving you issues and you feel like throwing yourself out a window. how do you get through it? How do you try and figure it out? Just want to hear your opinions -
imported some function from c++ dll to python using ctypes, but some functions doesn't work as expected
so i'm developing a backend using django and i got an image processing step for which i'm using a private c++ .dll developed by my company. i'm using ctypes to load the .dll file and managed to make some of the imported functions work properly. but some functions ("fr_get_fire_img" in this case) doesn't work as expected. i don't know if i am specifying the function's argtypes or the function restype incorrectly and need some guide, thanks in advance! here's the function signature in c#: [DllImport(DLL_NAME)] public static extern IntPtr fr_get_fire_img(byte instance, ref short W, ref short H, ref short step); here's the python code where i'm trying to use the imported function: import ctypes from ctypes import c_char_p as char_pointer from ctypes import c_short as short from ctypes import c_void_p as int_pointer zero = char_pointer(0) w = short(0) h = short(0) step = short(0) fire_dll.fr_get_fire_img.restype = int_pointer source = fire_dll.fr_get_fire_img(zero, w, h, step) print(source, type(source)) and finally this is the error i'm getting from ctypes: Traceback (most recent call last): File "PATH OF PYTHON FILE", line 44, in <module> source = fire_dll.fr_get_fire_img(zero, w, h, step) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ OSError: exception: access violation writing 0x0000000000000000 i couldn't find any reference online so i'd … -
Django Custom Field with Fernet Cannot Decrypt
This is my custom field that I call in a model. Migrations succeed and I'm able to insert an encrypted value into the data table. However, it will not decrypt. Here's the custom field class: class SecureString(CharField): """Custom Encrypted Field""" #kdf = X963KDF(algorithm=hashes.SHA256(), # length=32, #sharedinfo=None, # backend=default_backend()) key = bytes(settings.FERNET_KEY,'utf-8') f = Fernet(key) def from_db_value(self, value, expression, connection): return self.f.decrypt(str.encode(value)) def get_prep_value(self, value): return self.f.encrypt(bytes(value, 'utf-8')) And here is the error when trying to retrieve values from the data table: File /usr/local/lib/python3.8/site-packages/IPython/core/formatters.py:706, in PlainTextFormatter.__call__(self, obj) 699 stream = StringIO() 700 printer = pretty.RepresentationPrinter(stream, self.verbose, 701 self.max_width, self.newline, 702 max_seq_length=self.max_seq_length, 703 singleton_pprinters=self.singleton_printers, 704 type_pprinters=self.type_printers, 705 deferred_pprinters=self.deferred_printers) --> 706 printer.pretty(obj) 707 printer.flush() 708 return stream.getvalue() File /usr/local/lib/python3.8/site-packages/IPython/lib/pretty.py:410, in RepresentationPrinter.pretty(self, obj) 407 return meth(obj, self, cycle) 408 if cls is not object \ 409 and callable(cls.__dict__.get('__repr__')): --> 410 return _repr_pprint(obj, self, cycle) 412 return _default_pprint(obj, self, cycle) 413 finally: File /usr/local/lib/python3.8/site-packages/IPython/lib/pretty.py:778, in _repr_pprint(obj, p, cycle) 776 """A pprint that just redirects to the normal repr function.""" 777 # Find newlines and replace them with p.break_() --> 778 output = repr(obj) 779 lines = output.splitlines() 780 with p.group(): File /usr/local/lib/python3.8/site-packages/django/db/models/query.py:370, in QuerySet.__repr__(self) 369 def __repr__(self): --> 370 data = list(self[: REPR_OUTPUT_SIZE + 1]) … -
Customize Form for User adding/editing in admin Wagtail
I have customized user profiles in Wagtail by adding fields (drm, cpm). How can I modify the form, or more specifically, the values in the form's lists based on the currently logged-in user and their permissions? Hello everyone, I have customized user profiles in Wagtail by adding fields (drm, cpm). How can I modify the form, or more specifically, the values in the form's lists based on the currently logged-in user and their permissions? For example, let's say you have extended the user profile model in Wagtail to include custom fields drm and cpm, and you want to dynamically populate a choice field in a form based on the user's role or permissions. Here's how you might approach this: # in models.py from django.db import models from wagtail.users.models import UserProfile class CustomUserProfile(UserProfile): drm = models.CharField(max_length=50, blank=True, null=True) cpm = models.CharField(max_length=50, blank=True, null=True) Next, you can create a custom form for a Wagtail admin page and override the form fields based on the user's profile: # in admin.py from wagtail.contrib.modeladmin.options import ModelAdmin from wagtail.contrib.modeladmin.views import CreateView, EditView from wagtail.contrib.modeladmin.helpers import PermissionHelper from .models import CustomUserProfile class CustomUserProfilePermissionHelper(PermissionHelper): def user_can_edit_obj(self, user, obj): # Customize this method to check if the user has … -
Trying To setup MultiTenancy in Django using database schemas
I am trying to setup multitenancy in Django using multiple Databases. Initially my first database was "succesfully" migrated. But then I created another database, tried migration and got this** error !!** ModuleNotFoundError: No module named 'routers' Because of this error I deleted my project and created a new one. Now even the first Database give this error I have routers package installed as well. I don't know how to fix this. Screenshot of error Please help !!!! This is for my Uni project !!!! ........................................................................ -
Django - Form Not Saving Image on Form Submission
For my current ModelForm for some reason all the fields get updated on a form submission as they are supposed to except for the image field. What’s the best solution to get this working with my current code? I think it’s because request.FILES isn’t getting handled correctly in my views.py file but not 100% sure. Side note: If i upload an image to the Django backend, the image field updates how it’s supposed to. This is only happening when there’s a form submission on the front end when the image field isn’t getting updated. Below is my code. Screenshots attached of the Django admin backend and the front end where the data is being displayed. Any help is gladly appreciated. Thanks! views.py def account_view_myaccount_edit(request): user_profile = User_Info.objects.filter(user=request.user) instance = User_Info.objects.get(user=request.user) user = request.user if request.method == 'POST': form = HomeForm(request.POST, request.FILES, instance=instance) if form.is_valid(): listing_instance = form.save(commit=False) listing_instance.user = user listing_instance.save() return redirect('myaccount_edit') # Redirect to a success page else: form = HomeForm(instance=instance) context = { 'user_profile': user_profile, 'form': form } return render(request, 'myaccount_edit.html', context) models.py class User_Info(models.Model): id = models.IntegerField(primary_key=True, blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics', null=True, blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL,blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) address = models.CharField(max_length=100) city … -
Votes not being counted in django poll
I'm working through the polls tutorial and I want to be able to have multiple questions on the same page and only press the vote button once. Right now, I don't get any errors but it is not counting the votes. I tried to write unittests to trace the error but am not sure how to replicate an html form either. In the future, I would also like other types of questions (like free text) mixed in and am not sure if I should create another app for the other question type or modify the Question and Choice in models.py. I saw some other examples but people warned against hardcoding questions/choices in the html but my form should end up remaining pretty static. models.py from django.db import models import datetime from django.utils import timezone class Question(models.Model): def __str__(self): return self.question_text question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.shortcuts import render, get_object_or_404, … -
Error while migrating from a SQLite database to a MySQL database in a Django Project
I'm trying to migrate all of the data in my SQLite database to a new MySQL database, to do so, I've been following the following steps (which I found in another question What's the best way to migrate a Django DB from SQLite to MySQL?). I've tried the following approaches: First I run a py manage.py dumpdata > datadump.json. Then, I change my settings.py file to use my new MySQL database. After that, I run a py manage.py migrate --run-syncdb And then I exclude contentType data by: python manage.py shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() And Lastly, I try to run a py manage.py loaddata datadump.json I've also tried to just run py manage.py dumpdata --exclude contenttypes --exclude auth.permission --exclude sessions --indent 2 > dump.json, followed by py manage.py loaddata dump.json. The problem is that, in both approaches, in the very last step, when I'm trying to load the data into my new database, the following error is raised: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I've been trying to investigate what could prevent or fix this error but nothing has come up. Any help is appreciated. Thanks in advance. In case this … -
Djoser verify or activate email address when reset or changed
I was unable to Verfiy a user when user changed their email address serializers.py from djoser.serializers import UserCreateSerializer as BaseUserCreateSerializer, UserSerializer as BaseUserSerializer class UserCreateSerializer(BaseUserCreateSerializer): class Meta(BaseUserCreateSerializer.Meta): fields = ['id', 'name', 'email', 'password'] class UserSerializer(BaseUserSerializer): class Meta(BaseUserSerializer.Meta): fields = ['id', 'name', 'email'] class UserDeleteSerializer(Base...): pass settings.py DJOSER = { 'LOGIN_FIELD': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'SET_PASSWORD_RETYPE': True, 'SEND_CONFIRMATION_EMAIL': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SERIALIZERS': { ... }, 'PERMISSIONS': { ... } } models.py from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): ... user = self.model(email=email, **extra_fields) ... def create_user(self, email, password=None, **extra_fields): ... return self._create_user(email, password, **extra_fields) def create_superuser(self, email=None, password=None, **extra_fields): ... return self._create_user(email, password, **extra_fields) class User(AbstractUser): name = models.CharField(max_length=150) email = models.EmailField(unique=True) soft_deleted = models.BooleanField(default=False) username = None first_name = None last_name = None EMAIL_FIELD = "email" USERNAME_FIELD = "email" REQUIRED_FIELDS = ["name"] objects = UserManager() def get_full_name(self): full_name = "%s" % (self.name) return full_name.strip() def get_short_name(self): return self.name I want to add some functionality when user POST requested to base_url/auth/users/reset_email/ with email=registed_email@gmail.com we received a email with a link having uid and token in a link once user POST … -
MS auth - Django adding an 'http' to my URI at callback
I am building a PoC for web applications using Django with Microsoft Authentication. The app in my Azure Directory is all setup, my Site domain matches the URI expected in the app and an initial call was made successfully. BUT, for reasons unknown to me, django sends an additional 'http://'. the error it gives me I am no Django or Azure expert. Here are some snippets. settings.py: AUTHENTICATION_BACKENDS = [ 'microsoft_auth.backends.MicrosoftAuthenticationBackend', 'django.contrib.auth.backends.ModelBackend' ] MICROSOFT_AUTH_CLIENT_ID = env('MS_APP_ID') #the keys are correct in the .env, triple-checked MICROSOFT_AUTH_CLIENT_SECRET = env('MS_SECRET_KEY') MICROSOFT_AUTH_TENANT_ID = env('MS_TENANT_ID') MICROSOFT_AUTH_LOGIN_TYPE = 'ma' MS_AUTH_REDIRECT_URI = 'http://localhost:5000' #matches the redirect URI in the Azure app accounts/urls.py: urlpatterns = [ path('microsoft/', include('microsoft_auth.urls', namespace='microsoft')), path('', RedirectView.as_view(url='index'), name='home'), path('accounts/', include('django.contrib.auth.urls')), path('index/', index, name='index'), ] I tried changing the domain url in the 'admin/sites/sites' and in the settings.py variable MS_AUTH*_*REDIRECT_URI, removing the 'http://' prefix, but to no avail. -
What is the neatest way to implement an optional update for a django web app?
I am creating an open-source web app using Django that anyone can install on their local machine, Heroku, etc. The most obvious way for the clients to get updates in the app is to ask them to pull the latest version from GitHub. Is there a cleaner, more elegant way to do this? For example, can we have a webpage (in the same Django project) which has a button to trigger an update from GitHub, while the web app is already running? TLDR: How to make a Django web app update its own code when it's told to do so? -
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 …