Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to define columns from dictionary keys with Django tables 2?
I would like to create a table from multiple objects from a Django model called MyModel. The data are stored in a JSONField called weights with datetime as key like this {"2022-05-01T05:00:00Z": 0.123}. The name of the column should comes from a CharField called name. As you can see in the code below I iterate through the objects and create a Pandas Series to extract value and populate a dictionary. But how can I tell tables to take the column name from the dictionary key ? of is there a possibility to pass the columns names dierctly with a list ? view.py class MyappDetailView(SingleTableMixin, generic.DetailView): model = Country def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) dic = dict() for obj in MyModels.objects.filter(one_field=self.object): s = pd.Series(obj.weights)[-15 * 24:] * 100 dic['Datetime'] = s.index.tolist() dic[obj.name] = s.values.tolist() table_2 = WeightTable(dic) context['table'] = table_2 return context table.py import django_tables2 as tables class WeightTable(tables.Table): Datetime = tables.Column() key_1 = tables.Column() # here I would like to declare the name of the columns fom the key key_2 = tables.Column() key_3 = tables.Column() ... -
Django MultipleChoiceField field with filter
what should I write here to filter participants by event ID forms.py participants = forms.ModelChoiceField(queryset=Participant.objects.none(), empty_label=None,), so that I do not write to the queryset, I get all participants from all events. And I need to see those participants who sent an application for this event view.py form = EventForm(request.POST or None, instance=event) form.fields['participants'].queryset = Participant.objects.filter(event_id=Event.pk) would be very grateful for help -
my website is taking so much CPU on my computer
i'm using in this project django with pure css and js and it seems that my website is consuming so much cpu also i'm using a gradient animation with css body { background: linear-gradient(to right, rgb(247, 85, 202), rgb(18, 103, 248)); background-size: 400% 400%; animation: gradient 15s ease infinite; }.nav-link ,.navbar-brand ,.nav-link:hover ,.navbar-brand:hover { background: linear-gradient(to right, rgb(247, 85, 202), rgb(18, 103, 248)); -webkit-background-clip: text; background-size: 400% 400%; color: transparent; animation: gradient 15s ease infinite; } @keyframes gradient { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } } in addition i'm using event listener to whole document using Javascript document.querySelectorAll('.edit').forEach((button) => { . . . }) document.querySelectorAll('.filter-green').forEach(like => {...}) -
how do i solve the following Django serializer error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'Article'
Im quite new to django but i cant find the solution in the docs My question: I have a model with 2 OneToOne relations: class Slotting(ICSBaseMixin): # database fields article = models.OneToOneField( "ics_stock.Article", on_delete=models.CASCADE, related_name="slotting", null=False ) article_location = models.OneToOneField( "ics_stock.ArticleLocation", on_delete=models.CASCADE, null=False, related_name="slotting" ) def __str__(self): return str(self.record_id) class Meta: db_table = "ICS_Stock_Slotting" verbose_name = "Slotting" verbose_name_plural = "Slottings" # noqa I want to create and save a new instance through a serializer. serializer: class SlottingCreateUpdateSerializer(serializers.ModelSerializer): def update(self, instance, validated_data): article = validated_data.pop("article") instance.article_id = article article_location = validated_data.pop("article_location") instance.article_location_id = article_location instance.save() return instance def create(self, validated_data): article_id = validated_data.pop("article") article = get_object_or_404( Article, record_id=article_id ) article_location_id = validated_data.pop("article_location") article_location = get_object_or_404( ArticleLocation, record_id=article_location_id ) slotting = Slotting() slotting.article_location = article_location, slotting.article = article slotting.save() return slotting Now when trying to serialize and save i get the following error: raceback (most recent call last): File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'Article' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\000 Projects\Applications\ICS_Django_core\venv\lib\site-packages\django\core\handlers\base.py", line … -
Django Model.delete() not working in signal
I am trying to delete a model instance from within a signal callback @receiver(m2m_changed) def many_to_many_changed(sender, instance, action, **kwargs): if action == "post_remove": if not instance.invoices.all().exists(): payment = Payment.objects.get(pk=instance.pk) payment.delete() instance.delete() This is my code but neither instance.delete() or payment.delete() deletes anything, I have also tried to put Payment.objects.all().delete() but nothing changed. What could I try to do? Is it possible to do what I am trying to accomplish? -
django rest save api to bd
My task is to accept a post request with a link to a public api, and then save the data from json to my database, and display the last entry (before adding). I do all this in django rest. The problem is that I do not understand how to make a working serializer that accepts a link. Model serializer: class QSerialaizer(serializers.Serializer): color = serializers.CharField() age = serializers.CharField() Function that returns api by url: def j_request(url): response = requests.get(url) data = json.dumps(response.json(), sort_keys=True, indent=4) return(data) And finally, the function that I can't get is the post request in the view: def post(self, request): queryset = Cats.objects.all() data = request.data num = data['url'] for item in jservice_request(url): Question.objects.create( color=item['color'], age=item['age'] ) return Response({'queryset': queryset}) Is it necessary to use a serializer to create an entry in the database, and how to do it? -
is it possible to have two parameters in limit_choices_to in django models?
I'll shorten the code as simple as possible. Supposedly, we do have two models. models.py > Products table CATEGORY = ( ('Hard Disk Drive', 'Hard Disk Drive'), ('Solid State Drive', 'Solid State Drive'), ('Graphics Card', 'Graphics Card'), ('Laptop', 'Laptop'), ('RAM', 'RAM'), ('Charger', 'Charger'), ('UPS', 'UPS'), ('Mouse', 'Mouse'), ('Keyboard', 'Keyboard'), ('Motherboard', 'Motherboard'), ('Monitor', 'Monitor'), ('Power Supply', 'Power Supply'), ('Router', 'Router'), ('AVR', 'AVR'), ('Tablet', 'Tablet'), ('System Unit', 'System Unit'), ('Audio Devices', 'Audio Devices'), ('CPU', 'CPU'), ('Others', 'Others'), ) class Product(models.Model): model_name = models.CharField(max_length=100, null=True, blank=True) asset_type = models.CharField(max_length=20, choices=CATEGORY, blank=True) date = models.DateField(null=True, blank=True) And the other table > Order table class Order(models.Model): product_order = models.ForeignKey(Product, on_delete=models.CASCADE, null=False) employee = models.ForeignKey(User, models.CASCADE, null=False) date = models.DateTimeField(auto_now_add=True) remarks = models.TextField() And we all know that adding this code will limit the foreignkey choices under the Order form. limit_choices_to={"asset_type": "Hard Disk Drive"} limit_choices_to={"asset_type": "Solid State Drive"} My goal here is to show items from Products table whose asset_type is either "Hard Disk Drive" OR "Solid State Drive". I've read the documentation of Django for "limit_choices_to" and can't see any pertaining to some kind of solution in here. Thank you in advance who knows a way to make this possible. -
Getting ProgrammingError: relation "auth_user" does not exist while running test
Lately I faced this problem that is driving me crazy and didn't find any solution on the internet. I don't no when the problem created or what did I do that caused this but now every time I want to run my test in my Django app this errors show up: Traceback (most recent call last): File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/mohammad/Projects/IP_Camera/manage.py", line 22, in <module> main() File "/home/mohammad/Projects/IP_Camera/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/commands/test.py", line 68, in handle failures = test_runner.run_tests(test_labels) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/test/runner.py", line 1000, in run_tests old_config = self.setup_databases( File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/test/runner.py", line 898, in setup_databases return _setup_databases( File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/test/utils.py", line 220, in setup_databases connection.creation.create_test_db( File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/db/backends/base/creation.py", line 79, in create_test_db call_command( File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 198, in call_command return command.execute(*args, **defaults) File "/home/mohammad/Projects/IP_Camera/venv/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File … -
I am facing django api error. manage.py runserver is throwing importError
ImportError: cannot import name 'smart_text' from 'django.utils.encoding' (/home/ubuntu/django/env/lib/python3.8/site-packages/django/utils/encoding.py) -
password1 and password2 doesn't save in django form
I have created a (CustomUserForm) like the below: from django.contrib.auth.forms import UserChangeForm from .models import User from django import forms class CustomUserForm(UserChangeForm): username = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter Username'})) email = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Email'})) password1 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Password'})) password2 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Confirm Password'})) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and the corresponding view to create a new user: from django.shortcuts import render, redirect from django.contrib import messages from store.forms import CustomUserForm def register(request, self): form = CustomUserForm() if request.method == 'POST': form = CustomUserForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Registered Successfully") return redirect('/login') context = {'form': form} return render(request, 'auth/register.html', context) def login_page(request): return render(request, 'auth/login.html') and this is the register.html {% extends 'layouts/main.html' %} {% block title %} {{ category }} {% endblock %} {% block content %} <section class="vh-100" style="background-color: #eee;"> <div class="container h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col-lg-12 col-xl-11"> <div class="card text-black" style="border-radius: 25px;"> <div class="card-body p-md-5"> <div class="row justify-content-center"> <div class="col-md-10 col-lg-6 col-xl-5 order-2 order-lg-1"> <p class="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4">Sign up</p> <form class="mx-1 mx-md-4" action="" method="POST"> {% csrf_token %} … -
Dockerfile/Docker-compose for react app that is inside of a django project
I created a django project that contains a folder called 'frontend' (I did python startapp frontend for this). This folder contains my react components and frontend logic. I created a Dockerfile and docker-compose.yml in the main directory with the 'manage.py' file. The directory looks like the following: Image of Directory So far, I have this for my Dockerfile: FROM python:3.8-alpine ENV PYTHONUNBUFFERED=1 WORKDIR /pathfinder COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt COPY . . My docker-compose.yml looks like: version: "3.8" services: app: build: . volumes: - .:/django ports: - 8000:8000 image: app:django container_name: django_container command: python manage.py runserver 0.0.0.0:8000 I believe that I need to install the dependencies in the package.json file in my frontend folder, but how would I do that in my docker container? -
why is Django not accepting the file sending from React Native app?
I am using Django for the Backend Server and React Native for a mobile app I am trying to upload an image from there but it is giving a 500 server error. Views.py form Django @api_view(['POST']) def setFakeProfile(request): if request.method=='POST': user = Token.objects.get(key = request.META.get('HTTP_AUTHORIZATION').split(' ')[1]).user profile = Profile.objects.get(user=user) fakeProfiles = profile.fakeProfiles.filter(isProfileReadyToUse=False) print(request.data) print(request.FILES) if fakeProfiles.exists(): fakeProfile = fakeProfiles[0] fakeProfile.displayName = request.data["displayName"] fakeProfile.profilePicture = request.FILES.get('profilePicture') fakeProfile.isProfileReadyToUse = True fakeProfile.save() return Response({'status':'success', 'id':fakeProfile.id}) else: return Response({'status':'failed', "message":"First select the chating platform."}) return Response({ 'status':'success', }) return Response({'status':'failed'}) The error that I am getting is there. I knew about the error and I also tried a lot of ways to resolve it but not still don't know how to fix it. {'_parts': [['displayName', 'name'], ['profilePicture', {'cancelled': False, 'type': 'image', 'uri': 'file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540sumit2232%252FUnknownChats/ImagePicker/584abe5b-7f5e-45cb-81bd-fcb5751e3ed4.png', 'width': 1692, 'height': 1692}]]} app_1 | <MultiValueDict: {}> app_1 | Internal Server Error: /setFakeProfile/ app_1 | Traceback (most recent call last): app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner app_1 | response = get_response(request) app_1 | File "/py/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response app_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) app_1 | File "/py/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view app_1 | return view_func(*args, **kwargs) app_1 | File "/py/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view app_1 … -
Can users switch months on website using python calendar library
i am making web application with django. I am using python calendar library to create HTML calendar. I was wondering if there is a builtin way to allow users switch months while on website or if i have to make it work using JavaScript. Thanks for help. -
TypeError: create_superuser() missing 2 required positional arguments
I am trying to createsuper user when I entered email and password I got this error File "/mnt/c/Users/ZAKARIA/Desktop/project/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 232, in handle self.UserModel._default_manager.db_manager(database).create_superuser( TypeError: create_superuser() missing 2 required positional arguments: 'first_name' and 'last_name' my class managers from django.contrib.auth.base_user import BaseUserManager class UserManger(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError("Users must have an email address") if not first_name or last_name: raise ValueError("Users must have a first and last name") user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email,password, first_name, last_name): user = self.create_user( email=self.normalize_email(email), password=password, first_name=first_name, last_name=last_name, ) user.set_password(user.password) #user.is_staff = True user.is_superuser = True #user.is_admin = True user.save(using=self._db) return user I have been seeing a lot of questions similar to this but i still don't understand the answers given, some say add positional arguements, I don't quite understand can any one help me to solve this problem ? -
Django error with User form: AttributeError: 'tuple' object has no attribute '_meta'
i followed the lesson to make a user register using Django, he made this code, like what I have made: class CustomUserForm(UserChangeForm): username = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter Username'})) email = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Email'})) password1 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Enter The Password'})) password2 = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'form-control my-2', 'placeholder': 'Confirm Password'})) class Meta: model = User, fields = ['username', 'email', 'password1', 'password2'] when run the server this errors displayed: PS E:\osamaStartup> py manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "E:\deep\lib\threading.py", line 973, in _bootstrap_inner self.run() File "E:\deep\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "E:\deep\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "E:\deep\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "E:\deep\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "E:\deep\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "E:\deep\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "E:\deep\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "E:\deep\lib\site-packages\django\urls\resolvers.py", line 480, in check for pattern in self.url_patterns: File "E:\deep\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "E:\deep\lib\site-packages\django\urls\resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "E:\deep\lib\site-packages\django\utils\functional.py", … -
Styles not loading in Django
I have a site that needs some custom styles in Django and I can't get the static file to load. I have a static folder inside my main folder - The one where manage.py lives, Inside there is a CSS folder that contains a style.css. At the top of base.html, I load {% load static %} Then in the head of my HTML I load <link rel="stylesheet" href="{% static 'css/styles.css' %}"> and in my settings.py file I have loaded in # Static file route STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] When I load I just get a blank CSS file and no styles load, I'm fairly new to Django so please be kind, and thanks in advance. -
Allow empty foreign key selection in admin forms
i created a model(AnalysisFieldTemplate) with a foreign key to AnalysisFieldRule. What i want is to have the possibility to leave the field display_analysis_field_rule blank and save my admin form. class AnalysisFieldRule(models.Model): action_kind: str = models.CharField( choices=ActionKind.choices, default=ActionKind.DISPLAY, max_length=text_choices_max_length(ActionKind), verbose_name=_("action kind"), ) formula: str = formula_field() name: str = models.CharField(max_length=MAX_NAME_LENGTH, verbose_name=_("name")) def __str__(self): return f"{self.name}: {ActionKind(self.action_kind).label}" class Meta: constraints = [ UniqueConstraint(fields=("action_kind", "name"), name="%(app_label)s_%(class)s_is_unique"), ] ordering = ["name", "action_kind"] verbose_name = _("analysis field rule") verbose_name_plural = _("analysis field rules") class AnalysisFieldTemplate(models.Model): display_analysis_field_rule: AnalysisFieldRule = models.ForeignKey( AnalysisFieldRule, blank=True, limit_choices_to={"action_kind": ActionKind.DISPLAY}, null=True, on_delete=models.PROTECT, related_name="display_analysis_field_templates", verbose_name=_("display rule"), ) Now here is the problem. If i try to save my admin form without choosing one a value for display_analysis_field_rule it will result in an Validationerror. It seems that the standard empty value for a foreign key "------" is not a valid choice. @admin.register(AnalysisFormTemplate) class AnalysisFieldTemplateAdmin(admin.ModelAdmin): fieldsets = ( ( None, { "fields": ( "name", "name_for_formula", "ordering", "required", "kind", "display_analysis_field_rule", "highlight_analysis_field_rule", ) }, ), ( _("Text options"), {"fields": ("max_length",)}, ), ( _("Integer options"), {"fields": ("min_integer_value", "max_integer_value")}, ), (_("Amount of money options"), {"fields": ("min_amount_of_money", "max_amount_of_money")}), ) I debugged a little deeper and found that the "to_python" compares the choosen value with pythons standard "empty_values" but of course … -
Djongo + Django + MongoDB not support chainning filter
I have two model: Content and Tag that have ManyToMany realationship Content(models.Model): tags = models.ManyToManyField(Tag, null=False, blank=False, related_name="tags") Tag(models.Model): slug = models.CharField(max_length=255, null=False, blank=False, unique=True) name = models.CharField(max_length=255, null=False, blank=False, unique=True) Notice that I'm using MongoDB and djongo connector to work with my db. Now I want to filter "All of content that have n specific tags", example: all of the content that have tags = ["Movie", "News", "Science"], suppose id of them is: 1, 2, 3 corresponding. I have used chaining filter. content.objects.filter(tags=1).filter(tags=2).filter(tags=3) but it return not found. Yep, of course contents that have id = [1, 2, 3] are available in my database. But when I migrate to MySQL and try again, it work and return a queryset that I expected. -
403 error everytime I login to my site, but csrftoken is in my form. DJANGO
I am experiencing 403 error when I uploaded my site on pythonanywhere.com, but it works fine in localhost. It keeps on saying 403 forbidden when I try to login an account, even I input a wrong password. I tried to look at the request cookies in my browser, it does not detect the csrftoken, but when I check the checkbox that shows filtered out request cookies, I can see the csrftoken and its value and other things. I have {% csrf_token %} in my login form and I am using the default login view of django. here's my settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["jeremiramos.pythonanywhere.com"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my apps 'accounts.apps.AccountsConfig', #installed apps 'corsheaders', 'crispy_forms', 'rest_framework', 'main', 'cms', 'ckeditor', 'students', ] AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = ( # 'django.contrib.auth.backends.RemoteUserBackend', 'django.contrib.auth.backends.ModelBackend', ) MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', … -
Extend Filter functionality to use only if variable have value
I am using the django framework for make an blog app. my django version is Django version 4.0.4 i am supposed to do filter the data as per Title And category that blog does have my code is as follow searchTitle = request.GET.get('searchTitle') searchCat = request.GET.get('searchCat', '') if searchTitle or searchCat: blogs = Blog.objects.filter(blog_title__icontains=searchTitle).order_by('-blog_id') if searchCat: blogs = Blog.objects.filter(blog_title__icontains=searchTitle,blog_category=searchCat).order_by('-blog_id') else: blogs = Blog.objects.all().order_by('-blog_id') This is working perfect but this doesn't make sense since it does not follow DRY principle Here i've written Blog.object.filter code twice for search. so i want to minimize that and that problem in one line if possible. so could you guys guide over me -
Django + React , Google Login Button doesn't shown
I use frontend as React and backend as Django. I want to add Google social login, but button doesn't shown. I copy and paste this link, https://developers.google.com/identity/gsi/web/guides/display-button Here is my code. react - index.html <script src="https://accounts.google.com/gsi/client" async defer></script> <div id="g_id_onload" data-client_id="1234567890-myclientid.apps.googleusercontent.com" data-login_uri="http://127.0.0.1:8000/accounts/google/login/" data-auto_prompt="false"> </div> <div class="g_id_signin" data-type="standard" data-size="large" data-theme="outline" data-text="sign_in_with" data-shape="rectangular" data-logo_alignment="left"> </div> django - urls.py ... path('accounts/', include('allauth.urls'),), ... error occured. '/accounts' page works very well. [GSI_LOGGER]: Error parsing configuration from HTML: Unsecured login_uri provided. -
No idea why I am getting 'An existing connection was forcibly closed by the remote host' error message
I have been building a practice website for over a year and have never encountered this problem. I have not knowingly made any adjustments to my firewalls and internet settings. Today I tried to run a few different versions of my website (from between a few days and few months old) and I encountered the same issue on all of them. So I was able to rule out a rogue piece of code in a recent version causing the problem. I restarted my PC, cleared my cache on Google Chrome and also tested the issue on Firefox. Does anyone have any suggestions? I am scratching my head to what triggered this problem. -
Unauthorized response to POST request after JWT token refresh in Django
Goal: I am trying to get access to specific user data using JWT. Specifically, I aim to get the user id from the JWT token using request.user.id. Problem: I am able to run the api and refresh the tokens. Once the tokens expire, I am able to refresh them. However, after that happens, I don't seem to be able to access to my API However, once the tokens are refreshed, I get an error when I try to load the data again: "Unauthorized: /api/load/". Is there something that is clearly wrong here? Django view for api/load/ class LoadDataSet(APIView): serializer_class = LoadDataSerializer queryset = UserPantry.objects.all() permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] def post(self, request, format=None): user = request.user.id print(user) return Response(status=status.HTTP_204_NO_CONTENT) The api call in react native: const res = await request({ url:'/api/load/', method: 'POST', data: {'user_id': String(user_id)} }) Django JWT settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ ], 'DATETETIME_INPUT_FORMATS': ['%Y-%m-%d %H:%M'], 'DATIME_FORMAT': '%Y-%m-%d %H:%M', 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=3), 'REFRESH_TOKEN_LIFETIME': timedelta(days=60), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('JWT', 'Bearer'), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', … -
Django - Adding HTML Pages
I am having trouble adding a new html page. I added everything to the views.py and urls.py file, and even the base.html but I keep getting an error message (see on last line in terminal screenshot) enter image description hereenter image description hereenter image description here -
Create Django model where the default value is not shown in my form
Im trying to create a Django model with a default value, something like this: class ExampleModel(models.Model): image = models.URLField(max_length=200, default='https://example.com') And a form for this model: classExampleForm(forms.ModelForm): class Meta: model = ExampleModel fields = ('image') The thing is that by doing this when I display the form in an HTML template, the image field comes prepopulated with https://example.com, I want the filed to be empty and if the user doesn't input any value it takes the default one but that this is not shown in the form.