Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy Django App wih Dockerfile in Render
I'm trying to deploy Django application with Dockerfile in Render.com. I have added the below codes in Dockerfile - ARG PYTHON_VERSION=3.10-slim-buster ARG DEBIAN_FRONTEND=noninteractive FROM python:${PYTHON_VERSION} ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /code WORKDIR /code #install the linux packages, since these are the dependencies of some python packages RUN apt-get update && apt-get install -y \ libpq-dev \ gcc \ cron \ wkhtmltopdf \ && rm -rf /var/lib/apt/lists/* ! COPY requirements.txt /tmp/requirements.txt RUN set -ex && \ pip install --upgrade pip && \ pip install -r /tmp/requirements.txt && \ rm -rf /root/.cache/ COPY . /code And added the below codes in render.toml, [deploy] startCommand = "sh /code/release.sh" And, added the below in release.sh, #!/usr/bin/env sh python manage.py migrate python manage.py collectstatic --noinput python manage.py runserver 0.0.0.0:$PORT I have created all the above files in project's root directory. But, after building, it's not run/execute the release.sh. What's the proper way to implement this? -
500 Error when uploading images on Wagtail after deploying with Google Cloud Run
I have developed a blog website using Wagtail, and it works perfectly fine when I run it locally. However, after I deployed it with Google Cloud Run, I am facing the following two issues: I am unable to upload images to my website, and it always shows a 500 Error. I cannot access my website domain after mapping it. (Does it about ALLOWED_HOST or) I followed the steps to deploy my website from this link: https://codelabs.developers.google.com/codelabs/cloud-run-wagtail/. And some codes in settings.py that may help if (CLOUDRUN_SERVICE_URL): ALLOWED_HOSTS = [urlparse(CLOUDRUN_SERVICE_URL).netloc, '.thehomefixs.com'] CSRF_TRUSTED_ORIGINS = [CLOUDRUN_SERVICE_URL,'https://*.thehomefixs.com'] else: ALLOWED_HOSTS = ["*"] GS_BUCKET_NAME = env("GS_BUCKET_NAME") STATICFILES_DIRS = [] DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" GS_DEFAULT_ACL = "publicRead" I have tried several troubleshooting steps, including checking the Cloud Run logs, but I have not been able to resolve the issues. Any help would be greatly appreciated. -
Javascript: Create Date object from a string with a time
Project setup Django and Django REST Framework on the backend React and AntD on the frontend Problem I have a DateField and TimeField fields in my backend that return a string with format "YYYY-MM-DD" and "HH:mm:ss" respectively. I'm trying to get AntD to accept these values as an initial value, but the problem is that it seems that AntD expects a Date object, because anytime I try to pass the strings themselves I get an date.format is not a function error. I guess that AntD is trying to format the dates, but they're actually strings. Code Next is a minimal example of the problem I'm presenting. If running this with the following dependencies, it produces the error date.clone is not a function. import { Form, DatePicker, TimePicker, Input } from "antd"; const initial_data = { title: "Title", date: "2023-12-05", time: "10:23:00" } export function Playground() { return ( <Form initialValues={initial_data} > <Form.Item name="title" > <Input placeholder="Title" /> </Form.Item> <Form.Item name="date" > <DatePicker format={"DD/MM/YYYY"} placeholder="Pick a date" /> </Form.Item> <Form.Item name="time" > <TimePicker format={"HH:mm"} placeholder="Pick a date" /> </Form.Item> </Form> ); } Dependencies: react: 18.2.0 react-dom: 18.2.0 antd: 4.24.8 Things I've tried For the DateField I have no problem, simply I … -
Querying Different Models with Ordering and Pagination
I have a project where I store transactional records across about three models. These models have relatively different columns. I need to retrieve these records across these models for a transactions endpoint. The transactions need to be ordered in descending order by date across the models and also paginated. The current implementation I have retrieves the records from the database using different querysets, then a sorted and chain method to order them by date before passing it to the paginator. This method happens to be expensive because the queryset has to be evaluated before pagination. model1_qs = Model1.objects.filter(...) model2_qs = Model2.objects.filter(...) model3_qs = Model3.objects.filter(...) chained_list = sorted(chain(model1_qs, model2_qs, model3_qs), key=lambda: x: x.created, reverse=True) # I pass this chained list to the paginator. One other implementation I've tried is to combine the queryset using union, but I got this error: django.db.utils.OperationalError: SELECTs to the left and right of UNION do not have the same number of result columns and when I tried to use annotate to make the columns equal on both sides, I got a couple of errors like this: AttributeError: 'float' object has no attribute 'replace' I have decided against going this route because it was beginning to look … -
Problem with fetching other user in Django
Good day everyone, currently I'm working on building a twitter clone and am almost done but I cant seem to get some functionality working. I created a profile page where users are able to see what they have tweeted and the people that follow them, so I created link to each persons profile so they can be linked there however, when I try clicking on the link I still end up on my page. My url changes so I know theres not problem with the markup, I will highly appreciate some assistance. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) bio = models.TextField(null=False, blank=False, max_length=500) profile_picture = models.ImageField(null=True, blank=True, upload_to="pictures/") followers = models.ManyToManyField("self", blank=True, symmetrical=False) def __str__(self): return self.user.username class Talks(models.Model): user = models.ForeignKey(User, related_name="talks", on_delete=models.DO_NOTHING) body = models.TextField(null=False, blank=False, max_length=500) image = models.ImageField(null=True, blank=True, upload_to="talk-pictures/") talked_at = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, blank=True, related_name="talk_likes") def total_likes(self): return self.likes.count() def __str__(self): return f"{self.user} " f"{self.talked_at:%Y-%m-%d %H:%M}: " f"{self.body}" @receiver(post_save, sender=User) def auto_create(sender, instance, created, **kwargs): if created: user_profile = Person(user=instance) user_profile.save() user_profile.followers.set([instance.person.user.id]) user_profile.save() post_save.connect(auto_create, sender=User) views.py from typing import Any, … -
Resize images in django-tinymce
I have a tinymce form in my Django app, this is the configuration: TINYMCE_DEFAULT_CONFIG = { 'branding': False, 'height': '300px', 'width': '100%', 'cleanup_on_startup': True, 'custom_undo_redo_levels': 10, 'selector': 'textarea', 'plugins': 'link image table', 'toolbar': 'undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image table', 'toolbar_mode': 'floating', 'relative_urls': False, 'remove_script_host': False, 'convert_urls': True, 'images_max_dimensions': (800, 800), } But 'images_max_dimensions': (800, 800), doesn't work and images go beyond the borders they're supposed to. I tried to resize the images by rendering the view with pillow but it's taking too much resources. -
Django using context processor in email template
I created a custom context processor to display the name of companies in templates. It works correctly in page templates but it is not working in an email template. Nothing is inserted in the template for {{ cname.company_name }}. The context processor code: def cname(request): ti = request.tenant.id company = Tenant.objects.get(id=ti) return ({'cname': company}) The relevant view code: def form_valid(self, form): password = CustomUser.objects.make_random_password() account = form.save(commit=False) account.password = make_password(password) account.reset_password = True account.save() account.reset_token = default_token_generator.make_token(account) account.save() base64_encoded_id = urlsafe_base64_encode(force_bytes(account.pk)) reset_url_args = {'uidb64': base64_encoded_id, 'token': account.reset_token} url = self.request.build_absolute_uri(reverse("password_reset_confirm", kwargs=reset_url_args)) account_creation_email(account.email, f"{account.full_name}", url=url) return super().form_valid(form) The utils.py code: def account_creation_email(to, full_name, url): template = get_template('mail/account-creation.html') context = {"full_name": full_name, "url": url} html = template.render(context) email = EmailMultiAlternatives( subject="Account Creation Email", body=html, to=[to] ) email.attach_alternative(html, "text/html") email.send() The email template: <div> <div>Hello, {{ full_name }}</div><br> <div>An admin at the company intranet for {{ cname.company_name }} just added an account for you to the site.</div><br> <div><a href="{{ url }}">Click Here</a> to set a password and login</div> </div> Any ideas for getting this to work? -
how can i display foreignkey data in a different html template?. Btw im new to django, so it's a bit confusing for me
my views.py def schedule_work(request): form = schedule_form() if request.method == 'POST': form = schedule_form(request.POST) if form.is_valid(): form.save() return redirect('view_schedulework') return render(request, 'schedule_work.html', {'form': form}) def view_schedulework(request): data = schedule.objects.all() return render(request, 'view_schedulework.html', {'data': data}) def update_schedulework(request, id): data = schedule.objects.get(id=id) form = schedule_form(instance=data) if request.method == 'POST': form = schedule_form(request.POST or None, instance=data or None) if form.is_valid(): form.save() return redirect('view_schedulework') return render(request, 'edit_schedulework.html', {'form': form}) def delete_schedulework(request, id): schedule.objects.get(id=id).delete() return redirect('view_schedulework') def available_schedules(request): data = appointment.objects.all() return render(request, 'available_schedules.html', {'data': data}) my models.py class customuser(AbstractUser): is_worker = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) address = models.TextField(null=True) experience = models.CharField(max_length=25, null=True) photo = models.ImageField(upload_to='profile', null=True) class schedule(models.Model): date_available = models.DateField() start_time = models.TimeField(null=True) end_time = models.TimeField(null=True) class appointment(models.Model): Customuser = models.ForeignKey(customuser, on_delete=models.CASCADE, null=True) Schedule = models.ForeignKey(schedule, on_delete=models.CASCADE, null=True) status = models.IntegerField(default=0) my html template for available_schedules <div class="card"> <div class="card-body"> <table class="table table-bordered"> <thead> <tr> <th>Sl No.</th> <th>name</th> <th>Available Date</th> <th>Starting Time</th> <th>Ending Time</th> <th>Schedule an appointment</th> </tr> </thead> <tbody> {% for appointment in data %} <tr> <td>{{ forloop.counter }}</td> <td>{{ appointment.Customuser.username }}</td> <td>{{ appointment.Schedule.date_available }}</td> <td>{{ appointment.Schedule.start_time }}</td> <td>{{ appointment.Schedule.end_time }}</td> <td><button class="btn btn-primary" type="submit">Book appointment</button></td> </tr> {% endfor %} </tbody> </table> </div> </div> {% endblock %} im trying to display the … -
Django MiddlewareMixin replacement
We have this Middleware class and test in Django 3.2, How do we update the code for Django 4.2.1 as we get required parameter get_response missing Middleware class lass CountryMiddleware(MiddlewareMixin): def process_request(self, request): country_code = helpers.get_country_from_querystring(request) if country_code: request.COUNTRY_CODE = country_code def process_response(self, request, response): """ Shares config with the language cookie as they serve a similar purpose """ if hasattr(request, 'COUNTRY_CODE'): response.set_cookie( key=constants.COUNTRY_COOKIE_NAME, value=request.COUNTRY_CODE, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN, secure=settings.COUNTRY_COOKIE_SECURE, httponly=True, ) return response Test @pytest.mark.parametrize('country_code,country_name', choices.COUNTRY_CHOICES) def test_country_middleware_sets_country_cookie( client, rf, country_code, country_name ): settings.COUNTRY_COOKIE_SECURE = True request = rf.get('/', {'country': country_code}) response = HttpResponse() request.session = client.session instance = middleware.CountryMiddleware() instance.process_request(request) instance.pprocess_template_response(request, response) cookie = response.cookies['country'] assert cookie.value == country_code -
Mocking attribute of a file in python fails
I am trying to mock a function call inside file here is the file dummy.py from core.connection_util import create_graphql_client config = settings.ABCD gql = create_graphql_client(config) print("debug", gql) # this print statemet is not coming either. def get_instance(): return gql unit test file test_dummy.py def test_get_instance(): with patch('dummy.adapter.create_graphql_client') as mocked_create_graphql_client: \# Configure the mock's behavior mocked_gql = 'Mocked GraphQL Client' mocked_create_graphql_client.return_value = mocked_gql # Call the function under test instance = get_instance() # Assertions assert instance == mocked_gql mocked_create_graphql_client.assert_called_once_with(settings.ABCD) I tried with mocker fixture too still no luck. Any help would be appriciated thanks. I am running things in pycharm community edition and I tried running the test via terminal as well no luck. -
How to format Django templates without having formatting white-space in the output?
I need to generate some txt files and Jinja2 used for Django templates causes the template code to look really messy, because I cannot use line-breaks without having them in the generated result. The {% spaceless %} tags would probably make things only messier as it will be hard to insert the wanted space. An example: [{% if foo.condition %}x{% else %} {% endif %}] List of requirements fulfilled: {{ foo.requirements_fullfilled }} of {{ foo.num_requirements }} {% for requirement in foo.requirement %} - {{ requirement.number }}{% if requirement.name %}: {{ solution.exercise.name }}{% endif %}{% endfor %}{% endif %} Note the linebreak before - which makes the list add a linebreak before each bullet point and the missing linebreaks for all other tags, as they would be visible in the output. Using spaceless would allow for formatting, but also remove the linebreak before the bullet points. Without spaceless the line looks quite messy. I also tried to use {# #} with a linebreak inside the comment as workaround, but multi-line comments need to use the {% comment %} template tag, which itself has a quite verbose name and would result in, for example: [{% if foo.condition %}{% comment %} {% endcomment … -
How to run async GraphQL schema.execute() inside Celery shared_task?
I'm using Strawberry with Django for GraphQL and I created a shared_task() which should execute this query on the Schema but I get this error: GraphQLError("'coroutine' object has no attribute 'items'") query_total = """ query MyQuery($filters: Filter!) { something(filters: $filters) { items { id } total } } """ @shared_task() def my_function(filters, request): context = CustomContext(request) loop = asyncio.get_event_loop() total_result = loop.run_until_complete(schema.execute(query_total, variable_values={"filters": filters}, context_value=context)) I call the function like this: my_function.delay(...) I tried already with async-await, async_to_sync with a wrapper function. -
Cannot assign "2022": "Profile.year_of_passing" must be a "Batch" instance
This is my model.py file from asyncio import constants import profile from django.contrib.auth.models import User from django.db import models from django.utils import timezone import datetime, os from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from model_utils import FieldTracker from time import strftime from applications.adminportal.mail_helper import send_verification_email class Constants: SEX_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ('O', 'Other') ) ROLE_CHOICES = ( ('S','Student'), ('A','Alumni'), ) PROG_CHOICES = ( ('B.Tech', 'B.Tech'), ('B.Des', 'B.Des'), ('M.Des', 'M.Des'), ('M.Tech', 'M.Tech'), ('PhD', 'PhD') ) BRANCH = ( ('CSE', 'Computer Science and Engineering'), ('ECE', 'Electronics and Communication Engineering'), ('ME', 'Mechanical Engineering'), ('SM', 'Smart Manufacturing'), ('NS', 'Natural Sciences'), ('MT', 'Mechatronics'), ('DS', 'Design'), ('NA', 'Not Applicable') ) WORKING_STATUS = ( ('Is Working', 'Is Working'), ('Is Pursuing Higher Studies', 'Is Pursuing Higher Studies'), ('Is Self Employed', 'Is Self Employed') ) EMPLOYMENT_TYPE = ( ('ft', 'Full-time'), ('pt', 'Part-time'), ('se', 'Self-employed'), ('fr', 'Freelance'), ('in', 'Internship'), ('tr', 'Trainee'), ) `your text` YEAR_OF_ADDMISSION = tuple((n, str(n)) for n in range(2005, datetime.datetime.now().year)) ADMISSION_YEAR = tuple((n, str(n)) for n in range(1990, datetime.datetime.now().year + 1)) PASSING_YEAR = tuple((n, str(n)) for n in range(2005, datetime.datetime.now().year)) class Batch(models.Model): year_of_passing = models.IntegerField(primary_key=True) def __str__(self): return self.year_of_passing def upload_photo(instance, filename): name, extension = os.path.splitext(filename) return 'Profile_Pictures/' + str(instance.roll_no) + ".jpg" … -
Creating dynamic models in Appconfig.ready
I am working on a Django project for which I need to create dynamic models that are based on explicit/static models (i.e. classes in models.py). Right now I am using the class_prepared signal, but the models are not fully processed by Django yet at that time, which leads to reduced functionality. Is it possible to create dynamic models in the Appconfig.ready function? Code in the ready function will only be run after everything is properly initialized. If you create a dynamic model in that function, will it still be processed properly by Django or not? I've tried creating a model in the ready function, and it seems to work. I can access the _meta object and functions like _meta.get_fields() without errors. (Which is not possible before the ready function) I'm just scared that some internal Django stuff might work different because the model was created after Django is supposed to be done iniatializing. -
My {{ item.img.url }} doesnt work, doesnt even display url
So basicaly I am making an information panel and sometimes there needs to be a photo attached. I can assure you I searched the whole internet for the solution and yet after two hours I am here and need help. Please restore my sanity. My index.html - I am posting only the part where theres the {{ item.img.url }} <ul class="list-ohlasky"> {% for item in ohlasky %} <li class="polozka-ohlasky"> {{ item.den }}<br> {{item.text}}</li> {% if item.img %} <img src="{{ item.img.url }}" alt="PLS WORK"> {% else %} {% endif %} {% endfor %} </ul> My views.py from django.shortcuts import render from .models import Ohlasky from .models import Liturgicketexty from django.http import HttpResponse from django.template import loader # Create your views here. now = datetime.datetime.now() def index(request): order = Ohlasky.objects.all().order_by('den').values() order1 = Liturgicketexty.objects.all().order_by('id').values() template = loader.get_template('blog/index.html') context = { 'ohlasky': order, 'liturgicketexty': order1, } return HttpResponse(template.render(context, request)) Here is models.py from django.db import models # Create your models here. class Ohlasky(models.Model): den = models.DateField(blank=False) nazev = models.CharField(max_length=25, blank=False) text = models.TextField(blank=False) img = models.ImageField(upload_to='media', default=None, blank=True, null=True) def __str__(self): return self.nazev + ' | ' + str(self.den) Here is urls.py from django.contrib import admin from django.urls import path, include from django.conf import … -
How to merge two PDF files?
I'm trying to merge two PDF's but got this error. File "/code/aca_django/certificates/utils.py", line 10, in <module> from pypdf import PdfMerger File "/usr/local/lib/python3.10/site-packages/pypdf/__init__.py", line 10, in <module> from ._encryption import PasswordType File "/usr/local/lib/python3.10/site-packages/pypdf/_encryption.py", line 68, in <module> from Crypto.Cipher import AES, ARC4 # type: ignore[import] File "/usr/local/lib/python3.10/site-packages/Crypto/Cipher/ARC4.py", line 119, in <module> key_size = xrange(1,256+1) NameError: name 'xrange' is not defined. Did you mean: 'range'? I have tried with PyPDF2 3.0.1 and pypdf 3.8.1 like those imports. from PyPDF2 import PdfMerger or from pypdf import PdfMerger But got the same error. Any idea ? Thanks. -
CBV CreateView influences rendering of UpdateView
I've a model Anlieferung for which there are two forms and a CreateView and an UpdateView. CreateView and UpdateView use either one of the forms, depending on the user. The problem is that whenever the CreateView is called, all following GET requests to the UpdateView render a wrong information, i.e. the value rendered in field Spedition is not the same value as in the database. The value rendered in field Spedition is the value of the lastly created Anlieferung.spedition and not the value of the called record. Restarting the server solves, either by touching the wsgi.py script or by restarting apache itself, but this cannot be the solution. The configuration setup used is apache with mod_wsgi and this problem only occurs in the production environment. models.py: class Anlieferung(models.Model): spedition = models.ForeignKey(Spedition, blank=False, null=False, on_delete=models.CASCADE) ankunftszeit = models.TimeField(null=False, blank=False, ) fahrzeug = models.ForeignKey(Fahrzeug, on_delete=models.CASCADE, blank=True, null=True) anhaenger = models.ForeignKey(Fahrzeug, related_name='anhaenger', on_delete=models.CASCADE, blank=True, null=True) anzahlStellplaetze = models.IntegerField(null=False, blank=False, verbose_name="Anzahl Stellplätze") standort = models.ForeignKey(Standort, null=True, blank=True, on_delete=models.CASCADE) lieferant = models.CharField(max_length=100, blank=True, null=True, verbose_name="Lieferant / Kundenname") SpeditionsAuftrag = models.CharField(max_length=100, blank=True, null=True, verbose_name="Speditions Auftragsnummer") KundenAuftrag = models.CharField(max_length=100, blank=True, null=True, verbose_name = "Produzenten- oder Kundenauftragsnummer, " "Ordernummer oder Bestellnummer") leergut = models.ForeignKey(Leergut, null=True, blank=True, on_delete=models.CASCADE) leergut_anzahl … -
pgAdmin/postgresql is reordering my django model, prioritising character values over integer values
It's not a huge issue that the columns have been re-ordered, but I would like to understand why pgAdmin / PostgreSQL has prioritised the ordered of fields which have a character value over an integer value? See image of my django model below, and then an image of how it's structured in pgAdmin. Is there a reason why it would re-order the model? I was expecting the database to translate as per the order of the model -
Log files is busy by another proccess with open
I have script which get information from log file and create model with log info from that file when user log in or log out on our site But when i'm restarting pc i got an error that my log file is busy by another process How can i fix that? script.py def writing_logs(request, action): logger.info('{} {} {} {}'.format( request.user.email, get_client_ip(request), get_client_type_device(request), action)) with open('loggers/log_user_activity/user_activity.log', 'r', encoding='utf8') as filelog: for i_line in filelog.readlines(): if i_line.startswith('INFO') and len(i_line.split()) == 9: line_list = i_line.split() if line_list[3] != 'Watching': if not Log.objects.filter(log_date=line_list[1]): Log.objects.create(log_category=line_list[0], log_date=line_list[1]) -
How can i send form by type into input using htmx?
I have a search input and sort select. I wrapped it into form. How can i send form by typing into search input (hx-trigger="keyup changed delay:150ms") or selecting another item in select (hx-trigger="changed"). I need to send data from both of this elements. Here is my code: <form hx-get="{% url 'search-spec' %}" hx-target="#search-results" hx-trigger="keyup delay:150ms changed"> <div class="search w-100 mt-4 d-flex justify-content-center"> <div class="input-group rounded w-75 shadow-4-soft"> <span class="input-group-text me-2" id="search-addon"> <i class="fas fa-search"></i> </span> <input type="search" class="form-control rounded" placeholder="Начните набирать..." name="q" id="q"/> </div> </div> <div class="search w-100 mt-2 d-flex justify-content-center"> <span class="input-group-text me-2" id="search-addon"> <i class="fas fa-sort"></i> </span> <select name="sort" id="sort" value="0" class="form-select w-50"> <optgroup label="По дате публикации"> <option value="0">Последние публикации</option> <option value="1" selected>Первые публикации</option> </optgroup> <optgroup label="По обозначению"> <option value="2">Обозначение 0-9</option> <option value="3">Обозначение 9-0</option> </optgroup> <optgroup label="По наименованию"> <option value="4">Наименование А-Я</option> <option value="5">Наименование Я-А</option> </optgroup> </select> </div> </form> -
Django Custom User model field display User List
UserProfile is Custom User Model having columns avatar, bio and display fields. I want to Profile avatar in the User List I have added avatar_tag function to be called by the users list #models.py class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) def get_upload_avatar_to(self, filename): return f"images/avatar/{self.user.id}/{filename}" avatar = models.ImageField(upload_to=get_upload_avatar_to, null=True, blank=True) def avatar_tag(self): if self.avatar.url is not None: return mark_safe('<img src="{}" height="50"/>'.format(self.avatar.url)) else: return "" avatar_tag.short_description = 'Image' avatar_tag.allow_tags = True full_name = '' bio = models.TextField(default="", blank=True) display = models.CharField(default=full_name,max_length=512,blank=True) admin.py code is below class UserProfileInline(admin.StackedInline): model = UserProfile fk_name = 'user' can_delete = False verbose_name = "User profile" verbose_name_plural = 'Profiles' classes = ('text-capitalize','collapse open') extra = 1 list_display = ('avatar_tag') fieldsets = ( ("Profile", {'fields': ('avatar','bio', 'display',)}),) class UserProfileAdmin(UserAdmin): inlines = (UserProfileInline,) -
I am trying to fetch data with the Django ORM with filter and exclude both at the same time, but it returns the same data with and without exclude
I am trying to fetch the data from a model with a filter and exclude at the same time. Here is the query sharing = UserSharingPermissions.objects.filter( user_id = extra.user_id, is_deleted = False, archived = False ).exclude(pk = extra.current_company.pk) I am trying to exclude the current company from the results but this query includes the current company. I also tried with the Q, but this also gives me the same result. UserSharingPermissions.objects.filter(Q(user_id = extra.user_id, is_deleted = False, archived = False) & ~Q(pk = extra.current_company.pk)) I am not sure if am I missing something in a query or something else. Thanks. -
"msal" IdentityContextData for Django
I am working with MSAL for the django project that i am developing with. I Looked at the methods under class IdentityContextData(object) in context.py. I See that there is a variable self._id_token_claims = {} under the clear method. I have data coming in that variable. I saw a flask app that returns this variable as id_token_claims. Could someone add a property for id_token_claims similar to username or token_cache ` @property def username(self) -> str: return self._username ` ` @username.setter def username(self, value: str) -> None: self._username = value self.has_changed = True ` The above is the code snipet from class IdentityContextData(object) inside context.py. I need to get user email that is returned in _id_token_claims. But when i check the request in django, under request.identity_context_data, i can access request.identity_context_data._id_token_claims but i get the accessing protected property warning. I see data like prefered_username and email in this _id_token_claims but i also get a warning for the same. would appreciate someone adding the method to access this property directly like username or token_cache -
Making Both Value to be Condition for django_filters in DRF and Showing Customized Error if the condition is empty
I am trying to use Filter in Django Restful Framework using django_filters. I would like to use two fields so the condition must be met for both fields. This means the user must enter ref_code and expecting_time. But now, if the user enters ref_code the query still works. Lastly, if the query is empty I need a customized Message. filters.py import django_filters from myappointment.models import * class AppointmentFilter(django_filters.FilterSet): class Meta: model = AppointmentData fields =['ref_code', 'expecting_time'] api.py @api_view(['GET']) def AllAppointmentData(request): queryset = AppointmentData.objects.all() filterset = AppointmentFilter(request.GET, queryset=queryset) if filterset.is_valid(): queryset = filterset.qs if queryset is not None: serializer = AppointmentDataSerializer(queryset, many=True) return Response(serializer.data) else: return Response([], {'success': "The Query is empty"}, status=status.HTTP_200_BAD_REQUEST ) enter image description here -
Django KeyError at forms.py
I'm learning django and I'm playing around with forms and registering users. When I submit the registration form with the username, email, password, and confirm password fields filled, I get an error that states: KeyError at director/register/ "confirm_password" However, when I look at the POST data in the error message I clearly see the data I'm trying to access. see screenshot here csrfmiddlewaretoken: blahblahblabh username: dasdasd email: dasd@dsada.com password: test123! confirm_password: test123! Below are the forms.py, portion of the views.py, register.html files. forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ("email", "password") class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ("email", "password") class RegisterUser(forms.Form): username = forms.CharField(max_length=64, required=True) email = forms.EmailField() password = forms.CharField(max_length=128, widget=forms.PasswordInput(), required=True) confirm_password = forms.CharField(max_length=128, widget=forms.PasswordInput(), required=True) def clean_username(self): username = self.cleaned_data["username"] if CustomUser.objects.filter(username=username).exists(): raise forms.ValidationError("Email already exists") return username def clean_email(self): email = self.cleaned_data['email'] if CustomUser.objects.filter(email=email).exists(): raise forms.ValidationError("Email already exists") return email def clean_password(self): password = self.cleaned_data['password'] confirm_password = self.cleaned_data['confirm_password'] if password != confirm_password: raise forms.ValidationError("Passwords do not match") return password``` views.py (register_view) def register_view (request): if request.method == "POST": form = RegisterUser(request.POST) if form.is_valid(): new_user = form.save() login(request, …