Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create pdf file using Django template with proper CSS?
I am new to Django and stack overflow as well. I want to create Django template as a pdf file with all CSS styles .I used following code to create pdf file it renders file content properly but not CSS styles. Here is the code I have used : from io import BytesIO from xhtml2pdf import pisa from django.template.loader import get_template from django.http import HttpResponse from django.shortcuts import render def home(request): pdf = render_to_pdf("abc.html") return HttpResponse(pdf, content_type='application/pdf') def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') else return None -
Django CKEDITOR set max size of an image
how can I set the max size that an image can have in django-ckeditor? Here is the model's code: class Post(models.Model): ... text = RichTextUploadingField(max_length=1050,null=True,blank=True) I tried to use CKEDITOR_THUMBNAIL_SIZE but it didn't work. Also if I can't set the max size of an image is there any other way to resize the image? Thanks. -
Allow user website embed and export django
I am building a t $ c generator website with django. How do I allow user export files and website embed -
Why is google console shows anchor text as URL Django Template instead of actual text?
I have deployed a website using Django (https://www.pkelection.com/). This is my very first app so still trying to learn. So I was checking my SEO progress and ended up checking my google search console and saw this: Google search console results for top linking text The very first URL in top linking text pertains to (https://www.pkelection.com/by-election-p/provincial-assembly/1063-by-election-2022/). I am trying to figure out why google console is showing url text instead of actual anchor text. The same thing is happening with rest of the top linking text so I really fell that I am doing something wrong but can't figure our what. -
Unit testing with AWS Cognito and GraphQL
I'm currently writing tests for my software but got stuck at the point. I try to get data from my db with a normal GraphQL Query but my endpoint is first checking, if the idToken within the header is valid. For the user handling I'm using AWS Cognito but couldn't find a good way to mock the login to retrieve the valid token to query and mutate the data within various endpoints. Any idea how to handle this case? Here is my code from the graphene docs (https://docs.graphene-python.org/projects/django/en/latest/testing/): # Create a fixture using the graphql_query helper and `client` fixture from `pytest-django`. import json import pytest from graphene_django.utils.testing import graphql_query # https://docs.graphene-python.org/projects/django/en/latest/testing/ @pytest.fixture def client_query(client): def func(*args, **kwargs): return graphql_query(*args, **kwargs, client=client) return func # Test you query using the client_query fixture def test_some_query(client_query): response = client_query( ''' query GetAllProjectConfig{ getAllProjectConfig{ project{ id slug name } config{ id } } } ''', ) content = json.loads(response.content) assert 'errors' not in content -
How to get last six month data from date field - django
I do have a model as below class employee(models.Model): employee_name = models.CharField(max_length=100) joining_Date = models.DateField(blank=False, null=False) I want to get data for last six month(including current month) joined employee count month wise. Example: July : 12, June : 10, May : 8, April : 16, March : 13, February : 10, joining_Date storing like "2022-07-22".How to get done this by having date field. Thanks in advance. -
Pass multiple arguments to a custom filter Django
I have a custom filter that looks like this register = template.Library() @register.filter def makebreadcrumbs(value, arg): pass How can I pass multiple arguments to the filter? {% with request.resolver_match.namespace as name_space %} {{ request.path|makebreadcrumbs:name_space|safe }} {% endwith %} In the code above makebreadcrumbs is my custom filter, request.path is a variable (value), and name_space is an argument. -
Django: how to save form and perform math operation with along side saving the form in django?
i am trying to save a form, and after i want to get the new_balance and update the value, i have a function that would save a form, and the form have a field amount, so what i want is this, if i save the form i want to get the new_balance and substract the new_form.amount from the balance, it works but doesn't seems to be saving the new_balance when i refresh my page it shows this alert The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you want to continue?. views.py @login_required def withdrawal_request(request): user = request.user profile = Profile.objects.get(user=user) total_investment = PurchasedPackage.objects.filter(paid=True, user=request.user).aggregate(Sum("investment_package__price"))['investment_package__price__sum'] bonus_earning = profile.earning_point total_ref_earning = profile.referral_point indirect_ref_earning = profile.indirect_ref_earning daily_login_earning = profile.daily_login_earning bonus_point = profile.bonus_point social_share_points = profile.social_share_points pending_payout = WithdrawalRequest.objects.filter(user=request.user, status="pending").aggregate(Sum("amount"))['amount__sum'] if pending_payout == None: pending_payout = 0 total_payout = WithdrawalRequest.objects.filter(user=request.user, status="settled").aggregate(Sum("amount"))['amount__sum'] try: all_earning = total_investment + bonus_earning + total_ref_earning + bonus_point + social_share_points + indirect_ref_earning + daily_login_earning except: all_earning = bonus_earning + total_ref_earning + bonus_point + social_share_points + indirect_ref_earning + daily_login_earning try: new_balance = total_investment + bonus_earning + total_ref_earning + bonus_point + social_share_points + indirect_ref_earning + daily_login_earning … -
Yandex Oauth2 social_django 400 Unknown client with such client_id
When i used 'social_core.backends.yandex.YandexOAuth2', yandex returned it to me: 400 Unknown client with such client_id, what i can do? my setup settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup.apps.CleanupConfig', 'social_django', 'bootstrap5', ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.yandex.YandexOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_URL_NAMESPACE = 'social' YANDEX_OAUTH2_CLIENT_KEY YANDEX_OAUTH2_CLIENT_SECRET my template file <a href="social/login/yandex-oauth2" class="btn btn-light col-2 m-2"> -
Django ImageField image uploaded correctly, but not being displayed in template
I am using Django 3.2 settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'public', 'media') MEDIA_URL = '/media/' models.py def get_dir(instance, filename): return os.path.join('users/profiles', filename) class Foo(models.Model): profile_pic = models.ImageField(blank=True, null=True, upload_to=get_dir) @property def profile_image(self): if self.profile_pic and hasattr(self.profile_pic, 'url'): return self.profile_pic.url else: return getattr(settings, 'USER_DEFAULT_PROFILE_PIC', '/static/userprofile/img/blank-profile-picture.png') page.html <div> <div class="profile-img"> <img style="background-image: url('{{profile.profile_image}}');" /> </div> </div> When I create an instance of Foo and add a picture, the file is correctly saved in: /path/to/myproj/public/media/users/profiles/ However, when I view a page that renders the image, I get a 404 error: http://127.0.0.1:8000/media/users/profiles/tmp8jccrvwa.png However, when I do not load a picture, then the default blank profile is correctly displayed. Why is this? - and how do I fix it? Note: I have only tested this in development, and have not yet tested in production. Note: I am not appending STATIC and MEDIA paths to my urls.py (conditioned on DEBUG flag) - not sure if this is what is causing this issue. -
How do I get the size( gb , mb ) of a video in python?
class videos(models.Model): caption = models.CharField(max_length=200,null=True) videoes = models.FileField(default='Product.png', null=True, validators=[validators.FileExtensionValidator(allowed_extensions=['mp4','mkv']), validators.MaxLengthValidator(limit_value=(10))]) created = models.DateTimeField(auto_now_add=True) -
Individual product detail pages with django cms
I have an e-commerce app based on Django. The product model contains basic fields like name, brand, short description, etc. So far, I only have a "generic product detail page" that displays these information for each product. Now I want to create more extensive product detail pages for some of the products with django cms so that they contain more product information and seo keywords. This means that most products would just have the "generic" detail page and some have a more extensive version. I am using a url path like mydomain.com/products/ and the view finds the respective product to be displayed using the product-slug. So far, this "/products/..." path is handled outside of the django-cms url namespace. I am rather new to django cms and unsure how I should handle this project. My first idea would be: Add empty django-cms placeholders to the generic detail page Include the /products/... path in the django-cms namespace Run a script that creates a page in django-cms for each individual product (whenever a new product is added to the database, a new django-cms page must then be added as well programatically) Go to the products of high interest and add additional content with … -
TypeError at / Accept() got an unexpected keyword argument 'name'
I want to take data from user and save it to the database by using Django. Have tried to solve it. But I am not able to solve this problem and didn't find any working solution on the internet. I'm getting this error My views.py file def Accept(request): if request.method == "POST": name = request.POST.get("name","") phone = request.POST.get("phone","") email = request.POST.get("email","") school = request.POST.get("school","") degree = request.POST.get("degree","") university = request.POST.get("university","") skill = request.POST.get("skill","") about_you = request.POST.get("about_you","") previous_work = request.POST.get("previous_work","") accept = Accept(name=name,phone=phone,email=email,school=school,degree=degree,university=university,skill=skill,about_you=about_you,previous_work=previous_work) accept.save() return render(request,"accept.html") models.py class profile(models.Model): name = models.CharField(max_length=255) phone = models.CharField(max_length=12) email = models.EmailField(max_length=100) school = models.CharField(max_length=100) degree = models.CharField(max_length=100) university = models.CharField(max_length=100) skill = models.TextField(max_length=1000) about_you = models.TextField(max_length=1000) previous_work = models.TextField(max_length=1000) accept.html {% csrf_token %} Name Phone Email School Degree University Skills About You Previous Work Submit enter code here Here is the full traceback error -
Django oAuth2 without saving the user into the database
I'm currently coding a website with Django and I successfully implemented an external oAuth2. (I'm not using any libraries) the problem is that the user is saved in the database. I would like to avoid it for hosting costs reasons. In my current project, the oAuth2 is purely for verification purposes. Is there a way in Django to log in a user in without saving him to the database? I would like the website to keep him logged in if the page is refreshed but logged out if the page is closed. Thanks! -
Using icontains for search queries with spaces in Django
I made simple search through my site, which is searching through several models within app. It worked fine until i realized that it can't search queries with spaces. Is there any option to search with spaces? Model: class Event(BaseModel): name = models.CharField(max_length=255, blank=True) description = models.TextField(blank=True) Object Event.objects.create( name="Test query event", description="Test Description" ) Query itself: query = "test query" Event.objects.all().annotate(search=SearchVector("name")).filter(search__icontains=query) I'm using latest versions of Django+DRF+django-filters, but it's possible to add other packages to project. -
Makemigration with django4.0.6 and python3.10.5 doesn't work
I'm currently coding a blog as a side project, whenever I make a considerable modification in my models, I cannot migrate. This is my model from ckeditor.fields import RichTextField from django.contrib.auth.models import User from django.db import models from django.template.defaultfilters import slugify from django.urls import reverse class Tag(models.Model): name = models.CharField(max_length=255, default="Uncategorized") class Meta: ordering = ['name'] def __str__(self): return self.name def get_absolute_url(self): return reverse('blog:home') class Post(models.Model): ACTIVE = 'active' DRAFT = 'draft' CHOICE_STATUS = ( (ACTIVE, 'Active'), (DRAFT, 'Draft') ) title = models.CharField(max_length=255) title_color = models.CharField(max_length=50, default="white") header_image = models.ImageField(upload_to='images/headers', null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) table_content = RichTextField(default="CONTENTS", blank=True, null=True) body = RichTextField(blank=True, null=True) snippet = models.CharField(max_length=255, default="") date_published = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=CHOICE_STATUS, default=DRAFT) slug = models.SlugField() tag = models.ManyToManyField(Tag) def __str__(self): return self.title + ' | ' + self.author.get_full_name() def get_absolute_url(self): return reverse('blog:article_details', args=(str(self.id), self.slug)) @property def date(self): return self.date_published.date() def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) class PostPicture(models.Model): name = models.CharField(max_length=255, default="") files = models.FileField(upload_to="images/post") def __str__(self): return self.name Now, in my model, I had the class named Category and decided I don't need it anymore and just renamed it Tag. When I make migrations, I have this error … -
Dajngo template rendering
When i render blogpost.html page i can't see any content in my page. Please any devloper help me. My code look like this. My urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='Blog_home'), path('<slug:slug>', views.blogpost, name='blogpost'), ] my views.py from django.shortcuts import render from django.http import HttpResponse from blog.models import Post # Create your views here. def index(request): post = Post.objects.all() context = {'post':post} return render(request, 'blog/bloghome.html', context) def blogpost(request, post_id): post = Post.objects.filter(slug=slug) context = {'post':post} return render(request, 'blog/blogpost.html', context) Template Name:- blogpost.html {% extends 'basic.html' %} {% block title %}Blog{% endblock title %} {% block body %} <div class="contaier"> <div class="row"> <div class="col-md-8 py-4"> <h2 class=" blog-post-title">{{post.title}}</h2> </div> </div> </div> {% endblock body %} -
Where can I find a list of all available methods of a request object in Django DTL?
How can I know what methods are used for request object in DTL? {{ request.WHAT }} -
Django CMS: Error while setting up django-cms
I'm having a WSGI error while following the installation set up for django-cms from th official documentation. I ran test with python manage.py cms check and it was sucessful. Checking django CMS installation Sekizai Sekizai is installed [OK] Sekizai template context processor is installed [OK] Sekizai namespaces 'js' and 'css' found in 'home.html' [OK] Plugin instances ================ Plugin instances of 0 types found in the database [OK] The plugins in your database are in good order [OK] Presence of "copy_relations" All plugins and page/title extensions have "copy_relations" method if needed. [OK] PlaceholderField PlaceholderField configuration okay [OK] OVERALL RESULTS 9 checks successful! Installation okay But when I try running server, I get this thread of errors. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 22, 2022 - 08:47:41 Django version 3.2.14, using settings 'projcms.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\adedi\Documents\Dev\Projects\Django\dj-cms\env\lib\site-packages\django\utils\module_loading.py", line 13, in import_string module_path, class_name = dotted_path.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\adedi\Documents\Dev\Projects\Django\dj-cms\env\lib\site-packages\django\core\servers\basehttp.py", … -
Celery unavailable after dockerization in a Django app
I have a Django app that I've been trying to dockerize. I've successfully dockerized Django with gunicorn and nginx so the main part of the app is running. However, I also have tasks that need to be run using Celery. I dockerized rabbitmq, and I think that was successful, as before installing it I had Connexion refused and I don't anymore. I only lack Celery to be dockerized so, as my tasks are not executed nor stored in the database, my Celery configuration is probably wrong, however I couldn't find where I'm going wrong with it. Here is my docker-compose.yml: version: '3.8' services: django_gunicorn: volumes: - static:/app/static - media:/media env_file: - env build: context: . ports: - "8000:8000" nginx: build: ./nginx volumes: - static:/static - media:/media ports: - "80:80" depends_on: - django_gunicorn rabbitmq3: image: rabbitmq:3-alpine ports: - 5672:5672 celery: restart: always build: context: . command: celery -A main worker -l info env_file: - env depends_on: - rabbitmq3 - django_gunicorn volumes: static: media: Dockerfile: FROM python:3.10.5-alpine RUN pip install --upgrade pip RUN wget https://upload.wikimedia.org/wikipedia/commons/b/b9/First-google-logo.gif -O media/media.gif COPY ./requirements.txt . RUN pip install -r requirements.txt COPY ./src /app WORKDIR /app COPY ./entrypoint.sh / ENTRYPOINT ["sh", "/entrypoint.sh"] entrypoint.sh: #!/bin/sh python manage.py migrate python … -
Django placing order (like restaurant etc)
I'm building an online restaurant website, I have an app with a few models containing the Menu. I want to add another app that utilizes the Menu models to populate multiple choice field. Something like an ordering page. But I've no idea how to do that. Also, how should my order model look like? -
I am trying to create an app that uses the Django REST Framework and Flask, but it is not working correctly
I'm having trouble with my python app using django and flask framework. It's creating a database and all of that stuff but when it tries to make a request to /api/v1/users, it always comes back with data errors. I've tried looking at the logs for the site and it says the same thing "connection refused" when the server makes a connection attempt, and I can't seem to figure out why this is happening. My code looks like this right now: from flask import Flask, jsonify, request import datetime app = Flask(__name__) db=sqlite3.connect('data.db') class User(object): def __init__(self, id, name, email, password): self.id = id self.name = name self.email = email self.password = md5_hash(password).hexdigest() def __repr__(self): return "<User %s>" % (self.id,) @app.route("/api/v1/users", methods=('GET', 'POST')) def users(): if request.method == 'GET': users = db.execute('SELECT * FROM user ORDER BY id ASC').fetchall() data = dict(users=users) return jsonify(data) elif request.method == 'POST': newuser = User(request.form.get('id'), request.form.get('name'), request.form.get('email'), request.form.get('password')) db.executemany("INSERT INTO user VALUES (?,?,?,?)", (newuser.id, newuser.name, newuser.email, newuser.password)) return jsonify(status="ok") else: return "Invalid method." @app.errorhandler(404) def page_not_found(e): return jsonify(status='Not Found') if __name__ == "__main__": app.run(host='0.0.0.0', port=5000) The error message I get in the logs is: 127.0.0.1 - - Referer: http://localhost:5000/api/v1/users 127.0.0.1 - - Connection: close 127.0.0.1 … -
Django User cannot login
I made a simple register and login script, the register script works and sends the user information to a database but the login does not log the user in. This is the login function in views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, login, logout from .forms import LoguserForm # Create your views here. 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 not None: login(request, user) return redirect('home') context = {} return render(request, 'accounts/login.html', context) This is the login.html file: <body class="container"> <div class="loginbox"> <form id="login" class="input-group"> {% load static %} <img src="{% static 'accounts/images/logo.png' %}" id="loginlogo"> {% csrf_token %} <input type="text" class="inputfield" name="username" placeholder="Username"> <input type="password" class="inputfield" name="password" placeholder="Password"> <input type="submit" class="submitbtn" value="Login"></input> {% for message in messages %} <p>{{message}}</p> {% endfor %} <p1 class="registerp">New here? <a href="/register">Register</a></p1> </form> </div> This is the homepage code: def home(request): return HttpResponse('Home Page') When I try to login instead of redirecting me to the home page the URL changes to: http://127.0.0.1:8000/?csrfmiddlewaretoken=F63yG1ZNQTr4e6tRvjvj5TraSLeDDxAGCm1S89k4yuq21DyPgS4AlnfxA2KtnrA4&username=Tester&password=888tyuuyt -
how to display only domain name of the link in django?
i have a link <a href="{{ article.url }}" target="_blank">{{ article.title | safe}}</a> and link url name {{ article.url }} in my html file but i want to display only domain.com name without full url. i tried from urllib.parse import urlparse url = models.URLField() domain = urlparse(url).netloc in models.py than {{ article.domain }} in html file but get AttributeError: 'URLField' object has no attribute 'decode' -
Update form store none value when I submit the update form. How can I fix It?
I made a feedback form (def feedBack) so that a user can give feedback. It's working well. Now my motive to create an update form so that a user can be able update their feedback. I also have written a view for update feedback (def UpdateFeedback). But it's not working perfectly. When I submit the update form, then it updates none. Where did the actual problem occur? views.py: This view for storing feedback and it's working well. def feedBack(request,quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) if request.method == "POST" and request.user.is_authenticated: try: ProductREVIEWS.objects.create( user=request.user, product=quick_view, feedBACK=request.POST.get('feedBACK') ) return redirect('quick_view', quick_view_id) except: return redirect('quick_view', quick_view_id) else: return redirect('quick_view', quick_view_id) this view for update the feedback, but it's store none def UpdateFeedback(request, id): feedback = ProductREVIEWS.objects.get(pk=id) product_id = feedback.product.id reviewers = feedback.user if request.method == "POST": form = UpdateFeedbackForm(request.POST) if form.is_valid() and reviewers.id == request.user.id: UpdateFeedbackForm(request.POST) feedBACK = form.cleaned_data.get('UpdateFeedBACK') feedback.feedBACK = feedBACK feedback.save() messages.success(request, "Feedback is updated") return redirect('quick_view', product_id) forms.py: class UpdateFeedbackForm(forms.ModelForm): class Meta: model = ProductREVIEWS fields = ('feedBACK') labels = { 'feedBACK':'Change Your View' } widgets = { 'feedBACK':forms.Textarea(attrs={'class':'form-control', 'style':'font-size:13px;'}) } models.py: class ProductREVIEWS(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE) product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE) feedBACK = models.TextField(blank=True, null=True) urls.py: path("feedBack/<int:quick_view_id>/", views.feedBack, name="feedBack"), path("UpdateFeedback/<int:id>/", …