Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Using opencv to live videostream in django from android camera
hello everyone i'm using python opencv to live stream in django. Well i don't have a webcame how can i use a androidphone camera to live stream in the page. my views.py: def get_frame(): camera =cv2.VideoCapture(0) while True: _, img = camera.read() imgencode=cv2.imencode('.jpg',img)[1] stringData=imgencode.tostring() yield (b'--frame\r\n'b'Content-Type: text/plain\r\n\r\n'+stringData+b'\r\n') del(camera) def indexscreen(request): try: template = "screens.html" return render(request,template) except HttpResponseServerError: print("error") @gzip.gzip_page def dynamic_stream(request,stream_path="video"): try : return StreamingHttpResponse(get_frame(),content_type="multipart/x-mixed-replace;boundary=frame") except : return "error" my urls.py: re_path(r'^(?P<stream_path>(.*?))/$',views.dynamic_stream,name="videostream"), re_path(r'^stream/$',views.indexscreen), as i go into the stream page it just returnes a blank page its not givine any error but neither its gives anything. is there something wrong in the code? -
Django Dynamic filter over database view(virtual table)
How to query on virtual table(DataBase view) in django. there are 4 tables and i use UNION on all the certain fields. there are two field which are common in all 4 tables. what have i done so far- 1) created a migration file for this DB view CREATE VIEW `my_db_view` AS select * from table1 UNION select * from table2 .... 2) created a django class to map to this view class MyDBView(models.Model): # fields.... class Meta: managed = False 3) Quering on this model. MyDBView.objects.filter(field1=val1, field2=val2) now this is causing some performance issue as i’m filtering on db view after doing union operation. is there any way that I can dynamically pass these two fields to db view migration? using WHERE over the UNION instead of the tables, we degrade the performance. MySQL will create a temporary table containing the UNION, then query it over the WHERE clause. that we want to avoid. what i want something similar to below CREATE VIEW `my_db_view` AS select * from table1 where field1=val1, field2=val2 UNION select * from table2 where field1=val1, field2=val2 .... and pass the value of field1 and field2 from the django controller dynamically. (like mentioned in 3rd step … -
django rest framework - username field not rendering in browsable api html form
the django rest framework is not displaying username field in my browsable api html form but when i comment down the username in below code it is showing username field in my browsable api html form. I am new to django so anyone can please help me here from rest_framework import serializers from rest_framework.serializers import HyperlinkedIdentityField from .models import Note class NoteSerializer(serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='note-detail', lookup_field='pk') #username = serializers.StringRelatedField(many=False) class Meta: model = Note fields = ['url', 'id', 'username', 'note_text', 'created_date', 'updated_date'] -
question : Object of type 'datetime' is not JSON serializable
'facing this issue file quering data from database , i m not using Serializer' ''' using cursor in raw query on manager as u see''' its my view.py @login_required def index(request): if not request.user.is_superuser: raise(404) customers = Customer.objects.Customer_List() context = {'customers': json.dumps(customers)} return JsonResponse(context=context, safe=False) TypeError at /customers/ Object of type 'datetime' is not JSON serializable and here is my model.py class CustomerListManager(models.Manager): def Customer_List(self): from django.db import connection with connection.cursor() as cursor: cursor.execute(""" select customer_id ,last_30_days-perivous_30_days pace ,first_name ,last_name ,company ,tags ,date_created ,latest_order_date ,first_order_date ,customer_group ,store_type ,assigned_to ,total_orders ,days_active ,ofa ,ofaa ,total_spent ,average_order_value ,status from ( select customer_id ,last_60_days-last_30_days perivous_30_days ,last_30_days ,first_name ,last_name ,company ,tags ,date_created ,latest_order_date ,first_order_date ,customer_group ,store_type ,assigned_to ,total_orders ,days_active ,ofa ,ofaa ,total_spent ,average_order_value ,status from (select c.customer_id ,c.first_name ,c.last_name ,c.company ,c.tags ,c.date_created ,max(s.date_created) latest_order_date ,min(s.date_created) first_order_date ,g.name as customer_group ,c.store_type ,a.username assigned_to ,(select count(s1.sale_id) from sales_sale s1 where s1.customer_id =c.customer_id) total_orders --,max(s.date_created) - min(s.date_created) days_active ,( select max(s.date_created) - min(s.date_created) from sales_sale s where c.customer_id=s.customer_id ) days_active ,(select (max(s.date_created) - min(s.date_created))/count(s.sale_id) OFA from sales_sale s where s.customer_id =c.customer_id) ofa ,(select (current_date - max(s.date_created))- ( (max(s.date_created) - min(s.date_created))/count(s.sale_id) ) OFA_threshold from sales_sale s where s.customer_id =c.customer_id) ofaa ,(select sum(s1.total_inc_tax) total_spent from sales_sale s1 where s1.customer_id =c.customer_id … -
Image won't load from react app to Django server
I just started working with Django and I am trying to integrate it with my react app. I currently have everything working (set the TEMPLATES [DIRS:] to the folder containing html file in React project, and did the same for STATICFILES_DIRS), and the website is showing up properly styled and everything when I run it on the Django server, but for some reason just the images are not loading (which are stored in the public folder of my react-app). Here is an image of my directory: Let me know if any additional images/descriptions would help. -
Best practice to config the dynamically generated file
I made the file like this in views.py. csvDir = 'exportedCsv/' file_path = csvDir + 'test.csv' df.to_csv(path_or_buf=file_path,sep=',',float_format='%.2f',index=False,decimal=",",encoding='utf_8_sig') Dynamically generate file and path the filepath to html. Now there is my file in /exportedCsv/test.csv However I have no way to access this from html. My idea is basiclly wrong??? What should I do when I want to make csv file and let the user download it?? -
web hosting with python Django, Bokeh
I want to provide web application that provides data visualization. To achieve this, i use python Django and python Bokeh library to data visualization. And i tried to operate the server through pythonanywhere beginner account. But in bash, i got a response that "No module named 'bokeh'". So i entered the command "pip install bokeh". As a result, i got a response "ERROR: Could not install packages due to an EnvironmentError: [Errno 122] Disk quota exceeded". I think the reason for that response is that the private file storage provided by Pythonanywhere is 512MB in beginner account. Do you think I'm right? So what kind of web hosting service would help my application? thank you for reading it. (and sorry for my poor English.) -
How to make fields in a model unique to particular row or object in django?
class Question(models.Model): question = models.TextField() option1 = models.CharField(max_length = 20, null = False) option2 = models.CharField(max_length = 20, null = False) option3 = models.CharField(max_length = 20, null = False) option4 = models.CharField(max_length = 20, null = False) How to make all options to question should be different and unique? How to make all options of one Question object unique and different? option1 should not match with option2, option3, option4 of the same question. I have created a form to create a questions. -
How to filter price range from high to low and vice versa in django
Basically I am developing an eCommerce site where there is list of products in product listing page. And i need to show the products according to price range from high to low and vice versa. -
HTML5 player shows on webpage but, mp3 sound not playing
I'm new to programming, I'm trying to put up a mp3 file and player on a django web page the player is showing but, the song is not playing. **models.py** from django.db import models from django.contrib.auth.models import User class Song(models.Model): name = models.CharField(max_length=125) audio_file = models.FileField('media/') **audio.html** <!DOCTYPE html> <html> <body> <audio controls> <source src="JesusChrist.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> </body> </html> **media folder** JesusChrist.mp3 **Settings.py** STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'firegod/static/media') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/media/' -
ImportError: cannot import name 'render_to_response' from 'django.shortcuts'
from django.shortcuts import render_to_response ImportError: cannot import name 'render_to_response' from 'django.shortcuts' (C:\Users\gtdra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py) I have this error when i migrate django-chroniker into my django project , i read that render_to_response have been remove since Django 2.0 , how can i fix this error ?? thanks you -
Why to use signals in Django?
I referred to many documentation and many articles using signals in Django. but I could not understand this concept. which purpose using signals in Django? How it is work? Can please explain the signal concept and how to use it in the Django code. -
Case insensitive URLS in Django 3.0?
Is there a way to have case insensitive URLS with Django 2.0 and up syntax? For example path('profile/<str:username>/add/',views.AddFriendRedirect.as_view(),name='add_friend'), If I did profile/USERNAME, when the username is username in all lowercase, how can I make it so that it is case insensitive? So that even uSErnAmE is valid