Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Render HTML Templates in Django?
I have been trying to display html templates of Login and Register for an ecommerce website, using Django Framework and Python as server side scripting language. I want to make sure that If Users logs in using its email address and password then It should be redirected to its dashboard. New User has to first register then that user is allowed to login. I'm done with the backend coding of the templates, but now able to display UI first so that I can try to login from html template and the desired result should be display in default database of the Django. How I can do this? -
Error: must include rest_framework.authtoken in INSTALLED_APPS or set TOKEN_MODEL to None
I have a problem with the rest_framework_simplejwt package. I installed it and configured everything. and I am encountering an error. django.core.exceptions. ImproperlyConfigured: You must include rest_framework.authtoken in INSTALLED_APPS or set TOKEN_MODEL to None. this is my settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'dj_rest_auth.jwt_auth.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } REST_AUTH_TOKEN_MODEL = None REST_USE_JWT = True SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=5), } -
How to Display the Size of a file in Django
I have a pdf file in my media directory that i want users to download, the issue is that, how can i make the users see the size of the file so they are aware of the size of what they want to download. Also, is it better to create a model for the pdf file as shown below in models.py? What is the best approach to handle this. I need help. models.py (this is not part of my code for now) class PersonalStatement(models.Model): personal_statement = models.FileField(upload_to='personal_statement/') title = models.CharField(max_length=50) views.py def personal_statement_download(request): BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = 'Writing-a-Personal-Statement.pdf' filepath = BASE_DIR + '/media/personal_statement/' + filename path = open(filepath, 'rb') mime_type, _ = mimetypes.guess_type(filepath) response = HttpResponse(path, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response urls.py path('personal_statement/download/', views.personal_statement_download,name='personal_statement_download'), templates/index.html <a href="{% url 'personal_statement_download'%}" class="applyRightContentContainerSubDownloadLink"> Download File &#8681;</a> -
Run management commands on Django server in a Linux hosted App Service in Azure. Anything other than cronjobs?
Please Excuse me if this question has been posted before.I have a linux hosted App Service in Azure running a Django server. I want to run a management command periodically on the server. I am somewhat of an inexperienced person as far as cloud and architechure goes. So please be as elaborate as possible, mentioning the reasoning behind your recomendations, so that I can learn more. Tried using Cronjobs but it was not consistent and I did not have access to logs. Can't use Webjobs since the app service is on a linux machine and webjobs aren't supported on linux machines. Have read that funtions can be used. If so please point me in the right direction on how to setup and connect function to the App service and run command. -
ajax comment in django
I am trying to create a comment on a post in my Django application. I have a working form for the comment, but when I submit the form, I get an error message. The error message is: {"response": "forbidden"} I have checked my code and I am sure that the form is valid and that the request is being sent to the correct URL. I have also checked the permissions for the user who is trying to create the comment, and they are logged in and have the appropriate permissions. I am not sure what is causing the error. Can anyone help me? Code: class CommentForm(forms.ModelForm): author = forms.CharField(required=True, error_messages={'required': 'لطفاً نام خود را وارد کنید.'}) body = forms.CharField(required=True, error_messages={'required': 'لطفاً نظر خود را وارد کنید.'}) class Meta: model = Comment fields = ('author', 'body', 'post') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cleaned_data = {} def clean_author(self): author = self.cleaned_data.get('author', 'نام کاربری ناشناس') return author def clean_body(self): body = self.cleaned_data.get('body') return body function comment(slug, id) { var comment = document.getElementById("comment").value; $.post(`/posts/post/${slug}/comment/create/${id}`, { comment: comment }).then(response => { if (response['response'] === 'created') { var count = document.getElementById("count"); count.innerText = Number(count.innerText) + 1; document.getElementById("comment").value = ""; } else { var errors = … -
User Profile not updating and no errors is given
I am having an issue while i want to update my user profile in my django project. It is not updating, not saving to the database and not showing any error in the terminal. Here is the form: from django import forms from .models import CustomUser, Profile class UserUpdateViewForm(forms.ModelForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) phone_number = forms.CharField(max_length=20, required=False) address = forms.CharField(max_length=100, required=False) class Meta: model = Profile fields = ['image', 'first_name', 'last_name', 'address', 'phone_number'] Here is the View: from django.forms.models import BaseModelForm from django.http import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView, UpdateView from .models import CustomUser,Profile from .forms import UserUpdateViewForm class UserProfileView(LoginRequiredMixin, TemplateView): template_name = 'account/account.html' # Change this to the template name you want to use def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user_profile'] = self.request.user # Assumes a one-to-one relationship between CustomUser and Profile return context class UserProfileUpdateView(LoginRequiredMixin, UpdateView): model = Profile form_class = UserUpdateViewForm template_name = 'account/update_profile.html' def get_object(self, queryset=None): # Get the user's profile to be updated return self.request.user.profile def form_valid(self, form): self.object = form.save() success_url = reverse_lazy('profile_page') return HttpResponseRedirect(success_url) Here is the template too {% extends 'base/base.html' %} {% load static %} … -
Why is my django-channels project not able to connect to Websockets in my Heroku deployed site?
I've been stuck at this for daaaays now and I realise that solution is probably simple but I no matter how much I read here and try I get the same error... When loading the chats part of my site I get this error in the dev tools console: WebSocket connection to 'wss://vareberg-games-a44cb52aa87b.herokuapp.com/wss/chat/' failed: (anonymous) @ chats/:131 and line 131 in the chats.html is inside the script tags and looks like this: const chatSocket = new WebSocket('wss://' + window.location.host + '/wss/chat/'); This is all the files I think are relevant to get help: The projects settings.py file: from pathlib import Path import os import dj_database_url if os.path.isfile('env.py'): import env # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['vareberg-games-a44cb52aa87b.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'profiles', 'events', 'channels', 'chats', ] SITE_ID = 1 LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL … -
Payment Intent value is null Stripe Django
I successfully created a checkout session, but when I checked the payment_intent value, it was coming out as null. Here's the code I used: @csrf_exempt def create_checkout_session(request,id): request_data = json.loads(request.body) order = Order.objects.filter(id = id).last() stripe.api_key = PaymentConfig.objects.all().last().stripe_secret_key checkout_session = stripe.checkout.Session.create( # Customer Email is optional, # It is not safe to accept email directly from the client side customer_email=request_data['email'], payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': str(order.amount_type.lower()), 'product_data': { 'name': order.plan.title, }, 'unit_amount': int(order.amount * 100), }, 'quantity': 1, } ], mode='payment', success_url=request.build_absolute_uri( reverse('paymentsuccess') ) + "?session_id={CHECKOUT_SESSION_ID}", cancel_url=request.build_absolute_uri(reverse('paymentfailed')), ) order.stripe_payment_intent = checkout_session['payment_intent'] print(payment_intent) -- **null value** order.save() return JsonResponse({'sessionId':checkout_session.id}) It's essential to get this value and save it in the order object so that I can access the order in the handler view after payment. Here's the handler view's code: class PaymentSuccessView(TemplateView): template_name = "v3/payment-successful.html" def get(self, request, *args, **kwargs): session_id = request.GET.get('session_id') if session_id is None: return HttpResponseNotFound() stripe.api_key = PaymentConfig.objects.all().last().stripe_secret_key session = stripe.checkout.Session.retrieve(session_id) order = get_object_or_404(Order, stripe_payment_intent=session.payment_intent) --**HERE** call=AfterPaymentBackend(request, order.id) ctx = { 'order':order, 'siteInfo':Company.objects.all().last() } return render(request, self.template_name, ctx) Is there something I'm overlooking? Thanks. I tried asking chat GPT for the help but AI isn't that much powerful. I tried searching on google but couldn't find … -
user need to submit the feedback and in my models I'm having user field which is associated with User instance, now don't want to expose my user filed
Users need to submit feedback, and in my models, there's a "user" field associated with a User instance. I want to ensure that this "user" field remains confidential, so it is not identifiable to other individuals when they access the database. Additionally, I need a mechanism to prevent users from submitting feedback more than once. Validation should be in place to ensure that feedback can only be submitted once. Here is what I tried models.py class Trainer_Feedback(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) satisfaction_rate = models.IntegerField() addressed_questions_or_not = models.CharField(max_length=10) were_training_materials_clear_ornot = models.CharField(max_length=10) were_training_engaging_interactive = models.CharField(max_length=10) opportunity_given_to_participate_or_not = models.CharField(max_length=10) training_content_meet_expectation_ornot = models.CharField(max_length=10) complex_concepts_clearly_explained_ornot = models.CharField(max_length=10) which_activity_method_you_found_beneficial = models.CharField(max_length=10) aspects_of_training_which_could_improved = models.TextField() Suggestions= models.TextField() views.py @csrf_exempt def trainer_feedback(request): try: if request.method == 'POST': data = json.loads(request.body) session_id = data.get('session_id') try: user = validate_session(session_id) except ObjectDoesNotExist: return JsonResponse({'message': 'Invalid session ID'}, status=401) existing_feedback = Trainer_Feedback.objects.filter(user=user).first() if existing_feedback: return JsonResponse({'message': 'Feedback already submitted by this user'}, status=400) feedback = data.get('feedback') satisfaction_rate = feedback.get('1') addressed_questions_or_not = feedback.get('2') were_training_materials_clear_ornot = feedback.get('3') were_training_engaging_interactive = feedback.get('4') opportunity_given_to_participate_or_not = feedback.get('5') training_content_meet_expectation_ornot = feedback.get('6') complex_concepts_clearly_explained_ornot = feedback.get('7') which_activity_method_you_found_beneficial = feedback.get('8') aspects_of_training_which_could_improved = feedback.get('9') Suggestions = feedback.get('10') feedback_data = Trainer_Feedback( user=user, satisfaction_rate=satisfaction_rate, addressed_questions_or_not=addressed_questions_or_not, were_training_materials_clear_ornot=were_training_materials_clear_ornot, were_training_engaging_interactive=were_training_engaging_interactive, opportunity_given_to_participate_or_not=opportunity_given_to_participate_or_not, training_content_meet_expectation_ornot=training_content_meet_expectation_ornot, complex_concepts_clearly_explained_ornot=complex_concepts_clearly_explained_ornot, which_activity_method_you_found_beneficial=which_activity_method_you_found_beneficial, aspects_of_training_which_could_improved=aspects_of_training_which_could_improved, Suggestions=Suggestions ) feedback_data.save() … -
Page not found in database
Page inside the database is not being accessed by the server using Django framework. Why am I getting this error? Tried all methods and error checks to find a solution to the problem, but I couldn’t find any solution to the problem. -
DRF generateschema - change example domain and customise
When I run generateschema command in DRF, it produces YAML file with example containing example.com responses: '200': content: application/json: schema: type: object properties: count: type: integer example: 123 next: type: string nullable: true format: uri example: http://api.example.org/accounts/?page=4 previous: type: string nullable: true format: uri example: http://api.example.org/accounts/?page=2 results: type: array items: $ref: '#/components/schemas/Book' description: '' How can I make it to mydomain.com ? How can I customise the schema in general? Ideally without introducing another library? Thanks -
I implemented auto save function in my Django 4 web app using js and django view function but it keep saving new model instances at every interval
I have implemented auto save feature in my Django 4 web app using javascript and Django views.py function as the end point.I got it to save the form / model instances to database, bypassing the django forms validation. The problem now is that it keep saving new instances at every interval. The correct behavior is to create the first instance and at subsequent interval only update the database with new data if there has been changes since the last auto save. The problem is i don't know how to store the id of the model instance that was just created so that at every call of the auto save javascript i can check if this auto save request a new request or existing request. I have not tried anything yet at this point. Getting it to this point where I can save the unchecked form/model instance already took a lot of time for me. -
An error occurred on the migration command in dajngo throungt Sharding-Proxy to connect postgresql
When django connects directly to PG, execute python manage.py migrate and everything works fine. But when django adds shardingsphere-proxy, executing command return an error environment: - Django 3.2.12 - psycopg2-binary 2.8.6 - psycopg2-binary 2.8.6 - apache/shardingsphere-proxy 5.4.1 - postgres 11.14 exception detail: Traceback (most recent call last): File "/data/code/dtmg/.env/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/data/code/dtmg/.env/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/data/code/dtmg/.env/lib/python3.9/site-packages/django/db/backends/base/base.py", line 202, in connect self.init_connection_state() File "/data/code/dtmg/.env/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 224, in init_connection_state timezone_changed = self.ensure_timezone() File "/data/code/dtmg/.env/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 217, in ensure_timezone cursor.execute(self.ops.set_time_zone_sql(), [timezone_name]) psycopg2.errors.SystemError: Unknown exception: null PG timezone is Asia/Shanghai shardingsphere-proxy timezone is Etc/UTC sharding_db=> show time zone; timezone ---------- Etc/UTC (1 row) and in ensure_timezone function: def ensure_timezone(self): if self.connection is None: return False # conn_timezone_name = None conn_timezone_name = self.connection.get_parameter_status('TimeZone') timezone_name = self.timezone_name if timezone_name and conn_timezone_name != timezone_name: with self.connection.cursor() as cursor: cursor.execute(self.ops.set_time_zone_sql(), [timezone_name]) return True return False conn_timezone_name = None sharding-proxy log: dev_shardingsphere-proxy | [ERROR] 2023-11-04 16:37:22.657 [ShardingSphere-Command-28] o.a.s.p.f.c.CommandExecutorTask - Exception occur: dev_shardingsphere-proxy | java.util.NoSuchElementException: null dev_shardingsphere-proxy | at java.base/java.util.LinkedList$ListItr.next(LinkedList.java:894) dev_shardingsphere-proxy | at org.apache.shardingsphere.proxy.backend.postgresql.handler.admin.executor.PostgreSQLSetVariableAdminExecutor.execute(PostgreSQLSetVariableAdminExecutor.java:42) dev_shardingsphere-proxy | at org.apache.shardingsphere.proxy.backend.handler.admin.DatabaseAdminUpdateBackendHandler.execute(DatabaseAdminUpdateBackendHandler.java:44) dev_shardingsphere-proxy | at org.apache.shardingsphere.proxy.frontend.postgresql.command.query.simple.PostgreSQLComQueryExecutor.execute(PostgreSQLComQueryExecutor.java:77) dev_shardingsphere-proxy | at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.doExecuteCommand(CommandExecutorTask.java:126) dev_shardingsphere-proxy | at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.executeCommand(CommandExecutorTask.java:121) dev_shardingsphere-proxy | at org.apache.shardingsphere.proxy.frontend.command.CommandExecutorTask.run(CommandExecutorTask.java:78) dev_shardingsphere-proxy | at com.alibaba.ttl.TtlRunnable.run(TtlRunnable.java:60) dev_shardingsphere-proxy | at … -
Structure such that each column recieves a component
Here is what my Month component looks like essentially a grid with days as columns and hours of the days as rows import React from "react"; export function Month() { const currentDate = new Date(); const days = []; for (let i = 0; i < 7; i++) { const day = new Date(currentDate); day.setDate(currentDate.getDate() + i); days.push(day); } return ( <div className="container justify-content-center "> <div className="row "> <div className="col-md-1">hour</div> <div className="col "> <strong> {new Date().toLocaleDateString("en-US", { weekday: "long" })} </strong>{" "} </div> <div className="col"> <strong> {days[1].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[2].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[3].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[4].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[5].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> <div className="col"> <strong> {days[6].toLocaleDateString("en-US", { weekday: "long" })} </strong> </div> </div> <div className="row"> <div className="col-md-1">7:00</div> {days.map((day, index) => ( <div className="col pb-5 bg-light border border-dark" key={index}> {day.toLocaleDateString()} </div> ))} </div> <div className="row"> <div className="col-md-1 d-flex">8:00</div> <div className="col pb-5 bg-light border border-dark" style={{ height: "73.33px" }} ></div> <div className="col pb-5 bg-light border border-dark" style={{ height: "73.33px" }} ></div> <div className="col pb-5 bg-light border border-dark" style={{ height: "73.33px" }} … -
Django storing environment variables
I'm making a Django chat project in which all messages are encrypted when sent and decrypted when read. I have this task: “Use a standard cryptographic algorithm (such as AES) to encrypt and decrypt messages. The encryption key must be unique for each user session and stored in a secure location (for example, in environment variables or using a key management system)." I can't figure out how to store the per-session encryption key inside environment variables. My understanding is that static data like the secret key is stored inside environment variables, but it doesn't change on every session. How should I implement the functionality described in the task? -
How to redirect request from Django to FastAPI
I have a Django API and a FastAPI wrapper. Requests will be sent from clients to Django, but I want to redirect them to FastAPI to do some role check (I can't do it in Django for some reasons) then sent it back to Django. For now, I am able to sent request from FastAPI to Django using FastAPI's middleware; but I cannot write a proper middleware for Django to do the same (I am just started with Django for 1 week). Can someone please suggest a solution? -
Django PyLint: Django.core.exceptions.ImproperlyConfigured
My Django app works fine when i am just launch my application through python src/manage.py runserver But i would like to integrate pylint here, and when i launch the command pylint src --load-plugins pylint_django i got the following traceback: Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/pylint_django/checkers/foreign_key_strings.py", line 87, in open django.setup() File "/venv/lib/python3.11/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) ^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 82, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MO DULE or call settings.configure() before accessing settings. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/pylint_django/checkers/foreign_key_strings.py", line 114, in open django.setup() File "/venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load … -
Django Csv: Having trouble with writerow
This is basicly my code: def export_to_excel(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=responds.csv' writer = csv.writer(response) writer.writerow(["First row", "Foo", "Bar", "Baz"]) writer.writerow(["Second row", "A", "B", "C", '"Testing"', "Here's a quote"]) return response Everything looks ok, but when I really exported it there is something wrong: Everything in just a shell! Why? How so? What should I do? -
MultiValueDictKeyError at generated form element
This is my form: <form action="" method="POST"> {% csrf_token %} <div class="col-4"> <input type="text" name="ad" placeholder="İsim"> {% for question in model.get_questions %} <div class="question col-6"> <div class="header"> {{ question }} <input type="checkbox" name="answ{{forloop.counter0}}"> </div> </div> {% endfor %} <input type="submit" value="Gönder"> </form> When I try to get request.POST['ad'] in the views its pretty working but when I try to get like answ0 it doesnt working. That doesn't appear when I print request.POST also. This is the error I receive: MultiValueDictKeyError at /form/1 'answ0' What is the issue? -
ImportError when setting wagtail development environment : "cannot import name 'Query' from 'wagtail.search.models'"
I'm currently working on a fork of Wagtail (version 6.0a0) and attempting to set up a development environment for contributing to the project. I've followed the standard steps for setting up the project but have encountered an ImportError when running migrations for a Wagtail-based website. Steps I've Taken: Cloned the forked repository locally. Activated a Python virtual environment for my work. Installed the cloned project using "pip install -e .[testing,docs] -U." Executed "npm ci" and "npm run build" for JavaScript dependencies. Created a new Wagtail website in a separate directory. Ran "python manage.py migrate," and encountered the ImportError. Error Message: Traceback (most recent call last): File "path/to/manage.py", line 10, in ... from wagtail.search.models import Query ImportError: cannot import name 'Query' from 'wagtail.search.models' Additional Information: The released version of Wagtail (version 5.2a0) installs successfully using "pip install wagtail" without any issues. My requirements file specifies Django version 4.2, but Django version 4.0.10 is installed in my Python virtual environment.(this version was installed with the cloned wagtail project) The requirements.txt file in the website generated by Wagtail specifies the following: Django>=4.2,<4.3 // wagtail==5.2a0 I at first thought this might be a dependency versions problem because the released version works fine with the … -
How to filter ManyToMany field in Django queryset?
I have models: class VideoParameter(models.Model): member = models.ForeignKey(Tag, on_delete=models.DO_NOTHING, related_name="parameter_tag") value = models.PositiveIntegerField() class Video(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parameters = models.ManyToManyField(VideoParameter, related_name="video_parameter") url = models.URLField(verbose_name=_('Url')) (I mean that a video have some parameters like Key-Value (ex. {"rabbit": 1, "panda": 1, "lion": 0})) Then I am trying to get the video, specified by query parameter. (like this /video/?rabbit=1&panda=1&lion=0) The SQL code that I want to do is belows: SELECT app_video.id, count(*) AS match_count FROM app_video INNER JOIN app_video_parameters on app_video.id = app_video_parameters.video_id INNER JOIN app_videoparameter ON app_video_parameters.videoparameter_id = app_videoparameter.id WHERE (app_videoparameter.member_id = 1 AND app_videoparameter.value = 0) OR (app_videoparameter.member_id = 9 AND app_videoparameter.value = 1) OR (app_videoparameter.member_id = 11 AND app_videoparameter.value = 1) ... GROUP BY (app_video.id) ORDER BY match_count DESC; How can I realize this process in Django queryset? -
Categorial Tabs Not Displaying in Nav-Bar Despite Using For Loop - Need Assistance
I'm trying to add multiple category tabs to the nav-bar using a for loop, but the result doesn't seem to show anything. I'm not sure where I went wrong. <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="{% url 'category:category_list' %}" role="button" data-bs-toggle="dropdown" aria-expanded="true"> Danh mục sản phẩm </a> <ul class="dropdown-menu"> {% for category in category_list %} <li><a class="dropdown-item" href="{% url 'category:category_detail' category.id %}">{{ category.category_name }}</a></li> {% endfor %} <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> </ul> </li> This is result -
How to implement caching for tokens in Django Rest Framework and Firebase Auth
I'm building an API using Django Rest Framework and I was thinking about using Firebase for authentication. I have some questions about how to implement the caching layer. **This is how the application works: ** A user logs in using the frontend (React.js), then when I make an API call to DRF and I pass the auth token sent back by Firebase. Using that token, DRF calls Firebase again to retrieve the user, and finally I retrieve the UserProfile for that user in DRF by querying a Postgres db. I want all this operations to result in the least amount of calls to Firebase, hence I was thinking about caching the (user token, user id) pair. However, I have never implemented caching in Django before and would appreciate any guidance. Also, what caching strategy and tool can you recommend me? Thank you -
Cannot delete "Forgot Password?" on Sign in page. Seems completely unresponsive to code
I'm expecting code to delete "Forgot your Password"?. Screenshot of deployed site (marked problem area in red) I cannot delete "Forgot your Password?" link, the issue seems to be to do with django resorting to default code that I cannot locate. Screenshot here of templates structure In templates/allauth/account/password_change.html I have commented out code {% extends "account/base_manage_password.html" %} {% load allauth i18n %} {% block head_title %} {% trans "Change Password" %} {% endblock head_title %} {% block content %} {% element h1 %} {% trans "Change Password" %} {% endelement %} {% url 'account_change_password' as action_url %} {% element form form=form method="post" action=action_url %} {% slot body %} {% csrf_token %} {% element fields form=form %} {% endelement %} {% endslot %} {% slot actions %} {% element button type="submit" %} {% trans "Change Password" %} {% endelement %} <!-- <a href="{% url 'account_reset_password' %}">{% trans "Forgot Password? TESTHERE" %}</a> --> {% endslot %} {% endelement %} {% endblock content %} Repo links See my full repo here: github.com/lmcrean/Project-4 See deployed site here: http://lmcrean-ittib-b97fbbd27fb0.herokuapp.com/accounts/login/ So far I've tried ... lead to no change in deployed site. I've tried updating file structure to contain account within allauth I've updated settings to … -
Representing NFT wallet addresses in Django model fields
I'm building a Django app that involves working with NFTs, and I want to know the best way to represent NFT wallet addresses using a Django model field. NFT wallet addresses are typically hexadecimal strings, but I'm not sure how to design the model field to accommodate them efficiently. I think the best option is a customization of the CharField with a length constraint to store the hexadecimal address. But is there a recommended maximum length for NFT wallet addresses? I'd exclude UUIDField and TextField. I'd appreciate any examples and recommendations. Thank you!