Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How use FOR statement with continue/escape/break in this code Django?
I am developing a template in Django. In this template, I receive a list of bibliographies and a list of already associated bibliographies. I need to write a specific button inside the TD for when the bibliography is already associated. However, since Django does not provide any structure like break or continue in the FOR command, I am completely lost on how to do this. As it stands, it will eventually plot more than one button on the screen. Can someone help me solve this? I have already tried making custom filters, but I couldn't solve the problem. {% for bibliografia in page_obj %} <tr> <td>{{ bibliografia.titulo }}</td> <td>{{ bibliografia.autores }}</td> <td>{{ bibliografia.editora }}</td> <td>{{ bibliografia.ano }}</td> <td> {% if bibliografia.tipo_nome == 'Eletrônico' %} ∞ {% else %} {{ bibliografia.exemplares }} {% endif %} </td> <td>{{ bibliografia.tipo_nome }}</td> <td> {% if bibliografias_ja_associadas|length > 0%} {% for bib_associada in bibliografias_ja_associadas %} {% if bibliografia.id == bib_associada.id %} <button class="btn btn-secondary btnAssociacaoBibliografia" data-id="{{ bib_associada.ementa_bibliografia_id }}" data-bibliografia-id="{{ bibliografia.id }}" data-action="remover">Já associado como {{ bib_associada.categoria_nome }}</button> {% else %} <button class="btn btn-primary btnAssociacaoBibliografia" data-id="{{ bibliografia.id }}" data-bibliografia-id="{{ bibliografia.id }}" data-action="associar">Associar</button> {% endif %} {% endfor %} {% else %} <button class="btn btn-primary btnAssociacaoBibliografia" data-id="{{ … -
How to add a ForeignKey field to be saved in ModelForm Django?
While creating my website, I face the following problem: a user can add an article, and so the article model has a ForeignKey field - author. I created a form for adding it, inheriting from ModelForm, since I think it is more logical that way (as it interacts directly with db). The problem is that I cannot add this field to the Form, as it cannot be filled; it has to be taken from the request itself. author = request.user.pk So how can I make a form save the author id as well? Without it, there's an error: NOT NULL CONSTRAINT FAILED, which is logical as the form doesn't save pk and so it is null; but a FOREIGN KEY cannot be null. The only way is to inherit it from class Form? I don't really want to do it... I was thinking about 'overriding' method save() so that it has one more argument - author id: form.save(author=request.user.pk) This way it would work. But I changed my mind, because if something goes wrong, this will mess up the whole database... The save() method is too global. What's more, there might well be another way to solve my problem, which is … -
Trying to redirect using api
enter image description herehere I am trying to use a api to redirect to another url if a particular condition passes.In the first case if profile is already complete then it will redirect to home page if not then it must redirect me to profile completion page.Is there any changes in code I used do to achieve this I tried this code and applied the logic but in postman I'm unable to test this. How to solve this issue -
Find SQLite3 database location in Django project unit tests
I am trying to add more tests for this django project. I am struggling to load SQLite database and debug. A easy way to debug would be accessing the SQLite3 database during testing. How do I find SQLite3 database location in Django project unit tests and see if my endpoints are being tested as I expect? For example, the contest.py has from django.test import Client client = Client() Is there a way of reverse engineer this class and find the sqlite3 storage file? -
Remove model created with choices and the choices too
Sometime ago I created a model with some choices: class MyEnum(StrEnum): CREATE = "create" DELETE = "delete" class ShareHistory(models.Model): action = models.TextField(choices=MyEnum.get_choices()) created_at = models.DateTimeField(auto_now_add=True, auto_created=True) After some time I understood that I don't need that model. So I can just remove the class, run makemigrations, then run migrate and that is all, the table is gone. But I want to remove the choices too (MyEnum). If I do that the next time someone runs the migrations from scratch will receive an error, because the initial migration needs MyEnum. Is there a way to remove that? -
django payment, user balance [closed]
for example, I have a simple website where there is a list of posts, they are of two types: paid and free, paid ones can be purchased by authorized users and then they can read it, free ones can be read by anyone, after registration, all authorized users will have their own balance, there will be a payment system, and each authorized user can deposit at least 5$, after payment, so that the amount he deposited will be credited to his account, how can I implement this and what technologies do I need to use and what should I pay attention to? -
Initializing a Bokeh AjaxDataSource: source callback not receiving parameters on initialization
I have a Bokeh vbar plot in a figure which gets its data from an AjaxDataSource via a JavaScript callback. It works OK after resizing, but initializing the plot fails with a MultiValueDictKeyError, apparently because my callback function is being called without any of the necessary GET parameters being passed to it. (The error is in the line Amin = float(request.GET["Amin"] of the function ajax_data). How do I configure the plot so that it is initialized correctly on first loading? Here is my (anonymised) code: def plot(request): partnerID = int(request.GET['partnerID']) Amin, Amax, Bmax = 0, 50, 0.01 bokeh_html = get_bokeh_html(Amin, Amax, Bmax) c = {"bokeh_html": bokeh_html} c["bokeh_js"] = (f'<script src="https://cdn.bokeh.org/bokeh/' f'release/bokeh-{settings.BOKEH_VERSION}.min.js"' f' type="text/javascript"></script>') return render(request, 'myapp/plot.html', c) def get_bokeh_html(Amin, Amax, Bmax): fig = bp.figure( frame_width=1000, frame_height=800, title="PLOT", tools="box_zoom,wheel_zoom,reset", x_axis_label="Abcissa", y_axis_label="Data axis", ) fig.toolbar.logo = None fig.x_range = Range1d(Amin, Amax) fig.y_range = Range1d(0, Bmax) source = AjaxDataSource( method="GET", data_url=reverse("myapp:ajax_data"), name="ajax_plot_data_source", polling_interval=None, ) r = fig.vbar( x="x", top="top", width=f"width", source=source, ) callback = CustomJS( args=dict(xr=fig.x_range), code=""" $.ajax({ url: 'ajax-data', data: { 'Amin': xr.start, 'Amax': xr.end, 'partnerID': 2 }, success: function (data) { var ds = Bokeh.documents[0].get_model_by_name('ajax_plot_data_source'); ds.data = data; } }); """, ) fig.x_range.js_on_change("start", callback) fig.legend.click_policy = "hide" bokeh_script, bokeh_div = components(fig) … -
Remote Video Not Displaying in Django WebSockets Video Call Implementation
I'm trying to build a video call feature for two users (local and remote peers) using Django, WebSockets, HTML, and JavaScript. The local video is working fine, but the remote video is not showing up even though its exists. I'm getting the following error: Error: DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable The error occurs in this snippet of code: function handleAnswer(answer) { console.log('Handling answer:', answer); if (peerConnection.signalingState !== 'have-local-offer') { console.warn('Unexpected signaling state:', peerConnection.signalingState, 'Answer ignored.'); return; } peerConnection.setRemoteDescription(new RTCSessionDescription(answer)).then(() => { console.log('Remote description set for answer:', answer); }).catch(error => { console.error('Error setting remote description for answer:', error); }); } HTML: <div class="video-root" id="vid-area"> <div class="username-wrapper"><span class="user-name">+11ß</span></div> <video class="video-player" id="consultant" autoplay playsinline></video> <!-- Here where the remote comes in --> <div id="remoteVideoFrame" class="smallFrame" style="display : none;"> <video class="video-player" id="client" autoplay playsinline></video> </div> <div class="controls-wrapper"> <div class="icon-wrapper"> <i class='bx bx-microphone control-icon' id="mic-btn"></i> </div> <div class="icon-wrapper"> <i class='bx bx-camera-home control-icon' id="camera-btn"></i> </div> <div class="icon-wrapper"> <i class='bx bx-screenshot control-icon' id="screen-share"></i> </div> <div class="icon-wrapper"> <i class='bx bx-phone-off control-icon' id="leave-btn"></i> </div> </div> </div> JavaScript: document.addEventListener('DOMContentLoaded', function () { var loc = window.location; var wsStart = loc.protocol === 'https:' ? 'wss://' : 'ws://'; var … -
Django + VueJS multiple user type
I'm having a problem in Vue.js with handling multiple users. Before transitioning to this integration, my previous authentication used mixins to handle privileges for each user. Now, I want to use Vue as the frontend, but I'm unsure how to integrate it. I'm using the following user roles: #models.py class User(AbstractUser): is_secretary = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) contact_number = models.CharField(max_length=20, blank=True, null=True) REQUIRED_FIELDS = [] def user_type(self): if self.is_superuser: return "Superuser" elif self.is_secretary: return "Secretary" elif self.is_staff: return "Staff" else: return "User" def __str__(self): return f"{self.first_name} {self.last_name} ({self.user_type()})" I'm using serializers to manage user data. How should I handle this in Vue.js? Any advice or examples would be appreciated. Depending on each user's role, I want to redirect them to their specific dashboard. -
Best Server Configuration For Django
I am new at programing and I want to deploy my first project with django. I have a VDS server that i want to configure for multiple django projects which i will deploy first one. but I am not sure about which linux os or server to prefer. Thanks for answers. I installed cloudlinux, cpanel and nginx but im having issue with delivering static and media files so i want to configure server once to make it easier to deploy new apps in future. -
Why is everything grouped under "api" in Swagger UI with no division between task and subtask?
I'm working on documenting an API using Swagger UI. However, I've noticed that all endpoints are grouped under a single "api" section. There are no separate divisions for different resources such as "task" and "subtask". This makes the API documentation harder to navigate and understand. settings.py REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/schema/', SpectacularAPIView.as_view(), name='api-schema'), path('api/docs/', SpectacularSwaggerView.as_view(url_name='api-schema'), name='api-docs'), path('api/users/', include('user.urls')), path('api/tasks/', include('task.urls')), path('api/subtasks/', include('subtask.urls')), ] task\urls.py router = DefaultRouter() router.register('', views.TaskViewSet) app_name = 'task' urlpatterns = [ path('', include(router.urls)), ] -
How to apply ordering based on another model field data in DRF?
I am trying to develop an API to filter JobApplication model data, and facing problem to ordering the response data for a custom field. Here is my JobApplication model. class JobApplication(models.Model): job_post = models.ForeignKey(JobPost, on_delete=models.CASCADE) job_seeker = models.ForeignKey(AppUser, on_delete=models.CASCADE) applied_date = models.DateField(auto_now_add=True) experience = models.PositiveSmallIntegerField(null=True, blank=True) And filter models is: class JobApplicationFilter(django_filters.FilterSet): gender = django_filters.CharFilter(field_name='job_seeker__personaldetails__gender') age = django_filters.NumberFilter(field_name='job_seeker__personaldetails__age', lookup_expr='lte') experience = django_filters.NumberFilter(field_name='experience', lookup_expr='lte') class Meta: model = JobApplication fields = ['gender', 'age', 'experience'] And the views is: class JobApplicantFilterListView(generics.ListAPIView): serializer_class = JobApplicationSerializer filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_class = JobApplicationFilter pagination_class = CustomPageNumberPagination ordering_fields = ['age','experience'] Now I want to add a filed as full_name in JobApplicationFilter class, Where full_name field will generate from first_name and last_name fields from PersonaDetails model. And finally use this full_name field to ordering the response data. -
Django send mail works in localhost but not on server
I recently started to learn Django and I wrote a code to send an email in contact us page and it works fine in my localhost but when I uploaded it onto server it gave this error: SMTPServerDisconnected at /contact Connection unexpectedly closed this is my settings.py code: EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my@gmail.com' EMAIL_HOST_PASSWORD = 'app passwords' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' and this is my views.py send_mail('title', 'message', userEmail, [settings.EMAIL_HOST_USER], fail_silently=False,) I talked to the support group of my host server to check the ports but they said it was okay so I don't know if I'm missing something or not. -
Blocked a frame with origin "http://127.0.0.1:8000" from accessing a cross-origin frame. ((Django cors headers, S3 cors policy))
https://sparta-games.net/games/list/47/ <-- !! Sound Too Loud !! I'm trying to lower the sound of iframe or the whole page. The exact error message: 47/:644 Uncaught DOMException: Failed to read a named property 'AudioContext' from 'Window': Blocked a frame with origin "http://127.0.0.1:8000" from accessing a cross-origin frame. at iframe_element.onload (http://127.0.0.1:8000/games/list/47/:644:58) Iframe is a Unity WebGL game which is coming from S3 bucket. I'm using Django, EC2, mobaXterm, S3, nginx, gunicorn, RDS. (Windows11) My settings Django settings.py: INSTALLED_APPS = [ ..., "corsheaders", ..., ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ..., 'django.middleware.common.CommonMiddleware', ..., ] X_FRAME_OPTIONS = 'SAMEORIGIN' CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000", ] S3 CORS policy: { "CORSRules": [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "PUT", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [ "x-amz-server-side-encryption", "x-amz-request-id", "x-amz-id-2" ], "MaxAgeSeconds": 3000 } ] } versions: Django==4.2 django-cors-headers==4.3.1 Sending header through views.py like below didn't help either. def my_view(request): response = JsonResponse({'message': 'Hello, world!'}) response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8000' response['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS' response['Access-Control-Allow-Headers'] = 'Content-Type' return response I can't find the exact case like this. Recursively asked ChatGPT to solve it. django-cors-headers, s3 policy, directly sending headers, cors whitelist,... didn't get the problem. In fact, this also happen when user to modify and submit any … -
0 static files copied to 'C:\Users\Reynald\Desktop\Test\cdo_portal\staticfiles', 2365 unmodified
Hello everyone might someone here know how to fix this i just trying to run the py manage.py collectstatic but when i run the sytsem all of the design was a mess and when i check the collecstatic "0 static files copied to 'C:\Users\Reynald\Desktop\Test\cdo_portal\staticfiles', 2365 unmodified." not sure of that I already tried another way to fix this but still not working -
%20 in my url to static javascript file in django application
I have base template core/layout.html and it contains scripts block in it: <script type="text/javascript" src="{% static "core/js/tinymce/tinymce.min.js" %}"></script> <script src = "{% static "core/js/flowbite.min.js" %}"></script> <!-- <script src = "{% static "core/js/index.js" %}"></script> --> {% block scripts %} {% endblock scripts %} So the problem is in url to javascript file (index.js). If I include it in layout.html (base template) everything works perfect, but when i put it in my child template: {% block scripts %} <script src="{% static 'core/js/index.js' %}"></script> {% endblock scripts %} it throws an error: GET 127.0.0.1:8000/static/%20core/js/index.js net::ERR_ABORTED 404 (Not Found) I even have tried to hard code it, still the same problem. -
Mark a view function as being exempt from the CSRF view protection
(function) def csrf_exempt(view_func: _F@csrf_exempt) -> _F@csrf_exempt Mark a view function as being exempt from the CSRF view protection. Make sure disabling CSRF protection is safe here. sonarlint(python:S4502) How to fix this issue on sonarcloud?. (function) def csrf_exempt(view_func: _F@csrf_exempt) -> _F@csrf_exempt Mark a view function as being exempt from the CSRF view protection. Make sure disabling CSRF protection is safe here. sonarlint(python:S4502) -
why does my SQLlite database in django does not show the same records when I run it on a different machine; (running the server on Local Host)
So I am trying to build a basic Task managing app. The main issue is with the database, me and my friend have the exact same code we pulled from the rep, when he and I run the server on local host and try using the website, like creating account and adding tasks, but when we open the admin panel I can only see my tasks and the accounts in the User Database that were created on my machine, and my friend can see the accounts and tasks created on his machine, though our databases are same, they are not displaying the same records, this wasn't an issue before, if he would add a task and create account I can see it in my admin panel thru my machine and vice versa, I don't exactly know what happened. its like the databases are not synced are being emptied everytime you run the website on a different machine. this is giving us trouble, because we are working on an invite feature when you can enter a users email in a specific task then that user would start seeing the task on his machine, since the databases are not in sync the … -
Django model field "null together or not at all" constraint
I need a way to create either a validator or a constraint at model level to evaluate two or more fields to be able to be null/blank only if all of them are null/blank at the same time. For example, in the next model: from django.db import models class Example(models.Model): A = models.CharField(max_length=16,blank=True) B = models.DateField(null=True,blank=True) C = models.FileField(uploadto='/',null=True) if I try to create a new Example with either B or C values empty it should raise a ValidationError; but if both of them are empty it should be OK. -
SynchronousOnlyOperation Error in Django Class Based Views
I am making a Django app, but I can't use async views, I installed uvicorn and asgi, but I get this error: SynchronousOnlyOperation at /chatbot/chat/ You cannot call this from an async context - use a thread or sync_to_async. @method_decorator(login_required(login_url=settings.LOGIN_URL), name='dispatch') @method_decorator(never_cache, name='dispatch') class ChatView(View): async def get(self, request, *args, **kwargs): """ This method return our chatbot view """ response = await sync_to_async(render)(request, 'chatbot/chat.html') return response -
cv2.error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\qrcode.cpp:32: error: (-215:Assertion failed) !img.empty()
i write a bot to decode qr-codes from user's message and send im data back. now i have an error cv2.error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\objdetect\src\qrcode.cpp:32: error: (-215:Assertion failed) !img.empty() in function 'cv::checkQRInputImage' code: @decode_router.message(lambda message: True) async def decode(message: Message): await main.bot.send_message(message.chat.id, "Decoding...") fl = main.bot.download_file(message.photo, f"qrcode{message.from_user.id}.png") fl = FSInputFile(f"qrcode{message.from_user.id}.png", f"qrcode{message.from_user.id}.png") img = cv2.imread(f"qrcode{message.from_user.id}.png") detector = cv2.QRCodeDetector() data, vebb, f = detector.detectAndDecode(img) await message.reply(data) what that error means and what should i do to fix it? -
Google authentication with django-allauth fails due to "OAuth2Error: Invalid id_token"
I am trying to set-up Google authentication for my DRF + Next.js web app. I've been following this guide. I am using django-allauth 0.61.1 and dj-rest-auth 6.0.0. If I try to pass both access and it tokens: ... const SIGN_IN_HANDLERS = { credentials: async (user, account, profile, email, credentials) => { return true; }, google: async (user, account, profile, email, credentials) => { try { const response = await axios({ method: "post", url: process.env.NEXTAUTH_BACKEND_URL + "auth/google/", data: { access_token: account["access_token"], id_token: account["id_token"], }, }); account["meta"] = response.data; return true; } catch (error) { console.error(error); return false; } }, }; const SIGN_IN_PROVIDERS = Object.keys(SIGN_IN_HANDLERS); export const authOptions = { pages: { signIn: "/login", }, secret: process.env.AUTH_SECRET, session: { strategy: "jwt", maxAge: BACKEND_REFRESH_TOKEN_LIFETIME, }, providers: [ CredentialsProvider({ name: "Credentials", credentials: {}, async authorize(credentials, req) { console.log("here"); try { const response = await axios({ url: process.env.NEXTAUTH_BACKEND_URL + "auth/login/", method: "post", data: credentials, }); const data = response.data; if (data) return data; } catch (error) { console.error(error); } return null; }, }), GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, authorization: { params: { prompt: "consent", access_type: "offline", response_type: "code", }, }, }), ], callbacks: { async signIn({ user, account, profile, email, credentials }) { if (!SIGN_IN_PROVIDERS.includes(account.provider)) … -
How to add permissions in django admin panel for user?
I have a django app. And I added in the admin panel of django the following permission: Accounts | account | Can view account And in the code of admin.py of the accounts app. I added this: from django.contrib.auth import get_user_model from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from .models import Account User = get_user_model() user = User.objects.get(email='n@n.nl') content_type = ContentType.objects.get_for_model(Account) permission = Permission.objects.get( codename='view_account', content_type=content_type) user.user_permissions.add(permission) class AccountAdmin(UserAdmin): list_display = ( "email", "first_name", "last_name", "username", "last_login", "date_joined", "is_active", ) list_display_links = ("email", "first_name", "last_name") filter_horizontal = ( 'groups', 'user_permissions', ) readonly_fields = ("last_login", "date_joined") ordering = ("-date_joined",) list_filter = () User = get_user_model() user = User.objects.get(email='n@n.nl') content_type = ContentType.objects.get_for_model(Account) permission = Permission.objects.get( codename='view_account', content_type=content_type) user.user_permissions.add(permission) admin.site.register(Account, AccountAdmin) And when I start the django app. I don't get any errors. But when I login with the account with the user permission. I still see the message: You don’t have permission to view or edit anything. And the permissions: Is active Is staff are selected Question: how to add permissions for users? -
how to force a maximum map extent for geonode docker?
I’m running geonode docker, how do I need to modify the .env file to force a maximum map extent (e.g. Italy)? This is my local installation procedure using the default .env git clone -b 4.0.2 https://github.com/GeoNode/geonode.git cd .\geonode\ docker compose build docker compose up -d I modify the .env and run docker compose down and docker compose up -d (https://docs.geonode.org/en/master/install/basic/index.html#customize-env-to-match-your-needs) ADMIN_PASSWORD=admin4 # works and takes effect DEFAULT_MAP_ZOOM=10 # works and takes effect DEFAULT_MAP_CENTER_X=50 # does not work (if this does not work how can max force extent work) DEFAULT_MAP_CENTER=50 # does not work What are variable names and how to use them to force a maximum map extent ? -
Django random can't connect to mysql
In django I'm getting can't connect to mysql randomly it works fine and just gives it to me and on refresh it works fine, completely random, I can't even reproduce it. any ideas? compose file: networks: my_network: driver: bridge ipam: config: - subnet: 172.16.238.0/24 gateway: 172.16.238.1 services: web: extra_hosts: - "host.docker.internal:host-gateway" networks: my_network: ipv4_address: 172.16.238.6 restart: always depends_on: - db env_file: - ./backend/.env image: project-api build: context: . dockerfile: backend/Dockerfile.dev command: bash -c "python manage.py migrate && python manage.py collectstatic --noinput && gunicorn project.wsgi -b 0.0.0.0:9001" volumes: - ./backend:/code - ./backend/logs:/logs db: image: mysql:8.0 command: mysqld --default-authentication-plugin=mysql_native_password restart: always volumes: - ./backend/data:/var/lib/mysql - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql networks: my_network: ipv4_address: 172.16.238.9 environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: dev_db MYSQL_USER: dev_db_user MYSQL_PASSWORD: root