Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get what was type in a type="text" after submit, to output what was typed in
index.html get the "text" after "submit" do sth...which is to display an output = what was typed in index.html <form action="" method="GET"> Question: <input type="text" name="search"><br/> <input type="submit" value="Submit" /> </form><br/><br/> Output: {{ questions }} this code get the "search" then render it out as output views.py from django.shortcuts import render from django .http import HttpResponse def home(request): return render(request, 'index.html') def index(request): if request.GET.get('search'): search = request.GET.get('search') questions = search return render(request, 'index.html', {'questions': questions}) urls.py from django.contrib import admin from django.urls import path from . import views from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('', views.home ), url(r'^$', views.index, name='index') ] -
Django rest framework, update object after creation
I have a DRF API that takes in the following model: class Points(models.Model): mission_name = models.CharField(name='MissionName', unique=True, max_length=255, blank=False, help_text="Enter the mission's name" ) # Some irrlevant feid url = models.URLField(help_text='Leave Empty!', default=" ") date_added = models.DateTimeField(default=timezone.now) class Meta: get_latest_by = 'date_added' And it's serializer: from rest_framework.serializers import HyperlinkedModelSerializer from .models import Points class PointsSerializer(HyperlinkedModelSerializer): class Meta: model = Points fields = ( 'id', 'MissionName', 'GDT1Latitude', 'GDT1Longitude', 'UavLatitude', 'UavLongitude', 'UavElevation', 'Area', 'url', 'date_added' ) And the view: class PointsViewSet(ModelViewSet): # Return all order by id, reversed. queryset = Points.objects.all().order_by('-id') serializer_class = PointsSerializer data = queryset[0] serialized_data = PointsSerializer(data, many=False) points = list(serialized_data.data.values()) def retrieve(self, request, *args, **kwargs): print(self.data) mission_name = self.points[1] assign_gdt = GeoPoint(lat=self.points[2], long=self.points[3]) gdt1 = [assign_gdt.get_lat(), assign_gdt.get_long()] assign_uav = GeoPoint(lat=self.points[4], long=self.points[5], elevation=self.points[6]) uav = [assign_uav.get_lat(), assign_uav.get_long(), assign_uav.get_elevation()] area_name = f"'{self.points[-2]}'" main = MainApp.run(gdt1=gdt1, uav=uav, mission_name=mission_name, area=area_name) print('file created') return render(request, main) I want to update the URL field of the file to contain a constant pattern and format in the end the mission_name field. object.url = f'127.0.0.1/twosecondgdt/{mission_name}' How can that be achieved and where should I store such code, the views.py or serializers.py? -
how to reverse url in django template syntax
for example, I can reverse a url in this way: {% url 'home:index' %} but if I need to compare a url in a if sentence, like this: {% if request.path == url %} and I want to replace the url with a reverse one but I can't do this: {% if request.path == {% url 'home:index' %} %} So is there another way can solve this? Thanks a lot ! -
Django + AWS Secret Manager Password Rotation
I have a Django app that fetches DB secret from AWS Secret Manager. It contains all the DB parameters like username, password, host, port, etc. When I start the Django application on EC2, it successfully retrieves the secret from the Secret Manager and establishes a DB connection. Now the problem is that I have a password rotation policy set for 30 days. To test the flow, at present, I have set it to 1 day. Every time the password rotates, my Django app loses DB connectivity. So, I have to manually restart the application to allow the app to fetch the new DB credentials from the Secret Manager. Is there a way that secret fetching can happen automatically and without a manual restart of the server.? Once way possibly is to trigger an AWS CodeDeploy or similar service that will restart the server automatically. However, there will be some downtime if I take this approach. Any other approach that can seamlessly work without any downtime. -
Include Object and Object's Foreign Keys in One Query Django
I have the following models: class Document(models.Model): name = models.CharField(max_length=30, null=True, blank=True) reference = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.Name class Subdocument(models.Model) document = models.ForeignKey(Document, null=True, default=None) pdf = models.FileField(upload_to='media') Ultimately I want to show both the name from Document and the pdf from Subdocument in the same <li> in my template within a for loop. So it could be something like: {% for item in something %} <li class="list-group-item"> {{ item.Name }} {{ item.pdf }} </li> {% endfor %} My issue is because they are in separate models, I'm not sure how to get fields from both. So what query, or queries could I run in my view in order to make this possible? Any other approach is welcome, this is just to illustrate my end goal. Thank you! -
Model as a field of another model Django
I'm designing a payment system for a website, but I have trouble. A person can do a Payment and that Payment has a payment type, for example, debit card, credit card or PayPal. So, I need the possibility to add new payment options. The problem is I don't know how to link these two tables, I know that I need a third table with only the payment_id and the payment_type_id assigned. Is there a way to generate this with Django? class PaymentType(models.Model): """Payment option available""" name = models.CharField(unique=True, max_length=255) created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) def __str__(self): return self.name class Payment(models.Model): class PaymentStatus(models.TextChoices): DONE = '1', "DONE" PENDENT = '2', "PENDENT" CANCELED = '3', "CANCELED" status = models.CharField(max_length=10, choices=PaymentStatus.choices, default=PaymentStatus.PENDENT) # payment type created_on = models.DateTimeField(auto_now_add=True) -
Hide a django model field and generate it myself on form submit
I have a model with the following Fields: alert_text, next_run (next time alert will pop out) the next_run is auto filled by me (I dont want to user to fill it) so I hide it like so: #admin.py class AlertForm(forms.ModelForm): class Meta: model = Alert fields = '__all__' class AlertAdmin(admin.ModelAdmin): form = AlertForm fields = ['alert_text'] admin.site.register(Alert,AlertAdmin) The problem is that now I can't find a way to add it to the model when created. and I get an Error: 'AlertForm' has no field named 'next_run'. this is the model.py: class Alert(models.Model): alert_text= models.CharField(max_length=200) next_run = models.DateTimeField() Will appreciate any help here couldn't find a solution anywhere :( -
Django: ImportError: cannot import name 'get_user_model' from 'django.contrib.auth.models'
I have a problem using Djangos Default user from django.contrib.auth.models but trying to use it with my custom User model, using from django.contrib.auth.models import AbstractUser. Following those articles: Django Doc Medium SimpleIsBetter 1 SimpleIsBetter 2 So here is my User model: from django.db import models from django.contrib.auth.models import AbstractUser # from django.conf import settings from django_countries.fields import CountryField # https://github.com/SmileyChris/django-countries class User(AbstractUser): """auth/login-related fields""" is_a = models.BooleanField('a status', default=False) is_o = models.BooleanField('o status', default=False) def __str__(self): return "{} {}".format(self.first_name, self.last_name) and here is my Profile model: from django.db import models from django_countries.fields import CountryField # https://github.com/SmileyChris/django-countries from django.contrib.auth.models import get_user_model User = get_user_model() # https://medium.com/swlh/best-practices-for-starting-a-django-project-with-the-right-user-model-290a09452b88 from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): """non-auth-related/cosmetic fields""" user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) nationality = CountryField(null=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) def __str__(self): return f'{self.user.username} Profile' """receivers to add a Profile for newly created users""" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() and in my settings.py I added AUTH_USER_MODEL = 'mysite.User' settings.py: AUTH_USER_MODEL = 'mysite.User' INSTALLED_APPS = [ 'mysite.apps.MysiteConfig', 'django_countries', 'djmoney', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] … -
Django Form - Select foreign key from bootstrap modal pop up
I have created a js/ajax modal pop up in a form to help select an option for a foreign key field in the form. I am lost on how to pass the selected variable back to the form and close the modal. Here is my code : views.py def worker_wizard_popup(request, pk): data = dict() shift = Shift.objects.get(id=pk) skilled = EmployeeSkill.objects.filter(skill_id=shift.skill.id).values_list('employee_id', flat=True) on_other_shifts = ShiftWorker.objects.filter(shift_date=shift.date, employee_id__in=skilled).order_by('employee__first_name') on_other_shifts_ids = on_other_shifts.values_list('employee_id', flat=True) time_off = TimeOff.objects.filter(start_date__lte=shift.date, end_date__gte=shift.date, employee_id__in=skilled).exclude(Q(start_date=shift.date, start_time__gte=shift.shift_start)|Q(end_date=shift.date, end_time__lte=shift.shift_start)).order_by('employee__first_name') time_off_ids = time_off.values_list('employee_id', flat=True) available = User.objects.filter(id__in=skilled, is_active=True).exclude(Q(id__in=on_other_shifts_ids)|Q(id__in=time_off_ids)|Q(admin=True)).order_by('first_name') context = { 'shift': shift, 'on_other_shifts': on_other_shifts, 'time_off': time_off, 'available': available } data['html_form'] = render_to_string('events/includes/partial_availability_wizard.html', context, request=request, ) return JsonResponse(data) Here is the form where I want the chosen FK to pass to the selected option of the Employee field. <div class="col-lg-6 mb-4 bg-default"> <div class="card"> <div class="card-header">Add Worker</div> <div class="card-block"> {% bootstrap_form_errors form %} <form method='POST'> {% csrf_token %} <button type="button" class="btn btn-info btn-md js-worker-wizard mb-2" data-url="{% url 'events:worker_wizard' pk=shift.id %}"><span class="fas fa-hat-wizard fa-lg"></span> Shift Wizard</button> {% bootstrap_field form.employee %} {% bootstrap_field form.shift_date %} {% bootstrap_field form.shift_start %} {% bootstrap_field form.shift_end_date %} {% bootstrap_field form.shift_end_time %} {% bootstrap_field form.call_location %} {% bootstrap_field form.pay_rate %} {% if request.tenant.preferences.request_confirm == True %} {% bootstrap_field form.request_confirm %} {% … -
403 Forbidden Apache with Django
This is will probably get downvoted, but please before do, take in mind I am a complete newbie and desperate. I want to deploy my Django site with Apache server, I tried several pages -including Django's- and previous questions, either super old or incomprehensible, but I managed to pull off this httpd.conf for VirtualHost: ServerName 127.0.0.1 Listen 5000 <VirtualHost *:5000> ServerAlias localhost ServerAdmin webmaster@example.com DocumentRoot /home/kxdragon/server/myproj/renderer/templates #Alias /robots.txt /usr/local/www/documents/robots.txt #Alias /favicon.ico /usr/local/www/documents/favicon.ico #Alias /media/ /usr/local/www/documents/media/ <Directory /home/kxdragon/server/myproj/renderer/templates> <IfVersion < 2.4> Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.4> Options Indexes FollowSymLinks Includes ExecCGI Require all granted </IfVersion> </Directory> WSGIDaemonProcess example.com processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup example.com WSGIScriptAlias / /home/kxdragon/server/myproj/myproj/wsgi.py <Directory /home/kxdragon/server/myproj/> <IfVersion < 2.4> Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.4> Options Indexes FollowSymLinks Includes ExecCGI Require all granted </IfVersion> </Directory> </VirtualHost> And I have no idea why this returns 403, the answer for the other questions with same issue is very old and not updated, and sorry if this -most probably- answered before. Thanks. -
Python (Django) - Authenticate returning None
I'm using Django's authenticate function to let users register (create an account) and sign in (login after creating an account). Authenticate works fine for registration, but when I try signing the user in after logging out, it doesn't work. Registration Method: if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] raw_password = form.cleaned_data['password1'] user = authenticate(username=username, password=raw_password) #returns user object login(request, user) #works Sign in Method: if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(user=username, password=password) #returns None login(request, user) #doesn't work I looked at a few other threads that reported a similar issue and added the following code to my settings.py file. However, authenticate still returns none when I try signing in. settings.py code AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) -
run python script when django is runing under docker
I am working on a django docker image and I want to execute an function ussing command line, I know that I can enter to shell python docker container and run a function like this : docker container ls to find the container id and use in the next command docker container exec -it <container_id> python3 manage.py shell Then: [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> >>> from xx import foo >>> foo() # foo() has been excecuted However, i was wondering if i can use something similar like python flag -c which help to run small piece of python code as command line like this: python3 -c "from xx import foo; foo()" I tried to insert a cmd with linux tubes : echo 'from xx import foo; foo()' | docker container exec -it <container_id> python3 manage.py shell, However it doesn't work. I'd appreciate any advice, thanks for your time. -
How to call REST APIs from Django?
Not new to programming, but new to Django Where do I place the code in my Django project that calls an external REST API? In the simplest example: I have a form where the user enters their ZIP code and presses a "Check" button which tells if the customer's address can be serviced by the lawn care company. Upon getting a response, I have to the JSON to determine if it's serviceable, and what kind of services, etc. So I need to be able to send, and read responses. Where do I do this? There is no database involved, so I presume I don't use a model. I don't think the "View" is a good spot Where?! Thanks! -
Hello, Im trying to use Django on PyCharm and when im trying to: example "from django.shortcuts import render"
If someone could help me it would mean a lot to me as I have spending so much time trying to fix this. Im having this issue in a different projects too. -
Faker() raised Django ImproperlyConfigured Error
trying to run some fake data using Faker but been trying for a day now to solve and i cant. i need a little help here would be much appreciated below is the code and the error. im working on Windows 10, Sqlite, python 3.8.2 and django 3 and venv enviroment python -m venv name i have the django admin on already i do not know what would be the problem now... any help would be much appreciated. Thank you! import django import os import random from faker import Faker from first_app.models import AccessRecord, WebPage, Topic os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_app.settings') django.setup() fake = Faker topics = ['Search', 'Social', 'Marketplace'] def add_topic(): # t = Topic.objects.get_or_create(top_name=fake.name()) t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(n=5): for entry in range(n): top = add_topic() fake_url = fake.url() fake_date = fake.date() fake_name = fake.company() webpge = WebPage.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0] fkacc = AccessRecord.objects.get_create(name=webpge, date=fake_date)[0] if __name__ == '__main__': print("Populating script") populate(20) print("Done!!") Error message: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable e DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings . I've tried multiple way to try an access Django's setting module but its not working i believe … -
Django query get all A records with B records
My django project has a many to many relationship Doctor -- Speciality I'm trying to list only specialities with doctor records to allow users request an appointment. Just now I have this context['specialities'] = [s for s in Speciality.objects.all() if s.doctor_set.all()] but it's not an elegant solution. I wanna list only specialities with active (is_active=True) doctors. How can I add is_active filter? -
Annotate sum of timestamp in Django queryset
Is there a way by which I can annotate sum of timestamps in django. I am trying to do something like this: qs = MyModel.objects.annotate(sum_of_completed_time=Sum('mappings__completed_at')) when i try to do this i get following error: django.db.utils.ProgrammingError: function sum(timestamp with time zone) does not exist ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. so is there a way I can achieve this? -
Django only runs by command line but not in PyCharm
I'm trying to run a Django (version 2.1) project in PyCharm, and the run configurations are properly set to work with the right environment and to use the manage.py file to run the server. At least with other projects in PyCharm I can run without problems. But why I only get the following error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured only when running directly from PyCharm? By command line it runs perfectly fine with the command 'python manage.py runserver'. -
Fetch foreign key object in React from Django API
I have a model in my Django API with a foreign key for the parent, which references itself. I've serialized the data and returned it in a viewset. It returns an object in which the parent field shows the parent ID as an int. However, I'm trying to get it to display the actual values of the parent instead (name and category), so that I can then render the relevant data in my React frontend app. I've listed my model, serializer and viewset below, along with the object it's returning that shows the parent and also the child with the parent ID in the parent field. Can anyone please help? class ComponentModel(models.Model): name = models.CharField(max_length=50, blank=False) wattage = models.PositiveIntegerField(blank=True, null=True) category = models.CharField(max_length=13, choices=CATEGORY_CHOICES, blank=False) parent = models.ForeignKey( 'self', blank=True, null=True, on_delete=models.CASCADE ) class ComponentSerializer(serializers.ModelSerializer): class Meta: model = ComponentModel fields = ('id', 'name', 'wattage', 'category', 'parent') class ComponentViewSet(viewsets.ModelViewSet): queryset = ComponentModel.objects.all() serializer_class = ComponentSerializer [ { "id": 1, "name": "AMD", "wattage": null, "category": "cpu", "parent": null }, { "id": 5, "name": "760K", "wattage": 100, "category": "cpu", "parent": 1 } ] -
What means "Quit the server with CTRL-BREAK"?
Do i have to press keys "Ctrl" and "Break" on my keyboard or do i have to simply type "Ctrl-break" to my terminal?? Can't figure it out still. Have tried all possibilities. Sorry for such a dumb question. -
Can't update DB using HTML form in Django
I need to fill the field name and image to upload to the Django DB but I can't make it to update it using the form label of HTML views.py """Artist views.""" # Django from django.shortcuts import render, redirect from django.views import View from django.http import HttpResponse # Models from music.models import Artist # Forms from artist.forms import ArtistForm class AddArtistView(View): """Adding new artist.""" def upload_image(request): if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): m = Artist.objects.get(pk=image_id) m.model_pic = form.cleaned_data['image'] m.save() return HttpResponse('Image upload success') return HttpResponseForbidden('Allowed only via POST') template = "artist/create_artist.html" def get(self, request): """Render add artist form.""" form = ArtistForm() context = {"form": form} return render(request, self.template, context) def post(self, request): """Receive and validate add artist form.""" form = ArtistForm(request.POST) if not form.is_valid(): context = {"form": form} print(form.errors) return render(request, self.template, context) new_artist = Artist.objects.create_artist( name=form.cleaned_data["name"], ) return HttpResponse("<h1>Artist Added!</h1>") models.py """Music Models""" from django.db import models class Artist(models.Model): """Artist Model.""" name = models.CharField(max_length=200) image = models.ImageField(null=True, upload_to='artists/images/') def __str__(self): """Get str representation.""" return self.name def __repr__(self): """Get str representation.""" return self.__str__() forms.py """Artist forms.""" # Django from django import forms #from django.contrib.auth.models import Artist from music.models import Artist class ArtistForm(forms.Form): """Add new artist""" name … -
Optional url parameter in django 2.2
I am working on a solution where in the application I would like to have an url with an optional parameter, if it is not there, the location is for Germany. Below is my code with urls for django 2.2 and view. urls.py urlpatterns = [ path('<country>', HomeView.as_view(), name='home'), ] views.py class HomeView(TemplateView): template_name = 'data/index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) queryset = DataSet.objects.filter(location=self.request.GET.get('country', 'Germany')) return context -
not getting results in django search but individual searching is working fine
my problem is when I'm adding simple functionality to individual search fields, it's working fine for single search fields, like after adding functionality for location field it's working as i wanted but after adding another functionality for another field it's not showing anything even the first field also not showing results, i think it's a very silly problem but i can't figure out that, please help me coders! (i've added html and views.py codes let me know guyz if you need anything else) html code <form action="{% url 'search-page' %}" method=""> <div class="row"> <div class="col-12 col-lg-10"> <div class="row"> <div class="col-12 col-md-6 col-lg-3"> <select name="location" id="location" class="form-control"> <option value="">Location</option> {% for key,value in location_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-12 col-md-6 col-lg-3"> <select name="types" id="types" class="form-control"> <option value="all-types">All Types</option> {% for key,value in property_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-12 col-md-6 col-lg-3"> <select name="city" id="city" class="form-control"> <option value="01">All City</option> {% for key,value in city_choices.items %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="col-12 col-md-6 col-lg-3"> <select name="status" id="all" class="form-control"> <option value="01">Status</option> {% for key,value in status_choices.items %} <option value="{{ key … -
How logout from Djoser (installed with Django Rest Framework)
I have installed Djoser with Django Rest Framework, after loggin in as (url : /token/login ) I receive a token, but when I change url to '/token/logout/ ' it shows error as logging credential not provided. I am using browser url section to interact with DRF. Please advice me correct url to logout ? I can provide Token,username and password. -
How to design a Django API to handle a "Dynamic" form?
I have built an Angular form that contains a form array. So the user has the control to add fields or delete fields from the form. What I am trying to understand is how I can design a Django API that can handle the post for this kind of dynamic form? I do not want the user to create an account on the website in order to place his order. Is that even possible?