Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Variables are not rendenring [DJANGO]
I m making a blog site.And I have been trying to render drom a model RecentPosts objects rpost1 ..etc in my template blogs-base.html which is my blogs details page. But it is not rendenring. Any solution?? views.py from django.http import HttpResponse from django.shortcuts import render from blog.models import Post from django.contrib import messages from django.views.generic import ListView , DetailView from .models import Post , RecentPosts , Comment ,Contact ,Populars from datetime import datetime from .forms import CommentForm def index(request): return render(request, 'index.html') def path(request): return render(request, 'blog.html') def cv(request): return render(request, 'cv.html') class HomeView(ListView): model = Post template_name = 'listview.html' class ArticleDetailView(DetailView): model = Post template_name = 'base2.html' def rpost(request): template_name = "blogs-base.html" rpost = RecentPosts.objects.all() context = {'rpost' : 'rpost'} return render(request ,template_name,context) This is url portion. urls.py from django.urls import path from . import views from .views import HomeView ,ArticleDetailView ,contact ,Comment_page,popular urlpatterns = [ path('', views.index, name='index'), path('index.html', views.index, name='index'), path('cv.html', views.cv, name='cv'), path('blogs/',views.HomeView.as_view(),name="blogs"), path('blogs/<slug:slug>',ArticleDetailView.as_view(),name='base2'), path('contact/', views.contact, name='contact'), path('contact.html/', views.contact, name='contact'), path('comment.html/', views.Comment_page, name='comment'), path('popular', views.popular, name='popular'), ] This is the model portion. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.timezone import now # Create your models here. class Post(models.Model): … -
Django, check if an object present in query set using exists() method
I have a below model, class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) head = models.CharField(max_length=255) authors = models.ManyToManyField(Author) I have created an object in Entry model, when I try to check if there is any objects in Entry model it shows error as attached image -
bash: /python/run/venv/bin/activate: No such file or directory
I'm trying to deploy my django app through AWS elastic beanstalk, & I've been running into an issue for the past 2 days which i've narrowed down more. A command in the deployment process is failing, this command is as follows: container_commands: 01_migrate: command: "python3 manage.py migrate" leader_only: true The section of the AWS EB console logs that tell me this refer me to cfn-init.log, checking this tells me the same thing. In cfn-init-cmd.log however, i see this 2020-06-19 18:24:24,753 P5019 [INFO] Command 01_migrate 2020-06-19 18:24:24,771 P5019 [INFO] -----------------------Command Output----------------------- 2020-06-19 18:24:24,771 P5019 [INFO] Traceback (most recent call last): 2020-06-19 18:24:24,771 P5019 [INFO] File "manage.py", line 10, in main 2020-06-19 18:24:24,771 P5019 [INFO] from django.core.management import execute_from_command_line 2020-06-19 18:24:24,771 P5019 [INFO] ModuleNotFoundError: No module named 'django' 2020-06-19 18:24:24,771 P5019 [INFO] 2020-06-19 18:24:24,771 P5019 [INFO] The above exception was the direct cause of the following exception: 2020-06-19 18:24:24,771 P5019 [INFO] 2020-06-19 18:24:24,772 P5019 [INFO] Traceback (most recent call last): 2020-06-19 18:24:24,772 P5019 [INFO] File "manage.py", line 21, in <module> 2020-06-19 18:24:24,772 P5019 [INFO] main() 2020-06-19 18:24:24,772 P5019 [INFO] File "manage.py", line 16, in main 2020-06-19 18:24:24,772 P5019 [INFO] ) from exc 2020-06-19 18:24:24,772 P5019 [INFO] ImportError: Couldn't import Django. Are you … -
Iterate json response data to loop in django
$(document).ready(function(){ $("button").click(function(){ $.ajax( { type:"GET", url: "{% url 'updatetable' %}", data:{ year_id :1}, success: function( data ) { console.log(data) ; $("#loadtable").html(data); } }); }) ; }); <div class="table-responsive" > <table class="table table-striped"> <thead class="thead-dark"> <tr> <th scope="col">S.N</th> <th scope="col">Name</th> <th scope="col">Post</th> </tr> </thead> <tbody id="loadtable" > {%for dt in data %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{dt.name}}</td> <td>{{dt.post}}</td> </tr> {%endfor%} </tbody> </table> -
Python list of dicts not converting properly in javascript GET handler
i am sending data from views.py in Javascript Ajax function, but it was not converting string to dict here is my code //////////////////////////////////// views.py def SortShop(request,shortby): items = Item.objects.order_by(shortby) item_list = [] for item in items: item_list.append({'name':item.item_name,'title':item.item_titile, 'pricse':item.item_FrashPricse,'dicsount':item.item_Discount_pricse, 'image':item.item_image}) return HttpResponse([item_list]) ///////////////////////////////////////////ajax function $('#sorting').on('change', function(e) { selected_value = this.value $.ajax({ type: 'GET', url: '/shopsorting/' + selected_value, // data: formData, encode: true, success: function(data) { y = JSON.stringify(data) x = JSON.parse(y) console.log(x) } }); }); }); ////////////////////////////Result's is [{'name': 'Shoulder Bag', 'title': 'Boys Shoulder Bag (Yellow )', 'pricse': 15.99, 'dicsount': 0.0, 'image': <ImageFieldFile: man-1.jpg>}, {'name': 'Sweeter', 'title': 'Cotton Sweeter', 'pricse': 19.9, 'dicsount': 0.0, 'image': <ImageFieldFile: product-6.jpg>}, {'name': 'Shirt', 'title': 'Full Sleeves Shirt', 'pricse': 20.99, 'dicsount': 12.99, 'image': <ImageFieldFile: man-4.jpg>}, {'name': 'Jacket', 'title': 'Jackson Jacket', 'pricse': 20.25, 'dicsount': 0.0, 'image': <ImageFieldFile: man-3.jpg>}, {'name': 'Yellow Shoes', 'title': 'Leopard Shoes', 'pricse': 29.99, 'dicsount': 25.99, 'image': <ImageFieldFile: man-2.jpg>}, {'name': 'Bag', 'title': 'Mini Cary Bag', 'pricse': 14.99, 'dicsount': 12.99, 'image': <ImageFieldFile: women-4.jpg>}, {'name': 'Coat', 'title': 'Overcoat (Gray)', 'pricse': 17.7, 'dicsount': 0.0, 'image': <ImageFieldFile: product-3.jpg>}, {'name': 'TOWEL', 'title': 'Pure Pineapple', 'pricse': 19.9, 'dicsount': 0.0, 'image': <ImageFieldFile: women-2.jpg>}, {'name': 'Coat', 'title': 'Pure Pineapple', 'pricse': 17.9, 'dicsount': 11.9, 'image': <ImageFieldFile: product-1.jpg>}, {'name': 'TOWEL', 'title': 'Pure Pineapple (White)', 'pricse': 17.9, … -
ModuleNotFoundError: Apache, Bitnami, Django app failing to import from virtual env
I'm attempting to get a very simple Django app deployed on an AWS Lightsail instance for the first time. I provisioned an AWS Apache instance set up with bitnami and django, and followed the tutorial without a virtual environment successfully but have since spent hours attempting to add my own project with a virtual environment. Most things seem set up correctly and I start Apache fine, only to navigate by browser to my url and find in the error logs a ModuleNotFoundError: No module named 'requests' error. This is the first import of any pip-installed module in my code and so suggests my virtual env has not made it into my PYTHONPATH. I just found a solution by hardcoding the path to my site-packages and appending it using sys.path.append(...) in my wsgi.py file, but I don't think this is the correct way to configure mod_wsgi with a django app and am worried it will lead to unexpected problems later. All django projects on the server are located at /opt/bitnami/apps/django/django-projects/. Following the tutorial, this directory contained projects "Project" and "tutorial". To separate my requirements.txt file and virtual environment env frome these projects, I decided to locate my project (a very simple … -
How do I add a polymorphic class in Django?
I am trying to make an application for a restaurant in django; I have to create a menu for different types of items, and all of those different types of items have to essentially be a product, so that I can add that product to a user's corresponding cart. Here are my menu items: from django.db import models from django.contrib.auth.models import User class Product(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) class Pizza(Product): pizzatype = models.CharField(max_length=15) extras = models.TextField(max_length=50) size = models.CharField(max_length=10) class Subs(Product): name = models.TextField(max_length=64) size = models.CharField(max_length=10) class DinnerPlatters(Product): name = models.TextField(max_length=64) size = models.CharField(max_length=10) class Pasta(Product): name = models.TextField(max_length=64) class Salads(Product): name = models.TextField(max_length=64) As can be seen, I tried deriving the models for different types of menu items from a single model Product, but while running makemigrations, I get the following message on the terminal: You are trying to add a non-nullable field 'product_ptr' to dinnerplatters without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py I tried googling … -
django.db.utils.IntegrityError: UNIQUE constraint failed: first_app_topic.top_name
I'm a beginner Django user... I have this code in my models.py file from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic, on_delete=models.SET_NULL) # added on_delete parameter, because DJANGO > v2.0 is name = models.CharField(max_length=264, unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage, on_delete=models.SET_NULL) # same on_delete needed to be added otherwise t>python manage.py migrate fails date = models.DateField() def __str__(self): return str(self.date) The above code is updated for Django version > 2.0 (ie with on_delete=models.SET_NULL) included as an argument. I then run the following commands in the command console python manage.py makemigrations registers the changes to your application. python manage.py migrate python manage.py shell >>> from first_app.models import Topic >>> print(Topic.objects.all()) <QuerySet [Topic: Social Network]> >>> t = Topic(top_name="Social Network") >>> t.save() This gives the following error log Traceback (most recent call last): File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: first_app_topic.top_name The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> … -
Cross checking field input in Python
I am writing a web application using oTree and Django and I am totally new to both. I am willing to ask the user to compile a form with two fields on the same page. I need to have a validation that checks whether the sum of the two values inserted in the two fields is less than a maximum value (e.g. 10). If the sum is bigger, I need to raise an error not letting the user switch to the next page. That's the code in the html file relative to the user input: {% formfield player.attribute_1 label="Your attribute 1 (from 0 to 10):" %} {% formfield player.attribute_2 label="Your attribute 2 (from 0 to 10):" %} {% next_button %} And that's the relative piece of code in the models.py file: class Player(BasePlayer): attribute_1 = models.CurrencyField( min=0, max=10, doc="""Your attribute 1""" ) attribute_2 = models.CurrencyField( min=0, max=10, doc="""Your attribute 2""" ) Currently it checks each single formfield to be in the range 0-10. How can I check the sum to be less than 10 instead? Thank you very much in advance for any help. -
How can I get the kwarg of the current url in Django
I am calling a view via an async AJAX call to lazy load blog posts. Now I am searching for a solution to get the category keyword (or named) arguments (kwarg) of the current url to use it for the database query within the view. So I either have to somehow pass that category via AJAX to the view or call it in the view directly. I do neither know which solution is the better one nor how to implement them. What I have: urls urlpatterns = [ path('<category>', render_blog_category, name='HotStocks'), path('<category>', render_blog_category, name='AsiaPacific'), path('<category>', render_blog_category, name='Europe'), path('<category>', render_blog_category, name='America'), path('<category>', render_blog_category, name='Pennystocks'), path('<category>', render_blog_category, name='Charts'), url(r'^$', render_blog_main, name='render_blog'), url(r'^lazy_load_posts/$', lazy_load_posts, name='lazy_load_posts'), url(r'^lazy_load_search/$', lazy_load_search, name='lazy_load_search'), ] blog.html which extends base.html <script type="text/javascript"> // A CSRF token is required when making post requests in Django // To be used for making AJAX requests in script.js window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <div id="blog-wrapper"> <!-- Latest Posts --> <div id="latest-posts-ctn"> <div id="posts">{% include 'blog/posts.html' %}</div> </div> <div id="lazyLoad-ctn"> <a id="lazyLoadLink" href="javascript:void(0);" data-page="2"><div id="loadmore-button">Load More Posts</div></a> </div> </div> <!-- Close Blog-Wrapper --> base.html <ul id="navbar-navigation"> <li class="navigation-item"> <a href="{% url 'AsiaPacific' category='Asia Pacific' %}">Asia Pacific</a> </li> <li class="navigation-item"> <a href="{% url 'Europe' category='Europe' … -
Auto end video call session from a page Django
I'm developing a custom video call app in Django. I want to end the video call session after 1 hour. Is there any way other than using JS or AJAX to auto exit from the page? -
Cannot open raw files from cloudinary in django admin
I do config the raw file's storage to couldinary and I can't open it in django admin(it shown 404 error). Did I miss something? I have set the storage location in setting.py as below: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' DEFAULT_FILE_STORAGE1 = 'cloudinary_storage.storage.RawMediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'XXXXX', 'API_KEY': 'XXXXXX', 'API_SECRET': 'XXXX-XXXXX', } CKEDITOR_UPLOAD_PATH = DEFAULT_FILE_STORAGE CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } Added to urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('team_profile.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.DEFAULT_FILE_STORAGE) Set the raw file's upload path in models.py: from django.db import models from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField from cloudinary_storage.storage import RawMediaCloudinaryStorage class apply_position(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=8) mail = models.EmailField(blank=False) file = models.FileField(upload_to='add/file_save/', null=False, storage=RawMediaCloudinaryStorage()) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.name The forms.py is fine and I've put it to the views.py def recruit(request): form = addForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): form.save() return redirect('/') else: form = addForm() The Error I got when I try to open the files in admin site: https://res.cloudinary.com/xxxxx/raw/upload/v1/media/add/file_save/xxxx.pdf HTTP ERROR 404 -
Django website wow.js and animate.css is not working
I got animate.css to work fine , but when i imported wow.js into my static folder, it did not function on the scroll or just in general. The animation part only works without the "wow" class. As my website is built with django, im not sure if that has anything to do with it. Here is the code that includes the animate and wow files. <link rel="stylesheet" href="{% static 'css/animate.css' %}"> this is the only one that works: <div class="container"> <h1 class="animate__animated animate__bounce" style="color:black;">An animated element</h1> all of these do not work and i don't know what i am doing wrong: </div> <div class="container"> <h1 class="wow animate__bounce" style="color:black;">An animated element</h1> </div> <div class="container"> <h1 class="wow bounce" style="color:black;">An animated element</h1> </div> <div class="wow bounce"> <h1 class="wow bounce" style="color:black;">An animated element</h1> </div> I have these loaded in as well: <script language="javascript" type="text/javascript" src="{% static 'js/wow.min.js' %}"></script> <script>new WOW().init();</script> Attached image of my folder hierarchy The wow.js does not work wherever i put the containers on the page. All of this code is in my base.html folder (please refer to the image attached) On my website, they are further down with other information (i did not include as it would be too messy … -
How to use async_to_sync() & sync_to_async() in Django?
I need to use the asynchronous methods in the Django Views. How can I accomplish that. The documentation is available here, but the example is not provided. The below code is not working and I am getting the error coroutine. async def Dashboard(requests): txt = await api.com/mymessage return render(requests, 'Index.html', {'message': txt}) What is the proper way to wrap the method in the async_to_sync()? -
How can you sort the order of cards displayed in HTML
I'm using Python and Django to build a website. I'm making a rough version of the homepage with Bootstrap and HTML. I have a group of Cards that have a time written on them (i.e "12:00AM" or "2:30PM"). How can I sort these cards in order of earliest to latest? Here's a link to a rough version of my code. I put random data in there because I'm getting real data from Django : Codeply Link -
Django: Page not found (404) when posting form data
I am trying to create a form to submit a blog post on an author detail page, so that the blog post will automatically use the current author as its "blog_author" foreign key. The Django docs recommended using 1 parent view and 2 subviews to handle get and post respectively (https://docs.djangoproject.com/en/3.0/topics/class-based-views/mixins/). The page renders fine with the get, but the post gives me an error reading "Page not found (404) - no blog post found matching the query." The exception is raised by my parent view (blog.views.AuthorDetail), but there is no traceback. Here are my views: class BlogAuthorDetailView(generic.DetailView): model = BlogAuthor def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = BlogSubmitForm() return context class BlogSubmit(SingleObjectMixin, FormView): template_name = 'blogauthor_detail.html' form_class = BlogSubmitForm model = BlogPost def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() #Should I be overriding form_valid() to use the line above? Not sure if I'm doing my data #handling in the right place return super().post(request, *args, **kwargs) def form_valid(self, form): blogpost = form.save(commit=False) blogpost.blog_author = self.object blogpost.save() return redirect('blog_author-detail', pk=self.object.id) class AuthorDetail(View): def get(self, request, *args, **kwargs): view = BlogAuthorDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = BlogSubmit.as_view() return view(request, … -
Django: Official recommendations for using try - except (aka try catch exception handling)
In Django specifically, what are the recommendations for using try/except, for example, in a view or similar area of the code? I could not find an official document on best practices & performance considerations for Django specifically. For context, if an exception is raised in a view without a try-except, the error and some trace is reported in the log and the Django server keeps running. Now, there are some times when a try-except is necessary for logic. There are other times when it's not- the best course of action is to raise it anyhow and leave the function. Technically, almost every line of code could be a try-except. In practise, that code gets very long, and rather than having 1 central way to deal with raised exceptions, it creates lots of copying and pasting across the dev team which can result in consistency issues/cat herding. What are the official recommendations, and failing that, what rules of thumb are there? FYI, using Python3. -
Web Socket through connection handshake error, status: 200 on production while on local its working fine, Django + Angular
I'm trying to set up a web-socket for real-time notification. My Frontend is Angular & Backend is Django using docker for both backend and frontend. On the local machine, it's working perfectly fine. Connection successfully establish & signal can transmit/broadcast. But when I deployed it on the server it through error 200 Here is the backend connection code: main -> routers.py application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( sog.notification.routing.websocket_urlpatterns ) ), }) app -> routers.py websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer ) ] consumers.py class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] #usename self.room_group_name = self.room_name async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) Here is the Frontend code: While I'm on local machine In Frontend I wrote WEB-SOCKET URL: wss://localhost:8000/ws/chat/notification_'+ authService.getUsername() For Server I used: wss://domain.com/ws/chat/notification_'+ authService.getUsername() websocket.service.ts import { Injectable } from "@angular/core"; import * as Rx from "rxjs/Rx"; @Injectable() export class WebsocketService { constructor() {} private subject: Rx.Subject<MessageEvent>; public connect(url): Rx.Subject<MessageEvent> { if (!this.subject) { this.subject = this.create(url); console.log("Successfully connected: " … -
How to multiply 2 fields and save the result to another field in django
i want to multiply 2 fields of django database and save the result to another field. like i want to multiply the selling price and total quantity of a product to find total price of all those products. -
Return serialized JSON from DRF Serializer
I have a custom serializer that is returning a string representation of JSON. This serializer uses django.contrib.gis.serializers.geojson.Serializer which is much faster than the DRF serializer. The downside of this serializer is that it returns everything already serialized into a string, rather than as a JSON serializiable object. Is there a way to shortcut the DRF obj>json string process and just pass the string as the json response? Currently I am doing the following, but the obj>string>dict>string process is not ideal: from django.contrib.gis.serializers.geojson import Serializer from json import loads class GeoJSONFastSerializer(Serializer): def __init__(self, *args, **kwargs): self.instances = args[0] super().__init__() @property def data(self): # The use of json.loads here to deserialize the string, # only for it to be reserialized by DRF is inefficient. return loads(self.serialize(self.instances)) Which is implemented (simplified version) in the view: from rest_framework.mixins import ListModelMixin from rest_framework.viewsets import GenericViewSet class GeoJSONPlaceViewSet(ListModelMixin, GenericViewSet): serializer_class = GeoJSONFastSerializer queryset = Places.objects.all() -
how to get the context of an object in object_list?
I have a query set in the PostListView, and I would like to access the .likes attribute of a single object in a post.objects.all() query_set. But in the templates' context, I can only access the context dict of: context {'is_paginated': True, 'object_list': <QuerySet [<Post: aasd>, <Post: asd>, <Post: ads>, <Post: asd>, <Post: asd>]>, 'page_obj': <Page 1 of 3>, 'paginator': <django.core.paginator.Paginator object at 0x10e5901c0>, 'posts': <QuerySet [<Post: aasd>, <Post: asd>, <Post: ads>, <Post: asd>, <Post: asd>]>, 'view': <blog.views.PostListView object at 0x10e5904f0>} How can I get the context of the single Post object from the QuerySet and therefore accessing that Post.likes attributes? Thanks Edited: Views.py def home(request): post = get_object_or_404(Post, id=request.POST.get('post_id')) if post.likes.filter(id=request.user.id).exists(): is_liked = True context = { 'posts': Post.objects.all(), 'is_liked': is_liked, 'post': post, 'total_likes': post.total_likes(), } return render(request, 'blog/home.html', context) def like_post(request): # post like post = get_object_or_404(Post, id=request.POST.get('post_id')) is_liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True return HttpResponseRedirect('http://127.0.0.1:8000/') class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 is_liked = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['posts'] #attribute error, no attr likes in posts queryset if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return … -
Django select oneotone from queryset in view
view @login_required def users(request): """List all users page""" t_users = User.objects.all() users = t_users.usersettings.filter(search_hidden=False).select_related('user') context = {'users': users} return render(request, 'users/users.html', context) model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class UserSettings(models.Model): """Stores the user's settings.""" user = models.OneToOneField(User, related_name='usersettings', on_delete=models.CASCADE) public_profile = models.BooleanField(default=True) search_hidden = models.BooleanField(default=False) class Meta: verbose_name_plural = 'usersettings' def __str__(self): return f"{self.user}'s settings" @receiver(post_save, sender=User) def create_user_usersettings(sender, instance, created, **kwargs): if created: UserSettings.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_usersettings(sender, instance, **kwargs): instance.usersettings.save() I want to select all users that have search_hidden disabled, however what I've tried doesn't work.The error 'QuerySet' object has no attribute 'usersettings' is displayed whenever the page is requested. I probably need to select each user and retrieve the settings, but I don't know how to do that in an efficient manner. -
Find the specific work via beautifulsoup in django
i started to learn beautifulsoup. I tried to make web application with django that have a html form and get the keyword from this form. When it get keyword, need to find related words inside the website.It can successfully retrieve the form from post request but for some reason, the function is not returning the rendered html as expected. its also not printing output.text. When i change the code for find tags(div,p,a etc...) it's working without any problem. This code giving output until i make any request. i didn't understand where is the problem, render or patterns? How can i fix this problem? if request.method == "POST": keyword = request.POST['keyword'] if '£#$½{[]}' in keyword: print("Please enter invalid words") else: url = 'https://www.emu.edu.tr/en' contents = requests.get(url) page_html = contents.text pagesoup = bs4(page_html, 'html.parser') mykeyword = pagesoup.find_all(keyword) for output in mykeyword: if output.select('p')[0].text == '1': print(output.text) return render(request, 'BeatifulSoup.html', {} -
Do Django models tests need database usage?
Here an minimal example (full code), a foobar application with a Class Fruit whom I want to test the __str__() method. foobar.models : from django.db import models class Fruit(models.Model): """An MVC for testing models without using Django DB""" name = models.CharField(max_length=42) def __str__(self): return self.name.upper() foobar.tests from pytest import mark from foobar.models import Fruit fruit_name = "cherry" def test_fruit__str__py(): """testing Fruit.__str__() whitout using Django DB""" test_fruit = Fruit(name=fruit_name) assert test_fruit.__str__() == fruit_name.upper() @mark.django_db def test_fruit__str__dj(): """testing Fruit.__str__() using Django DB""" Fruit.objects.create(name=fruit_name) test_fruit = Fruit.objects.last() assert test_fruit.__str__() == fruit_name.upper() Question : Since the method you would test do not involve database or pre-loaded dataset and if I want to unit-test, is the first one (test_fruit__str__py()) enough relevant? -
Django collectstatic does not collect media files from react npm build folder
I have a frontend react app, after using npm run build it creates build folder with: build favicon.ico index.html service-woker.js static After using django's python manage.py collectstatic I noticed what django has done was that it pulls out only the static folder, favicon.ico is not pulled out. So, my website icon doesn't work. In my index.html, <link rel="apple-touch-icon" href="%PUBLIC_URL%/favicon.ico" /> In my settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, '../frontend/build/static') ] STATIC_ROOT = '/var/www/web/home/static/' STATIC_URL = 'home/static/' In chrome inspect in the headers element: <link rel="icon" href="./home/favicon.ico"> How do I get it to display my web icon. Thankyou!