Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
window.open() popup doesn't show anything
I have a Django website with this url that has this code in its template footer: <img referrerpolicy='origin' id = 'rgvjjxlzwlaoesgtfukzjxlz' style = 'cursor:pointer' onclick = 'window.open("https://logo.samandehi.ir/Verify.aspx?id=314061&p=xlaorfthaodsobpdgvkarfth", "Popup","toolbar=no, scrollbars=no, location=no, statusbar=no, menubar=no, resizable=0, width=450, height=630, top=30")' alt = 'logo-samandehi' src = 'https://logo.samandehi.ir/logo.aspx?id=314061&p=qftinbpdshwllymawlbqnbpd' /> which displays this image in the footer: When it is clicked, it should display a popup page like this: (this is in the footer of another website called "toplearn.com" which I just gave as an example, but it looks exactly like this page.) But it runs a blank page. Thank you for helping me find the problem -
Image is not loading on page
my image file is not loading in webpage it is showing The 'Img' attribute has no file associated with it models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=100,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(default=timezone.now()) status = models.IntegerField(choices=STATUS, default=0) Img = models.ImageField(null =True, blank = True, upload_to='static/images') class Meta: ordering = ['-created_on'] def __str__(self): return self.title urls.py from django.contrib import admin from django.conf.urls import include from django.urls import path from portfo import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.firstpage,name='firstpage'), path('', include('portfo.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static") ] MEDIA_URL ="/images/" MEDIA_ROOT=os.path.join(BASE_DIR,'static/images') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' I have a file name images inside the static. -
how can i solve this book search box in django?
im working with django making a book searcher, here is my code,im using a youtube video for making this project, i did exactly what he does but it doesnt work views.py: 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_list = [] for i in range(10): result_dict = { 'title':answer['items'][i]['volumeInfo']['title'], 'subtitle':answer['items'][i]['volumeInfo'].get('subtitle'), 'description':answer['items'][i]['volumeInfo'].get('description'), 'count':answer['items'][i]['volumeInfo'].get('pageCount'), 'catagories':answer['items'][i]['volumeInfo'].get('catagories'), 'rating':answer['items'][i]['volumeInfo'].get('pageRating'), 'thumbnail':answer['items'][i]['volumeInfo'].get('imageLinks').get('thumbnail'), 'preview':answer['items'][i]['volumeInfo'].get('previewLink') } result_list.append(result_dict) context={ 'form':form, 'result':result_list, } return render(request,'dashboard/books.html',context) else: form = DashboardForm() context = {'form':form} return render(request,'dashboard/books.html',context) forms.py: class DashboardForm(forms.Form): text = forms.CharField(max_length=100,label='Enter your search : ') books.html: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class='text-center container'> <h2>Search books and browse your favorite</h2> <p>just enter the search query to obtain the results</p><b></b> <form action="" method="post"> {% csrf_token %} {{form}} <input class="btn btn-danger" type="submit" value="Submit"> </form><br> <a href="#" target="_blank"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-3"> <img class="img-fluid" src="" alt=""> </div> <div class="col-md-9"> <h3 class="p-0 m-0">title</h3> <b> <u> <h5 class="p-0 m-0">subtitle</h5> </u> </b> <h6 class="p-0 m-1">description</h6> <b> <h6 class="ml-0 mt-3">Category: name</h6> <h6 class="ml-0 mt-1">Pages: 100</h6> <h6 class="ml-0 mt-1">Rating: 4</h6> </b> </div> </div> </div> </div> </a> <br> </section> {% endblock content %} actually when i … -
Docker-compose django
want to launch 3 containers. db, nginx, web. Web isn't working. Problem: ModuleNotFoundError: No module named 'api_yamdb'. I know that it's my own module, but i don't know why it's don't found. Please help. structure of project settings in settings.py docker-compose.yaml Dockerfile docker log -
Django paypal payments
I am trying to enable user to user payments in my django application with paypal integration. I can send payments to the business account. I need to know hot to let users to pay with each other. I used payee object but it did not work. can anyone help me, if it is I appreciate. Thank you! -
Django: never_cache is not working, it still shows same data on browser back button
I have a create view which is used to make an object of type Course(model). i'm using never_cache decorator to reload the page from server everytime i use it. now if i create a course it gets added in the Course database, now if i press browser back button it still shows me the data with course name that i wrote, which allows me to resubmit the same data, how can i prevent this?(ik i can prevent saving same data twice by overriding save method but i want to prevent user from going back to form in which he entered data). @method_decorator(never_cache, name='dispatch') class CourseView(CreateView): model = Course template_name = 'teacher/course.html' fields = ['name', 'year'] def get_context_data(self, **kwargs): kwargs['course_list'] = self.model.objects.all().order_by('name','year') return super().get_context_data(**kwargs) def form_valid(self, form): messages.success(self.request, 'Course added successfully.') return super().form_valid(form) def get_success_url(self): return self.request.GET.get(key='next', default=reverse('teacher:course')) -
Override (save_model) in django admin for All models/apps in projects
How could I implement override save method for all models in all Apps inside Admin panel? def save_model(self, request, obj, form, change): pass I can implement it in one or two models "inherit and adding it in register method", but I really need it to execute whenever admin clicks save in Admin panel and implement some code before save. -
Is using UUId as pk a good idea in microservices?
I am working on a microservice project which contains 4 services developed in django i use dj rest auth to handle login and register process , each service has its own database and the information of users are kept in account service and other 3 services get the users information via an api request to account service , in each service i have only access to logged in user pk (dj rest auth handles this) and when i need to save a record for example location of logged in user ,i save a user object which only has pk alongside other info so the record in db will be like this : user=request.user(which saves logged in user but i only see the pk) lat = latitue number lng = longitude number everything is fine but if i loose the database of account service and restore the backup and some how the records generate a different pk (for example before restoring backup some new records would be added) from the ones saved in other services which makes a huge problem in all services. the solution i tried is to change the pk to uuid filed but is it a good idea? … -
Keywords Must Be Strings When Passing Variable As Parameter
I'm trying to pass a variable as a keyword argument like this: true_frequency = 'weeks' next_month = today + relativedelta(**{true_frequency: true_loop}) This is for a django site and it doesn't error when I run this through the site. However, when I run a test I'm getting this error: next_month = today + relativedelta(**{true_frequency: true_loop}) TypeError: keywords must be strings I'm not entirely sure how to solve this as I've never passed a keyword as a variable before so I'm not overly familiar with the process. This is happening on a receiver object. Thanks -
productId = data['productId'] KeyError: 'productId' in django
when i added a item to cart it is successfully added by prviding the product id like Action: add Productid: 1 But when i make payment it is showing error like productId = data['productId'] KeyError: 'productId' and cart count also not updated after clicking payment here is my code def updateItem(request): data=json.loads(request.body) print(data) print("sasi") productId = data['productId'] action=data['action'] print('Action:',action) print('Productid:',productId) customer=request.user.customer product=Product.objects.get(id=productId) order,created=Order.objects.get_or_create(customer=customer,complete=False) orderItem,created=OrderItem.objects.get_or_create(order=order,product=product) if action == 'add': orderItem.quantity=orderItem.quantity+1 elif action == 'remove': orderItem.quantity=orderItem.quantity-1 orderItem.save() if orderItem.quantity<=0: orderItem.delete() return JsonResponse('Item was added',safe=False) -
DJANGO: caching a services.py method so it's always available
I'm trying to use this python ML library and turn it into an APIView for my project. There is a single line that loads the ML model which took around ~20s, so I separated that line into services.py and decorated with @lru_cache so it doesn't always take ~20s. Because lru_cache is Least Recently Used caching method, the cached model is quickly un-cached and makes user wait for another 20s sooner or later. So I am looking for a way to either cache load_model() method so it's always available, or cache it within a certain time. I tried using cache_page method for the latter but had no luck so far. Is there a better method I can use, or would just tweaking the lru_cache's maxSize be a more elegant solution? This APIView isn't called very often, which makes user wait ~20s every time. I was hoping to just make it always available so user don't have to wait. views.py from .services import load_model, extract_keyword class ExtractKeyphrase(ApiAuthMixin, APIView): def post(self, request): try: text = request.data["text"] kp_model = load_model() # the line that takes ~20s keyphrases = extract_keyword(kp_model, text) return JsonResponse(keyphrases, status=status.HTTP_200_OK, safe=False) except requests.exceptions.RequestException: Response("Request Failed", status=status.HTTP_400_BAD_REQUEST) services.py from functools import lru_cache … -
How to profiling django tests
In my django (very very ancient 1.9) project tests are very slow - Ran 758 tests in 1017.001s, ~ 1.3 s/test How to profile its using Pycharm? Or another IDE. -
Is it possible to reconnecting the Django channels socket by passing the parameter when click the button?
python class BookConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.execute_websocket_ticker() async def process_message(self, message): asyncio.create_task(self.send_json(message)) async def start_binance_depthsocket(self, symbol=None): client = await AsyncClient.create() bsm = BinanceSocketManager(client) if not symbol: symbol = 'btcusdt' async with bsm.depth_socket(symbol=symbol, depth='10') as ts: while True: data = await ts.recv() res = {'site': 'binanceSpot', 'type': 'depthsocket', 'data': data} await self.process_message(res) async def execute_websocket_ticker(self): asyncio.create_task(self.start_binance_depthsocket()) js var book_socket = new WebSocket('ws://' + window.location.host +'/ws/book?session_key=${sessionKey}') book_socket.onmessage = function (e) { let data = JSON.parse(e.data) let site = data['site'] let type = data['type'] if (type == 'depthsocket') { update_orderbook(site, data['data']['asks'], data['data']['bids']) } } What i'm trying to do button click reconnect depth_socket by passing the parameter What I've tried caching symbol value when button click fetch and set cache (But I don't think it's a good way and can't reconne) If it's impossible, I'd appreciate it if you could recommend another way. -
How to set "DJANGO_SETTINGS_MODULE" for a "config" module divided into common, local, production files
I'm setting up a wsgi.py to deploy my django app in DigitalOcean, but I'm getting the following errors during deployment phase after successful build. From the error trace, I think there is a problem with os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config") this line inside wsgi.py. My config files are organized as a python module with common, local, and production settings. I'm not sure where and how to fix this problem, and I've been stuck here for a few days now. Would appreciate any input! ERROR TRACE [2022-07-31 03:29:55] Traceback (most recent call last): [2022-07-31 03:29:55] File "<frozen importlib._bootstrap>", line 908, in _find_spec [2022-07-31 03:29:55] AttributeError: 'ConfigurationImporter' object has no attribute 'find_spec' [2022-07-31 03:29:55] [2022-07-31 03:29:55] During handling of the above exception, another exception occurred: [2022-07-31 03:29:55] [2022-07-31 03:29:55] Traceback (most recent call last): [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker [2022-07-31 03:29:55] worker.init_process() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process [2022-07-31 03:29:55] self.load_wsgi() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi [2022-07-31 03:29:55] self.wsgi = self.app.wsgi() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi [2022-07-31 03:29:55] self.callable = self.load() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load [2022-07-31 03:29:55] return self.load_wsgiapp() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp [2022-07-31 03:29:55] return … -
Django schema made, but "No tenant for hostname" error
I was able to create a schema (and I confirmed this via database) but for some reason, I am getting this error "No tenant for hostname" and I am not sure what is causing it. Below is my code: views.py def post(self, request): form = CreatePortalForm(request.POST) if form.is_valid(): getDomain = form.cleaned_data.get('name') instance = form.save(commit=False) user_id = request.user.id user = User.objects.get(id=user_id) tenant = Client(schema_name=getDomain, name=getDomain, created_by=user) tenant.save() domain = Domain() domain.domain = getDomain + ".example.com:8000" domain.tenant = tenant domain.is_primary = True domain.save() with schema_context(tenant.schema_name): instance.save() redirect = 'http://' + getDomain + '.example.com:8000' return HttpResponseRedirect(redirect) return render(request, "registraton/create_portal.html", {"form": form}) Like I said, the schema is creating and migrating successfully but I still cannot get to the domain.example.com as it throws the "No tenant for hostname" error. Not sure if another table is made for "tenant_domains"? Any ideas on what is causing this? -
How to achieve deleting or updating model that doesn't effect previously created object
I have three models Product, Order, and OrderItem Once someone places an order I don't want the product object associated with the orderitem model on the receipt to change or get deleted if I were to delete or update the product model. How to achieve this? #model class Product(models.Model): price = models.DecimalField() class Order(models.Model): buyer = models.ForeignKey(Buyer, on_delete=models.SET_NULL) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL) order = models.ForeignKey(Order, on_delete=models.SET_NULL) #view @login_required def receipt(request): orderitems = OrderItem.objects.filter(order__buyer__user=request.user) -
Django, Should the attribute name of the model (or form) and the name of the input tag be exactly the same?
If the user at the front-end has an additional function on the form, how do I control it in views.py? And how can I send form to HTML from views.py? Ex <form> <input type="text" class=".." name='input_1'> <input type"button" onclick="add_input()"> </form> -
Email backend for django application not working
I tried to use the usual way of having my gmail account send user activation email to used but it keep failing. Please is there any new changes made to Django or Gmail that is preventing this and how do I work around it. Please see below for the error detail: raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials s2-20020a05620a29c200b006af0ce13499sm6006618qkp.115 - gsmtp') -
Django Field 'id' expected a number but got datetime.datetime error
I am working on a Django-Tenant (Multi-Tenant) application. I am writing the script to create the subdomain. I am getting this error Field 'id' expected a number but got datetime.datetime error and I am unable to tell where it is coming from. views.py class CreatePortal(View): def get(self, request): form = CreatePortalForm() return render(request, "registration/create_portal.html", {"form": form}) def post(self, request): form = CreatePortalForm(request.POST) if form.is_valid(): getDomain = form.cleaned_data.get('name') instance = form.save(commit=False) user_id = request.user.id user = User.objects.get(id=user_id) tenant = Client(schema_name=getDomain, name=getDomain, created_by=user) tenant.save() domain = Domain() domain.domain = (getDomain + ".example.com:8000") domain.tenant = tenant domain.is_primary domain.save() with schema_context(tenant.schema_name): instance.save() redirect = 'http://' + form.cleaned_data['name'] + '.example.com:8000' return HttpResponseRedirect(redirect) return render(request, "registraton/create_portal.html", {"form": form}) forms.py class CreatePortalForm(forms.ModelForm): class Meta: model = Client fields = ["name"] models.py This is the line that I am working with models.py created_by = models.ForeignKey(User, on_delete=models.CASCADE) I have verified that I am getting the correct user id, but now I get this error. -
Django channels allows only one connection
I've created web socket between django and react app. I can establish connection only with one client. When i try to connect from other tab it gives me an error [Errno 61] Connect call failed ('127.0.0.1', 6379) and whole channels/ redis crushes. What i'm trying to do is send to all users the same number. Consumers.py import json from random import randrange from channels.generic.websocket import WebsocketConsumer from datetime import * import time class DiceConsumer(WebsocketConsumer): def connect(self, immediately=True): self.accept() while True: if datetime.now().strftime('%S') != '00': self.send( json.dumps({'action': "nothing", 'time': datetime.now().strftime('%S')})) elif datetime.now().strftime('%S') == '00': self.send(json.dumps( {'action': "start dice", 'winning_value': randrange(1, 6)})) time.sleep(1) Asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter from channels.auth import AuthMiddlewareStack from channels.routing import URLRouter from Dice.routing import ws_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Core.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns)) }) -
DoesNotExist at / Profile matching query does not exist in Django project
I am working in a Django project. I created user model, and views but suddenly it started giving me this error: raise self.model.DoesNotExist( core.models.Profile.DoesNotExist: Profile matching query does not exist. [31/Jul/2022 00:57:01] "GET / HTTP/1.1" 500 72187 This is the error from local host page: DoesNotExist at / Profile matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.6 Exception Type: DoesNotExist Exception Value: Profile matching query does not exist. Exception Location: /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/query.py, line 496, in get Python Executable: /Library/Frameworks/Python.framework/Versions/3.10/bin/python3 Python Version: 3.10.5 Python Path: ['/Users/slau8405/Desktop/work_space/work_space/django-social-media-website', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages'] Server time: Sun, 31 Jul 2022 00:57:01 +0000 I couldn't get rid of this error. Can I get some help ? My code looks like this: models.py from django.db import models from django.contrib.auth import get_user_model import uuid from datetime import datetime User = get_user_model() # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) id_user = models.IntegerField() bio = models.TextField(blank=True) profileimg = models.ImageField(upload_to='profile_images', default='blank-profile-picture.png') location = models.CharField(max_length=100, blank=True) def __str__(self): return self.user.username views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.http import HttpResponse from django.contrib.auth.decorators import login_required from .models import Profile, Post, LikePost, FollowersCount from itertools import … -
Django pass user id before form is submitted
I am working on a Django-Tenant (Multi-Tenant) application. I am writing the script to create the subdomain. I am trying to get it to where created_by is set to the current users id that is logged in. How can I get current user ID to populate the created_by field? views.py class CreatePortal(View): def get(self, request): form = CreatePortalForm() return render(request, "registration/create_portal.html", {"form": form}) def post(self, request): form = CreatePortalForm(request.POST) if form.is_valid(): getDomain = form.cleaned_data.get('name') instance = form.save(commit=False) tenant = Client(schema_name=getDomain, name=getDomain, created_by=**[NEED USER ID HERE]**) tenant.save() domain = Domain() domain.domain = (getDomain + ".example.com:8000") domain.tenant = tenant domain.is_primary domain.save() with schema_context(tenant.schema_name): instance.save() redirect = 'http://' + getDomain + '.example.com:8000' return HttpResponseRedirect(redirect) return render(request, "registraton/create_portal.html", {"form": form}) forms.py class CreatePortalForm(forms.ModelForm): class Meta: model = Client fields = ["name"] models.py This is the line that I am working with models.py created_by = models.ForeignKey(User, on_delete=models.CASCADE) I also get an error if it is not User type and if I do not pass an actual number for id, Field 'id' expected a number but got datetime.datetime I have tried this as well: user = request.user.id tenant = Client(schema_name=getDomain, name=getDomain, created_by=user) but then get this error: Cannot assign "1": "Client.created_by" must be a "User" instance. … -
Uploading a django project to a github repo
I am relatively new to github and I am still trying to take my django application into production using a github repository. The problem is that for some reason, github has refused to commit a certain folder to the main branch. When I try to commit the changes I get the following message: On branch main Untracked files: (use "git add ..." to include in what will be committed) blog/ nothing added to commit but untracked files present (use "git add" to track) So I assume its telling me that there are some untracked files within the blog folder but when I try to add the folder, I get the following error: warning: adding embedded git repository: blog hint: You've added another git repository inside your current repository. hint: Clones of the outer repository will not contain the contents of hint: the embedded repository and will not know how to obtain it. hint: If you meant to add a submodule, use: hint: hint: git submodule add blog hint: hint: If you added this path by mistake, you can remove it from the hint: index with: hint: hint: git rm --cached blog hint: hint: See "git help submodule" for more information. … -
How can i insert a serial number for the following query in Django?
Info: I want to a serial number to come along with all objects in queryset using Django rest framework instead of object ID. The example image is below. the serial start from first object in queryset list. serializers.py class LiveStreamSerializer(serializers.ModelSerializer): def get_serial(self, obj): return LiveStream.objects.count() serial = serializers.SerializerMethodField('get_serial') class Meta: model = LiveStream fields = ['id', 'channel', 'live_stream_id', 'serial', 'stream'] -
How can I Display Link in List when User is found in another Django Model
I have a search box with a list of users with a hyperlink for approving applications. I want to show Approved on the link on any user whose application is already approved and Approve link on not approved application. I have tried putting the hyperlink in a for loop with a conditional statement to do the check but the Approve button is displaying twice on those users whose application not Approved while on the those Approved Application, the Approve and Approved links are displayed. someone should gracefully help as I am Django beginner so I finding it difficult to go from here. Any better way of achieving the same thing would be much appreciated. Thanks Models code: class Fee(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) email = models.CharField(max_length=30, null=True) phone = models.CharField(max_length=20, null=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Payments: {self.applicant}' class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) def __str__(self): return f'{self.applicant.username}-Profile' views code: def search_applicants(request): #Set an Empty Dict of Context context = {} #Search Applicant Form searchForm = SearchApplicantForm(request.GET or None) payments = Fee.objects.all() if searchForm.is_valid(): #Value of search form value = searchForm.cleaned_data['value'] …