Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Count not working in signals if sender and receiver are not same
if sender and receiver are not same in my Blog model the number of count not showing in my base.html. I am using signals in my models. Count is working for my blogcomment model but it's not working in my blog model if sender and receiver are different. if I use sender = blog.author and receiver = blog.author then it working and counting. see the picture for get an idea: here is my models.py #this model for author class Blog(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,max_length=100) title = models.CharField(max_length=300,unique=True) #my others fields.... #here signals stating def blog_notify(sender, instance, *args, **kwargs): blog = instance blog_title = blog.title #sender =blog.author #only count working if sender and receiver is same sender = User.objects.filter(username="admin1") receiver = blog.author if sender == blog.author and blog.is_published == "published": notify = Notifications(blog=blog, sender=sender, receiver=receiver,text_preview = blog_title[:250], notification_type="post approved") notify.save() if sender == blog.author and blog.is_published == "pending": notify = Notifications(blog=blog, sender=sender, receiver=receiver,text_preview = blog_title[:250], notification_type="pending post") notify.save() if sender == blog.author and blog.is_published == "rejected": notify = Notifications(blog=blog, sender=sender,receiver=receiver,text_preview = blog_title[:250], notification_type="post rejected") notify.save() #this model for comment user. if anyone comment on blog post class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True) #my others fields.... #here signals stating def user_comment(sender, instance, *args, … -
Flask in showing 404 Error in Existing Routes
I am facing a very weird Issue, In my Flask App when index route (https://sitename.com/) is called everything is fine, but as i navigate to a route like https://sitename.com/about it shows 404 Error, even when About route is created in main.py . This App works all perfect in localhost:5000 but when I deployed it too a VPS It is showing that Error of showing 404 on every route My main.py from os import environ from flask import Flask, redirect, render_template, request, url_for import requests import json import datetime def getUserData(route): if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] else: ip = request.remote_addr with open("users.txt", "a") as f: f.write(f"Page Visited: {route}\n") f.write(f"User Agent: {request.headers.get('User-Agent')}\n") f.write(f"Remote Addr: {ip}\n") f.write(f"DateTime: {datetime.datetime.now()}\n") f.write(f"\n\n\n") app = Flask(__name__) app.debug = True # Website @app.route('/') def index(): getUserData("Index Page") return render_template('index.html') @app.route('/gallery') def gallery(): getUserData("Gallery") return render_template('pages/gallery.html') @app.route('/faqs') def faqs(): getUserData("FAQs") return render_template('pages/faqs.html') @app.route('/about') def about(): getUserData("About") return render_template('pages/about.html') @app.route('/contact') def contact(): getUserData("Contact") return render_template('pages/contact.html') # 404 Handling @app.errorhandler(404) def not_found(e): getUserData("404 Page") return render_template("pages/404.html") if __name__ == '__main__': app.run() -
Render the same form in template with initial data
I'a stuck with the following problem. I an Employer model, an Employee model, an HourCode model and a ReportModel. I will begin with the outcome i want to see, maybe then its clear what iam asking. Every employee has a employer and every employer has hourCodes for time registration. For Example: John is working at xerox, he worked 10 normal hours and 5 extra hours. In this case the hourcode are "normal hours" and " extra hours ". In my template i want to render a sort of table view so that de hours can be filled by the employer. So in this case he had to fill in 10 hours on "normal hours" and 5 hours on "extra hours" at John. But, the employer has ofcourse multiple employees, so he has to fill in several lines with the worked hours and extra hours per employee. Employeename. Normal hours. Extra hours John. 10. 5 Eva. 3. 5 SaveButton After savebutton pressed the forms (in this case 2, each for every employee) has to be saved to the ReportModel. The Reportmodel has some fields (ForeignKey fields to employer, employee and hourcodes. Long story, my question how can i render the view … -
AttributeError: 'QuerySet' object has no attribute '_meta'
I'm trying to do login() with Discord OAuth2 and a custom authentication backend but I get an error. When a user logs in for the first time, it works but if they log out and then log in again, this error pops up. def discord_login_redirect(request, *args, **kwargs): code = request.GET.get("code") exchange_user = exchange_code(code) discord_user_auth = DiscordAuthenticationBackend.authenticate(request=request, user=exchange_user) # discord_user_auth = list(discord_user_auth).pop() login(request, discord_user_auth) return redirect("/app") Full Traceback: Internal Server Error: /app/oauth2/login/redirect Traceback (most recent call last): File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Internet\Desktop\Programming\Discord\exo_website\website\exo_dashboard\dashboard\home\views.py", line 188, in discord_login_redirect return redirect("/app") File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 126, in login request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) AttributeError: 'QuerySet' object has no attribute '_meta' [19/Jul/2021 14:20:18] "GET /app/oauth2/login/redirect?code=code HTTP/1.1" 500 79016 -
Object of type MultipleObjectsReturned is not JSON serializable
I've been receiving this error from our crash reporting service in Django, I have not been able to replicate the issue but it happens several times a day apparently without crashing the web app, any hints on where to look will be appreciated, I've been stuck on this for a week now Internal Server Error: /api/v1/users/ TypeError at /api/v1/users/ Object of type MultipleObjectsReturned is not JSON serializable Request Method: POST Request URL: url/api/v1/users/ Django Version: 3.0.2 Python Executable: /layers/google.python.pip/pip/bin/python3 Python Version: 3.7.10 PATH_INFO = '/api/v1/users/' QUERY_STRING = '' RAW_URI = '/api/v1/users/' REMOTE_ADDR = '127.0.0.1' REMOTE_PORT = '25307' REQUEST_METHOD = 'POST' SCRIPT_NAME = '' SERVER_NAME = '0.0.0.0' SERVER_PORT = '8081' SERVER_PROTOCOL = 'HTTP/1.1' SERVER_SOFTWARE = 'gunicorn/20.0.4' gunicorn.socket = <socket.socket fd=10, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 8081), raddr=('127.0.0.1', 25307)> wsgi.errors = <gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x3e87ac0ea1d0> wsgi.file_wrapper = '' wsgi.input = <gunicorn.http.body.Body object at 0x3e87ac136b10> I've omitted some of the stack trace for security reasons but this is the view that's causing this issue: @api_view(['GET']) @permission_classes([IsUserAuthenticated, IsUserAdmin]) def get_users(request): limit = int(request.GET.get('limit', 0)) offset = int(request.GET.get('offset', 0)) first_name = request.GET.get('first_name', '') last_name = request.GET.get('last_name', '') email = request.GET.get('email', '') paid = request.GET.get('paid', '') gender = request.GET.get('gender', '') country = request.GET.get('country', '') sign_in_device = request.GET.get('sign_in_device', … -
How to set an unspecified value to Meta class (How to create a template table class) django_tables2
I have more than 30 tables, so I don`t want to write the same code for all of them. Even its copypaste. All my tables should look like this one: class MyTable(tables.Table): edit_link = tables.columns.Column(viewname='edit_table_field', kwargs={'table_name': 'MyModel', 'pk': A('pk')}, text='edit) ... class Meta: model = MyModel ... I want to make a tamplate from this class which will take the name of the model (MyModel) as an argument and create the same tablestables for each of them in one class. I don't know how to pass a value from a class to a metaclass. Also, maybe someone know any frameworks for python that implements the mapping and CRUD methods for my tables like it`s in Vaadin (Java)? -
Unsupported operand type(s) for /: 'int' and 'NoneType' on Custom Save - Django Form
I am trying to make a custom save on Django form because I have some variables that depends on other's values. When I use the admin form, it works perfectly, all the variables on my custom save are created with no problems and with the correct values. But when I use my form (the one from my template), I get the error: Traceback (most recent call last): File "/home/monique/.local/share/virtualenvs/SISTEMA-rPBRM75u/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/monique/.local/share/virtualenvs/SISTEMA-rPBRM75u/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/monique/MEGA/FORREST/SISTEMA/sepProdMachos/views.py", line 17, in add obj = form.save() File "/home/monique/.local/share/virtualenvs/SISTEMA-rPBRM75u/lib/python3.8/site-packages/django/forms/models.py", line 468, in save self.instance.save() File "/home/monique/MEGA/FORREST/SISTEMA/sepProdMachos/models.py", line 50, in save self.porcContaminacao = (self.nFemeasCQ*100)/self.amostragemTotal Exception Type: TypeError at /sepProdMachos/add/ Exception Value: unsupported operand type(s) for /: 'int' and 'NoneType' My model code is: from hatching.models import Hatching from django.db import models # Create your models here. class SepProdMachos(models.Model): created = models.DateTimeField(auto_now_add=True, null=True, blank=True) hatching = models.OneToOneField(Hatching, on_delete=models.PROTECT, null=True, blank=True) data = models.DateField(null=True, blank=True) inicio = models.TimeField(null=True, blank=True) fim = models.TimeField(null=True, blank=True) nBandejas = models.IntegerField(null=True, blank=True) bandejasDescartadas = models.IntegerField(null=True, blank=True) bandejasSeparadas = models.IntegerField(null=True, blank=True) mlMachos = models.FloatField(null=True, blank=True) mlMachosRepassado = models.FloatField(null=True, blank=True) mlFemeas = models.FloatField(null=True, blank=True) nOperadores = models.IntegerField(null=True, blank=True) nFemeasCQ = models.IntegerField(null=True, … -
how can I load qr_code in xhtml2pdf in django?
I am trying to print qrcode in xhtml2pdf but it didn't work with my. It is working on normal html template but when I render html2pdf it is not displaying. This my html2pdf template. I am using xhtml2pdf library. {% for company in companys %} <table> <tr> <td style="padding-left:40px;width:70px;"> {% load qr_code %} {% qr_from_text 'Hello World!' %} <img style="width:70px;height:70px;" src="./staticfiles/toyota.png"> </td> <td style="padding-right:30px;font-size:25px;">{{ company.name }}</td> <td style="padding-right:20px;width:110px;"> <img style="width:70px;height:70px;" src="../staticfiles/isuzu.png"> </td> </tr> <tr> <td style="width:150px;"></td> <td style="padding-right:30px;font-size:15px;">{{ company.tel }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ company.address }}</td> <td></td> </tr> <tr> <td style="width:150px;"></td> <td style="padding-right:30px;font-size:15px;">{{ company.tax_num }}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ company.com_num }}</td> <td></td> </tr> </table> {% endfor %} -
save() got an unexpected keyword argument 'commit'
I am implementing a feature that allows a user to upload images to their blog. When the user uploads a single image I get the error 'PostImages' object is not iterable and when a user uploads multiple images I get the error save() got an unexpected keyword argument 'commit' this is the one I am currently trying to fix view def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) formImages = PostImagesForm if request.method == 'POST': formImages = PostImagesForm(request.POST, request.FILES) files = request.FILES.getlist('images') if formImages.is_valid(): for f in files: formImages = formImages.save(commit=False) formImages.post = Post.objects.get(pk=pk) formImages.save() else: print(formImages.errors) context = { 'post':post, 'formImages':formImages, } return render(request, 'blog/post_detail.html', context) form class PostImagesForm(ModelForm): class Meta: model = PostImages fields = ('images',) widgets = { 'images': forms.ClearableFileInput(attrs={'multiple': True}), } I found this stack post that was also dealing with the same error but I dont really understand it. I have done the same thing on all my other forms without issue. -
Django-Admin not found despite installing Django
I am a beginner with Django, and when it comes to stuff dealing with installing packages on computers, I get confused very easily. I've already installed Django, and yet when I try to create a project, the following message appears... can't open file 'U:\django-admin': [Errno 2] No such file or directory I've seen on other questions asked, that it would require one to have a virtual environment; however, on the tutorials I've been following, it doesn't install an environment. -
Factory Boy SelfAttribute is not returning what I expect
I have the following model that I am trying to replicate the functionality of in tests: class Client(TimeStampedModel): user = models.OneToOneField(User, related_name="client", on_delete=models.CASCADE) business_name = models.CharField(_("business name"), max_length=255, blank=True) business_phone = PhoneNumberField(_("business phone"), blank=True, null=True) business_address = models.CharField( _("business address"), max_length=255, blank=True ) business_city = models.CharField(_("business city"), max_length=255, blank=True) business_state = USStateField(_("business state"), blank=True) business_zip = USZipCodeField(_("business zip"), max_length=255, blank=True) business_url = models.URLField(_("business website"), blank=True) @property def email(self): return self.user.email def __str__(self): return f"{self.business_name}" The thing that is causing issues is the email property. It should return the email address of a user. With DjangoModelFactory, I am creating a user and client with the following two factories: class UserFactory(DjangoModelFactory): class Meta: model = get_user_model() django_get_or_create = ["username"] username = Faker("user_name") email = Faker("email") phone_number = Faker("phone_number") first_name = Faker("first_name") last_name = Faker("last_name") city = Faker("city") state = Faker("state_abbr") zip = Faker("zipcode_plus4") # these are overrideable password = "fakePassword" is_staff = False @classmethod def _create(cls, model_class, *args, **kwargs): """Override ``_create``""" kwargs["password"] = make_password(kwargs["password"]) kwargs["is_staff"] = kwargs["is_staff"] return super(UserFactory, cls)._create(model_class, *args, **kwargs) class ClientFactory(DjangoModelFactory): class Meta: model = Client user = factory.SubFactory( UserFactory, ) business_name = Faker("company") business_address = Faker("street_address") business_city = Faker("city") business_state = Faker("state_abbr") business_zip = Faker("postalcode") email = factory.SelfAttribute("user.email") … -
Using jQuery DateTimePicker in Django Admin form get error - Enter a list of values
It looks like when you use DateTimeField in Django, it expects to return two values, one with date and one with time, then adds and writes to the database in one field. What I have is it returns one value="2021-07-19 20:17:43". Help solve the problem. model.py start_date = models.DateTimeField(blank=True, null=True) end_date = models.DateTimeField(blank=True, null=True) widgets.py from django.forms import DateTimeInput class DateTimePicker(DateTimeInput): template_name = 'widgets/datetimepicker.html' def get_context(self, name, value, attrs): datetimepicker_id = f'datetimepicker_{name}' if attrs is None: attrs = dict() attrs['data-target'] = f'#{datetimepicker_id}' attrs['class'] = 'form-control datetimepicker-input' context = super().get_context(name, value, attrs) context['widget']['datetimepicker_id'] = datetimepicker_id return context class Media: css = { "all": ( "//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css", "//cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.39.0/css/tempusdominus-bootstrap-4.min.css", ) } js = ( '//cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js', '//cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.39.0/js/tempusdominus-bootstrap-4.min.js', ) widgets/datetimepicker.html <div class="input-group date" id="{{ widget.datetimepicker_id }}" data-target-input="nearest"> {% include "django/forms/widgets/input.html" %} <div class="input-group-append" data-target="#{{ widget.datetimepicker_id }}" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <script> django.jQuery(document).ready(function ($) { $("#{{ widget.datetimepicker_id }}").datetimepicker({ format: 'YYYY-MM-DD HH:mm:ss', }); }); </script> admin.py formfield_overrides = { models.DateTimeField: {'widget': DateTimePicker}, } widget error when saving Thanks for reading and for the help. -
Define CSS variables from Django Models
I'm trying to create an app where the user would be able to customize the design. As for now, I would like to make something very simple and just let the user define the value of some colors like this: class PageSettings(models.Model): base_color = ColorField(default='#FFFF00') mi css code define variables like this: :root { --blue: #0061f2; --indigo: #5800e8; --purple: #6900c7; --pink: #e30059; --red: #e81500; --orange: #f76400; --yellow: #f4a100; I'm wondering if there's a way where I can tell mi CSS file not to use some color, let's say 'blue' as #0061f2, but insted use the value of 'base_color'. -
Custom auth system django
I have an app with ability to unite users by groups. So you can auth in it using built-in django auth system and use app in single mode, but also login in group (that adds additional functionality). Need to auth user in group-mode using group data, then write that group in user's foreign key for group. So I have user model like this: class CustomUser(AbstractUser): ... note_group = models.ForeignKey(NoteGroup, on_delete=models.DO_NOTHING, null=True, blank=True) ... And group model: class NoteGroup(models.Model): id = models.BigAutoField(primary_key=True) group_name = models.CharField(max_length=25) password = models.CharField(max_length=25) For now I have this view: def group_notes_view(request): if request.method == 'POST': form = GroupSignInForm(request.POST) if form.is_valid(): group = NoteGroup.objects.get(group_name=form.instance.group_name) if group: if group.password == form.instance.password: user = request.user user.note_group = group user.save() ... else: form = GroupSignInForm() ... Form looks lie this by now class GroupSignInForm(ModelForm): class Meta: model = NoteGroup fields = ('group_name', 'password') It's working but I believe there is much better way to do it. -
Django Stripe account link return_url and refresh_url redirects causes user to be logged out of web application platform
I'm integrating stripe into my Django web application platform. When sellers onboard with Stripe Connect, an Account is created for them, and an AccountLink is created with a specified return_url and refresh_url that Stripe uses to redirect back to my web application. However, when the sellers are redirected back to my web application they are no longer logged into the web application. Is there a better solution than forcing the user to log back in? The following are some code snippets: views.py def stripe_on_boarding(request): if request.method == "GET": stripe_sk = settings.STRIPE_SECRET_KEY stripe.api_key = stripe_sk user = request.user account = None print("I'm logged in as and am onboarding stripe [" + user.first_name + "]") if user.stripe_account is None: account = stripe.Account.create(type='express') user.stripe_account = account.id user.save() print("Saved User Object!") else: account = stripe.Account.retrieve(user.stripe_account) if account is not None and not account.details_submitted: account_links = stripe.AccountLink.create( account=account.id, refresh_url='http://098c818fbf8a.ngrok.io/marketplace/stripe_on_boarding_refresh', return_url='http://098c818fbf8a.ngrok.io/marketplace/seller_return', type='account_onboarding', ) return redirect(account_links.url) return render(request, 'become_seller_part_1.html', {'msg' : "You've already registered with stripe.", 'is_registered' : True}) # TODO: render a page if this view was triggered by a method other than GET. Could this be happening because I'm using ngrok to redirect to my localhost? -
NoReverseMatch at / Reverse for 'products' with arguments '('',)' not found. 1 pattern(s) tried: ['products/(?P<pk>[^/]+)/$']
I have tried viewing the other solutions of the community, but nothing came in help. I was just trying to match the inputs to database entries and thus show a result in the "products.html" page. Would be grateful if anyone could breakdown the solution. views.py from django.shortcuts import render, redirect from .forms import ProductForm from .models import Product def home(request): form = ProductForm() if request.method == "POST": form = ProductForm(request.POST) form.save() if form.is_valid(): return redirect('/') context = { 'form':form } return render(request, 'bye/home.html', context) def products(request, pk): product = Product.objects.get(id = pk) if request.method == "POST": return redirect('/') context = { 'product': product } return render(request, 'bye/products.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name ='home'), path('products/<str:pk>/', views.products, name = 'products') ] home.html </div> <div class = "col-md-12"><a href = "{% url 'products' product.id %}" class="btn btn-info btn-sm">Submit</a></div> </div> products.html {% extends 'bye/base.html' %} {% block content %} <p></p> {{product.name}} {% endblock %} Traceback Traceback (most recent call last): File "D:\DJPROJ\try\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\DJPROJ\try\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\DJPROJ\try\okay\bye\views.py", line 17, in home return render(request, 'bye/home.html', context) File "D:\DJPROJ\try\env\lib\site-packages\django\shortcuts.py", line … -
How to properly handle SMTP errors in Django + Ajax
I have a simple contact form on my site. It communicates with Gmail SMTP server through AJAX call. Here's the view: def contact(request): if request.is_ajax(): sender_name = request.POST.get('sender_name') sender_email = request.POST.get('sender_email') message_subject = request.POST.get('message_subject') message_text = request.POST.get('message_text') remote_addr = request.META['REMOTE_ADDR'] remote_host = request.META['REMOTE_HOST'] context = { 'from': sender_name, 'email': sender_email, 'subject': message_subject, 'message': message_text, 'IP': remote_addr, 'HOST': remote_host } html_message = render_to_string('homepage/submit.contact.form.html', context) try: send_mail( f'Contact Form: {message_subject}', f'{message_text}', 'me@gmail.com', ['me@gmail.com', ], html_message=html_message ) return JsonResponse({}, status=200) except SMTPException as e: return JsonResponse({'error': e}, status=500) else: return redirect('homepage:index') And the AJAX code: $('#contactForm').submit(function(e){ e.preventDefault() $('#sent-message').css("display", "none") $('#loading').css("display", "block") $.ajax({ type : "POST", url : "/contact/", data: { sender_name : $('#name').val(), sender_email : $('#email').val(), message_subject : $('#subject').val(), message_text : $('#message').val(), csrfmiddlewaretoken : csrftoken, datatype : "json", }, success: function(){ $('#loading').css("display", "none"), $('#sent-message').css("display", "block"), $('#contactForm')[0].reset() }, error: function(e){ alert(e) } }); }); The above code works if everything is ok, but the exception handling is not working properly and I'm not an expert in this area. The issues I'm facing when there's an exception (I use a wrong password for the email account to raise it): First, I get Object of type SMTPAuthenticationError is not JSON serializable in the console. Second, the … -
filter django queryset by onetoone model field property
i have two model classes and they are related by OneToOneField like here class Book(models.Model): is_user_ok = models.BooleanFiled() class Mybook(models.Model): book = models.OneToOneField( Book, related_name="Book", null=True, blank=True, on_delete=models.SET_NULL) now i want make a queryset filter by book field property. but here book.is_user_ok cannot be used. how can i make this queryset filter? queryset = Mybook.objects.filter(book.is_user_ok=True) -
'method' object is not subscriptable trying for google api books
Trying to get data from google books API but it is showing the error ' 'method' object is not subscriptable' I know the “TypeError: ‘method’ object is not subscriptable” error is raised when you use square brackets to call a method inside a class. To solve this error, make sure that you only call methods of a class using round brackets after the name of the method you want to call. def books(request): if request.method == "POST": form = DashboardForm(request.POST) text = request.POST['text'] url = 'https://www.googleapis.com/books/v1/volumes?q='+text r = requests.get(url) answer = r.json result = [] for i in range(10): result_dict= { 'title':answer['items'][i]['volumeInfo']['title'], # This line is showing error. 'subtitle': answer['items'][i]['volumeInfo']['title'].get('subtitle'), 'description': answer['items'][i]['volumeInfo']['title'].get('description'), 'count': answer['items'][i]['volumeInfo']['title'].get('pageCount'), 'categories': answer['items'][i]['volumeInfo']['title'].get('categories'), 'rating': answer['items'][i]['volumeInfo']['title'].get('pageRating'), 'thumbnail': answer['items'][i]['volumeInfo']['title'].get('imageLinks'), 'preview': answer['items'][i]['volumeInfo']['title'].get('previewLink') } result.append(result_dict) context={ 'form':form, 'results':result, } return render(request,'dashboard/books.html',context) else: form = DashboardForm() context = {'form':form} return render(request,'dashboard/books.html',context) -
Implementation of a Quantited-MultiSelect "Material List" in Django
I'm trying to write a django app to track materials required on each job in my business, but struggling to find the right approach. Planning to use the Admin for forms if possible. The ideal form field will let me search from ~200 materials options, select between 1-20 for each job, and add a quantity to each, e.g. 40x red two-inch screws 4x blue one-inch screws 13x purple two-inch screws I'm looking at "Many-To-Many" fields and "Iterating Relationship Choices" but am honestly confused. -
Django id field coming None
This is the first time it has happened. Normally Django would automatically add a primary key field in the model but this time is giving a none value. I also added an AutoField to the model but its still giving None class Note(models.Model): note_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(null=True, blank=True) note = models.TextField() date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def save(self, *args, **kwargs): l = self.title.lower().split(' ') self.slug = '_'.join(l) super(Note, self).save(*args, **kwargs) This is my Note model And this is the admin interface -
Django Webserver on Linux Apache Webserver
I am trying to install a Django Webserver on a Linux Apache2 Webserver. I am Stuck and dont know why I am not getting any Response from the Webserver. My Apache Conf: WSGIPythonHome /var/venvs/djangoVenv WSGIPythonPath /var/www/DjangoProject/ Listen 8080 <VirtualHost *:8080> DocumentRoot /var/www/DjangoProject Alias /static /var/www/DjangoProject/static WSGIScriptAlias / /var/www/DjangoProject/DjangoProject/wsgi.py WSGIProcessGroup DjangoProject WSGIPassAuthorization On <Directory /var/www/DjangoProject/DjangoProject> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/DjangoProject> Require all granted </Directory> <Directory /var/www/DjangoProject/static> Require all granted </Directory> ErrorLog /var/www/logs/error.log CustomLog /var/www/logs/custom.log combined </VirtualHost> And my Python wsgi File: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoProject.settings') application = get_wsgi_application() I have running the Standard Apache Webserver on Port 80 and my Django Server on Port 8080 but Chrome only shows me, that the Website is unreachable. Chrome Reply -
Django error faced whil making the project list is not getting displayed
I am creating this tab in Django and wants that it will display the list of 10 youtube searches but it is showing only one below is the code for my view.py youtube method and below that is my template section can someone help me I want the list of my top ten searches will be displayed ut it is only showing 1 I don't know why def youtube(request): if request.method=="POST": form = DashboardForm(request.POST) text = request.POST['text'] video = VideosSearch(text,limit=10) result_list=[] for i in video.result()['result']: result_dict={ 'input':text, 'title':i['title'], 'duration':i['duration'], 'thumbnail':i['thumbnails'][0]['url'], 'channel':i['channel']['name'], 'link':i['link'], 'views':i['viewCount']['short'], 'published':i['publishedTime'] } desc='' if i['descriptionSnippet']: for j in i['descriptionSnippet']: desc+=j['text'] result_dict['description']=desc result_list.append(result_dict) context={'form':form, 'results':result_list} return render(request,'dashboard/youtube.html',context) else: form =DashboardForm() context={'form':form} return render(request,'dashboard/youtube.html',context) {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class='text-center container'> <h2>Search Videos in Youtube</h2> <p>search videos and select any video to open in youtube</p> <form action="" method="post"> {% csrf_token %} {{form}} <input class="btn btn-danger" type="submit" value="Submit"> </form><br> {% for result in results %} <a href="{{result.link}}" target="_blank"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-5"> <img class="img-fluid" src="{{result.thumbnail}}" alt=""> </div> <div class="col-md-7"> <h3 class="p-0 m-0">{{result.title}}</h3> <b> <u> <h5 class="p-0 m-0">{{result.channel}}</h5> </u> </b> <h6 class="p-0 m-1">{{result.description}}</h6> <b> <h6 class="ml-0 mt-3">{{result.duration}}</h6> <h6 class="ml-0 … -
Django Custom Manager + DRF + UWSGI setup : Incorrectly applied queryset filters
We are using Django 3.1.5, python 3.8, and Django Rest Framework ModelViewSet Architecture for our application. Our application is a multi-tenant system where all the tenants of our application are using the same database and schema, we have added a foreign key to tenant to make the models tenant aware (if applicable). For our system, we call tenants Clients. To filter all the queries by the client by default, we have done the below steps: Used local thread storage to store client id for each request. This is set at a middleware before each request and gets cleared in the end. Created a custom manager to override objects working. Here, we filter queries by client_id stored in the local thread.So, everytime, some_model_query = SomeModel.objects.all() is done, then some_model_query is filtered by client stored. Our view sets are written in the below format: class SomeModelViewSet(CustomModelViewSet): queryset = SomeModel.objects.all() serializer_class = SomeModelSerializer filterset_class = SomeModelFilter We are using uwsgi to run our application on servers. Now, the problem with uwsgi: The first time, when a process is run, then, all the view sets are initialized and hence their querysets. During initialization, querysets are set with the current client_id. So, it becomes: SomeModel.objects.filter(client_id=1).all() … -
Python Django LineBot Error 54 'Connection reset by peer'
I'm trying to crete linebot through python Django, I want to send some messages and let it scrape the website. Since there is form on the website, I use post request to send the form. Although I scrape the data successfully, there is error message showed in the python. It seems linebot occupy post method in Django and I send another post request again. I'm not sure my understanding is correct. I can't find any solution about this. Could someone teach me how to fix it? Exception happened during processing of request from ('127.0.0.1', 50246) Traceback (most recent call last): File "/usr/local/anaconda3/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/anaconda3/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/anaconda3/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "/usr/local/anaconda3/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/usr/local/anaconda3/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/anaconda3/lib/python3.8/socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer