Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to - Implement simple Websocket in a Django DRF project created with CookieCutter that sends a simple `unread_count`
I have a project created using cookiecutter-django and has a uvicorn/gunicorn setup I am able to get a ping websocat wss://<url> -v --ping-interval=5 Now I want to create a url what out give unread_count to the request user Is there any way of doing this without using Channels? I am trying to get this done as simple as pissible -
npm rollup.js ReferenceError: _default is not defined
Have spent hours trying to solve this, but have limited experience creating modules. The error returned is: ReferenceError: _default is not defined tsconfig.json { "compilerOptions": { "target": "es5", "jsx": "react", "module": "esnext", "sourceMap": true, "declaration": true, "outDir": "dist" }, "include": [ "src" , "src/index.tsx" ] } rollup.config.js import typescript from '@rollup-plugin-typescript'; import replace from 'rollup-plugin-replace'; export default { input: { Wordpress: 'src/Wordpress.tsx', ContactForm7: 'src/ContactForm7.tsx' }, output: { dir: 'dist', format: 'cjs', }, plugins: [ typescript({ tsconfig: 'tsconfig.json' }), replace({ 'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE) }), ], external: ['react'], }; package.json { "name": "test-wordpress", "version": "1.0.2", "description": "Test project", "main": "./dist/index.d.ts", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "rollup -c --bundleConfigAsCjs" }, "repository": { "type": "git", "url": "git+https://github.com/test-project/nextjs-wordpress.git" }, "license": "ISC", "bugs": { "url": "https://github.com/test-project/nextjs-wordpress/issues" }, "homepage": "https://github.com/test-project/nextjs-wordpress#readme", "devDependencies": { "@types/axios": "^0.14.0", "@types/node": "^18.11.18", "rollup": "^3.10.1", "rollup-plugin-replace": "^2.2.0", "@rollup/plugin-typescript": "^11.0.0" }, "dependencies": { "axios": "^1.2.3" } } ./dist/index.d.ts import { sendForm } from "./ContactForm7"; import { getPage } from "./Wordpress"; declare const _default: { getPage: typeof getPage; sendForm: typeof sendForm; }; export default _default; -
No static files after deploying Django app
I've deployed a multi container Django application to AWS EB with ECS running on 64bit Amazon Linux 2/3.2.3 platform. Here's the Dockerrun.aws.json file. { "AWSEBDockerrunVersion": "2", "containerDefinitions": [ { "essential": true, "image": "${AWS_ACOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${IMAGE_NAME}:${IMAGE_TAG}", "mountPoints": [ { "containerPath": "/code/static", "sourceVolume": "web" } ], "name": "web", "hostname": "web", "memoryReservation": 1200, "portMappings": [ { "containerPort": 8000, "hostPort": 8000 } ] }, { "name": "nginx-proxy", "image": "nginx", "essential": true, "memoryReservation": 128, "portMappings": [ { "containerPort": 80, "hostPort": 80 } ], "mountPoints": [ { "sourceVolume": "nginx-proxy-conf", "containerPath": "/etc/nginx/nginx.conf" } ], "links": ["web"] } ], "volumes": [ { "name": "web" }, { "name": "nginx-proxy-conf", "host": { "sourcePath": "/var/app/current/nginx.conf" } } ] } Here's the nginx.conf user nginx; events { worker_connections 1024; } http { server { listen 80; location /static/ { alias /static/; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } This is the Dockerfile. FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get upgrade -y COPY ./requirements.txt requirements.txt RUN apt-get install -y realmd RUN pip install -r requirements.txt WORKDIR /code EXPOSE 8000 COPY . . RUN chmod +x entrypoint.sh ENTRYPOINT ["./entrypoint.sh"] and the entrypoint.sh #!/bin/bash python manage.py migrate … -
Django templatetag to access arbitrary form field as defined by argument
This particular block of code repeats about a hundred million times, just with different form fields, and so I want to replace all those lines with templatetags: <label for="{{ form.building_name.id_for_label }}">Building</label> <input name="{{ form.building_name.name }}" value="{{ form.instance.building_name }}"> So instead of writing this: <label for="{{ form.building_name.id_for_label }}"> <!-- plus many more lines just for this one element --> <label for="{{ form.building_title.id_for_label }}"> <!-- plus many more lines just for this one element --> ... I am looking to write this: {% someTag 'building_name' %} {% someTag 'building_title' %} After much mucking about, I arrived at one of the ugliest ways of writing an inclusion tag that I've ever had the misfortune of laying eyes on. The convoluted nature of accessing the field is because I found no other way of accessing an arbitrary field of the form. The tag: @register.inclusion_tag("main/sff.html") def sff(form, field_name, label): field = form._meta.model._meta.get_field(field_name) return {'form': form, 'field': field, 'label' : label, 'ph' : placeholder} sff.html: <label for="{{ field.id_for_label }}">{{ label }}</label> <input type="text" \ name="{{ field.name }}" \ value="{{ form.instance.field }}"> </div> With all of that said and done, here's how I call it from my HTML template: {% sff form 'building_name' 'Enter property name' %} … -
Django validate fileds on form
Мне необходимо сделать проверку полей на форме и вывести ошибку в шаблон FORMS class UserForm(forms.Form): first_name= forms.CharField(max_length=20, label='Имя') last_name= forms.CharField(max_length=20, label='Фамилия') password= forms.CharField(label='Пароль') repassword= forms.CharField(label='Подтвердить пароль') def clean(self): cleaned_data = super().clean() self.password = cleaned_data('password') self.repassword = cleaned_data('repassword') if self.password != self.repassword: raise ValidationError('Пароли должны совпадать') VIEW def index(request): form = UserForm() if request.method == 'POST': form = UserForm(request.POST or None) if form.is_valid(): firstname= form.cleaned_data.get("first_name") lastname= form.cleaned_data.get("last_name") password = form.cleaned_data.get('password') re_password = form.cleaned_data.get('repassword') form = UserForm() context = {'form': form, } return render(request, 'create_users/index.html', context) return render(request, 'create_users/index.html', {'form': form}) В результате получаю ошибку dict' object is not callable -
OAuthlib thinks request is insecure because of reverse proxy
I have noticed that for every request, request.scheme is http. I can't find any official source why, but I have been told by my peers this is because of Cloudflare acting as reverse proxy and a tls terminator, causing my server's hosting provider to see http instead of https. One part of my app uses the Google Classroom API, and I have configured a callback to a secure endpoint of my server. Upon attempting to fetch a token from the callback's absolute uri, oauthlib raises oauthlib.oauth2.rfc6749.errors.InsecureTransportError: (insecure_transport) OAuth 2 MUST utilize https. because it thinks the request is http and insecure. I have researched and found out I can set os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' to mitigate this issue, but I am hesitant to do so because I am unsure if that compromises security. My thought process is to manually change the request url to https when I'm absolutely sure it is secure. Inspecting request.META to find which headers are set in the case of a reverse proxied http request, the code looks like this: authorization_response = request.build_absolute_uri() if ( authorization_response.startswith("http://") and request.META["HTTP_X_FORWARDED_PROTO"] == "https" and request.META["HTTP_ORIGIN"].startswith("https") and json.loads(request.META["HTTP_CF_VISITOR"])['scheme'] == "https" ): authorization_response = "https://" + authorization_response[7:] ... fetch the token passing … -
Is there a way to clear the cache of a django form field in the admin page?
My problem is that, on the website I created using django and hosted with apache, after modifying some models through the admin interface I noticed that there is a URLField that whenever the page is reloaded after I make changes this field always loads in the browser with a value in it (even though that field is null in the database) and whenever I forget to check that field and save the model the field will contain that "cached" value that was loaded with the page and save it in the database, and I don't want that. There is also this piece of code in the ModelAdmin class for the model with the described problem that I thought it was the cause of the problem but I don't think it's from this def get_form(self, request, obj=None, change=False, **kwargs): form = super(ResourceAdmin, self).get_form(request, obj, change, **kwargs) if obj and obj.yt_video_id: form.base_fields['youtube_url'].initial = f'https://www.youtube.com/watch?v={obj.yt_video_id}' return form I tried CTRL + F5 since I heard that this way of refreshing clears the cached resources for that website but it didn't work. Is there a way of getting rid of that value that loads in the field whenever I am changing a model on … -
Need help running Django at a local machine after deploying it to DigitalOcean apps
I'm using Digital Ocean app platform to host my website but after following the settings from the end of this documentation from the website (at the end of step 2), there's something I think I'm missing cause I have deployed the app following the guide but now I can't run it on my local machine. The error comes from this snippet, throwing the Exception "DATABASE_URL environment variable not defined" elif len(sys.argv) > 0 and sys.argv[1] != 'collectstatic': if os.getenv("DATABASE_URL", None) is None: raise Exception("DATABASE_URL environment variable not defined") DATABASES = { "default": dj_database_url.parse(os.environ.get("DATABASE_URL")), } Any clue? I thought I should use something like python-dotenv or django-dotenv or having multiple Django settings modules, but my brain right now is just frosted. Please help -
Django ASGI/channels with Streaminghttpresponse
I add channels to my project and it's creating a problem, I have a stream func that streama video with streaminghttpresponse , and that work well before I add asgi/channels to run the server I saw that it's some bug that will be fixed in django 4.2 but I look for solution for now/ or if someone suggests another library for a socket that will now cause a similar problem this is my code Django v - 4.0 channels - 3.0.5 views.py def stream(source,startVideo): if startvideo : url = source + str('.mp4') cap = cv2.VideoCapture(url) while (cap.isOpened()): ret, frame = cap.read() if not ret: check = False break results = model(frame,augment=False,size=320) det = results.pred[0] results.render() annotator = Annotator(frame,line_width=2, pil=not ascii) im0 = annotator.result() image_bytes = cv2.imencode('.jpg', im0)[1].tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + image_bytes + b'\r\n') cap.release() cv2.destroyAllWindows() @csrf_exempt def video_feed(request): if request.method == 'POST': global startvideo,start,content startvideo=True content = request.GET.get('url','not') return StreamingHttpResponse(stream(content,startvideo), content_type='multipart/x-mixed-replace; boundary=frame') ASGI.PY application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket':AuthMiddlewareStack(URLRouter( webcam.routing.websocket_urlpatterns )) }) setting.py INSTALLED_APPS = [ 'channels', ...... 'webcam', ...... ] ASGI_APPLICATION = 'stream.asgi.application' routing.py websocket_urlpatterns = [ re_path(r'ws/socket-server/',consumers.ChatConsumer.as_asgi()), ] consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'test' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def … -
Django form.instance.field displaying incorrect datetime value on HTML template despite having the correct value at hand
I'm running Django 4.1, and the view that serves the template is a FormView-child. To start off with, here's the canonical answer as to what the correct value is, taken directly from the database: In [6]: DCF.objects.last().appreciation_date Out[6]: datetime.date(2023, 1, 24) The first HTML template invocation of that same field: <h5>Title: {{ form.instance.appreciation_date }}</h5> And the result is as expected: About 30 lines of code below (none of which do anything particularly functional, it's just a boatload of div declarations for CSS and styling), inside a <form>, on a modal: <div class="mb-3"> <label for="{{ form.appreciation_date.id_for_label }}">Date</label> <input class="form-control datepicker" placeholder="Please select date" type="text" onfocus="focused(this)" onfocusout="defocused(this)" name="{{ form.appreciation_date.name }}" value="{{ form.instance.appreciation_date }}"> </div> And now, prepare for the result - which also highlights the question I am about to get to: What in Django's ghost in the shell is going on? How did 2023-01-24 become 2023-01-01 for no apparent reason? Or said differently, why and how can the same context invocation have two different values in the same render of the same template? I would very much like for the second invocation to show the correct value - meaning the value that is both in the database, and presumably also in … -
Django Form unexpected keyword argument
i have a form which contains a choiceField and i need to populate it from a view, so i'm trying to use the kwargs inside the init function like this : class SelectionFournisseur(forms.Form): def __init__(self,*args, **kwargs): super(SelectionFournisseur, self).__init__(*args, **kwargs) self.fields['Fournisseur'].choices = kwargs.pop("choixF",None) Fournisseur = forms.ChoiceField(choices = ()) my view : formF = SelectionFournisseur(choixF=choices) but i get the error BaseForm.__init__() got an unexpected keyword argument 'choixF' -
Django Unitest, can't recognize the error
I am wondering if could anyone help out here, I am trying to send a post request to the URL, but I am not sure about the best way of doing it? The idea here is to test the creation of the card object, but I am getting an error which I am not managing to figure out, if anyone could help me out here it would be fantastic. here the code and the error below it def test_create_card(self): payload = { 'title': "Sample card title", 'description': 'Get a free coffee for every 10 coffee you buy', 'points_needed': 10, } res = self.client.post(CARDS_URL, self.company, **payload) print(res) self.assertEqual(res.status_code, status.HTTP_201_CREATED) card = Card.objects.get(id=res.data['id']) for k, v in payload.items(): self.assertEqual(getattr(card, k), v) self.assertEqual(card.company, self.company) ERROR ERROR: test_create_card (card.tests.test_card_api.PrivateCardAPITests) Test creating a card Traceback (most recent call last): File "/app/card/tests/test_card_api.py", line 141, in test_create_card res = self.client.post(CARDS_URL, self.company, **payload) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 295, in post response = super().post( File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 208, in post data, content_type = self._encode_data(data, format, content_type) File "/py/lib/python3.9/site-packages/rest_framework/test.py", line 179, in _encode_data ret = renderer.render(data) File "/py/lib/python3.9/site-packages/rest_framework/renderers.py", line 914, in render return encode_multipart(self.BOUNDARY, data) File "/py/lib/python3.9/site-packages/django/test/client.py", line 245, in encode_multipart for (key, value) in data.items(): AttributeError: 'Company' object has no … -
How properly request.user.is_superuser inside function in django admin.py
I am learning Djnago and I have this function inside admin.py that counts how many participants in an activity, it is working fine until, I want to know if the current user is a superuser and added request inside def set_count(self, request, obj) expecting to make a request for the user. Since I am getting an error, this means, this it's not how to do it and wrong. How to correct this? Thanks. Below is what I want to do, evaluate the user.is_superuser if true, it will display in the list_display the link to the participants_changelist otherwise, display a plain text. def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate(set_count=Count('activity_activity')) return queryset def set_count(self, request, obj): counter = obj.set_count if request.user.is_superuser: url = ( reverse("admin:activity_announcements_participants_changelist") + "?" + urlencode({"activity__id": f"{obj.id}"}) ) return format_html('<a href="{}">{} Paticipants</a>', url, counter) else: counter = obj.set_count return format_html('{} Paticipants', counter) set_count.short_description = "No. of Paticipants" Error: TypeError at /admin/activity_announcements/activity/ ActivityAdmin.set_count() missing 1 required positional argument: 'obj' Request Method: GET Request URL: http://localhost:8000/admin/activity_announcements/activity/ Django Version: 4.1.5 Exception Type: TypeError Exception Value: ActivityAdmin.set_count() missing 1 required positional argument: 'obj' Exception Location: /py/lib/python3.11/site-packages/django/contrib/admin/utils.py, line 280, in lookup_field Raised during: reversion.admin.changelist_view Python Executable: /py/bin/python Python Version: 3.11.1 Python Path: … -
datetime.datetime.now() is five minutes off
I'm currently developing a django backend. I use auto_now_add=True in my model to populate a start point on create(). I use datetime.datetime.now() to add an endpoint on update(). The entire code for that is datetime.datetime.now().replace(tzinfo=pytz.timezone(settings.TIME_ZONE). Here's an example for an instance that was created at 2023-01-21T19:26:04.561888Z and updated only seconds later. As you can see, the endpoint populated on update() is somehow before the startpoint, which is not intended behavior. Thank you -
Error while Installing Django on Visual Studio
I install Django on Visual studio but I have these errors enter image description here enter image description here Downloading virtualenv-20.17.1-py3-none-any.whl (8.8 MB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.8/8.8 MB 4.5 MB/s eta 0:00:00Collecting platformdirs<3,>=2.4 Downloading platformdirs-2.6.2-py3-none-any.whl (14 kB) Collecting filelock<4,>=3.4.1 Downloading filelock-3.9.0-py3-none-any.whl (9.7 kB) Collecting distlib<1,>=0.3.6 Downloading distlib-0.3.6-py2.py3-none-any.whl (468 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 468.5/468.5 KB 9.8 MB/s eta 0:00:00Installing collected packages: distlib, platformdirs, filelock, virtualenv WARNING: The script virtualenv.exe is installed in 'C:\Users\bienh\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed distlib-0.3.6 filelock-3.9.0 platformdirs-2.6.2 virtualenv-20.17.1WARNING: You are using pip version 22.0.4; however, version 22.3.1 is available. You should consider upgrading via the 'C:\Users\bienh\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe -m pip install --upgrade pip' command. PS C:\Users\bienh\OneDrive\Documents\Django> virtualenv env virtualenv : The term 'virtualenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + virtualenv env + ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundExceptiontype here How to do this: "Consider adding this directory to PATH or, if you prefer to suppress … -
I'm struggling with coinbase, i want to make an app using django that accept users to buy coins with cyptocurrency
i was working in a project and the client ask me to add a way to let users buy coins (coins are the balance of the users so they can buy tickets) what i want is if someone can help me to know how to do it by using coinbase because it is not possible in my country to use another way -
AttributeError Exception: Serializer has no attribute request in DRF
I have written following code in serializer where I am validating data: class MySerializer(serializers.ModelSerializer): class Meta: model = models.MyClass fields = "__all__" def validate(self, data): role = data["role"] roles = models.Role.objects.filter( -->(exception) organization=self.request.user.organization ) if role not in roles: raise serializers.ValidationError("Invlid role selected") return data But I am getting following exception: 'MySerializer' object has no attribute 'request'. And it is coming in the mentioned line. I want to access current user in validate function. How can I do that? -
Nextjs React Rollup Module You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file
I have been trying everything I can find online to solve this error. Based on what I have read this module is configured correctly, but still errors. I am using yalc to link to the main project. Using npx rollup -c --bundleConfigAsCjs to compile. Error ./node_modules/test-wordpress/dist/index.d.ts Module parse failed: Unexpected token (3:8) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | import { sendForm } from "./ContactForm7"; | import { getPage } from "./Wordpress"; > declare const _default: { | getPage: typeof getPage; | sendForm: typeof sendForm; tsconfig.json { "compilerOptions": { "target": "es5", "jsx": "react", "module": "esnext", "sourceMap": true, "declaration": true, "outDir": "dist" }, "include": [ "src" , "src/index.tsx" ] } rollup.config.cjs import typescript from '@rollup/plugin-typescript'; export default { input: { Wordpress: 'src/Wordpress.tsx', ContactForm7: 'src/ContactForm7.tsx' }, output: { dir: 'dist', format: 'cjs', sourcemap: true, }, plugins: [ typescript() ], external: ['react'], }; package.json { "name": "test-wordpress", "version": "1.0.2", "description": "Wordpress test project", "main": "./dist/index.d.ts", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/test-project/wordpress.git" }, "author": "Paul Winter", "license": "ISC", "bugs": { "url": "https://github.com/test-project/wordpress/issues" }, "homepage": … -
In Django, is it possible to see which method is generating a SQL query?
When creating a custom User (inherits from AbstractUser) we have a signal which creates a randomized password (from Django's get_random_string) and send it out in an email in a celery task to the user: # signals.py @receiver(post_save, sender=User, dispatch_uid="c_employee") def create_employee(sender, instance: User, created, **kwargs): if not instance.has_usable_password(): password = get_random_string(length=12) email_args = { # we're collecting information for the celery task "password": password, } email_send_as_task.delay( email_args, "Sending PASSWORD CREATE email to {{ instance.email }}" ) if password: logger.debug(f"CREATE PASSWORD FOR INSTANCE: {instance}") sender.objects.filter(pk=instance.pk).update(password=make_password(password)) # .update so we don't trigger signal again And looking through my (logging level DEBUG) logs, I can see the following: D0121 18:55:35.434 accounts.signals:81 CREATE PASSWORD FOR INSTANCE: Employee @ Example D0121 18:55:35.641 django.db.backends:123 (0.000) UPDATE "accounts_user" SET "password" = 'pbkdf2_sha256$260000$FKRktQOZAwQ4OjcvD3QHGn$dmg9T1Y3mEwN1nbI5W2EyOAHp2chU4MGvSlaOTORNxY=' WHERE "accounts_user"."id" = 394; args=('pbkdf2_sha256$260000$FKRktQOZAwQ4OjcvD3QHGn$dmg9T1Y3mEwN1nbI5W2EyOAHp2chU4MGvSlaOTORNxY=', 394) So far so good. But then, later in the logs, this query appears: D0121 18:55:35.770 django.db.backends:123 (0.015) UPDATE "accounts_user" SET "password" = '', "last_login" = NULL, "is_superuser" = false, "username" = 'employee@example.com', "first_name" = 'First name', "last_name" = 'Employee', "email" = 'employee@example.com', "is_staff" = false, "is_active" = true, "date_joined" = '2023-01-21T17:55:35.044046+00:00'::timestamptz, "company_id" = 20, "venue_id" = 297, "avatar" = 'users/avatar.jpg', "is_admin" = false, "is_developer" = true, "role" = 'event', … -
Django third-party library views: determining async vs sync
I want to incorporate async into my Django library. If I have a Django library that has 1) a sync view and 2) a urls.py that points to that sync view, how do I support both sync and async? Presumably, I could ask the developer to set a setting to LIBRARY_ENABLE_ASYNC, then in views.py, I could write: from django.conf import settings if settings.LIBRARY_ENABLE_ASYNC async def view(request): pass else: def view(request): pass But that doesn't seem quite... right? Admitedly, I believe because we integrate with the Django ORM, we'll be splitting the views into two separate files/directories/and urls.py files, and the developer would simply include() the correct urls.py based on whether they're using ASGI/WSGI, but in the event the above does happen, is there a better way to determine whether a user is using ASGI/WSGI? -
Django multi-language does not load the custom-translated files when changing the user language but only works when LANGUAGE_CODE explicitly set
when I change the language of the user by URL or calling translation.activate(lang_code) only the default texts are translated and the custom translation that I created not loading, but if I change the LANGUAGE_CODE to the target language in the settings file the translation shows without any issue. but I want when to change the user language show the custom translations that I create its my model: from django.db import models from django.utils.translation import gettext as _ class Test(models.Model): test = models.CharField( max_length=100, verbose_name=_("test text"), ) my admin: from django.contrib import admin from lng.models import Test @admin.register(Test) class TestModelAdmin(admin.ModelAdmin): ... my settings: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', "django.middleware.locale.LocaleMiddleware", # Here ! 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ BASE_DIR / 'locale/', ] my urls : from django.urls import path ,include from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] translatable_urls = [ path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns(*translatable_urls) my project structure: . ├── db.sqlite3 ├── lng │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ └── __init__.py │ ├── models.py │ ├── tests.py … -
Using if statement in django template to detect a NULL
My web application stores dances and the YouTube link to that dance. The table shows the dance name and a link to the video which is passed to a new page to show the embedded video. This all works fine but some dances do not have a video and the return from the database for video_id is NULL.as below http://localhost:8000/video_test/HjC9DidEwPc,%20Big%20Blue%20Tree --- with video or http://localhost:8000/video_test/NULL,%20Baby%20Kate ---- with no video I want include a test for the null in the template which tabulates the dances so that the link does not appear if no video tabulated output is the word video is a link to video_test Column A Column B The dance name Video The dance name Video I have tried using {% if i.video == NULL %} is NULL, is None, but none work.I have looked at various other questions which seem to suggest that one of the above should work. I either get an unable to parse error or the if statement has no effect. . Model class Dances(models.Model): name = models.CharField('name', max_length=120) video_id = models.CharField('video_id', max_length=50) level = models.CharField('level', max_length=3) def __str__(self): return str(self.name) view def video_test(request, id, name): vid_id= id d_name = name return render(request, 'alineapp/video_test.html',{'vid_id':vid_id, 'd_name':d_name}) … -
how to display in models img to html in django
I tried to display to html changeable profile image with admin. can someone explain please models in Portfolio app : class ProfileImage(models.Model): profile = models.ImageField(("Profile image"), upload_to=None, height_field=None, width_field=None, max_length=None) this is base html in template folder (i tried this one) : <img src="{{ portfolio.models.ProfileImage.progile.url }}" alt="profile"><br /> -
Increment field value by 1 from the last value if a boolean field is checked - Django
I have a simple model of application: class Application_data(Models.model): application_sn=models.AutoField(primary_key=True) applicant_name=models.CharField(max_length=20) sanction_sn=models.IntegerField(default=0) is_sanctioned=models.BooleanField(default=False) In this model, I may have multiple applications, not sanctioned. I want that if I set is_sanctioned as true,sanction_sn gets incremented by 1, and for the next random row from the db, if I set the boolean as true, sanction_sn gets again incremented by 1, i.e. 2. And setting boolean as False should also decrease the values of sanction_sn, accordingly. For example: in a set of 130 rows, at 124th sanction_sn, I set the boolean as False, so 123 records before that particular record, have no effect at all but after 123, 125th record will have sanction_sn as 124 and 130th record will have sanction_sn as 129. -
Install Django on Visual studio
I install Django on Visual studio but I have these errors enter image description here How to do this: "Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location." Could you please help me to fix them? Thank you very much