Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
add another objects on click django
I have an object with name, surname and email and I have a button that when clicked should create another empty object for me to fill in and then with another button create the two objects in the database. How can I create the event that generates a new object for me? -
Displaying data in a leaderboard - Django
I have the following model: class UserDetail(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) requests = models.IntegerField(blank=True, null=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) I want to get the top 5 users with the most points and display them in an HTML leaderboard template. Please help -
How to check the type of uploaded file?
I only want .xlsm files to be uploadable to the form. This my field in models.py ... pdf = models.FileField( upload_to=customer_directory_path, null=True, blank=True) ... How can I do that? -
Can't access django server remotely
I cannot access localhost / 0.0.0.0:8000 from any other device. The current django project is built off of an older project I was playing around with last year where this worked. Unfortunately i've lost the previous project so I cannot compare their settings.py files, although there should be hardly any difference between them. . The setup Dropbox - holds project and sqlite database file Laptop - running server, had no changes over last year Desktop - / iPhone - / . Where the problem is The fault must be on my laptop where the server is running because I cannot access the server on either my desktop nor my iPhone, the latter worked last year with the previous project, I did not have my desktop at the time. . The project's allowed hosts list I've added several as i've been trying out different solutions recommended by others. ALLOWED_HOSTS = [ '*', '0.0.0.0.', '0.0.0.0:8000', 'localhost' 'localhost:8000' '{laptop's IP address}', '{desktop's IPv4 address}', '{desktop's Default gateway}', ] . When I try to access the localhost on desktop or iPhone Nothing appears in the laptop's terminal, the quit server help line remains the last line. I remember last year, it would update with … -
Could not import view_production.views. Error was: No module named reportlab.graphics.shapes
First of all, I am not a django expert or even a web dev, I dont have any documentation for this app, and the guy that have made it, last time I saw it, was 4 years ago. I am migrating one web app that contains django 0.97 with python 2.7 and wgsi 4.5.15, from a shared host to a new shared host. On my new shared host, Apache is working, and while testing that webservice, I notice that for a login form, I was obtaining this error: ViewDoesNotExist at /login/ajax/ Could not import view_production.views. Error was: No module named reportlab.graphics.shapes Traceback (most recent call last): File "/home/user1/apps/django/RMA/django/core/handlers/base.py" in get_response 68. callback, callback_args, callback_kwargs = resolver.resolve(request.path) File "/home/user1/apps/django/RMA/django/core/urlresolvers.py" in resolve 163. sub_match = pattern.resolve(new_path) File "/home/user1/apps/django/RMA/django/core/urlresolvers.py" in resolve 163. sub_match = pattern.resolve(new_path) File "/home/user1/apps/django/RMA/django/core/urlresolvers.py" in resolve 119. return self.callback, args, kwargs File "/home/user1/apps/django/RMA/django/core/urlresolvers.py" in _get_callback 128. raise ViewDoesNotExist, "Could not import %s. Error was: %s" % (mod_name, str(e)) ViewDoesNotExist at /login/ajax/ Could not import view_production.views. Error was: No module named reportlab.graphics.shapes I've already installed all python 2.7 dependencies that it were in previous host, but no changes. On /home/user1/apps/django/RMA/view_production/urls.py I have this: from django.conf.urls.defaults import * from django.views.generic import list_detail, … -
Should I change DEBUG to False using git or directly on the server?
I am developing my Django project using git and GitHub and pulling the updates from Digital Ocean. I know that DEBUG should be set to False in production, but what is the workflow? Should I change DEBUG to False locally and then commit, push and pull from the remote, or change it directly on the server? -
how to submit data from modal to database in django?
I want to send data from bootstrap Modal to database . Data should be stored in multiple Model in database. -
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") …