Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework returns less data when using custom permission
I've built an app that query django rest framework and creates a form based on the structure returned by OPTIONS method. I've tired to allow requesting those fields to anyone so user can read them before authenticating. I put this code in my API views: SAFE_METHODS = ['OPTIONS'] class IsAuthenticatedOrReadOnly(permissions.BasePermission): """ Allow OPTIONS to anyone """ def has_permission(self, request, view): if (request.method in SAFE_METHODS or request.user and request.user.is_authenticated): return True return False And added the option to the serialize view: class NeedyPageViewSet(viewsets.ModelViewSet): """ API endpoint that allows needy page to be viewed or edited. """ queryset = NeedyPage.objects.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) authentication_classes = [SessionAuthentication, BasicAuthentication, TokenAuthentication] serializer_class = NeedyPageSerializer permission_classes = [IsAuthenticatedOrReadOnly] I'm no longer getting Authentication credentials were not provided. error with anonymous user but the data is missing most of the fields. Usually I get something like this when I'm authenticated: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "name": "Needy Page List", "description": "API endpoint that allows needy page to be viewed or edited.", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "name": { "type": "string", "required": false, "read_only": false, "label": "Name", "max_length": 25 … -
object has no attribute '_meta' in django
im new in django and sqlite. i want to make login system. but im stuck. Exception Value: 'tuple' object has no attribute '_meta' this is my code: def index(request): if request.method == 'POST': usernames = request.POST['name'] passwords = request.POST['pass'] c.execute(f"SELECT * FROM ogrenciler WHERE ogrenci=? AND sifre=?",(usernames,passwords)) a= c.fetchone() if not a: return redirect("index") elif a: auth.login(request,a) return redirect("test") else: return render(request, 'pages/index.html') how can i solve that ? my problem is in auth.login(request,a) -
How to show generated QR Code in generated PDF Django
I want to show generated qr code in my generated PDF but it doesn't show. If in html it's showed but not in pdf. I want to show qrcode in PDF without save it to media Here is my code in views.py : path_qr = 'localhost:8000/qrcode/detail/1' qr = QRCode() qr.add_data(path_qr) img = qr.make_image() data = { 'qr_code': img } template = get_template(template_src) html = template.render(data) result = BytesIO() pdf1 = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) return HttpResponse(result.getvalue(), content_type='application/pdf') And here is my code in html: <img src="{{ qrcode }}" width="100" height="100"> -
Calculate the Average delivery time (days) Django ORM
I want to calculate the average delivery time (in days) of products using ORM single query (The reason of using single query is, I've 10000+ records in db and don't want to iterate them over loops). Here is the example of models file, I have: class Product(models.Model): name = models.CharField(max_length=10) class ProductEvents(models.Model): class Status(models.TextChoices): IN_TRANSIT = ("in_transit", "In Transit") DELIVERED = ("delivered", "Delivered") product = models.ForiegnKey(Product, on_delete=models.CASCADE) status = models.CharField(max_length=255, choices=Status.choices) created = models.DateTimeField(blank=True) To calculate the delivery time for 1 product is: product = Product.objects.first() # delivered_date - in_transit_date = days_taken duration = product.productevent_set.filter(status='delivered') - product.productevent_set.filter(status='in_transit') I'm here to get your help to getting started myself over this so, that I can calculate the average time between all of the Products. I'd prefer it to done in a single query because of the performance. -
Django rest, hide output values in the response
I have a "published" table in models with the value true or false. I want to hide the ones with the false value in the response.enter image description here #models class Menu(models.Model): name = models.CharField(max_length=64) content = models.TextField(blank=True) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) published = models.BooleanField(default=True) #views class MenuAPIList(generics.ListCreateAPIView): """ обзор меню, доустпен всем зарег и нет """ queryset = Menu.objects.all() serializer_class = MenuSerializer permission_classes = (IsAuthenticatedOrReadOnly, ) #serialisers class MenuSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Menu fields = ("name", "content", "published", "user") -
Next redirected view indicates anonymous user even though login was successful
So I have this code. However, although I am able to login correctly with sessionid set, the redirected view still indicates request.user.is_authenticated is False. Any assistance is greatly appreciated. class TeacherLoginView(SuccessMessageMixin, TemplateView): form_class = TeacherLoginForm template_name = 'accounts/teacher-login.html' success_message = 'Logged in Successfully!' error_message = 'Staff ID or Password incorrect!' def get(self, request): form = self.form_class() message = '' return render(request, self.template_name, context={'form': form, 'message': message}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = TeacherBackend.authenticate(self, username=form.cleaned_data['staff_id'], password=form.cleaned_data['password'], ) if user is not None: login(request, user, backend='accounts.backends.backends.TeacherBackend') if request.GET.get('next') and request.user.is_authenticated: return redirect(request.GET.get('next')) return redirect('userviews:teacher-home') else: messages.error(self.request, self.error_message) return render(request, self.template_name, context={'form': form}) This is view am trying to redirect to after a successful login class TeacherHomeView(LoginRequiredMixin, View): template_name = 'userviews/teachers/index.html' login_url = '/accounts/login-teacher/' redirect_field_name = 'next' -
Store Django filter_backends search keyword
I want to store the keyword that filter_backend uses to search. This is the class being used. class SearchListView(generics.ListAPIView): queryset = TrainingDetail.objects.all() serializer_class = TrainingDetailSerializer filter_backends = [filters.SearchFilter] search_fields = ['^course_name'] The URL being called is: http://localhost:8003/api/company/search/?search=Danphe&ordering=-created_date So, basically I want to store the word Danphe. How can this be achieved ? -
how to pass model data to template using a function based view?
I have a simple model for a Group: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) email_list = ArrayField( models.CharField(max_length=255, blank=True), blank=True, default=list, ) With four views for it: DetailView, UpdateView, DeleteView, and send_notifications. The first two are class based and the last is function based. This is where I'm having an issue. When I move from my base.html to any of my class based views: path('group/<int:pk>/', GroupDetail.as_view(), name='group_detail'), path('group/<int:pk>/edit/', UpdateGroup.as_view(), name='update_group'), path('group/<int:pk>/delete/', DeleteGroup.as_view(), name='delete_group'), I'm able to pass the specific model's data using it's primary key: <a href="{% url 'group_detail' group.pk %}">DETAILS</a> <a href="{% url 'update_group' group.pk %}">EDIT</a> <a href="{% url 'delete_group' group.pk %}">DELETE</a> So when I'm in one of these three views I'm able to render things like {{group.name}} or {{group.description}}, but when I go to my function based view: def notifications(request, pk): group = Group.objects.get(id=pk) if request.method == 'POST': subject = request.POST['subject'] message = request.POST['message'] recipients = group.email_list for recipient in recipients: send_mail ( subject, message, NOTIFICATION_EMAIL, [recipient], fail_silently=False ) return render(request, 'send_notifications.html', {'subject': subject, 'message': message}) else: return render(request, 'send_notifications.html', {}) via its url: path('group/<int:pk>/notifications/', notifications, name='send_notifications'), and link: <a href="{% url 'send_notifications' group.pk %}">SEND NOTIFICATIONS</a> I'm not … -
Axios "PUT" request returning bad request 400
I am trying to update a users profile but keep getting 400 bad request. When I try on postman it works fine. My api call: // Data const data = { header_pic: JSON.stringify(new_header_pic), avi_pic: JSON.stringify(new_avi_pic), email: JSON.stringify(new_email), first_name: JSON.stringify(new_first_name), last_name: JSON.stringify(new_last_name), username: JSON.stringify(new_username), location: JSON.stringify(new_location), bio: JSON.stringify(new_bio), url: JSON.stringify(new_url) }; //Update Profile const updateProfile = async () => { console.log(JSON.stringify(data)) try { await axios.put(url, JSON.stringify(data), { 'headers': { 'Content-Type': 'multipart/form-data', 'Authorization': 'token' } }).then(res => { console.log(res.data) {res.data === 200} { navigation.navigate('MyProfile') } }); } catch (e) { console.log(e) }; } If i change the content type to application/json I get 415 Unsupported Media Type My backend view (django): class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer parser_classes = [MultiPartParser, FormParser] queryset = User.objects.all() def put(self, request): user_id = self.request.user header_pic = request.data.get('header_pic') avi_pic = request.data.get('avi_pic') email = request.data.get('email') first_name = request.data.get('first_name') last_name = request.data.get('last_name') username = request.data.get('username') location = request.data.get('location') bio = request.data.get('bio') url = request.data.get('url') user = User.objects.update( user_id, header_pic, avi_pic, email, first_name, last_name, username, location, bio, url ) user.save() serializer = UserSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) Appreciate any help! -
Django Hello World - does not appear to have any patterns in it - what causes the problem
Hi I'm a python dev (among other things), trying to learn Django and I'm already stuck at the hello world. It's tricky cause I'm not quite sure what I'm dealing with at this stage, so maybe you can help me figure it out. I've got the environment configured via anaconda 2.x, I've tested everything was working until I created the first app. So here are the sources, maybe you can tell what's causing the error. File structure For the project: settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages_app.apps.PagesAppConfig', ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('pages_app/', include('pages_app.urls')), ] For the pages_app: apps.py from django.apps import AppConfig class PagesAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'pages_app' urls.py from django.urls import path from . import views url_patterns = [ path('', views.homePageView, name='home'), ] views.py from django.http import HttpResponse def homePageView(request): return HttpResponse("Hello, world. You're at the polls index.") I'll note that this is my second attempt at hello world app, first one was deleted after I found out name "pages" was taken by a python package in my general_env and I deleted it, all references and created pages_app … -
Django Migration fails because of incompatibility in foreign key type
I have added secondary_client and secondary_pi fields in List table and when I run migrations I am getting this error: django.db.utils.OperationalError: (3780, "Referencing column 'secondary_client_id' and referenced column 'id' in foreign key constraint 'todo_list_secondary_client_id_cd997cc0_fk_todo_client_id' are incompatible.") This is my models.py: class Client(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) organisation = models.CharField(max_length=60) email = models.EmailField(max_length=70, blank=True, null=True, unique=True) class List(models.Model): ... client = models.ForeignKey(Client, related_name='client', blank=True, null=True, on_delete=models.CASCADE) pi = models.ForeignKey(Client, related_name='pi', blank=True, null=True, on_delete=models.CASCADE) secondary_client = models.ForeignKey(Client, related_name='secondary_client', blank=True, null=True, on_delete=models.CASCADE) secondary_pi = models.ForeignKey(Client, related_name='secondary_pi', blank=True, null=True, on_delete=models.CASCADE) ... The migrations are working on my local machine However failing on the server. -
Django - I would like to fill a form with data from an api get request, data will then be reviewed and submitted
My goal is to have the user input a barcode number which is used to make an API JSON fetch from: https://world.openfoodfacts.org/api/v0/product/${barcode}.json where I will map the data, something like this: const OffData = [barcodeData].map((result) => ( { brand: result.brands, name: result.product_name, allergens: result.allergens, barcode: result._id, category: result.categories, weight: result.product_quantity, }) to then fill my product form: (set each input value) <div class="flex justify-center space-x-7"> <div class="card bg-base-200 shadow-2xl w-96 flex flex-row justify-center items-center pb-4 px-2"> <div class="form-control w-full max-w-xs"> <label class="label"> <span class="card-title">Manual entry</span> </label> <form id="" action="" class=""> <div class="flex flex-row items-center space-x-4"> <input id="barcode_lookup" name="" type="number" placeholder="Enter EAN" class="input input-bordered w-full max-w-xs" /> <i class="fa-solid fa-magnifying-glass fa-lg cursor-pointer" onclick="document.getElementById('barcode_lookup').submit()"></i> </div> <div class="flex flex-row items-center align-middle space-x-6 px-7 py-2"> <div class="flex flex-col"> <input type="text" placeholder="Brand" class="input input-ghost w-full max-w-xs" /> <input type="text" placeholder="Name" class="input input-ghost w-full max-w-xs" /> <input type="number" placeholder="Weight" class="input input-ghost w-full max-w-xs" /> </div> <div class="flex flex-col"> <input type="text" placeholder="Category" class="input input-ghost w-full max-w-xs" /> <input type="text" placeholder="Allergens" class="input input-ghost w-full max-w-xs" /> <label class="input input-ghost cursor-pointer w-full "> <span class="input-ghost">Perishable?</span> <input type="checkbox" checked="checked" class="checkbox checkbox-xs" /> </label> </div> </form> </div> </div> </div> product form screenshot which I can later submit to my database This … -
'int' object has no attribute 'save' in Django?
I get this error 'int' object has no attribute 'save' when i try to asign a new integer value to a field in my model. I have tried chaging the int to str(250) but i want it to be an integer and not a string profile_id = request.session.get('ref_profile') if profile_id is not None: recommended_by_profile = Profile.objects.get(id=profile_id) print(profile_id) p1 = recommended_by_profile.indirect_ref_earning + 250 p1.save() -
Extending class-based generic views two have 2 models (SIMPLEST WAY) + template
I need to extend the (generic.DetailView): to include my second class, PostImage. According to the documentation (https://docs.djangoproject.com/en/4.0/topics/class-based-views/generic-display/), class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' should include something like this: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['image_list'] = PostImage.objects.all() return context models.py from django.db import models from django.contrib.auth.models import User from django.forms import ImageField from django.utils.safestring import mark_safe STATUS = ( #tuple (0,"Draft"), (1,"Publish") ) # Create your models here. class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images', null=True, blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='images', null=True, blank=True) def __str__(self): return self.post.title views.py from django.views import generic from .models import Post, PostImage # Create your views here. class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' urls.py from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] Can I leave the urls unchanged? post_detail.html {% extends 'base.html' %} {% block content %} {% load static %} <div class="container"> … -
User having multiple accounts need to perform single account flow django
I am trying to select any one of the account that user has and should proceed with that account flow in django.how to send requests to django which should only ferch details of the selected account -
django + tailwind : tailwind not working in deployment environment on a ubuntu server
I have build a website in development environment using django and tailwind. I pushed the project to github and then cloned inside of a ec2 instance. The deployment worked fine (website running) besides the fact that tailwind won't work. Please forgive me if my question is dumb, it is my first project using tailwind. I have made sure that node.js version and npm version are the same on my local environment and on my ubuntu server but I am still getting the issue. From the django-tailwind documentation https://django-tailwind.readthedocs.io/en/latest/usage.html , getting tailwind to deployment was the following command. python manage.py tailwind build doing that on my production server outputs the following error: node:internal/modules/cjs/loader:939 const err = new Error(message); ^ Error: Cannot find module 'semver' Require stack: - /usr/share/nodejs/npm/lib/utils/unsupported.js - /usr/share/nodejs/npm/lib/cli.js - /usr/share/nodejs/npm/bin/npm-cli.js at Module._resolveFilename (node:internal/modules/cjs/loader:939:15) at Module._load (node:internal/modules/cjs/loader:780:27) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.<anonymous> (/usr/share/nodejs/npm/lib/utils/unsupported.js:2:16) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Module._load (node:internal/modules/cjs/loader:827:12) at Module.require (node:internal/modules/cjs/loader:1005:19) { code: 'MODULE_NOT_FOUND', requireStack: [ '/usr/share/nodejs/npm/lib/utils/unsupported.js', '/usr/share/nodejs/npm/lib/cli.js', '/usr/share/nodejs/npm/bin/npm-cli.js' ] } Node.js v18.2.0 that is strange because I installed it and still won't find it: which semver /usr/local/bin/semver and 2. It was needed and not even there in development environment. … -
Building a website to query large datasets in database
I have downloaded filings from the SEC website and created code to parse the txt files into DataFrames in Pandas. The data contains approximately 13M lines of records so I have exported the data to a CSV file on my local drive. I would like to be able to build a website similar to that of a Bloomberg Terminal where I can query the data from any location (other than my local computer). What would be the best way to store this data (MS Access has size limitations, Oracle maybe? MySQL?) to be able to build an interface to manipulate this data? Building a website from scratch is no small feat so any suggestions/advice would be appreciated. -
else block not executing in Django/python
query= request.GET.get("query") if query: story=Story.objects.filter(Q(title__icontains=query) | Q(body__icontains=query)| Q(des__icontains=query)) else: tag=get_object_or_404(Tag, slug=query) story=Story.objects.filter(tags__in=[tag]) I am implementing this search functionality in my django project. It is intended to allow me search database by title, body, description, and tags. While I can search the first three with strings, tags can only be searched by id, hence the need to seperate it into a seperate else block. But I don't understand why the else block isn't executing when I expect it to. -
how do i perform a math operation in django?
i am trying to calculate the new_balance when a user withdraw any amount from thier main balance. i am trying to perform this operation when the form is being submitted but i do not know if this is the perfect way to perform this operations. This is what i am trying to achive. @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 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 except: all_earning = bonus_earning + total_ref_earning try: new_balance = total_investment + bonus_earning + total_ref_earning + bonus_point + social_share_points except: new_balance = bonus_earning + total_ref_earning if request.method == "POST": form = WithWithdrawalRequestForm(request.POST) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user if new_form.amount > all_earning: messages.warning(request, "You cannot withdraw more than what is in your wallet balance.") return redirect("core:withdrawal-request") elif pending_payout > new_balance: messages.warning(request, "You have reached your wallet limit") return redirect("core:withdrawal-request") else: new_form.save() new_balance = new_balance - new_form.amount messages.success(request, f"Withdrawal Request Is Been Processed...") return redirect("core:withdrawal-request") else: form = WithWithdrawalRequestForm(request.POST) context = { "form":form, "new_balance":new_balance, } … -
Django Login suddenly stopped working - timing out
My Django project used to work perfectly fine for the last 90 days. There has been no new code deployment during this time. Running supervisor -> gunicorn to serve the application and to the front nginx. Unfortunately it just stopped serving the login page (standard framework login). I wrote a small view that checks if the DB connection is working and it comes up within seconds. def updown(request): from django.shortcuts import HttpResponse from django.db import connections from django.db.utils import OperationalError status = True # Check database connection if status is True: db_conn = connections['default'] try: c = db_conn.cursor() except OperationalError: status = False error = 'No connection to database' else: status = True if status is True: message = 'OK' elif status is False: message = 'NOK' + ' \n' + error return HttpResponse(message) This delivers back an OK. But the second I am trying to reach /admin or anything else requiring the login, it times out. wget http://127.0.0.1:8000 --2022-07-20 22:54:58-- http://127.0.0.1:8000/ Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response... 302 Found Location: /business/dashboard/ [following] --2022-07-20 22:54:58-- http://127.0.0.1:8000/business/dashboard/ Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response... 302 Found Location: /account/login/?next=/business/dashboard/ [following] --2022-07-20 22:54:58-- http://127.0.0.1:8000/account/login/? next=/business/dashboard/ Connecting to 127.0.0.1:8000... … -
Avoid Django form being resubmitted by using HttpResponseRedirect
My views.py runs code fine when I press a button on my HTML page, views.py: def start_or_end_fast(request): #If starting fast, add a row to the db: #fast_finished = False #start_date_time using = current time #end_date_time using = current time if request.method == 'POST' and 'start_fast' in request.POST: add_fast = logTimes(fast_finished=False,start_date_time=datetime.now(),end_date_time=datetime.now()) add_fast.save() print(add_fast.start_date_time,add_fast.end_date_time) print('Fast started') #return render(request,'startandstoptimes/index.html') return HttpResponseRedirect('startandstoptimes/index.html') You can see my commented return line, this works but when I refresh the page I can resubmit the data, I want to avoid this. In researching my solution, I saw this could be solved using HttpResponseRedirect but I am not able to get this to work with my code, the more I change the more broken things become. My application urls.py: from turtle import home from django.urls import path,include from . import views urlpatterns = [ path('', views.start_or_end_fast,name="start_or_end_fast") ] My project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('startandstoptimes.urls')) ] I believe it is related to the URLs, due to the 404 message I see: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/startandstoptimes/index.html Using the URLconf defined in myfastingsite.urls, Django tried these URL patterns, in this order: admin/ [name='start_or_end_fast'] The current path, startandstoptimes/index.html, didn’t match any of these. Am … -
get values from html select in views with django
I would like to get the value and even the string if possible of the selected value in my HTML file. index.html <form action="#" method="post"> <select id="drop1"> <option disabled selected value> -- select value -- </option> {% for i in df %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> </form> views.py def index(request): if request.method == 'POST': selected_value = request.POST.get('drop1') print(selected_value) else: return render(request, 'index.html', {'df': df.designation_list}) With this, nothing is returned. I saw that I have to use <form></form> to get an html value but I can't find what to put in the action= field. Can you see what is missing in my code? Thanks in advance -
How to prerender html/JS with django
I am currently using fancyTable.js https://github.com/myspace-nu/jquery.fancyTable to paginate results and allow a dynamic search. The pagnation and search works very well after the page loads, however, the initial page load is delayed (~2-3 seconds) due the large amount of data being paginated (with a smaller data set this delay is not noticeable) I tried to prerender the page using <link rel="prerender" href="{% url 'dashboard' %}"> in the header, but I'm assuming the prerender isn't working because the django url has not been called, meaning the data has not been passed to the web page. What is the best way to prerender this page? dashboard.html (companies is the issue, it contains 3000+ objects): <table id="mytableID" style="width:100%; " class="table table-striped sampleTable"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> {% for user in companies %} <tr class="tableHeaderData" style="display: none"> <td class=""> <input class="checkboxHeaderData" style=" " type="checkbox"> </td> <td class="headerNameMainData"> <div class="nameHeaderData"> <p class="textStyleData">{{ user.company }}</p> </div> </td> <td class="headerStageMainData"> <p class="textStyleData">{{ user.stage }}</p> </td> <td class="headerStatusMainData"> <p class="headerStatusData">In Progress</p> </td> <td class="headerSubmarketMainData"> <p class="headerSubmarketData">{{ user.submarket }}</p> </td> <td class="headerKeywordsMainData"> <p class="headerKeywordsData">Keyword</p> </td> </tr> {% endfor %} </table> The js script: <script type="text/javascript"> $(document).ready(function() { $(".sampleTable").fancyTable({ /* Column number for initial sorting*/ sortColumn:1, /* Setting pagination … -
Using Pillow in Django with pathlib instead of os
I'm doing a project in Django 4.0.6, which uses pathlib instead of os. I installed Pillow to include an image in the user's profile, but when I try to save the image I get the following error: TypeError at /admin/account/profile/2/change/ expected str, bytes or os.PathLike object, not tuple In settings.py this is the media setting: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR, 'media' If I import os and set MEDIA_ROOT = os.path.join(BASE_DIR, 'media/'), then it works, but I would prefer using pathlib, and no mixing pathlib and os, this is just a personal preference, but I would like to understand why this error is happening. Below is the tracebak complete: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/account/profile/2/change/ Django Version: 4.0.6 Python Version: 3.10.4 Installed Applications: ['account.apps.AccountConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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 (most recent call last): File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/contrib/admin/options.py", line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/ro/CS/rypptc/polmanv0.0.0.1/env/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 242, … -
type object 'Task' has no attribute '_meta'
Am starter in Django and tried CreateView class and got the following error: Am unable to find the issue. ListView and DetailView works fine. Trace Log : System check identified no issues (0 silenced). July 20, 2022 - 22:38:33 Django version 3.2.12, using settings 'configs.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /task/create/ Traceback (most recent call last): File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 168, in get return super().get(request, *args, **kwargs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 133, in get return self.render_to_response(self.get_context_data()) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data kwargs['form'] = self.get_form() File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 32, in get_form form_class = self.get_form_class() File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\views\generic\edit.py", line 101, in get_form_class return model_forms.modelform_factory(model, fields=self.fields) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 563, in modelform_factory return type(form)(class_name, (form,), form_class_attrs) File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 261, in new fields = fields_for_model( File "C:\Users\mayank.shah.virtualenvs\TASKS1-M_IXiD8r\lib\site-packages\django\forms\models.py", line 150, in fields_for_model opts = model._meta AttributeError: type object 'Task' has no attribute '_meta model : class Task(models.Model): user =models.ForeignKey(User,on_delete=models.SET_NULL,null=True,blank=True,related_name='usertasks') title = models.CharField(max_length=200,blank=False, null=False) description = models.TextField(null=True, blank=True) complete …