Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble Creating QuerySet of Django model objects with self-referential ForeignKey
Simply put I have two models A dialogue model: class Dialogue(models.Model): content = models.TextField() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) And a choice model: class Choice(models.Model): option = models.CharField(max_length = 255) content = models.TextField() dialogue = models.ForeignKey( Dialogue, related_name = "choices", blank = True, null = True, on_delete = models.CASCADE ) subChoices = models.ForeignKey( "self", related_name = "parent", blank = True, null = True, on_delete = models.CASCADE ) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) You may have noticed the recursive ForeignKey "Choice.subChoices". This is where my issue lies. If I attempt to use the add() method via the instance of this model that I want to be added to a Choice's list of further choices, I get a "'Choice' object has no attribute 'add'". If I attempt to the the reverse and add an instance of the Choice model to a Choice's parents attribute it overwrites instead of creating a query set. Examples of both below: choice1 = Choice.objects.get(id = 1) choice2 = Choice.objects.get(id = 2) choice3 = Choice.objects.get(id = 3) choice1.subChoices.add(choice2) >>> AttributeError: 'Choice' object has no attribute 'add' choice2.parent.add(choice1) choice3.parent.add(choice2) print(choice1.subChoices) >>> Choice object(3) A print statement of choice1.subChoices.all() returns … -
celery app.delay() is keep on waiting for the response, not working
I am trying to experiment with celery with Redis broker in my Django application, but I am having a hard time getting it write can anyone point me where I am missing things my init.py from __future__ import absolute_import from .celery import app as celery_app __all__ = ('celery_app', ) my base_settings.py CELERY_BROKER_URL = 'redis://localhost:6379/' CELERY_RESULT_BACKEND = 'redis://localhost:6379/' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_ALWAYS_EAGER = True my celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.enable_utc = False app.conf.update(timezone='Asia/Kolkata', task_always_eager=True) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) In my views.py @app.task(name="test celery") def add(a, b): print(a, b, a + b) @api_view(['GET']) def testcelery(request): a = request.GET.get('a', 0) b = request.GET.get('b', 0) add.delay(a, b) the output of my celery worker >celery -A lylo worker --loglevel=info -c 5 -------------- celery@LAPTOP-VQHQANA1 v5.1.1 (sun-harmonics) --- ***** ----- -- ******* ---- Windows-10-10.0.19041-SP0 2021-09-08 22:00:46 - *** --- * --- - ** ---------- [config] - ** … -
valueerror invalid model reference, how can i reference correctly
I had to change a number of my ManyToMany relations to reference a string instead of importing the model into the file so to avoid a number of circular importing errors. but when trying to run, now I am getting this error. ValueError: Invalid model reference 'dsi.administration.libraries.Library'. String model references must be of the form 'app_label.ModelName'. I don't know what would be the best way to reference this and I'd love to get anyone's input on this. the reference in question models.ManyToManyField("dsi.administration.libraries.Library", verbose_name='library choices') settings.py installed modules SHARED_APPS = ( "storages", "django_tenants", # mandatory 'dsi.events.event', 'dsi.administration.libraries', 'dsi.account' ) the app folder structure ├── dsi │ ├── account │ │ ├──__init__.py │ │ ├── models.py │ ├── events │ │ ├── event | │ │ ├── __init__.py | │ │ ├── models.py │ │ ├──__init__.py │ ├── administration │ │ ├── libraries | │ │ ├── __init__.py | │ │ ├── models.py │ │ ├── general | │ │ ├── __init__.py | │ │ ├── models.py │ │ ├── __init__.py │ ├── __init__.py │ ├── urls.py │ └── settings.py ├── manage.py -
django server error (500) when DEBUG=False
This is base.py file from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent SECRET_KEY = 'h@1lneuTr@lt1P - Holla!!! this is something crazy, $2423$#@$#@E@e#R3\e[' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ # typical django code... MIDDLEWARE = [ # typical django code... ] ROOT_URLCONF = 'neutraltip.urls' TEMPLATES = [ # typical django code... ] WSGI_APPLICATION = 'neutraltip.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ # typical django code... ] STATIC_URL = '/static/' # Static settings STATICFILES_DIRS = [ BASE_DIR / 'static', ] # Media settings MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' This is production.py from .base import * import environ import django_heroku env = environ.Env( DEBUG=(bool, False), ) SECRET_KEY = 'lol' # right now for convenience I've hard-coded these # despite having environ package DEBUG = False ALLOWED_HOSTS = ['*'] MIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware') DATABASES['default']['CONN_MAX_AGE'] = 60 STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' # Activate Django-Heroku. django_heroku.settings(locals()) I've renamed the original settings.py to base.py, and extended it to production.py. And also updated manage.py, wsgi.py and asgi.py. Basically following this approach -> https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html Everything looks just fine … -
No reverse match when rendering an email template with uid/token variable
I wrote a view for user signup including email verification. However, once the view tries to render the mail template, it breaks due to the below error. I don't even understand the error itself. Insights would be appreciated. According to some googling it may be that the uid is no string? NoReverseMatch at /signup/ Reverse for 'activate' with keyword arguments '{'uidb64': 'MTE', 'token': 'asnwwr-550108ae10aa04da212561866c8d1ae3'}' not found. 1 pattern(s) tried: ['activate/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] Mail template {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} View def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your Poller Account' message = render_to_string('userprofile/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), # Issue might sit here? 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') -
How to check if a user exists in the model that I made in Django?
I'm making login page and data is already saved in model I made and not usercreateform... and instead of searching the user in my model(UserAuthentication), it searches in Users ... view.py def loginpage(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is UserAuthentication: #UserAuthentication is my model where data is stored login(request, user) return redirect('index') else: messages.warning(request, "Username OR Password is incorrect!") return redirect('login') else: return render(request, "HTML/login.html", context={}) login.html <form action="#" method="POST"> {%csrf_token %} <input class="text" type="text" name="username" placeholder="Username" required="" /> <br /> <br /> <input class="text" type="password" name="password" placeholder="Password" required="" /> <br /> <br /> {%for message in messages%} <p id="messages">{{message}}</p> <br /> {% endfor %} <input type="submit" value="LOGIN" /> </form> -
Django - "check_token" always returns TRUE
When a user registers on my app, an account verification link is sent to his email. When clicking on the link the first time, everything is fine and the account is verified, but when clicking on the same link again, the validation goes through, whereas it should raise an "authentication failed" error, since the "check_token" should return false, right? Here's the verification serializer: class VerifyAccountSerializer(serializers.Serializer): uid = serializers.CharField(min_length=1, write_only=True) token = serializers.CharField(min_length=1, write_only=True) class Meta: fields = ['uid', 'token'] def validate(self, attrs): uid = attrs.get('uid') token = attrs.get('token') uidb64 = force_text(urlsafe_base64_decode(uid)) user = UserAccount.objects.get(pk=uidb64) if user is None: raise AuthenticationFailed('Invalid account. Please contant support') if not PasswordResetTokenGenerator().check_token(user, token): raise AuthenticationFailed('Account verify link is invalid. Please contant support.') user.is_guest = False user.save() return user And the view function: @api_view(['POST']) def verify_account(request): if request.method == 'POST': data = {} serializer = VerifyAccountSerializer(data=request.data) if serializer.is_valid(): user = serializer.validated_data data['user'] = UserSerializer(user).data data['token'] = AuthToken.objects.create(user)[1] # delete previous token tokens = AuthToken.objects.filter(user=user.id) if len(tokens) > 1: tokens[0].delete() return Response(data, status=status.HTTP_200_OK) data = serializer.errors return Response(data, status=status.HTTP_400_BAD_REQUEST It's kinda weird why it's not raising an error, because, in my other serializer for resetting the password via a link as well, I have the exact same … -
Django .raw query doesn't return translations in Mysql, but does in SQLite
I have the following query in Django: available_vouchers = Vouchers.objects.raw( 'SELECT count(shops_shops.id) as total_coupons, * ' 'FROM vouchers_vouchers ' 'INNER JOIN shops_shops ON ' 'vouchers_vouchers.shop_id = shops_shops.id ' 'WHERE vouchers_vouchers.voucher_code <> vouchers_vouchers.voucher_parent ' 'AND vouchers_vouchers.voucher_aquired = 0 ' 'GROUP BY vouchers_vouchers.voucher_parent' ) The query is performed on 2 tables, that both have translations, using django.parler. This query works absolutely fine on SQLite3, and returns the translated fields (voucher_name) normally, even if its not in the query. (When running this query against SQLite directly, its doesn't show the voucher_name which is a translated field, so i guess the ORM takes care of that) While migrating to Mysql8, the query translates to this: available_vouchers = Vouchers.objects.raw( 'SELECT 1 as id, count(shops_shops.id) as total_coupons, vouchers_vouchers.* ' 'FROM vouchers_vouchers ' 'INNER JOIN shops_shops ON ' 'vouchers_vouchers.shop_id = shops_shops.id ' 'WHERE vouchers_vouchers.voucher_code <> vouchers_vouchers.voucher_parent ' 'AND vouchers_vouchers.voucher_aquired = 0 ' 'GROUP BY vouchers_vouchers.voucher_parent' ) The weird "1 as id" is needed by Django ORM, as the primary key need to be returned always in raw queries. But here, the translated fields are not returned. Running both queries against their respective database outside Django, return the same columns. Anybody ever encountered something like this? Django > … -
carousel not working inside for loop django
i have a posts that iterate and display them my images is showing but my carousel's button next and prev are not working.i spend more time on finding solutions but nothing... and i notice it works fine without the for loop but with for loop it is a problem .this is what i have tried so far it is not working at all... {% for post in posts %} <div class="w3-container w3-card w3-white w3-round"> <!-- skip --> <!-- my problem starts here --> {% with posts=post.imageprofilepost_set.all %} {% if posts %} {% if posts.count > 1 %} <div id="myCarousel{{ post.pk }}" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for i in posts %} {% if not forloop.counter0 %} <li data-target="#myCarousel{{ post.pk }}" data-slide-to="{{ forloop.counter0 }}" class="active"></li> {% else %} <li data-target="#myCarousel{{ post.pk }}" data-slide-to="{{ forloop.counter0 }}"></li> {% endif %} {% endfor %} </ol> <div class="carousel-inner"> {% for i in posts %} {% if not forloop.counter0 %} <div class="item active"> <div class="imgbox"> <a href="{{ i.images.url }}"> <img class="center-fit" src="{{ i.images.url }}"></a></div> </div> {% else %} <div class="item"> <div class="imgbox"> <a href="{{ i.images.url }}"> <img class="center-fit" src="{{ i.images.url }}"></a></div> </div> {% endif %} {% endfor %} </div> <a class="left carousel-control" href="#myCarousel{{ post.pk }}" … -
Learning PynamoDB and it's integration with Django
How can I learn PynamoDB from scratch? Is it necessary to learn Amazon SES before approaching PynamoDB? -
Why won’t the images automatically size when I upload them from the Django site
I’m new and don’t know CSS. I used a template on my Django site. When I add image links directly on the html page, they automatically size into the picture grid. However, when I add code and upload the pictures from the website, they all display with different sizes. I want them all consistent and fitting the pre-determined box size. -
Define constraints on the default through table of a ManyToManyField from meta class
I want to add some constraints to the meta class of a model that is an auto-created through model of a ManyToManyField. I followed the official docs here, and also implemented a meta class that sets the constraints successfully on the Meta class of the through model (assured by getting Model.many_to_many_field.through._meta.constraints value using the Django shell itself). The problem here is that the migration does not detect any changes on the mentioned through model hence no migration is created for the defined constraint. The question is then, is there any way to change the meta options of a through model without implementing them explicitly? -
Issues with CSRF on login form with React SPA and Django
I am building a React SPA with Django backend and Oauth using Django OAuth toolkit and have been asked by someone in the security team to implement CSRF protection on the login form of the app. No CSRF cookie will be present as Django is not serving the frontend app nor will users be logging in via Django sessions. I have created an API endpoint to provide CSRF tokens - to some degree following the instructions in this guide: https://www.stackhawk.com/blog/react-csrf-protection-guide-examples-and-how-to-enable-it/ The React app makes a call to this endpoint to retrieve a CSRF token. To add the CSRF protection on the login url - provided by Oauth toolkit /o/token I have subclassed the Oauth toolkit TokenView and pointed my login URL at it. I have used a decorator to add csrf protection: @method_decorator(csrf_protect, name="dispatch") class GetToken(TokenView): pass This seems to work correctly but when making the login request I cannot seem to get Django to accept the CSRF token I have retrieved from my endpoint - I am trying to provide it in the request body (as csrfmiddlewaretoken) and as a HTTP header (X-CSRFToken). When I make the request and debug Django CSRF middleware I can see that the request … -
When trying to add a link to the label of a form field an __init __ () got an unexpected keyword argument 'initial' error occurs
When I try to add a link to the label of a UserCreationForm field, I get the error __init __ () got an unexpected keyword argument 'initial'. My code looks like this: #forms.py class RegisterUserForm(UserCreationForm): email = forms.EmailField(required=True, label='Адрес электронной почты') check = forms.BooleanField() def __init__(self): super(RegisterUserForm, self).__init__() self.fields['check'].label = 'Принимаю политику конфиденциальности' % reverse('user:privacy') class Meta: model = AdvUser fields = ('username', 'email', 'password1', 'password2', 'check') views.py look like this: #views.py class RegisterUserView(SuccessMessageMixin, CreateView): model = AdvUser template_name = 'users/register_user.html' form_class = RegisterUserForm success_url = reverse_lazy('articles:list_view') success_message = 'Вы успешно зарегистрировались!' def form_valid(self, form): valid = super(RegisterUserView, self).form_valid(form) username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1') new_user = authenticate(username=username, password=password) login(self.request, new_user) return valid def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 5 тегов с наибольшим количеством публикаций context['tags_list'] = Tag.objects.annotate(articles_quantiy=Count('taggit_taggeditem_items')).order_by( '-articles_quantiy')[:10] context['securities_types_list'] = StocksETFsBonds.objects.all() return context How can I solve this problem? -
Django Sending Email : SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed
I am trying to send email to an AOL account via Django and I am getting the following error: Traceback (most recent call last): File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dom\Documents\Python_Projects\Django\TDD_with_Python_and_Django\superlists\accounts\views.py", line 21, in send_login_email [email], File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\__init__.py", line 62, in send_mail return mail.send() File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\backends\smtp.py", line 104, in send_messages new_conn_created = self.open() File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\backends\smtp.py", line 71, in open self.connection.login(force_str(self.username), force_str(self.password)) File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 721, in login initial_response_ok=initial_response_ok) File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 631, in auth (code, resp) = self.docmd("AUTH", mechanism + " " + response) File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 421, in docmd return self.getreply() File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 391, in getreply + str(e)) smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed by the remote host "POST /accounts/send_email HTTP/1.1" 500 130728 Here are my settings: EMAIL_HOST = 'smtp.aol.com' EMAIL_HOST_USER = 'myemail@aol.com' EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') EMAIL_PORT = 465 EMAIL_USE_SSL = True I am following along with the book TDD with Python on Chapter 18, which has a custom authentication backend: class PasswordlessAuthenticationBackend(object): def authenticate(self, uid): print('uid', uid, file=sys.stderr) … -
Django application not working in Docker Container
I have a django website, works fine on local server, but when I build a docker image with it and run it as a container it gives me this error - 'TemplateDoesNotExist at /base.html ' My settings and file structure is correctly configured, proved by the fact that it is working locally, i'm not sure if something is changing the file structure during the containerization process Here is my dockerfile - `FROM python:3.9 WORKDIR /myapp ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install pipenv COPY Pipfile . COPY Pipfile.lock . RUN pipenv install COPY . /myapp EXPOSE 8000 CMD ["pipenv", "run" ,"python", "manage.py", "runserver", "0.0.0.0:8000"] ` Template settings - TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'main', 'templates', 'main')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] My templates are stored in 'app/main/templates/main' with app being the project folder and main being the folder for the app. -
Django 3.2 wsgi:error Not Found: /pwa-worker.js
I recently set up a new instance of django fresh under apache. All I have added is the admin page and the urls to the various authentication pages. The only app I installed is django-bootstrap-v5 (but its not currently installed in settings). I saw that the error log has Not Found: /pwa-worker.js when any of the pages are loaded. For example when this simple password reset is loaded {% block content %} <form action="" method="post"> {% csrf_token %} {% if form.email.errors %} {{ form.email.errors }} {% endif %} <p>{{ form.email }}</p> <input type="submit" class="btn btn-default btn-lg" value="Reset password"> </form> {% endblock %} I just didn't expect to see errors on a fresh install. Any idea what this file is or how to resolve it? -
Is there a way to grab specific "fields" from request.data sent to the Django REST framework API in a POST method
I've got a Project model, with a project_code field. When the API receives a POST request, the request.data will also contain a project_code. I then want to filter my Project model objects based on the project_code inside the request.data Once I've linked to request.data project_code to the Project model's project_code field, I want to save my Ticket model object to the database. Inside my Ticket model, there is a field called project which is related with a ForeignKey to the Project model. Thus in essence the project_code inside the POST request.data needs to be used in order to save my Ticket model to the database with the correct Project model foreign Key. Here are my models: from django.db import models class Project(models.Model): project_code = models.TextField(blank=True) project_description = models.TextField(blank=True) def __str__(self): return self.project_code class Ticket(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) ticket_url = models.TextField(blank=True) time_submitted = models.DateField(blank=True, auto_now_add=True) description = models.TextField(blank=True) user = models.TextField(blank=True) type = models.TextField(blank=True) def __str__(self): return self.description Here are my serializers: from rest_framework import serializers from ticketing_app_api.models import Ticket, Project class TicketSerializer(serializers.ModelSerializer): class Meta: model = Ticket fields = ['id', 'ticket_url', 'description', 'user', 'type'] And here are my views: from ticketing_app_api.models import Ticket from ticketing_app_api.serializers import TicketSerializer from rest_framework … -
Is there a way to upload prepared list of books to my library django app? Or a have to input every book separately?
I'm making my own Library computer application in Django and I am wondering if is there some json file or some database from which I can take prepared list of books with authors and some other informations or I have to input it on my own? And how about book's covers? Can I use it in my website or it woudl infringe the copyright? -
In Django Project show me UserInfo matching query does not exist
Here is views.py code. In the def index section, I use UserInfo model.Here information store in one to one relation so I write (user__pk=user_id) from django.shortcuts import render from Login_app.forms import UserForm, UserInfoForm from Login_app.models import UserInfo from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.contrib.auth.decorators import login_required from django.urls import reverse def index(request): dict={} if request.user.is_authenticated: current_user = request.user user_id = current_user.id user_basic_info = User.objects.get(pk=user_id) user_more_info = UserInfo.objects.get(user__pk=user_id) dict = {'user_basic_info':user_basic_info, 'user_more_info':user_more_info} return render(request, 'Login_app/index.html', context=dict) Here is models.py code.where I create UserInfo model.It store user,facebook_id,profile_pc. from django.db import models from django.contrib.auth.models import User # Create your models here. class UserInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) facebook_id = models.URLField(blank=True) profile_pic = models.ImageField(upload_to = 'profile_pics', blank=True) def __str__(self): return self.user.username -
Set iframe url to access pages in navigation bar in Django
I am new to Django framework. I am trying to use html pages in templates and get the interfaces. I got all of the pages one by one. Now I want them appear in an iframe. Here is my html code in homeAdmin.html page. <body> <div class="main-nav"> <div class="main-nav-ul"> <a href="{% url 'welcomeAdmin' %}" target="frame1"><span class="fa fa-home fa-lg"></span> Home</a> <a href="{% url 'register' %}" target="frame1"><span class="fa fa-user-plus fa-lg"></span> Register</a> <a href="{% url 'company' %}" target="frame1"><span class="fa fa-building fa-lg"></span> Company</a> <a href="{% url 'supplier' %}" target="frame1"><span class="fa fa-taxi fa-lg"></span> Supplier</a> <a href="{% url 'category' %}" target="frame1"><span class="fa fa-mouse-pointer fa-lg"></span> Category</a> <a href="{% url 'role' %}" target="frame1"><span class="fa fa-id-badge fa-lg"></span> Role</a> </div> <div class="target"> <iframe src="{% url 'welcomeAdmin' %}" name="frame1" id="frame1" style="width: 100%;height: 540px; float: right;"></iframe> </div> </div> </body> And here is the views.py code that I have written for this problem. ``` from django.shortcuts import render from django.http import HttpResponse def welcomeAdmin(request): return render(request, 'newapp/welcomeAdmin.html') def category(request): return render(request, 'newapp/category.html') def company(request): return render(request, 'newapp/company.html') def register(request): return render(request, 'newapp/register.html') def role(request): return render(request, 'newapp/role.html') def supplier(request): return render(request, 'newapp/supplier.html') def homeAdmin(request): return render(request, 'newapp/homeAdmin.html') ``` I am lack of knowledge about what to do next in which file, like in … -
Avoid different representation of the same serializer. Django Rest Framework
Imagine I have a model which looks like following: class Author(models.Model): book = models.ManyToManyField() and a serializer for Book objects: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title',) def to_representation(self, obj): return obj.title I am using it to represent Book objects for Author entities. I have two different serializers for GET and POST requests but the books field is absolutely the same. class AuthorSerializer(serializers.ModelSerializer): books = BookSerializer(read_only=True, many=True) class Meta: model = Author fields = ('books', ...) My problem is that one AuthorSerializer (GET requests) returns data correctly: books = ['...', '...'] while the one for POST requests returns it with IDs. books = [{'id': 1, 'title': '...'}] What am I missing? Thanks. -
How to extend an array or append a value to array field on Django ORM's Queryset Update? [Postgresql]
I have an ArrayField to store Colors for a given Dish object in a Schema and the dishes also have a category class Dish(models.Model): colors = ArrayField(models.CharField(max_length=16)) category = models.CharField(max_length=32) Let's say I have 15 Dish objects, out of which 13 belong to the "Cookware" category and the remaining 2 belong to "Modware" Now I want to append a color to the existing list of colors for a given category in a single update query method (Which has to append my new color to all the array fields of matching Dishes, 13 items in my case) Following are the ways that I have tried to perform this operation and ended up having errors Dish.objects.filter(category="Cookware").update(colors=F("colors")+"red") Dish.objects.filter(category="Cookware").update(colors=F("colors")+["red"]) Following is the error message I am facing when I am trying with the above two queries No operator matches the given name and argument types. You might need to add explicit type casts The following obviously doesn't work as apppend will return None Dish.objects.filter(category="Cookware").update(colors=F("colors").append("red")) PS: Using Django(3.2), Django ORM, Postgres ArrayField from django.contrib.postgres.fields import ArrayField Thanks in advance for spending your time to help me solve this. -
How to I added load more button to show more comments in my django project template with jquery or ajax?
In my django template i don't want to list all comments.If user click show more button,load some more comments.I researched much but I don't know any jquery ,ajax or javascript knowledge.So I did't.Is there anyone who can help me? profile.html <div class="widget review-listing"> <ul class="comments-list" id="loadmorecomment"> {% if comments %} {% for comment in comments %} <li> <div class="comment"> <img class="avatar avatar-sm rounded-circle" alt="User Image" src="{{comment.comment_user.image.url}}"> <div class="comment-body"> <div class="meta-data"> <span style="white-space:pre" class="comment-author">{{comment.comment_user.unvan}} {{comment.comment_user.get_full_name}}</span> <span class="comment-date">{{ comment.updated_date|timesince }}</span> <div class="review-count rating"> {% if comment.star != 0 %} {% for i in comment.star|rjust:comment.star %} <i class="fas fa-star filled"></i> {% endfor %} {% endif %} {% if comment.none_star != 0 %} {% for i in comment.none_star|rjust:comment.none_star %} <i class="fas fa-star"></i> {% endfor %} {% endif %} </div> </div> <p class="comment-content"> {{comment.comment}} </p> </div> </div> </li> {% endfor %} {% else %} <p style="color: orange;">No comment</p> {% endif %} </ul> <!-- Show All --> <div class="all-feedback text-center"> <a id="#loadMore" name="more_comments" href="#" class="btn btn-primary btn-sm"> Load more comments <strong>({{comments.count}})</strong> </a> </div> <!-- /Show All --> </div> -
How to get all the fields from my model in Django
Here is my Model.py class BlogModel(models.Model): blog_id = models.AutoField(primary_key=True) title = models.CharField(max_length=1000) content = FroalaField() user = models.ForeignKey(User, blank=True , null=True , on_delete=models.CASCADE) image = models.ImageField(upload_to='public') created_at = models.DateTimeField(auto_now_add=True) upload_to = models.DateTimeField(auto_now=True) Here is my View.py def my_blogs(request): d = BlogModel.objects.all().filter(user = request.user) return render(request,"my_blogs.html",{'message' : d}) But when I try to get the blog_id and created_at fields then it will shows an error that the requested fields are not present in the respective table. But you can see that the field is n the table itself. Please help