Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Command 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' returned non-zero exit status 1
Here I am trying to communicate between 2 docker containers, namely djangoapp and gridd-alpha. Here the command 'docker cp product.yaml gridd-alpha:/' is executing fine from inside django app in djangoapp container, but the next command 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' is throwing a error - Command 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' returned non-zero exit status 1. ## views.py ## import subprocess cmdCpToContainer = 'docker cp product.yaml gridd-alpha:/' cmdCreateProduct = 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' resultCoppied = subprocess.run(cmdCpToContainer, shell=True, capture_output=True, universal_newlines=True, check=True) print('resultCoppied: ' + str(resultCoppied.stdout)) resultCreatedProduct = subprocess.run(cmdCreateProduct, shell=True,capture_output=True , universal_newlines=True, check=True) print('resultCreatedProduct: ' + str(resultCreatedProduct.stdout)) Here I am communicating through /var/run/docker.sock version: "3.9" services: app: container_name: djangoapp build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - /var/run/docker.sock:/var/run/docker.sock networks: default: name: mongodb_network I have also tried using --user, but it throws the same error. docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml Output ## OUTPUT ## Exception Type: CalledProcessError Exception Value: Command 'docker exec -it gridd-alpha grid product create --owner myorg --file product.yaml' returned non-zero exit status 1. Can anyone help me resolve this, and thanks … -
How to save the implementation in javascript in Django
I am a student who is learning Janggo. I am implementing a page that represents the information of the selected option when I select the option. The source code can be written as follows to adjust the quantity, and the price has been implemented to change depending on the quantity. I want to save the quantity and price parts in db, but I have no idea what to do. How can we solve this? html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"></div> </div> script <script> $().ready(function() { $("#optionSelect").change(function() { var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var price = parseInt($("#price").text()); var test = … -
How to subtract date (in numbers) in python? [duplicate]
I have a weird need. Lets say, I have start_date = 2021-08-31 00:30:00 date = "120 days" How to subsctract start_date with the days with 120 days ? Is it even possible ? And by the way am asking this to use in "django" -
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?