Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My Django minutes being read reads as month?
Hi so I've been developing a countdown timer account, and I made a code like the following (following a tutorial): {% for time in timer %} <p id="tm" style="margin-top:-8px;margin-bottom:20px;display:none;">{{time.time|date:"M d, Y H:m:s"}}</p> {% endfor %} I have set the timer in the clock widget to 03:50 but when I console.log via javascript const timeLength = documents.getElementById('tm'); console.log(timeLength.textContent) It prints 03:12, always been read as month instead of minutes. But the minute is always set to be read as month, And I am already sure that M (uppercase) supposed to represent month, and the m (lowercase) represents the minute, right?? Where did I go wrong? I have been stuck here for days, and from the research on google I have done, always said that M is month, and m is minute.. Thank you in advance. -
How to import Weazyprint properly
I am trying to import Weazyprint but it is not working for some reason, I have followed the instructions from: https://pypi.org/project/WeasyPrint/ https://weasyprint.readthedocs.io/en/latest/install.html#step-5-run-weasyprint but still nothing is working, I am using Pycharm and it is showing underlined error: No module named weasyprint I have python -m pip install WeasyPrint but it doesn't seem to be reading it, although when I try to reinstall it an error saying it is already satisfied Here is the views.py import weasyprint @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order,ordered=True, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0]+ '/css/bootstrap.css')]) return response My question: How to properly install it so that it can be recognized? Is there a way to install it through conda to be installed in my virtual environment? -
Cannot assign "('1',)": "Booking.package" must be a "Package" instance
I am trying to access my package key in my another model this is in my models.py class Booking(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE,null=True) and i am trying to access my package id in package like this booking = Booking() booking.package = id booking.save() but it gives me this error on my template Cannot assign "('1',)": "Booking.package" must be a "Package" instance. -
How to prevent multiple form submissions in Django from server?
Is there a robust way to prevent multiple submissions from server-side? I am aware of the JS solution but I require a server-side solution for peace of mind. -
Django Admin: How to list related objects and add custom attributes
I have the models Lecture and Student in a online homework submission system. Students can be enrolled in lectures, where they can achieve points. The Lecture model has a method called get_grade(self, student) that calculates the current student grade. I would like to have a custom admin page, where all students enrolled in a specific lecture are listed, along with their grade in that lecture. Is there a way to add custom attributes when using list filters? I would like to avoid inlines on the Lecture modifiy page, since the grade calculation takes a while (scanning all the submissions for every student and exercise, selecting the maximum value, summing it up, computing the grade using a grading scale). -
Cant get many to many object in Django-Rest Framework
I am creating a basic restaurant management app using Django-Restframework. I have following models and serializers. Here is my models: from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=5,decimal_places=2) photoUrl = models.URLField(blank=True) category = models.CharField(max_length=50) details = models.CharField(max_length=250) class Restaurant(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=250) logoUrl = models.URLField(blank=True) class Menu(models.Model): restaurant = models.OneToOneField(Restaurant, on_delete=models.CASCADE,primary_key=True,) name = models.CharField(max_length=100) products = models.ManyToManyField(to=Product,blank=True,related_name='menus') class Customer(models.Model): name = models.CharField(max_length=50) surname = models.CharField(max_length=50) class Order(models.Model): Oproducts = models.ManyToManyField(to=Product,blank=True,related_name='orders') customer = models.OneToOneField(Customer,on_delete=models.CASCADE) restaurant = models.OneToOneField(Restaurant,on_delete=models.CASCADE) issueTime = models.DateTimeField(auto_now_add=True) And these are my serializers: from rest_framework import serializers from django.contrib.auth.models import User from .models import * class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password') class ProductSerializer(serializers.ModelSerializer): class Meta : ordering = ['-id'] model = Product fields = ('id','name','price','photoUrl','category','details','menus','orders') extra_kwargs = {'menus':{'required':False},'orders':{'required':False}} class MenuSerializer(serializers.ModelSerializer): products = ProductSerializer(many=True,read_only=True) class Meta: ordering = ['-id'] model = Menu fields = ("restaurant","name","products") extra_kwargs = {'products':{'required':False}} class RestaurantSerializer(serializers.ModelSerializer): menu = MenuSerializer(read_only= True) class Meta: ordering = ['-id'] model = Restaurant fields = ("id","name","address","logoUrl","menu") extra_kwargs = {'menu':{'required':False}} class CustomerSerializer(serializers.ModelSerializer): class Meta: ordering = ['name'] model = Customer fields = ("id","name","surname","order") class OrderSerializer(serializers.ModelSerializer): orders = ProductSerializer(many=True,read_only=True) restaurant = RestaurantSerializer(read_only=True) customer = CustomerSerializer(read_only=True) class Meta: ordering = ['-id'] model … -
Is There An URL That I Can Use To Implement Authentication With Google OAuth2 With Django? [closed]
I'm working on an online Chess Game with Python and Django, but I've gotten a bit stuck on the authentication. I've tried searching the Internet, even on Stack Overflow, but can't find an answer, but I'm basically looking for a url that I can use in my code to exchange an authorization code for the refresh/access token so I can impliment the Log In with Google button. Could someone help me? I know the question might seem a bit silly and simple, but I can't seem to find an answer. Thanks. -
Django get data of object from ManyToManyField form
Hello i created this form : class CartForm(ModelForm): class Meta: model = Cart fields =( 'products',) from theses models : class Product(models.Model): title = models.CharField("Titre", max_length=120) subtitle = models.CharField("Sous-titre", max_length=250) description = models.TextField("Description") picture = models.ImageField(upload_to='objects/') enabled = models.BooleanField("Activé") class Cart(models.Model): products = models.ManyToManyField(Product) and i want to display on my template an list of choice with their data So i send form from views but i don't find any way to get the products description i only get their names ! please help me have a nice day -
Changing the table DRF Token Authentication uses
I have a React Native application that uses a Django backend. I wanted to handle authentication using tokens. I've followed the example at https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication but the issue is that my login is handled this way: I have an OAUTH at the RN application for google login. I get the email from there and send it to my backend. I'd want to get a token for that email and pass it back to my application Current implementation def generateToken(email): Token.objects.get_or_create(email=email) class Authentication(APIView): def post(self, request): userDeserialized = Users.objects.filter( email=request.data['email']) user = UsersSerializer(userDeserialized, many=True) generateToken(request.data['email']) Now this obviously won't work since DRF TokenAuth is looking at the Django admin User table. I want it to look for the email in my Users table. What's the way I could pull that off? -
Google App Engine Django project read-only file system
I'm deploying my project on Google Cloud. All works fine, but uploading images through admin page is failing It gives [Errno 30] Read-only file system: error. I couldn't see any setting to give the write permission on driver etc. Settings.py STATIC_ROOT = 'static' STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ ........ ] if settings.DEBUG: urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Traceback Environment: Request Method: POST Request URL: .../admin/Blog/post/7/change/ Django Version: 2.2.7 Python Version: 3.8.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Blog'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/contrib/admin/options.py" in wrapper 606. return self.admin_site.admin_view(view)(*args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/contrib/admin/options.py" in change_view 1637. return self.changeform_view(request, object_id, form_url, extra_context) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.8/site-packages/django/contrib/admin/options.py" in … -
Routing Issue Dash Visualization to Django App
I am trying to add a simple bar chart to my app but while going through a tutorial, I've added in the bottom portion to my Settings.py code and now my app will not load at all. I've tried adjusting this line to just 'routing.application' and moving it to the bottom of my code but neither has worked. Any thoughts? Error: Traceback (most recent call last): File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Python38\lib\site-packages\channels\management\commands\runserver.py", line 107, in inner_run application=self.get_application(options), File "C:\Python38\lib\site-packages\channels\management\commands\runserver.py", line 132, in get_application return StaticFilesWrapper(get_default_application()) File "C:\Python38\lib\site-packages\channels\routing.py", line 30, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'django_dash.routing Settings.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).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! … -
Django form fields are not displayed
I want to make a form for adding comments, but I only display a form without fields for input, it does not give any errors. I would also like to know how this code can be improved. Any help is appreciated! Here is my forms.py: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] views.py: def comments(request, id): if request.method == 'POST': cf = CommentForm(request.POST or None) if cf.is_valid(): body = request.POST.get('body') comment = Comment.objects.create(post=post, user=request.name, body=body) comment.save() return redirect(post.get_absolute_url()) else: cf = CommentForm() context = { 'cf': cf, } return render(request, 'main/article_detail.html', context) urls.py: from django.urls import path, include from . import views from .views import * urlpatterns = [ path('', PostListViews.as_view(), name='articles'), path('article/<int:pk>/', PostDetailViews.as_view(), name='articles-detail'), path('register/', register, name='register'), path('login/', login, name='login'), ] My form in template: <form method="POST"> {% csrf_token %} {{ cf.as_p }} <button type="submit" class="btn btn-primary" style="width: 100px;position: relative;">Submit</button> </form> my models.py: class Comment(models.Model): post = models.ForeignKey(Article, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() date = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['date'] def __str__(self): return f'Comment {self.body} by {self.name}' -
Stripe - Creating new card for customers
I'm trying to create a card for customers in these steps: 1. Retrive Customer customer = stripe.Customer.retrieve(user_stripe) 2. Token token = request.POST['stripeToken'] 3. Create a new card card = customer.Cards.create(card=token) I'm having a problem with step-3. Seems like 'Cards' is backdated. I also tried card = customer.sources.create(card=token) from some other StackOverflow similar question. But 'sources' are also backdated I think. Now I'm stuck in the middle of a project. Please help me with this. -
Add extra field to ModelSerializer
I want to make a quiz app and I have two models that looks like this: class Question(models.Model): question = models.CharField(max_length=100) class Answer(models.Model): answer = models.CharField(max_length=30) is_true = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE) Now I want to create a ModelSerializer that contains the question and the answes related. Something like this: [ { 'question': 'Something', 'answers': [ 'something1', 'something2', 'something3' ] } ] The problem that I face is that the ForeignKey is in the Answer model not in the Question model. How can I add the Answers in the Question model? Thanks -
Django: How To Pass Some Fields Into A Choice List
I have a model that holds the categories of items which are all BooleanFields. I want to display these categories in each post but there are too many to show so I want to make a form that allows the user to select 5 of their selected categories to display in the posts and then it will say (+ 5 more) or something like that. So is there a way that i can pass only the categories of which the value is true as choices in a ChoiceField? -
how can i create templates directory in community edition of pycharm?
I want to create directory of templates of Django in community edition of pycharm I run this command in community edition of pycharm django-admin startproject mysite but it does not create directory of templates i create that manually but always when I run server to url that are in templates directory always return Django templates does not exist -
Django RDF 'Request' object has no attribute 'accepted_renderer'
I've tried to use a custom render for my RDF responses, then this error suddenly appeared, her is my code: My serializer and API view codes class SupplierSerializer(serializers.ModelSerializer): class Meta: model = models.Supplier fields = [ # "plan", "type", "created", "id", "name", "bio", "established", "logo", "last_updated", "is_active", "date_to_pay", "mobile", "password", ] class SupplierViewSet(viewsets.ModelViewSet): """ViewSet for the Supplier class""" def initial(self, request, *args, **kwargs): """ Runs anything that needs to occur prior to calling the method handler. """ self.format_kwarg = self.get_format_suffix(**kwargs) # Perform content negotiation and store the accepted info on the request neg = self.perform_content_negotiation(request) request.accepted_renderer, request.accepted_media_type = neg # Determine the API version, if versioning is in use. version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted self.perform_authentication(request) self.check_permissions(request) self.check_throttles(request) queryset = models.Supplier.objects.all() serializer_class = serializers.SupplierSerializer permission_classes = [permissions.IsAuthenticated] My custom rendering method and settings from rest_framework.renderers import BaseRenderer from rest_framework.utils import json class ApiRenderer(BaseRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): response_dict = { 'status': 'failure', 'data': {}, 'message': '', } if data.get('data'): response_dict['data'] = data.get('data') if data.get('status'): response_dict['status'] = data.get('status') if data.get('message'): response_dict['message'] = data.get('message') data = response_dict return json.dumps(data) Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', # <-- … -
How to choose (not upload) file from server in admin (Django)
I need to display icon(representing the type of the document inside the post) along with each post. There are hundreds of posts each year. There are about a dozen types of documents hence I need that much icons. The problem is that if I use models.ImageField it will upload a new image each time a post is created, and I will end up with bunch of same icons pretty soon. So I am wondering how to implement the following logic: preview_icon -> choose from server upload_icon -> If the wanted icon does not exists on the server then upload and choose it from server via preview_icon field. My initial idea is to make a new model: class PostIcon(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="icons") post_icon = models.ImageField(upload_to=f"path") So you can connect icon to post. But I am wondering if there is a way to implement the first logic I mentioned, because it would be much neater. Thank you. -
404 error when trying to add item to cart on other websites than main
so Im making webstore. Everything works fine on base url (127.0.0.1:8000) I can add "recommended" items to cart from here but when i go into the page that has all the details about this product (more pictures, description etc) and I want to add to cart from there I get error 404 127.0.0.1:8000/detail/1/updateItem cart.js var updateBtn = document.getElementsByClassName("update-cart") for (i = 0; i < updateBtn.length; i++){ updateBtn[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log(productId,action) console.log(user) if (user === "AnonymousUser"){ console.log("user not logged in") }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log("user created an order") var url = 'updateItem' fetch(url, { method:'POST', headers:{ 'Content-Type': 'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ location.reload() }) } My bet is that the error is in cart.js but im sooo bad at js... urls.py path('updateItem', views.updateItem, name='updateItem'), path('cart', views.cartDetail, name='cart'), views.py def cartDetail(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: order = {'get_cart_total':0,} items = [] print(items) context ={ 'items':items, 'orders':order, } return render(request,'cart.html',context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer,complete=False) orderItem, created … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/login
I already posted this error but I couldn't find an answer, now I'm reposting with more details of my code. I'm new in coding field. I decided to start a project with Django & Python, but I got stuck due to some errors. For the past 3 weeks, I tried to figure out what was the issue but couldn't find it. Please help me to figure out the problems. I have 3 problems: 1-Welcome Page 2-Login & Registration(Sign-up) 3-Seach part 1.Welcome Page Welcome Page is the first page. It's the first page that any users see whenever he comes to the website and it is also a page where he has to login if he want to go to the second page. PROBLEM 1:\ whenever I get to the website, I won't see the content of the first page which is the welcome page. It will take me directly to the second page without even login 2- Login & Registration(Sign-up): Before getting into the second web page, The user has to login. If he can't login, he has to register. After registering, he will be redirected to the login page. PROBLEM 2:\ When I'm trying to Login, I received the … -
Modal Form Connected to SQLite3
I have the following code that is purposed to display a table of data and allow the user to add a new row by clicking a +New button, which opens a modal with the correct form, and then the user hits submit and the new row saves in the table. I am struggling to convert the modal from static, fake data to the data coming from my SQLite3 database. Anytime I try and add my fields (e.g. { stakeholder.employee }) into the modal I get an error: Error: Invalid block tag on line 123: 'stakeholder.id'. Did you forget to register or load this tag? Table of existing data with a button on top to add a new row: <div class="col-md-12"> <button type="button" class="btn btn-primary badge-pill float-right" style="font-size: 14px; width:80px;" data-toggle="modal" data-target="#new">+ New</button> </div> <table class="table table-hover" style="width:90% "> <thead> <tr style="font-family: Graphik Black; font-size: 14px"> <th scope="col">#</th> <th scope="col">Employee</th> <th scope="col">Stakeholder Group</th> <th scope="col">Quadrant</th> <th scope="col">Description</th> </tr> </thead> <tbody> {% for stakeholder in stakeholder_list %} <tr style="font-family: Graphik;font-size: 12px"> <td>{{ stakeholder.id }}</td> <td style="font-size: 15px">{{ stakeholder.employee }}</li></td> <td>{{ stakeholder.stakeholder_group }}</td> <td>{{ stakeholder.stakeholder_quadrant }}</td> <td>{{ stakeholder.description }}</td> <td><button type="button" class="btn btn-danger btn-sm badge-pill" style="font-size: 11px; width:60px" data-toggle="modal" data-target="#new">Edit</button></td> </tr> {% endfor … -
django_neomodel fails to connect to a running database while neomodel works
I made these setting on settings.py, as directed on Getting Started: NEOMODEL_NEO4J_BOLT_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:password@localhost:7687') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_neomodel', 'utils' ] But I only get this error with python manage.py install_labels: neo4j.exceptions.ServiceUnavailable: [SSLCertVerificationError] Connection Failed. Please ensure that your database is listening on the correct host and port and that you have enabled encryption if required. Note that the default encryption setting has changed in Neo4j 4.0. See the docs for more information. Failed to establish encrypted connection. (code 1: Operation not permitted) I know the database and neomodel are ok, because neomodel_install_labels models.py --db bolt://neo4j:password@localhost:7687 works perfectly and creates the nodes on the database. I don't know where I can look for the source of this exception. -
how to integerate jazzcash sandbox with django app?
I am implementing a Django app I need a payment method in it. I wanted to implement JazzCash sandbox in my app how can implement it in my app? -
Accessing one-to-one table field value in Django
I have a Django model which creates a one-to-one-field relationship with Django sites from django.contrib.sites.models import Site class SiteSettings(models.Model): site = models.OneToOneField(Site, related_name="settings", on_delete=models.CASCADE) header_text = models.CharField(max_length=200, blank=True) I want to access the header_text field in the SiteSettings table from the Site model. I have tried getting the value using: value = Site.settings.header_text print(value) I get the error: AttributeError: 'ReverseOneToOneDescriptor' object has no attribute 'header_text' Any help is appreciated. -
Number format wrong
Hi i'm trying to convert html to pdf with WeasyPrint(https://weasyprint.org/), the only problem is the format of the numbers : this is what i should get ( this is rendered with django) the page correct rendered with django this one is the pdf i get from WeasyPrint: page with the numbers with wrong format