Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
drf-yasg custom json body
How to customize drf-yasg schema in ClassBased django views? I tried this part of code, but the generated swagger doesn't respect the change. class CustomView(CreateAPIView): permission_classes = (IsAuthenticated,) serializer_class = CustomSerializer @swagger_auto_schema(request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'phone': openapi.Schema(type=openapi.TYPE_STRING, description='string'), 'body': openapi.Schema(type=openapi.TYPE_STRING, description='string'), })) def create(self, request: Request, *args, **kwargs): phone = request.data.get('phone') body = request.data.get('body') ... -
Task Scheduler Python Django Windows
Can someone give me an advice of what tools I need to use if I want to insert all the new data which is inserted in one system into another system, and this system should be automatically updated(and visualize in the web system) when someone insert a new record in the first system. I read a lot about Cron jobs, Celery and Task Scheduler. I'm using Windows, so what is the best way to make it? I saw that Celery doesn't have full support on Windows 10. Please, correct me if I'm wrong. Can someone tell me the steps, because I'm really confused about this work in 'background'. I'm using Python with Django, but still research for the db, but maybe PostgreSQL or MySQL. Thanks all! -
Django Rest Framework: How to pass value using url and perform calculation
I am new to Django and created simple api which displays message using GET method views.py: @api_view(["GET"]) def message(request): if request.method == 'GET': return Response({"Print": "GET request from browser works"}, status=status. HTTP_200_OK) urls.py: urlpatterns = [ path('',views.index,name='Home'), path('message',views.message,name='message'), ] Output: Now I want to take 2 inputs from user through url and perform addition on that inputs and return its result using GET and POST methods. Example: http://127.0.0.1:8000/message/?a=2&b=3 (something like this) and it should return addition results. Most of tutorials online are on fetching data from database but I want to create api which takes input from user and return its output. Can anyone show me how to achieve above task? -
How to position table in list format
I am new in Django and in stackoverflow and need your help. I have a list year=[2020,2019,2018,2017,2016] grade=[20,90,40,30,69] category=[fail,distinction,satisfactory,fail,good] I want to have the following format: 2020 20 fail 2019 90 distinction 2018 40 satisfactory 2017 30 fail 2016 69 good The format i use is <table> </table> botstrap Would be thankful for your help. I am new in html. -
Django 3 Python 3.8 whitenoise not serving request.user
I get the error 'WSGIRequest' object has no attribute 'user' When writing: x.user = request.user x.save() In Django, I updated whitenoise to the latest version and I'm pretty sure that a post request would have the user attached. How do I return the request.user from the post request in Django? -
Using a subquery in Django and annotate the results with the average value - remove GROUP BY
I'm using Django 3 and am trying to get a subquery going to retrieve the average value from a different table. Here is my setup: class People(models.Model): name = models.CharField(max_length=255) class Rating(models.Model): people = models.ForeignKey(People, on_delete=models.CASCADE) rating = models.PositiveSmallIntegerField() # rating from 1-10 rated_by = models.ForeignKey(User, on_delete=models.CASCADE) So you can get multiple users to give a rating to individual people. What I would like to get is therefore the average rating for each record in the People table. Something like: people_id | people_name | avg_rating ------------------------------------- 1 | maria | 7.2 2 | john | 5.3 3 | marta | 7.3 4 | felipe | 4.1 In SQL, this would be something like: SELECT people.*, (SELECT avg(rating) FROM rating WHERE people_id=people.id) AS avg_rating FROM people This is how I tried in Django: rating = Rating.objects.filter(people=OuterRef("people")).values("rating") avg_ratings = ratings.annotate(avg_rating=Avg("rating")).values("avg_rating") people = People.objects.all().annotate(average_rating=Subquery(avg_ratings)) But it returns this error: more than one row returned by a subquery used as an expression When I analyze the SQL code, this is what it generates: SELECT people.*, (SELECT avg(rating) FROM rating WHERE people_id=people.id GROUP BY rating) AS avg_rating FROM people So basically the GROUP BY rating part is what needs to be removed... without that, this … -
How to share local Postgres database with docker?
I have a django project with PostgreS database. I need to use my local database in docker container. How to share localhost of the machine with docker container? My docker-compose.yml : version: '3' services: web: build: ./ network_mode: "host" command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput --i rest_framework && gunicorn orion-amr.wsgi:application --bind 0.0.0.0:8000 --workers=2" ports: - "${webport}:8000" - "${pgport}:${pgport}" env_file: - ./.env Django settings.py: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': os.environ.get('pgdatabase'), 'USER': os.environ.get('pguser'), 'PASSWORD': os.environ.get('pgpassword'), 'HOST': os.environ.get('pghostname'), 'PORT': os.environ.get('pgport'), } } I added listen_addresses = '*' to postgresql.conf file and below is my pg_hba.conf file: # TYPE DATABASE USER ADDRESS METHOD # IPv4 local connections: host all all 0.0.0.0/0 trust # IPv6 local connections: host all all ::/0 trust # Allow replication connections from localhost, by a user with the # replication privilege. host replication all 127.0.0.1/32 trust host replication all ::1/128 trust Now I have an error: web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "127.0.0.1" and accepting web_1 | TCP/IP connections on port 5432? web_1 | Who can help me? Please! -
Django Inventory update function
I'm new Django and I'm working on a small project, I have two models Item and Stock. For Item model, I have a form where a user can select a product and choose its quantity he/she wants to purchase. If the customer selects product 1 and quantity 30, I want the function to subtract 30 from product1 in Stock model. How can this be implemented in views.py , I believe my views.py is incorrect. this is models.py class Item(models.Model): product_choices = (('product1', 'product1'),('product2','product2'),) product = models.CharField(max_length = 100, choices = product_choices) quantity_choices = (('30','30'),('60,'60'),) quantity = models.CharField(max_length = 100, choices = quantity_choices) class Stock(models.Model): product1 = models.IntegerField(default='0', blank=True, null=True) product2 = models.IntegerField(default='0', blank=True, null=True) views.py def checkout(request): item = Item.objects.all() stock = Stock.objects.all() form = ItemForm(request.POST or None) if request.method == 'POST': if item.product == 'product1' and item.quantity =='30': stock.product1 = stock.product1 - 30 elif: if item.product == 'product1' and item.quantity =='60': stock.product1 = stock.product1 - 60 else: return None -
Load iframe html tag in django template to show maps
I have a django application where I am showing details of hospitals located in different location. I am able to render all the details but unable to render the source of iframe location to the template. Below is my field to get source of iframe location. models.py class mydetails(models.Model): Name=models.CharField(max_length=100,blank=True) City=models.CharField(max_length=100,blank=True) Location=models.TextField(max_length=5000,blank=True) #getting source of iframe And I am rendering the the value of location as below in my html. detail.html <iframe class="g-maps" src="{{ mydetails.Location}}" frameborder="0" style="border:0;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe> I tried taking the Location value as URLField as well in my models but was of no help. When I inspected my template, found that my source details were empty even after loading the tag. -
How to create scheduledtasks without credentials from python?
Users of my app can click on a link which call a function that create a .bat file (does it fine) and scheduledtask that will call that .bat file. My problem is in invoked RegisterTaskDefinition function. No matter kind of login strategy I choose, I'm getting an exception in any case.But I need create tasks without credentials, so how can I achieve it? -
I am getting this error while trying to test the django code using selenium
Here is tests.py: from django.test import TestCase from selenium import webdriver from .forms import HashForm import hashlib from .models import Hash class FunctionalTestCase(TestCase): def setUp(self): self.browser = webdriver.Firefox() def test_there_is_homepage(self): self.browser.get('http://localhost:8000') self.assertIn('Enter hash here:', self.browser.page_source) def test_hash_of_hello(self): self.browser.get('http://localhost:8000') text = self.browser.find_element_by_id("id_text") text.send_keys("hello") self.browser.find_element_by_name("submit").click() self.assertIn( '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824', self.browser.page_source) def tearDown(self): self.browser.quit() class UnitTestCase(TestCase): def test_home_homepage_tempalte(self): response = self.client.get('/') self.assertTemplateUsed(response, 'hashing/home.html') def test_hash_form(self): form = HashForm(data={'text': 'hello'}) self.assertTrue(form.is_valid()) def test_hash_func_works(self): text_hash = hashlib.sha256('hello'.encode('utf-8')).hexdigest() self.assertEqual( '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824', text_hash) def saveHash(self): hash = Hash() hash.text = 'hello' hash.hash = '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824' hash.save() return hash def test_hash_object(self): hash = self.saveHash() pulled_hash = Hash.objects.get( hash='2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824') self.assertEqual(hash.text, pulled_hash.text) def test_viewing_hash(self): hash = self.saveHash() response = self.client.get( '/has/2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824') self.assertContains(response, 'hello') -
Filter by category dropdown
I am using a dropdown to filter a table by year how can i do filtering without refreshing the whole page. enter image description here enter image description here enter image description here category dropdown -
Is it a good idea to nest custom serializer classes in django?
So I have this code and it is working: class X(serializers.Serializer): class Y(serializers.Serializer): class Z(serializers.Serializer): id = serializers.IntegerField() description = serializers.CharField() stdout = serializers.CharField(allow_null=True, allow_blank=True) time = serializers.FloatField() memory = serializers.FloatField() stderr = serializers.CharField(allow_null=True, allow_blank=True) token = serializers.CharField() compile_output = serializers.CharField(allow_null=True, allow_blank=True) message = serializers.CharField(allow_null=True, allow_blank=True) status = Z() submissions = Y(many=True) But is this a good idea to nest serializer classes? The nested classes(Y and Z) are only used within X class. -
How can i add different timers as a column in bootstrap datatables rows according to date given?
So, i am trying to add a countdown timer on a table that gets the value of the due date and adds a cell showing the remaining time.Currently it works with one record but on adding two or more rows, i get a replica of the last row timer duplicating on all the records' timer cells <div class="card mb-3"> <div class="card-header"> <i class="fa fa-table"></i> <sup><span class="badge badge-warning"> {{ new}} New</span></sup>New Orders From Clients </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <td>Reference Code</td> <td>Title</td> <td>Number of Pages</td> <td>Take this Task</td> <td>Due Date</td> <td>Remaining Time</td> </thead> {% for t in order %} <tbody> <tr> <td> <a href="{% url 'view_order' pk=t.pk %}">{{ t.urlhash }}</a> </td> <td>{{ t.title }}</td> <td>{{ t.Number_of_pages }}</td> <td> {% if t.status == False %} <a href="{% url 'claim' pk=t.pk %}" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm">Take order</a>{% else %} <span>&#10004; Taken</span> {% endif %} </td> <td>{{ t.due_date }} </td> <td id="time" class="text-warning"></td> </tr> <script> // Set the date we're counting down to var countDownDate = new Date("{{ t.due_date.isoformat }}").getTime(); // console.log(dex); //var countDownDate = new Date("July 18, 2020 19:27:25").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get … -
Django-Filter: multiple select2 choices on a foreign-key field
I'm having a multiple select 2 like this: Multilple Select 2 The filter needs to return all the Route Template that matches the mentioned select 2 SOLUTION: Model: from django.db import models class Route(models.Model): route_template = models.ForeignKey(RouteTemplate, blank=True, null=True, on_delete=models.CASCADE) Filter: import django_filters class RouteFilter(django_filters.FilterSet): route_template = django_filters.AllValuesMultipleFilter(field_name='route_template__name') I've struggled a lot with MutlipleChoice, overriding method, etc. and the solution is AllValuesMultipleFilter -
Best resource for understanding Rest framework in Python Django [closed]
I'm a beginner to Django and REST frameworks it is a bit complicated with the resources provided with the official DJANGO REST framework Documentation available out there. https://www.django-rest-framework.org/ I keep confusing myself on choosing which is the better resource to start with.. Can you please suggest any other best resources for better understanding REST frameworks & Django(youtube videos, courses or documents.. any suggestion would be much helpful) also Should I go on with any other base understandings before I pursue in this?? Although, I know Python and few basics in Django. Thanks in advance guys!! -
Setup postgres in Github Actions for Django
I'm currently working on a website right now on Django. On my computer, I am running it on Docker with a postgres database. Here's the docker-compose file I have: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . volumes: - .:/usr/src/app ports: - "8000:8000" And here's the relevant part in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } When I run my tests in the docker container with this setup, it works find and the tests run. However, in github actions, it doesn't work. Here's my workflow file: name: Django CI on: push jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.7, 3.8] services: db: image: postgres env: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres ports: - 5432:5432 steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} - name: Install Dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Tests run: | python manage.py test When this runs in github actions, I get the following error: django.db.utils.OperationalError: could not translate host name "db" to … -
Django Authenticate Backends with Email
I want to login with email not username like this, please help class loginUser(View): def get(self, request): lF = loginForm return render(request, 'UserMember/login.html', {'lF': lF}) def post(self, request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return render(request, 'UserMember/private.html') else: return HttpResponse('login fail') -
Using aggregate sum on Django doesn't update the dict unless server refreshes/restarts
aggregate sum works, but it does not update until the server refreshes. If I add a new instance to the Reservation class total_guests is not called and the HTML does not show the updated guest_num sum count. Is there a way for it to update every time a new instance is created or updated? views.py: queryset = Reservation.objects.filter(reserve_date=datetime.datetime.now(), shift='lunch') total_guests = queryset.aggregate(Sum("guest_num")) print(total_guests) # Override context to add total_guest as context def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['total'] = self.total_guests return context html: <p> total guests: {{ total.guest_num__sum }} </p> -
Git post-recieve hook to run virtualenv, Django & various python scripts
I've been successfully using Git post-receive hook for a while to push files from local to server using the following in my post-receive file: #!/bin/sh git --work-tree=/home/myuser/myproject/app --git-dir=/home/myuser/myproject/myproject.git checkout -f Now I want to also start virtual env, run Django manage.py and various python scripts after files are pushed to server using post-receive. Based on this other question I have added following to my original post-receive file: #!/bin/sh git --work-tree=/home/myuser/myproject/app --git-dir=/home/myuser/myproject/myproject.git checkout -f source /home/myuser/venv/bin/activate #python /home/myuser/myproject/manage.py makemigrations #python /home/myuser/myproject/manage.py migrate python /home/myuser/myproject/app/python_script1.py python /home/myuser/myproject/app/python_script1.py sudo systemctl restart gunicorn But it appears that the virtual env is not being started giving me error: remote: hooks/post-receive: 4: hooks/post-receive: source: not found Also, the remaining errors appear related to virtual env not starting. manage.py doesn't execute with following error: SyntaxError: invalid syntax remote: File "/home/tendies/tendies/manage.py", line 16 remote: ) from exc The python scripts appear to run but because virtual env is not starting they are not finding modules. Does anything look obviously wrong or missing with my code for this? -
Can I use Textarea as form for modelformset in Django?
So I'm have this form, which is forms.Textarea. And I wanted this to be in formset style, so managed to do so. However what I get in the page for the input area is the little box which seems like forms.CharField. Let me show you the code. models.py class Answer(models.Model): ... answer = models.CharField(max_length=500, default="none") forms.py class AnswerForm(forms.ModelForm): answer = forms.Textarea(attrs={ 'rows' : 4, 'class' : 'answers', }) class Meta: model=Answer fields=['answer',] views.py def answerInput(request): ... AnswerFormSet = modelformset_factory(Answer, form=AnswerForm, extra=1) formset = AnswerFormSet(queryset=Answer.objects.filter(authuser = request.user, questionNumber=1)) ... And what I get in the page looks like this: I can't figure out what went wrong. Any ideas? Thank you very much in advance. -
How to stop having anonymous user in django
So I have a django project and there is one view(home view) which displays the posts of the followed users and that requires a user to be authenticated, if there is no user loged in, then the code returns a 'AnonimousUser' is not iterable error and I will like my code to redirect the anonymous user to the login page if the person is on the home view. After some investigation I realized that this can be done with a custom middleware but I dont know how to do it so currently that middleware just prints if a user is logged in or if it is anonymous. What can I do to Complete this middleware and get rid of that Anoniomus User error? middleware.py class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): if(request.user.is_authenticated): print(Authenticated") else: print("Anonimous user") views.py def home(request): user = Following.objects.get(user=request.user) followed_users = [i for i in user.followed.all()] followed_users.append(request.user) contents = Post.objects.filter(user__in = followed_users) context = { "contents": contents, } print("nice") return render(request, 'home.html', context) urls.py urlpatterns = [ path('', views.home, name='home'), path('login', views.login, name='login'), path('register', views.register, name='register'), path('logout', views.logout, name='logout'), path('<username>/', views.profile, name='profile'), … -
Stop spinner after Django FileResponse Save
I have a template link of a url that runs a view function that generates a file and returns a FileResponse. Works great, but in cases it can take a while to generate the file so I'd like to start and stop a spinner before and after. I've tried using a click event on the link to run and $.ajax() or $.get() function that sends the url, and in this way I can start the spinner. But the FileResponse doesn't generate a Save window in this case. (code below) Is there a way to generate and save a file in a Django view via JavaScript? The following never opens the file save window. $("#ds_downloads a").click(function(e){ urly='/datasets/{{ds.id}}/augmented/'+$(this).attr('ref') startDownloadSpinner() $.ajax({ type: 'GET', url: urly }).done(function() { spinner_dl.stop(); }) }) -
Is inheritance possible in django when the models have same fields but different help_text
I have 2 models that have the exact same fields. The only difference is that the help text for each is different. Is. there a way I can remove this repetition e.g using inheritance or something? Here are my 2 classes class IgnoreListGsheet(models.Model): key = models.CharField(max_length=255, help_text="The key of the Google Sheet holding the ignore list.") worksheet_name = models.CharField(max_length=255, help_text="The name of the workspace containing the ignore list") column_name = models.CharField(max_length=255, help_text="The column name containing the ignore list.") def __str__(self): return self.key class RespondListGsheet(models.Model): key = models.CharField(max_length=255, help_text="The key of the Google Sheet holding the respond to list.") worksheet_name = models.CharField(max_length=255, help_text="The name of the workspace containing the respond to accounts") column_name = models.CharField(max_length=255, help_text="The column name containing the respond to accounts.") def __str__(self): return self.key -
Simple Django Project Structure
I have built the virtual environment and root directory for my django project, which will be a simple website for a event venue. The site will simply have a few different tabs on the navigation bar which shows the user some of the venue specifics which include pricing, a photo gallery, and the venue's history. My problem is that there is so much conflicting information on the web concerning "The best practice for project structure". Should I create an app for the home page and each of the pages that follow, or just create a core app that houses the majority of the project? If this is the case, is this project a good example? --> https://github.com/justdjango/django-ecommerce Does anyone know of a simple project that I can reference? Again this is a pretty simple project with only a few urls and no forms. I would greatly appreciate anyone who has taken the time to read through this and help me.