Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count all category objects in a filtered querry in django?
I am desperately trying to count the objects in a category in my model. To be more clear: I am scraping news articles and I have this model: class News(models.Model): title = models.CharField(max_length=2000) link = models.CharField(max_length=2083, default="", unique=True) published = models.DateTimeField() desc = models.CharField(max_length=2083) site = models.CharField(max_length=30, default="", blank=True, null=True) and this view filtering objects and serving them upon request: class SearchResultsView(ListView): model = News template_name = 'search_results.html' context_object_name = 'articles' def get_queryset(self): query = self.request.GET.get('q') min_dt = self.request.GET.get('qf') max_dt = self.request.GET.get('qt') object_list = News.objects.filter(Q (title__icontains=query)| Q (desc__icontains=query) & Q (published__range=(min_dt, max_dt))).order_by('-published') I need to put on my html django website how many articles I get for each site Here is my html <div class="row"> <table> <tbody> <h2>{{ articles.count }} articles found in total </h2> HERE I NEED TO PUT HOW MANY ARTICLES PER SITE BELOW IS THE ACTUAL LIST ON A TABLE {% for a in articles %} <tr> <td> <a href="{{ a.link }}">{{ a.title }}</a> </td> <td> <p> Source: {{ a.site }} </p> </td> <td> <p> Published: {{ a.published }} </p> </td> <td> <p> More info: {{ a.desc }} </p> </td> </tr> {% endfor %} </tbody> </table> -
Django rest framework serializer validation error messages in array
Is there a way to get array of error messages instead of object when retrieving validation errors from serializers? For example: [ "User with this email already exists.", "User with this phone number already exists." ] Instead of: { "email": [ "User with this email already exists." ], "phone_number": [ "User with this phone number already exists." ] } -
Django auth +MySQL migrations, row size too large
This migration file fails which is included in the contrib.auth /Users/xxx/.virtualenvs/xxxx-0LdyW30-/lib/python3.8/site-packages/django/contrib/auth/migrations/0012_alter_user_first_name_max_length.py from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.AlterField( model_name='user', name='first_name', field=models.CharField(blank=True, max_length=150, verbose_name='first name'), ), ] error: web_1 | MySQLdb._exceptions.OperationalError: (1118, 'Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs') note: I'm using a docker-compose environment -
Django: Is There A Way To Refresh Page Without Going Back To The Top Of The Page
I am using a like button but everytime i press it it needs to refresh the page which sends the user back to the top of the page. I want to find a way to refresh the page but keep the position at the post they liked. Is there a good way to do this. I know it can be done because most social media sites do this. views.py: def like_post(request, pk): post = Post.objects.get(id=pk) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('home-new')) -
How to get one to many like result in a queryset
How to achieve one to many like result in a queryset. I am doing a query that returns results that match checkout date. Is it possible to modify the result so as to return array of rooms under one ref_id where the ref_id and checkout date is matching?. # models.py class Booking(models.Model): ref_id = models.TextField(null=True) room = models.ForeignKey(Room, on_delete=models.SET_NULL, null=True) check_in_date = models.DateField(blank=False, null=False) check_out_date = models.DateField(blank=False, null=False) # serializer.py class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = ('id', 'room_number',) class BookingsSerializer(serializers.Serializer): ref_id = serializers.CharField() room = serializers.ListField(child=RoomSerializer()) # room = RoomSerializer(many=True) check_out_date = serializers.DateField() # views.py class ReadBookings(APIView): filter = {} filter['check_out_date']=check_out_date bookings = Booking.objects.filter(**filter) serializer = BookingsSerializer(bookings,many=True) return Response(serializer.data) enter code here Returned result [ { id: 1 ref_id: "o6eWRjURKP-e4c6d0ca96a145419f528db1a9994029-1609055850117" check_out_date: "2020-12-29" room:{ id: 8 room_number: "006" }, { id: 2 ref_id: "o6eWRjURKP-e4c6d0ca96a145419f528db1a9994029-1609055850117" check_out_date: "2020-12-29" room:{ id: 9 room_number: "007" } ] Desired result [ { id: 1 ref_id: "o6eWRjURKP-e4c6d0ca96a145419f528db1a9994029-1609055850117" check_out_date: "2020-12-29" rooms:[ { id: 8 room_number: "006" }, { id: 9 room_number: "007" } ] }, { ......... ..... } ] -
Django: Invalid block tag on line 14: 'endblock', expected 'endfor'. Did you forget to register or load this tag?
I am a new python learner and I am currently going through Chapter 19 of Python Crash Course edition and I am encountering this problem with topics.html file Django: Invalid block tag on line 14: 'endblock', expected 'endfor'. Did you forget to register or load this tag? My topics.html file looks like this: {% extends "learning_logs/base.html" %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <li> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a> <li> {% empty %} </ul> <a href="{% url 'learning_logs:new_topic' %}">Add a new topic</a> {% endblock content %} The Line 14 which it was referring to was this: {% endblock content %} I searched for similar tickets like this and I thought it was the spacing in that line. I edited it and I still get the same issue. I checked the rest of the file and it seems to follow the proper spacing of the { and %. Please help me figure this one out. Would greatly appreciate it. -
Packages to share contents on social media with Django Rest Framework
My app uses a Django backend and vuejs frontend, with API's served with Django Rest Framework. Now at the front end, I need to add social media links to share my contents on social media, notably Facebook, Instagram and Twitter. I have tried googling around for a resource but can't seems to find any, except django-rest-auth and allauth packages which work for authentication, not sharing. I will appreciate if anyone can direct or guide me to packages I can use for this purpose? -
"no such column adoptions_pet.submissions.date" error
Doing the "Become a Django dev" on LI Learning. However, I have trouble getting the column date values of a .csv into my website. Any help appreciated. If I don't formulate the problem well for you to help me, please let me know what extra information I should give. The error goes, after visiting http://localhost:8000/admin/adoptions/pet/: File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: adoptions_pet.submissions_date The db.sqlite3 file looks fine in my DB browser. db browser image models.py file: from django.db import models class Pet(models.Model): SEX_CHOICES = [('M', 'Male'), ('F', 'Female')] name = models.CharField(max_length=100) submitter = models.CharField(max_length=100) species = models.CharField(max_length=30) breed = models.CharField(max_length=30, blank=True) description = models.TextField() sex = models.CharField(max_length=1, choices=SEX_CHOICES, blank=True) submissions_date = models.DateTimeField() age = models.IntegerField(null=True) vaccinations = models.ManyToManyField('Vaccine', blank=True) class Vaccine(models.Model): name = models.CharField(max_length=50) load.pet.data.py from csv import DictReader from datetime import datetime from django.core.management import BaseCommand from adoptions.models import Pet, Vaccine from pytz import UTC DATETIME_FORMAT = '%m/%d/%Y %H:%M' VACCINES_NAMES = [ 'Canine Parvo', 'Canine Distemper', 'Canine Rabies', 'Canine Leptospira', 'Feline Herpes Virus 1', 'Feline Rabies', 'Feline Leukemia' ] ALREDY_LOADED_ERROR_MESSAGE = """ If you need to reload the pet data from the CSV file, first delete the db.sqlite3 file to destroy … -
How to Call A Particular Relational Field in Django 3.*
I have two models like so: class model1(model.Models): a=model.ForeignKey('model2') // the goal is to call only value **c** that is present in model2 class Model2(model.Models): b=some codes c= some codes What I am trying to do is that anytime I call a in the template.html, then {{a}} should render value of c that is in Model2 Please is there any parameter that exists in django3 for this to work? -
How to do migratiobn in django?
Initially I migrated one app models after that I added one field there pol_id = CharField(max_length=25, unique=True) now if I am running makemigrations its showing me You are trying to add a non-nullable field 'pol_id' to Health 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 In my db there is no any object, I saw many answer to put there null=True, but I can't add null=True in pol_id, is there any hard migration command to fix this issue? -
How do I send email through button click in django?
I am a beginner in Django. I can not go to the view via ajax code. I have coded it at the button click. This code was written to send an email through button click. In view.py, while code in def error displayed and otherwise if code in class email sent when document load . Email should be sent on button click. Can you help me with that? user_profile.html <button class="btn btn-orange" id="btn_delete" onclick="delete_profile1()">Delete</button> <script> function delete_profile1() { $.ajax({ type: 'POST', url: '{% url "delete_profile" %}', data: { }, success: function () { toastr.info('Preference Updated Successfully') } }); } </script> urls.py path('delete_profile', delete_profile.as_view(), name='delete_profile'), views.py class delete_profile(View): def post(self, request, *args, **kwargs): print("nothing") template = loader.get_template("frontend/subscription-start.html") email_content = "deletion confirmation" send_mail( 'No Dowry Marriage - Subscription', email_content, 'developer@goodbits.in', [rihla1995@gmail.com], html_message=email_content, fail_silently=False ) -
how to manage the folder for media files in production environment?
I have my Django-app and I am using fileSystemStorage to store my media files and now I want to deploy my app on heroku. But the problem is that my code for media file storage is as follows: urls.py if settings.DEBUG: urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) settings.py . . # Upload Media Files MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') . . And in production mode we have to set "DEBUG to FALSE" which will produce a problem for storing the files. Can you suggest some ways to deal with this issue? Ps: I know that FileSystemStorage shouldn't be used in production environment but it's fine for my case since I'm using it to store files temporarily. -
how to not redirect to other page after JsonResponse in django?
I have 2 views which are post_detail_view and login_function. I use post_detail_view to render login form and login_function to handle POST request. # views.py def tutorial_detail_view(request, pk): context = {} context['object'] = TutorialPost.objects.get(id = pk) context['login_form'] = LoginForm() return render(request, "tutorial/tutorial_detail.html", context) def login_function(request): if request.method == "POST": login_form = LoginForm(request.POST) if login_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email = email, password = password) if user is not None: login(request, user) return JsonResponse({'success': True}, status=200) else: return JsonResponse({'form_errors': login_form.errors}, status=400) return JsonResponse({}, status=400) # urls.py path('post/<slug:pk>/', tutorial_detail_view, name="tutorial_detial"), path('login/', login_function, name="login") # tutorial_detail.html <form action="{% url 'login' %}" method="POST"> {% csrf_token %} {{ login_form.email }} {{ login_form.password }} <button type="submit">log in</button> </form> What I want is to get response or error response from JsonReponse and stay in tutorail_detail.html and post/<slug:pk> url and I have some javascript code to get that response but it keeps redirecting me to login url and display response there. How can i fix it? -
how can i use Django with html CSS JS?
I am making a website and through some sources ,I find out that Django is for backend and html CSS and JS is for front end ,so I am designing my pages in the later 3 and not started developing the backend so, is there any way that I can use Django with html CSS and JS? (please suggest an easy method as I am a newbie ,however I am quite familiar with python ) -
PostgreSQL: How to store and fetch historical SQL data from Azure Data Lakes (ADLS)
I have one single Django web application deployed on Azure with a transactional SQL DB i.e. PostgreSQL. At the beginning of every month, the older month's data needs to be dumped away into the ADLS repository. This unified ADLS repository will also be utilized by a Power BI portal to gain access into all the historical data it contains. Question. A) Is this scenario possible? Would the power bi portal be able to navigate through this huge heap of ADLS Data? Within the Django application, every day this historical data needs to be accessed (eg: to show the pattern over a period of years, months etc.) from the ADLS. However, the ADLS will only return a single/multiple Files, and my application needs an intermediate such as Azure Synapse to convert this unstructured data into Structured DB in order to perform Queries on this historical data to show it within the web application. Question. B) Would Azure Synapse fulfil this 'unstructured to structured conversion' requirement, or is there another Azure alternative. Question. C) Since Django is inherently tied to ORM (Object Relation Mapping), would there be any compatibility issues between the web app's PostgreSQL and Azure Synapse (i.e. ArrayField, JSONField etc.) … -
Unable to POST data in Django Rest Framework
I have developed a sample applications using Python Django Rest framework to implement basic CRUD operations. In this application , I am using MySQL database. I have created database named roytuts and a table named as user. In this user table i have declared various fields such as : id,name,email,phone,address . PROBLEM : The problem is I have declared id as AUTO INCREMENT. When i post data without providing id it gives error(although it should not give as id is auto increment). I have to manually provide id to POST data. Below are the screen shots Repository Github Link : https://github.com/mohitkrsharma/RestAPI.git Any solution please ? -
Django all auth facebook login with Use Strict Mode for Redirect URIs
Hi I am trying to implement Facebook login for my website using Django Allauth. As we can no longer disable Use Strict Mode for Redirect URIs I am getting an error when I try to login via facebook. The callback URL formed at the time of Facebook login is of this format - https://example.com/accounts/facebook/login/callback/?code=AQB7W48oY-1XxZv2xU9iahxS80ZPs4oBNLlXWTY7Y93dclyIElEPG-jWKB5ELV7Pv11ckcRYg3L67Wfcz6xqC8yhNLBaFaOQjd4F2AEp8nfScltnY3LoY79g9NjtslCSbQnSlc_hDdBm_rxQtScz-rLChNvAJaky3KYMG_USSTkm9qdyvw5lIMdcIHQjz3CTF8KdgmuFG1T8_WvVqdGDEpfhC_PD7w5tnkcChBEowHnWR656DYa1wrMR1fbP2rqxBocNn6fKPCy_GM_DZynPp8mx0F0YP55vzw2Kv8KchB2nxCaHwQ4dRvJq785w5CfCgDVc6REhbc3CNG2KqZxdxjuG&state=eukVyjHYk04X#_=_ This URL contains the query params code and state because of which it is not an exact match and I checked it via Redirect URI to Check which reported it as invalid. So on the authentication_error.html I get the following error. {'provider': 'facebook', 'code': 'unknown', 'exception': OAuth2Error('Error retrieving access token: b'{"error":{"message":"Can\'t load URL: The domain of this URL isn\'t included in the app\'s domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings.","type":"OAuthException","code":191,"fbtrace_id":"AxoTkIBeoUSKsxuWvMx-Wg4"}}'',)} My Valid OAuth Redirect URIs has the following URL's https://example.com/accounts/facebook/login/callback/ https://www.example.com/accounts/facebook/login/callback/ Please help me with this issue, I have looked into all the existing issue but haven't found a solution. -
Django / Python: TypeError at / 'NoneType' object is not subscriptable
Hey pretty gals and boys, would you mind helping me out on this, please? Errors showing in views.py at line data = cartData(request) and utils.py cartItems = cookieData['cartItems'] Thanking you in advance angels :) views.py from . utils import cookieCart, cartData def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'store/store.html', context) utils.py def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems': cartItems, 'order': order, 'items': items} -
celery apply_async not clearing previous task
I'm using Django 2.2 and Celery for periodic tasks I have the following task configuration @celery.task(name='payments.recheck_payment_status') def recheck_payment_status(payment_id): """ Recheck payment status :param payment_id: Payment id for which recheck the status :return: """ logger.info('Checking status for payment %s' % payment_id) payment = Payment.objects.get(id=payment_id) if timezone.now() > payment.created + timedelta(days=1): logger.info('Payment done is more than 1 day. Sending email to the admin') send_incomplete_payment_email.apply_async(args=(payment_id,)) return if not payment.completed: logger.info('Payment status is incomplete. Checking payment status') payment_ = payment.recheck_payment() if payment_.completed: order = payment.order order.external_reference = payment.external_reference order.save() if not payment_.completed: logger.info('Payment %s is not completed yet.' % payment_id) recheck_payment_status.apply_async( args=(payment.id,), countdown=1800 ) And the task is called by recheck_payment_status.apply_async(args=(payment_id,), countdown=300) For a few payments, which failed to check after 300 seconds, are requeued by 1800 seconds again and again. But the past queue is not cleared and the task send_incomplete_payment_email is executed multiple times due to the previously scheduled tasks. -
Handling data during django migrations?
class Material(models.Model): name = models.CharField(max_length=50, blank=False) short_name = models.CharField(max_length=2, blank=False, unique=False, default='Al') def __str__(self): return self.name class Meta: db_table = 'material' I have created this model. Let suppose I have added a new field called status = models.IntergerField(default=1) After that If I run command python manage.py makemigrations, then django will add a new field status in table. Let's I have 3 rows in the table, then value will be as below: 1. Material1, M1, 1 2. Material2, M2,1 3. Material3, M3, 1 With this migration, I also want to change the status of every row and add new row also like 1. Material1, M1, 1 2. Material2, M2,0 3. Material3, M3, 0 4. Material4, M4, 1 Is there any way to handle data manipulation along the schema migration in django? -
Direct assignment to the forward side of a many-to-many set is prohibited. Use school_name.set() instead
I was set that code with set still i'm getting this error there i modified in serializer file. model.py class Teacher(Model): name = CharField(max_length=64, db_index=True) mobile_number = CharField(max_length=12, blank=True, db_index=True) email = EmailField(max_length=32, blank=True, db_index=True) city = CharField(max_length=18, blank=True, db_index=True) school_name = ManyToManyField(School, related_name="teacher", null=True) associated_class = ManyToManyField( StudentClass, related_name="teachers", blank=True, ) subject = ForeignKey( Subject, related_name="teach", blank=True, null=True, on_delete=CASCADE, ) user = ForeignKey( User, null=True, blank=True, on_delete=CASCADE, ) created_at = DateTimeField(auto_now_add=True, null=True) updated_at = DateTimeField(auto_now=True, null=True) class Meta: verbose_name = "Teacher" verbose_name_plural = "Teachers" this is my serializer.py file here i changed my code but still it's pointing that error in serializer. serializer.py class TeacherSignupSerializer(serializers.ModelSerializer): user = UserCreateSerializer() class Meta: model = Teacher fields = ( 'name', 'email', 'mobile_number', 'city', 'school_name', 'subject', 'associated_class', 'user', ) extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create_user(**user_data) teacher = Teacher.objects.create(**validated_data) teacher.set_user(user) return teacher this is views.py file here i declared that pulling the things which i mentioning in the serializer. views.py class TeacherSigupAPIView(generics.GenericAPIView): serializer_class = TeacherSignupSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): teacher = serializer.save() if teacher: return Response({ "status": True, "teacher": TeacherSerializer(teacher, context=self.get_serializer_context()).data, }) return Response({ "status": False, "message": "Teacher is already … -
python crash course 19-1 edit posts not working
This is the error I get when clicking on Edit post under any one of the posts. Would appreciate any help as all this django stuff is confusing me but trying my best to learn. My new post function works and clicking blog/posts to go to the overview page for the blog or to look at all the posts works as well. NoReverseMatch at /edit_post/1/ Reverse for 'posts' with arguments '(1,)' not found. 1 pattern(s) tried: ['posts/$'] Error during template rendering In template C:\Users\seng\Desktop\Python projects\c19\nineteen_one\blogs\templates\blogs\base.html, error at line 0 urls.py """Defines url paterns for blogs""" from django.urls import path from . import views app_name = 'blogs' urlpatterns =[ #Home page path('', views.index, name='index'), # Page that shows all posts/ path('posts/', views.posts, name='posts'), #Page for adding a new blogpost path('new_post/', views.new_post, name='new_post'), #Page for editing a post #maybe remove the id? path('edit_post/<int:post_id>/', views.edit_post, name='edit_post'), ] views.py from django.shortcuts import render, redirect from .models import BlogPost from .forms import BlogPostForm # Create your views here. def index(request): """The home page for blogs""" return render(request, 'blogs/index.html') def posts(request): """Show all blogposts""" posts = BlogPost.objects.order_by('date_added') context = {'posts': posts} return render(request, 'blogs/posts.html', context) def new_post(request): """Add a new blogpost""" if request.method != 'POST': #No … -
dockerizing django, docker-compose works but not docker run
I have a django app (url shortener for k8s) here [https://github.com/MrAmbiG/shorty/tree/k8s][1]. The docker-compose version works with the same docker image but the docker run doesn't work (I cannot access from host). Docker and docker-compose up both are from docker.io and both are using the same docker image but why the difference? I apologize for not posting all the contents of the file but rather posting the github url itself. version: '3.7' services: django: image: gajuambi/shorty ports: - 80:8001 env_file: - ../.env Below Doesnt work docker run --name shorty -it --env-file .env gajuambi/shorty -p 8001:8001 -
Why does Okta-React Login redirect to blank page when using Django?
I am using Okta-React for authentication in my React project and when I run the React test server my login authenticates successfully and redirects to the account page. When I run the React build command and render the build files with Django, my login authenticates properly, but when it redirects back to my site I get a blank /implicit/callback page, no login token or user info, and the code & state gets stuck in the URL. Does anyone know why this is only happening when using Django, and what I can do to resolve this issue? Here is my authConfig: const config = { issuer: 'https://dev-#######.okta.com/oauth2/default', redirectUri: window.location.origin + '/implicit/callback', clientId: '#@#@#@#@#@#@#@#@#', pkce: true }; export default config; Here is my accountAuth import React, { useState, useEffect } from 'react'; import { useOktaAuth } from '@okta/okta-react'; import '../scss/sass.scss'; import "../../node_modules/bootstrap/scss/bootstrap.scss"; import 'react-bootstrap'; const AccountAuth = () => { const { authState, authService } = useOktaAuth(); const [userInfo, setUserInfo] = useState(null); useEffect(() => { if (!authState.isAuthenticated) { // When user isn't authenticated, forget any user info setUserInfo(null); } else { authService.getUser().then((info) => { setUserInfo(info); }); } }, [authState, authService]); // Update if authState changes localStorage.setItem("username", userInfo && userInfo.given_name) const login = … -
datetime.now() vs Django runserver
I have a simple function: from datetime import datetime def GetEmployeeLeaveV2(user, thisYear=datetime.now().strftime("%Y")) print ("GetEmployeeLeaveV2 thisYear: ",thisYear) print ("GetEmployeeLeaveV2 datetime.now(): ",datetime.now().strftime("%Y")) (.....) By default, when I call this function and I dont pass in a variable for thisYear, it takes the current year at the time its called. For the most part this works fine, especially in my local machine. Both print statements generate the expected same value by default. This same code was then uploaded to a cloud server, where it has been working fine. However, recently, the output for both the print statements began to differ. Here I reran the code on my local machine I changed my machine date to '2019', executed runserver and the print statements are generating the expected data. I then changed the date to '2020' without cancelling runserver to simulate the year changing in the cloud server and my output now do not match. What is happening here and how do I solve it? I would presume restarting of the cloud server would fix this, but the core issue I want to know is how to solve this without doing so, so that I dont have to restart it every year. Python 3.7 Django …