Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django display user's todolist using login via google
I am trying to display all user's todolist via google login method I'm using auth_user table and created a todolist table query below. CREATE TABLE todoitem( id SERIAL PRIMARY KEY, content char(100) NOT NULL, userid int NOT NULL, constraint fk_userid foreign key (userid) references auth_user(id) ); add sample data using pgadmin insert into todoitem(content,userid) values('each users must have their own todolist',2); select b.first_name,b.last_name,a.content AS Todo from todoitem a INNER JOIN auth_user b ON a.userid = b.id where a.userid = 2; first_name | lastname | Todo testfirstname | testlastname | each users must have their own todolist here's my model.py class Todoitem(models.Model): # I created this id because after i use inspectdb there's no id here id = models.IntegerField(primary_key=True) content = models.CharField(max_length=100) userid = models.ForeignKey(AuthUser, models.DO_NOTHING, db_column='userid') class Meta: managed = False db_table = 'todoitem' class AuthUser(models.Model): # I also created this id id = models.IntegerField(primary_key=True) password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.BooleanField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.CharField(max_length=254) is_staff = models.BooleanField() is_active = models.BooleanField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' here's my views.py def todoView(request, id=None): # I assume that id == id from auth_user? … -
How to migrate Ferris Framework with Webapp2 to Django
one of my application is running in python2 Ferris framework with webapp2 in Gcloud , Now I decided to migrate the application into python 3. please anyone can help what we follow to migrate the application. -
django how to expire session after few seconds
I am using django session in my views for show message but the problem is I can't set session expire time. I tried this request.session.set_expiry(1) but didn't work. here is my code: request.session["error_message"] = "your comment didn't submitted. Please try again" request.session.set_expiry(1) -
Django - passing list as an onlick parameter | it works but there are errors
I pass the 'country_names' from my views.py return render(request, 'update.html', { 'country_names': all_countries_names,}) and trying to use it as a parameter with <button onclick="updateCountries({{ country_names }})">Update</button> it does work as I expected however there are two errors saying that '{' : Property assignment expected.javascript and '}' : ',' expected.javascript although it's working, the errors are somewhat annoying... I've been trying to look for the solution for an hour but couldn't find what matches my case. -
How to do that if there is no answer for more N seconds then return None (because it will be infinite if no message is sent )
`async def async_function(): ws_conn = None ws_url = 'websocket:4000' print(ws_url) try: timeout = 5 try: ws_conn = await asyncio.wait_for(websockets.connect(ws_url), 1) except asyncio.exceptions.TimeoutError as e: print('Error connecting.{}'.format(e)) response = await ws_conn.recv() await ws_conn.close() return response except: await ws_conn.close() return None` -
How does this code link two classes to each other?
this is the code from a django website from django.db import models from django.db.models.deletion import CASCADE class ToDoList(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() def __str__(self): return self.text I was just wondering what exactly does todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE) do? It obviously creates a variable called todolist which is simply a model of a foreignkey (as it's not an object defined within Django), but why is there the class "ToDoList" in it? does it take this as an argument or something? I don't quite understand how this links the item class (or the object of that class) to the ToDoList class/object? I hope this is not too confusing -
How to use third party api which has Basic Auth(username, password) in django?
I have one third party API (an URL). To access that URL I have to give basic auth which is Username and password. how to get data from that API using basic Auth in django? -
Django-Celery function not working properly
The test always return abc.is_online True. But abc.is_online should be False because celery task makes is_online False after 60 second from now. Error Meassge: assert True == False where True = <ABC: Charles Reyes>.is_online @app.task(name="task.xyz_last_active") #Celery task def abc_last_active(): now = timezone.localtime() for xyz in ABC.objects.all(): if not xyz.last_active: continue elapsed = now - xyz.last_active if elapsed.total_seconds() >= settings.ABC_TIMEOUT: #60 Sec xyz.is_online = False xyz.save() @pytest.fixture def create_abc(): abc = ABC.objects.create( phone="123234432", location=Point(1, 4), last_active=timezone.localtime() - timezone.timedelta(seconds=162), is_online=True, ) return abc @pytest.mark.django_db def test_inactive_abc_gets_deactivated(create_abc): print(create_abc.is_online, "before deactivation") abc_last_active() print(create_abc.is_online, "after deactivation") assert create_abc.is_online == False -
How i convert django jinja template code into jquery ajax
I am using django rest framework. I want to change django jinja template code to jquery ajax.I am new to jquery. I want to make following conditions with jquery ajax with image, video and audio src. Please help me. Here is my code: {% if ".jpg" in blogs.image.url or ".jpeg" in blogs.image.url %} <img class="img-circle" src="{{blogs.image.url}}" height="200" width="200"> <style> .img-circle { border-radius: 50%; } </style> {% endif %} {% if '.mp4' in blogs.image.url or '.mkv' in blogs.image.url %} <video width='400' controls> <source src="{{blogs.image.url}}" type='video/mp4'> Your browser does not support the video tag. </video> {% endif %} {% if '.mp3' in blogs.image.url %} <audio controls width="320" height="240"> <source src="{{blogs.image.url}}" type="audio/ogg"> </audio> {% endif %} -
What is the purpose of __exact in Django querysets API?
What is the purpose of using __exact in the Django querysets API? For example: >>> Library.objects.filter(id = 15942) <QuerySet [<Library: bee>]> >>> Library.objects.filter(id__exact = 15942) <QuerySet [<Library: bee>]> And: >>> Library.objects.filter(title = 'bee') <QuerySet [<Library: bee>]> >>> Library.objects.filter(title__exact = 'bee') <QuerySet [<Library: bee>]> Noting that it's apparently not about case sensitivity: >>> Library.objects.filter(title = 'Bee') <QuerySet []> >>> Library.objects.filter(title__exact = 'Bee') <QuerySet []> -
django set a cusotme page number in paginate_queryset
I want to write a code that find the user page number and return that page: this is the code that find the page_number: class UserScoreBoard(GenericViewSet, mixins.ListModelMixin): permission_classes = (IsAuthenticated,) queryset = User.objects.all().order_by('-xp_balance') serializer_class = UserSerializerReadOnly @action(url_path='user-page', methods=['get'], detail=False, url_name='user-page') def get_user_page(self, request): page_size = int(request.query_params.get('page_size')) if request.query_params.get('page_size') else \ self.pagination_class.page_size user_page = User.objects.filter(xp_balance__lt=request.user.xp_balance).count() // page_size + 1 queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) serializer = self.get_serializer(page, many=True) return serializer which the user_page is the page that contains the user. how can i set the user_page in this code? -
Where to find the imageField label text "Currently, ... ect"
here i have a form i did find were to control label and input field of the imagefield but label only controls the Avatar text not the "currently ....ect", is there a way to access it i want to add a class to style it and cant find its object in python ? this my attempt and it is not working only gives me the "avatar" ext only class ProfileUpdateModelForm(ModelForm): class Meta: model = Profile fields = ('first_name', 'last_name', 'bio', 'avatar') def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['avatar'].label = False #hides "avatar" text and the rest of text still there -
How to Load a .dump File Format Using manage.py loaddata in Django?
I have a data.dump file for mysql and am trying to use manage.py loaddatato fill my db with this data file, but getting this error: CommandError: Problem installing fixture '˜/Downloads/data': dump is not a known serialization format. Apparently this is not a known format for Django loaddata. The question is how I can convert a .dump to .json, so I can use it with loaddata command? -
Django does not pass new data to my functions in testing
Intro: I am following this tutorial django channles. Problem: The new data does not pass to the consumer or any functions unlike the regular testing with Django testcase or with RestApi testcase. class ChatTests(ChannelsLiveServerTestCase): serve_static = True # emulate StaticLiveServerTestCase def setUp(self): from Functions.TestClass import make_test_data from Functions.calendar_setup import calendar_setup calendar_setup(self) make_test_data(self) @classmethod def setUpClass(cls): super().setUpClass() try: # NOTE: Requires "chromedriver" binary to be installed in $PATH cls.driver = webdriver.Chrome('/Users/apple/Desktop/vytrac/vytrac-24106/backend/chromedriver') except: super().tearDownClass() raise @classmethod def tearDownClass(cls): cls.driver.quit() super().tearDownClass() def test_when_chat_message_posted_then_seen_by_everyone_in_same_room(self): Chat.objects.create(name='my_new_room') print(Chat.objects.count()) #return 1 ✅ class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): x = await sync_to_async(Chat.objects.count)() print(x) # return 0 🔴 -
Could not parse the remainder: '(5+6)' from '(5+6)'
I was playing with jinja template and suddenly found some error with the DateTime field compare. Then try with simple numeric compare like this: {% if (5+6) > 1 %} <p> This will display if the condition is true </p> {% endif %} But it says error like (for this if condition): TemplateSyntaxError at /examevent/ Could not parse the remainder: '(5+6)' from '(5+6)' Why does it happen and how can it be fixed? -
Django rest framework create object with many-to-many filed serializer
i can't create project object with many-to-many field to languages model, i need the best way to implement this, i have tried the django rest framework docs but it didn't work for me, is the language objects need to be created before the project object or DRF will handle this ?, this problem apper when i add the owner field then i needed to add the create method inside the ProjectSerializer to save the object owner but then this error Direct assignment to the forward side of a many-to-many set is prohibited. Use languages.set() instead. then i tried languages.set() steal not work models.py from django.db import models from django.contrib.auth.models import User class Language(models.Model): name = models.CharField(max_length=100, blank=True, default='') description = models.TextField() owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['id'] def __str__(self): return self.name class Developer(models.Model): name = models.CharField(max_length=100, blank=True, default='') age = models.IntegerField() bio = models.TextField() created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['created'] def __str__(self): return self.name class Project(models.Model): name = models.CharField(max_length=100, blank=True, default='') stars = models.IntegerField() developer = models.ForeignKey(Developer, related_name='projects', on_delete=models.CASCADE) languages = models.ManyToManyField(Language) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['stars'] def __str__(self): return self.name serializers.py from rest_framework import serializers from … -
Alternative to list_display for Django Admin?
I am working on a project when I need the list to automatically filter when a person views the list. In the model I have a field known as "active". If the country is an active country it should display in the list. The issue with list_filter is that it requires the user to sort by a certain field. I need this filter to happen as the page loads. (i.e an Automatic Filter) but also it should link to a page I have already created (not the default Django Admin List page). I'd be grateful if anyone could help :) -
django: send two ajax requests from the same initial form
I have a form generated in a templates that is triggering an ajax request to make calculations from the input data. Everything works fine. Here is what my setup look like: index.html <form method="POST"> {% csrf_token %} <label><h3>Input variables to calculate EOQ:</h3></label> <br> <br> <span style="color:black">Annual demand <input type="text" id="annual_demand"> <br> <br> <span style="color:black">Order cost <input type="text" id="order_cost"> <br> <br> <span style="color:black">Unit cost <input type="text" id="unit_cost"> <br> <br> <span style="color:black">Holding cost <input type="text" id="holding_cost"> <br> <br> <input id="ajax-call" type="submit" value="Calculate EOQ"> </form> <span style="color:black">Optimal EOQ<fieldset type="text" id="ajax"></fieldset></span> and my views.py look like the following: def index(request): return render(request, "index.html") @csrf_exempt def compute(request): annual_demand = request.POST.get("annual_demand") order_cost = request.POST.get("order_cost") unit_cost = request.POST.get("unit_cost") holding_cost = request.POST.get("holding_cost") result = m.sqrt((2*float(annual_demand)*float(order_cost))/(float(unit_cost)*float(holding_cost))) return JsonResponse({"operation_result": result }) Now I am trying to add a second calculation from the form input data, and I cannot successfully achieve that. I have tried including the calc inside of the "compute" view but it does not work, I have also tried generating a new view, so a second ajax call for the second calculation which was unsucessful either. Here is what I got: Added a new view for the second call: @csrf_exempt def compute2(request): annual_demand = request.POST.get("annual_demand") order_cost = request.POST.get("order_cost") … -
Couldn't use for loop in Django html
When the runserver and see it . It show {%block body%}{%endblock%}I was trying to show information from database using django and return html -
how to use webcam streaming from a django app?
I am trying to test webcam streaming in a simple Django app with just a views.py and a html. It shows just simple html text on screen without opening the webcam. What am I missing here? This is my views.py from django.shortcuts import render from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def livef(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed- replace;boundary=frame") except: # This is bad! replace it with proper handling pass def index(request): return render(request, 'home.html') and this is my home.html - <html> <head> <title>Video Live Stream</title> </head> <body> <h1>Video Live Stream</h1> <img src="{% url 'livef' %}"> </body> </html> -
Django Test.py django.db.utils.IntegrityError: UNIQUE constraint failed: books_book.id
when I run python manage.py tests I get this error as django.db.utils.IntegrityError: UNIQUE constraint failed: books_book.id it causes most of the other tests to fail Here are the full tests.py file: class BookViewTests(TestCase): self.user=get_user_model().objects.create_user( username='test', email='test@gmail.com', city='city', state='state', password='secret', is_active =True, id_2 ='96540845', pincode ='121006', education= 'NIT Kurukshetra', work = 'Wipro' ) self.user2=get_user_model().objects.create_user( username='test2', email='test2@gmail.com', city='city', state='state', password='secret', is_active=True, id_2 ='97173660', pincode ='272896', education = 'NIT Banglore', work = 'TCS' ) self.book =Book.objects.create( title='Shoe Dog', author='Phil Knight', genre ='Non-Fiction', owner =self.user, id ='88001198', is_approved=True available=True ) self.book2 =Book.objects.create( title='The Shining', author='Stephen King', genre ='Horror', owner =self.user2, id ='75777553', is_approved=True, available=True ) self.book4 =Book.objects.create( title='How to Win Friends and Influence People', author='Dale Carnegie', genre ='Self-help', owner =self.user2, id ='75777559', is_approved=False, available=False ) #book detail view def test_book_detail_view(self): self.client.login(username='test',password='secret') resp =self.client.get(reverse('book_detail',kwargs={'book_id':75777553})) self.assertEqual(resp.status_code,200) self.assertTemplateUsed(resp,'book_detail.html') resp1 =self.client.get(reverse('book_detail',kwargs={'book_id':88001198})) self.assertEqual(resp1.status_code,302) self.assertEqual(resp1.url,'/books/mybooks/') resp2 =self.client.get(reverse('book_detail',kwargs={'book_id':75777559})) self.assertEqual(resp2.status_code,404) My model: class Book(models.Model): id=models.SlugField(max_length=8,primary_key=True) genre_choices=[(i,i) for i in ['Biography','Business','Children','Classic','Comedy','Fantasy','History','Horror','Mystery','Mythology','Poetry','Religion','Romance','SciFi','Self-Help','Spirituality','Thriller','Non-Fiction','Fiction','Others']] title =models.CharField(max_length =255) author =models.CharField(max_length =255,validators=[alphabet_validate]) genre =models.CharField(max_length=100,choices=genre_choices) date=models.DateTimeField(auto_now_add =True) available =models.BooleanField(default =True) owner =models.ForeignKey(settings.AUTH_USER_MODEL,related_name ='book_owner',db_index=True,on_delete =models.CASCADE,) shared_with =models.ForeignKey(settings.AUTH_USER_MODEL,related_name='shared_with',on_delete=models.CASCADE,null=True,blank=True) slug = models.SlugField(verbose_name='Slug', null=True,blank=True,max_length = 200) How to solve this issue? Thanks in Advance. -
Comparing Datetime in Jinja
I am working with Django. I have following variable in my template: startingTime it's value come from database (DateTimeField) currentTime actually a variable that contain the value of datetime.datetime.now() durationInMinits actually a integer field, contain int value (in minutes) Now I need to determine if the difference between currentTime and startingTime is greater than durationInMinits or not. I have tried in my template.py like this: {% if startingTime < currentTime < startingTime + durationInMinits %} <p> This will display if current time is greter than startingtime, but duration is not over </p> {% endif %} But it gives error. Please suggest how can I compare time in jinja? -
Django: view content in with a certain id
enter image description hereenter image description herehow can I make sure that with a certain category I only get the films of that category? (I attach photos of the models and views) thanks in advance Sorry for the Englishenter image description here -
Django multi tenant shared schema implementation
I am starting a new project that requires a multitenant saas application. I have looked all around the internet and it seems that most of the articles around djnago multi tenant are focused on "same db different schema" approach. I am looking for a good examples and best practices for creating an application with the "same db same schema" approach. Topics: User model extension Authentication adjustments Cross tenat data queries protection Will appreciate any direction or assistance in that matter Thanks! -
What type of database is good for heavy django project
What type of database is good for Heavy Django project like Project Management System?