Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make search more accurate in Django?
so on the way of learning process, I am making my first side-project on django. I want to make my search more accurate, for example: when post body contains text with 3 words "I love stackoverflow" and someone searches for "I stackoverflow" (without word LOVE), result is not shown on the search page. What could be the best approach in this case to get the result, even if the post body does not contain words in that order as a search query? views.py def search(request): posts = Post.objects.all().order_by('title') query = request.GET.get('q') print(query) if query: posts = Post.objects.filter( Q(title__icontains=query)| Q(body__icontains=query) ) context = { "posts": posts, } return render(request, "search.html", context) -
How do I create a Friend model with accept field?
I want to create a social networking app, where we can add friends and see their posts. In this I want to create a friend model like this: class Friend(models.Model): from = models.ForeignKey(User) to = models.ForeignKey(User) accepted = models.NullBooleanField(null=True) class Meta: unique_together = ('from', 'to') I am just confused about reverse relation between from and to. For example, if A is friend of B, then B is also friend of A. I am having problem in getting all friends of a user, because the user can exist in from as well as in to. -
How to only allow logged in users connect to websocket in Django Channels?
I have a chat app and I want only users that are logged in to be able to connect to the websocket. How can you achieve that? Is there something like the @login_required decorator for Django channels? I know from the documentation that that's how you can access the user: class ChatConsumer(WebsocketConsumer): def connect(self, event): self.user = self.scope["user"] But how do you deny the connection if the user isn't logged in? -
Chart.js first row bar not showing in django
my chart work properly but as first starting point 1st bar not showing here is the code: $(function () { var $populationChart = $("#population-chart"); var res = ['20','20','30'] $.ajax({ url: $populationChart.data("url"), success: function (data) { var ctx = $populationChart[0].getContext("2d"); new Chart(ctx, { type: 'bar', data: { labels: data.label, datasets: [{ label: 'Price', backgroundColor: 'blue', data: res, }] }, options: { responsive: true, legend: { position: 'top', }, title: { display: true, text: 'Rating Analysis' } } }); } }); }); Screenshot: Is there any way to show minimum value first bar properly? -
Django __init__() takes 1 positional argument but 2 were given (added .as_view())
After i run the server and go to the .../article/ url it return an error File "/home/anhhao/Documents/Data/LuanVan/realestate/project/user/views.py", line 21, in get return Response(serializer.data) TypeError: __init__() takes 1 positional argument but 2 were given Attention line 21: in get return Response(serializer.data) models.py class User(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=300) def __str__(self): return self.name views.py class UserInfo(APIView): def get(self, request, format=None): user = User.objects.all() serializer = UserSerializer(user, many=True) return Response(serializer.data) user/urls.py urlpatterns = [ path('user/', UserInfo.as_view(), name='list_user') ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('user.urls')) ] urlpatterns = format_suffix_patterns(urlpatterns) I had added .as_view() Please help me -
how to save python Dynamic code to database with proper indentation(formatted style)
Consider Following code result = [] for i in range(1,11): if i%2 == 0: result.append("Even") else: result.append("Odd") print(result) I want to save it in (Sqlite3)database as it is and fetch it and display on web pages using html and css. but when i am saving it into sqlite all indentation not saving properly I have Tried pygements still no success Any other way to save and retrieve python code with formatted python code -
The best way for doing something in background Django
I need my django app processing some functions in background periodically. What is the best way for making such functions? And how can I call some functions when server starts? For example, functions of pre-init. -
Check whether value in dict with for loop in Django's template
I have the following data in my views. months = [1,2,3,4,5,6,7,8,9,10,11,12] mydict = {3:'a',4:'b'} The key means month,if this month exists value,then render the value,else leave blank. Here's my template. {% for j in months %} {% if mydict.j %} <th class="align-middle">{{ mydict.j }}</th> {% else %} <th class="align-middle"></th> {% endif %} {% endfor %} But the result always is blank. I can access the value by mydict.3,but i can't get the value by mydict.j with a forloop. -
in django using foreign key, if there is only one row(data) then it is possible to retrieve data but i am not able to fetch multiple row(data)
def yourtrip(request): cstid = request.session['uid'] a = Cabbooking.objects.all().filter(customerID=cstid) counta=a.count() # cid = a[0].cabID # cd = Cabdriver.objects.all().filter(cabID=cid) # did = cd[0].driverID arrays=[] for i in range(counta): cid = a[i].cabID did = Cabdriver.objects.all().filter(cabID=cid) dids = did[0].driverID arrays.append(dids) for x in arrays: print(x) return render(request, "yourtrip.html",{"a":a}) here cabboking is a table from where i retrieve appropriate customer id. here #(commented) code is for single row(data) fetch. i used loop for multiple data fething but its not working -
Django queryset filtering with Taggit app
I am using Django 2.2. I am using the taggit app to provide tagging functionality. However, I also want to use tagging to create functionality for retrieving 'related' items. I have an object Foo which can have one or more tags associated with it. I want to be able to retrieve all Foo objects that have a specified tag. This is the code I have so far: from djando.db import models from taggit.managers import TaggableManager class FooManager(models.Manager) def get_related_foos(self, tag): qs = super(FooManager,self).get_queryset().filter(tag__name) class Foo(models.Model): title = models.CharField(max_length=32) tags = TaggableManager() objects = FooManager() My question is, how do I implement the function get_related_foos ? -
Django: How to exclude a View from session creation?
My Django Project heavily relies on sessions, and the Framework does a very good job with this. It manages Session Cookies, the Session Database and so on, mostly done through the SessionMiddleware. But there a some Views that explicitly do not require a session. And those Views often appear as an entry to the page. Can I exclude these Views from the SessionMiddleware creating new sessions? If a user visits such a View and leaves, there is no need for setting a Cookie or creating a database record in the sessions table. -
Cannot view the image uploaded on the admin panel
Picture gets uploaded on the django admin panel but when i click on the image on the panel it shows the page not found error. forms.py class ApproveImgForm(forms.Form): class Meta: model = ApprovImg fields = "__all__" urls.py path('w_p.html', views.WProduct_list, name='WProduct_list'), views.py def WProduct_list(request, category_slug=None): category = None categories = Category.objects.all() wproducts = Product.objects.filter() if category_slug: category = get_object_or_404(Category, slug=category_slug) wproducts = Product.objects.filter() if(request.method=='POST'): form = ApproveImgForm(request.POST) f = form.data['fileToUpload'] ph = ApprovImg(photo=f) ph.save() context = { 'category': category, 'categories': categories, 'wproducts': wproducts, } return render(request, 'shop/w_p.html', context) models.py class ApprovImg(models.Model): photo=models.ImageField(upload_to='products/%Y/%m/%d') def __str__(self): return str(self.photo) Can someone please help? -
The system cannot find the path specified: 'app_pickfeel/images/
I'm trying to load a random image from a directory. I get this error when I run the code: The system cannot find the path specified: 'app_pickfeel/images/' random_image.py import os import random from django import template from django.conf import settings # module-level variable register = template.Library() @register.simple_tag def random_image(image_dir): try: valid_extensions = settings.RANDOM_IMAGE_EXTENSIONS except AttributeError: valid_extensions = ['.jpg', '.jpeg', '.png', '.gif', ] if image_dir: rel_dir = image_dir else: rel_dir = settings.RANDOM_IMAGE_DIR rand_dir = os.path.join(settings.MEDIA_ROOT, rel_dir) files = [f for f in os.listdir(rand_dir) if os.path.splitext(f)[1] in valid_extensions] return os.path.join(rel_dir, random.choice(files)) pickfeel.html snippet <img src="{{ MEDIA_URL }}{% random_image "app_pickfeel/images/" %}"> Location of images are in the following directory: 'PickFeel/app_pickfeel/images/' images directory -
How to link multiple models with Foreign Key and make corresponding views to get the data rendered at templates in Django?
I am creating a web application in which a user can sell his old phone on the website and get maximum available value for the phone. The process is kind of similar to Cashify.(https://www.cashify.in/sell-old-mobile-phone). Once the user clicks on a particular brand, it lists all the available devices under that brand. When the user clicks on a particular device, it goes to a URL showing different variants of the Phone. When the user selects the variant, maximum available price of the device it shown to the user. Here's the code: models.py class Brand(models.Model): title = models.CharField(max_length=50) brand_image = models.ImageField() slug = models.CharField(max_length=50, default='slug') class Meta: verbose_name_plural = "Brands" def __str__(self): return self.title class Storage(models.Model): ram_storage = models.CharField(max_length=2, default=1) rom_storage = models.CharField(max_length=3, default=2) class Meta: verbose_name_plural = "Storages" def __str__(self): return (self.ram_storage + "/" + self.rom_storage) class Mobile(models.Model): title = models.CharField(max_length=50) thumbnail = models.ImageField() slug = models.CharField(max_length=50) max_selling_price = models.IntegerField(default=10000) brand = models.ForeignKey(Brand, default="Apple", related_name='brand', verbose_name="Brands", on_delete=models.SET_DEFAULT) storage = models.ForeignKey(Storage, related_name='storage', default=1, verbose_name="Storage", on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('brand-detail', kwargs={ 'slug': self.slug }) views.py def brand_detail_view(request, slug): phone = Mobile.objects.filter(brand__slug = slug) context = { "phones": phone } return render(request, "brand-detail.html", context) def phone_detail_view(request, slug): phone = get_object_or_404(Mobile, … -
Django REST Framework Tutorial 1: Serialization How to use the python manage.py shell to post?
I am very new to django and web developement in general . I am trying the Django REST Framework tutorial and I am blocked in very first part of the tutorial. I would like to post some json using then python manage.py shell for the model . There is no example and I don't find anywhere some information. Is it so trivial ? ! Can some one help me ? Thank you in advance all the best :) -
Getting data from a dataset in Django
I have a dataset that I am trying to read data from and display on my site I am using the Pandas package to read the data into a DataFrame. I want to display a subset of the data on my Django website, however I don't know what is the correct way of achiving this, should I import the dataset into my PostgreSQL database and read from there? -
Count number of post in a category
I want to list all the categories in my news table plus add the number of post in each categories. Here is my model : class Blog(models.Model): titre_article = models.CharField(max_length=255) auteur_article = models.ForeignKey(User, on_delete=models.CASCADE) date_article = models.DateTimeField(auto_now_add=True) modif_article = models.DateTimeField(auto_now=True) categorie_article = models.ForeignKey('BlogCat', on_delete=models.CASCADE, default='1') contenu = RichTextField(null=False) def __str__(self): return self.titre_article def get_absolute_url(self): return f"/blog/{self.id}" class BlogCat(models.Model): nom_categorie = models.CharField(max_length=255) def __str__(self): return self.nom_categorie def get_absolute_url(self): return f"/blog/cat/{self.nom_categorie}" From there I can't imagine what the code in the view.py should be. Can someone help ? Thx a lot :) Jeff -
Django: What test cases should be there for any model
I am making test cases for healthcare management system which has many models like patient, physician, hospital, visit, payor, plan etc. I have to write test cases of all these models so I want to know what all test cases are important to test for any model. Like I have made Patient model: from django.db import models from django.core.validators import RegexValidator # Create your models here. class Patient (models.Model): pid = models.IntegerField(unique=True) pfname = models.CharField(max_length=100, default='Enter First Name') plname = models.CharField(max_length=100, default='Enter Last Name') paddress = models.CharField(max_length=100, default='Enter Address') phone_regex = RegexValidator(regex=r'^\+?1?\d{10,15}$', message="Phone number format: '+999999999'.") pphone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True) def __str__(self): return self.pfname So what test cases can be made model patient? -
Django 2.2 url pattern not matching to specified function
I am using Django 2.2 for a website. I have come accross the following problem. My URLS are not being matched to the correct view function - despite the urlpatterns variable being correctly configured AFAICT. All requests seem to be being directed to the getPosts function. Here is my code: myapp/urls.py urlpatterns = [ # ... path('blog/', include('blog.urls', namespace="blog")), # ... ] blog/urls.py app_name = 'blog' urlpatterns = [ # url(r'home', blog_views.getPosts, name='home'), url('', blog_views.getPosts, name='index'), url('posts/<int:id>/<slug:postslug>', blog_views.getPost, name='postdetail'), url('posts/tagged/<slug:tagslug>/<int:pagenum>', blog_views.getTagged, name='post-tagged'), #url(r'^post/edit/', include('tinymce.urls')), # RSS feeds url(r'^feeds/posts/$', blog_views.PostsFeed()), ] views.py # @user_passes_test(some_custom_check) def getPost(request, postSlug=None): # Get specified post post = None #Post.objects.filter(slug=postSlug) # Display specified post return render_to_response('blog/post.html', { 'posts':post}) def getPosts(request, selected_page=1): # Get all blog posts posts = Post.objects.all().order_by('-pub_date') # Add pagination pages = Paginator(posts, 5) returned_page = pages.page(selected_page) # Display all the posts return render_to_response('blog/posts.html', {'posts':returned_page.object_list}) def getTagged(request, tagslug=None, pagenum=1): return render_to_response('blog/tagged.html', { 'posts':None}) The following URL match correctly: http://127.0.0.1:8000/blog The following URLS fail to match (they get matched to blog.views.getPosts) - http://127.0.0.1:8000/blog/posts/1/this-is-a-test - http://127.0.0.1:8000/blog/posts/tagged/foo-slug/1 - http://127.0.0.1:8000/blog/feeds/posts Why are all the URLs being mapped to blog.views.getPosts() ? -
ValueError: Field 'id' expected a number but got 'select'
When I run the "python manage.py migrate" command Error is occuring: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, travello Running migrations: Applying travello.0005_auto_20200313_1046...Traceback (most recent call last): File "C:\Users\uc\Envs\test\lib\site-packages\django\db\models\fields__init__.py", line 1772, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'select' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\uc\Envs\test\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\uc\Envs\test\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\uc\Envs\test\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\uc\Envs\test\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\uc\Envs\test\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\uc\Envs\test\lib\site-packages\django\core\management\commands\migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "C:\Users\uc\Envs\test\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\uc\Envs\test\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\uc\Envs\test\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\uc\Envs\test\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\uc\Envs\test\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Users\uc\Envs\test\lib\site-packages\django\db\backends\base\schema.py", line 564, in alter_field self._alter_field(model, old_field, new_field, old_type, new_type, File "C:\Users\uc\Envs\test\lib\site-packages\django\db\backends\postgresql\schema.py", line 152, in _alter_field super()._alter_field( … -
Overriding LoginView with Django-OTP
I want to use django-otp package to add 2 factor authentication to my logins. However, their LoginView have 2 forms. 1 with anonymous users which shows otp token input field with username and password. Other one is for the authenticated users which shows only otp token input field. However the problem is that, even the user doesn't have 2 factor authentication device is setup, it shows token input field for OTPAuthenticationForm and that's confusing for the users who didn't setup anything. It's in a way that you don't have to fill that field and still you can login but it's still confusing for the user I believe. it's their LoginView: class LoginView(auth_views.LoginView): otp_authentication_form = OTPAuthenticationForm otp_token_form = OTPTokenForm @cached_property def authentication_form(self): user = self.request.user if user.is_anonymous or user.is_verified(): form = self.otp_authentication_form else: form = partial(self.otp_token_form, user) return form def form_valid(self, form): # OTPTokenForm does not call authenticate(), so we may need to populate # user.backend ourselves to keep login() happy. user = form.get_user() if not hasattr(user, 'backend'): user.backend = self.request.session[BACKEND_SESSION_KEY] return super().form_valid(form) However, what I want to do is first show Django's builtin AuthenticationForm to authenticate, if user is authenticated then show OTPTokenForm which only requires 2 factor auth token … -
How to Group product based on brand & fetch min price product in django
I have two table one is brand and other is product now product have 1 foreign of brand_id. 1 brand has multiple products at different prices. now, the problem is I want to fetch only 1 product for each brand not more than 1 and that 1 product is fetch based on minimum price. how to achieve it in Django ORM? Note: If a brand has no product then that brand should not fetch! here, what I tried but it does not work well. def price_chart(request, category_slug): labels = [] price_data = [] price_analysis_data = Product.objects.filter(brand__category__category_slug = category_slug).values('brand__brand_name').annotate( Min('product_price') ).order_by('-product_price') for data in price_analysis_data: labels.append(data['brand__brand_name']) price_data.append(data['product_price']) return JsonResponse(data={ 'labels': labels, 'price_data': price_data, }) Please suggest me good solution! -
Should I store images in backend or frontend
I just started learning about Django and backend development and am currently trying to integrate it with my front end react app. I was wondering, up until now I had stored all images for my website in the public folder of my react app, but I am wondering if it is better to store it somewhere in the backend in Django? -
Django xhtml2pdf declaration Group tags not found
I going through an issue that, I am trying to print a pdf but through the following error: CSSParseError at Declaration group closing '}' not found:: ('{mso-level-start-at:2;\n\tmso-level-text:', '%1;\n\tmso-level-tab-s') I have huge line of code in the same files, when i remove these css from the file, it works, I am not getting whats wrong with these css?: @list l0:level1 {mso-level-start-at:2; mso-level-text:%1; mso-level-tab-stop:none; mso-level-number-position:left; text-indent:-18.0pt;} @list l5:level1 {mso-level-start-at:2; mso-level-tab-stop:none; mso-level-number-position:left; text-indent:-18.0pt; mso-ansi-font-weight:bold; mso-bidi-font-weight:bold;} @list l7:level1 {mso-level-start-at:3; mso-level-text:%1; mso-level-tab-stop:none; mso-level-number-position:left; text-indent:-18.0pt;} Can anyone help me to fix this issue? Can anyone help to fix this? -
What is the best strategy to create an Amazon-like product search and filter with django?
I need to create a search and filter page that should work similarly to Amazon. So I search first in the search bar and then, I filter using checkboxes, dynamically, without clicking on the submit button. I have been googling for literally months and tried many things (nothing works), and I can't find a tutorial helps me doing what I want. I have been looking at: django forms django filter package django rest framework I think that django forms does not do what I need. Django filter package getting started tutorial is impenetrable for a beginner. Finally in django rest framework, many tutorial describe only how to work with the API interface, but nobody finishes by creating a dynamic filter. Can you point me to a tutorial, video or webpage that can help me?