Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get multiple radio button values from django template
My model contains passages and each passage have some questions and each question have four answers. I wrote a simple form to show the questions and showed the related answers with radio buttons, but I can't retrieve the answer for a specific question in Django View Django Template: <h2>Choose the right answer from the choices for any question</h2> <form action="{% url 'exam:submit' passage.id %}" method="post"> {% csrf_token %} {% for question in passage.question_set.all %} <h5>{{ forloop.counter }}-{{question.text }}</h5> {% for answer in question.answer_set.all %} <input type="radio" name="answer[{{ question }}]" id="answer{{ answer.id }}" value="{{ answer.id }}" /> <label for="answer{{ answer.id }}">{{ answer.text }}</label> <br/> {% endfor %} {% endfor %} <input type="submit" value="Submit" /> </form> Django View: def submit(request, passage_id): passage = get_object_or_404(models.Passage, pk=passage_id) if request.method == 'POST': answer_list = request.POST.getlist('answer') context = { 'List': answer_list, 'passage': passage, } return render(request, 'exam/submit.html', context) I want to show the list of answers that choose for their question in a list (e.g. [1, 2, 4, 3, 1] are the answers chosen for question 1, 2, 3, 4, 5), but the browser just shows an empty list (e.g. []). -
Custom Django decorator- whenever it is called, Django raises a circular import error
I'm trying to write a custom decorator for a Django view that is a lot like login_required, except it does something else when it finds that the user is not logged in. I initially put it in a custom.py file in the same directory as my views, but it returned a "circular import error" every time I tried to import it into the views. Then, I made it its own folder, and it returned the same error. As a last resort, I copied and pasted it into the django.contrib.auth.decorators folder. When I imported this entire file, it did not return the circular import error, but when I tried to call the decorator, it did. Why is it doing this? I checked the files and am sure I'm not making circular imports. Error: raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. View imports: from django.shortcuts import render from django.views.decorators.http import require_http_methods import django.contrib.auth.decorators The decorator: def check_login(test_func): def decorator(view_func): @wraps(function) def _wrapped_view(request, *args, **kwargs): if test_func(request.user.is_authenticated): return view_func(request, *args, **kwargs) else: print("not written yet") return … -
Django middleware - exclude for specific path
I have implemented a health check for Django web server The health check by default calls all the middlewares which executes cache invalidation, db calls, feature flags calls etc. I would like to avoid calling the middlewares for this specific path For every middleware there is __call__ method implemented where the code is executed where can I define what middleware will be executed based on path? -
changing context of django-access views
I've installed django-access to control signup, login, and password reset functionality to my site. Values such as {{domain}} appear in some of the templates that comes with django-access. Do you know how I might go about overriding the context being passed into these default templates that django-access provides? Thanks! -
TestCase writing for Django authenticated API View
I have successfully write at TestCase and it's working very fine. At first have a look at my code: Below is my tests.py from django.shortcuts import reverse from rest_framework.test import APITestCase from ng.models import Contact class TestNoteApi(APITestCase): def setUp(self): # create movie self.contact = Contact(userId=254, name="The Space Between Us", phone=2017, email='doe@f.com') self.contact.save() def test_movie_creation(self): response = self.client.post(reverse('getAndPost'), { 'userId': 253, 'name': 'Bee Movie', 'phone': 2007, 'email': 'ad@kjfd.com' }) self.assertEqual(Contact.objects.count(), 2) Above snippet working fine but the problem is.. Once i implement authentication system, it not works below is my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } if i change into AllowAny in permisison, The test works nice but if keep IsAuthenticated instead of AllowAny , it not works. I want the test should run nicely even once i keep IsAuthenticated in permission. Can anyone suggest me how can i do it? I am not getting what to change or what add in my tests.py file. -
Python 3.7 / Django 2.2.1: Check field before save
The objective is the user only can save Marking model if the date that he is putting is in the range of dates, start_date to end_date, of DateRange model and if field enable is True. models.py: class DateRange(models.Model): class Meta: ordering = ['-first_date'] start_date = models.DateField(blank=False, null=True, verbose_name='Start Date') end_date = models.DateField(blank=False, null=True, verbose_name='End Date') enable = models.BooleanField(default=False, verbose_name='Enable') def __str__(self): return '{} to {} is {}'.format(self.first_date, self.end_date, self.enable) class Marking(models.Model): class Meta: ordering = ['-first_date'] date = models.DateField(blank=False, null=True, verbose_name='Date') order = models.BooleanField(default=False, verbose_name='Order') def __str__(self): return '{} / {}'.format(self.date, self.order) forms.py class DateRangeForm(forms.ModelForm): class Meta: model = DateRange fields = [ 'start_date', 'end_date', 'enable', ] class MarkingForm(forms.ModelForm): class Meta: model = Marking fields = [ 'date', 'order', ] views.py def add_marking(request): form = MarkingForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(reverse("marking_info")) context = {"form": form} return render(request, 'add_marking.html', context) I tried several options and none of them worked. Can someone help me on the right path? Thank you! -
Django project with custom user model load fixture error
I am setting up a new django(version 2.2) project and want to use custom user model. When I load fixtures data, it failed with error like below: django.db.utils.IntegrityError: Problem installing fixtures: insert or update on table "doctors_doctor" violates foreign key constraint "doctors_doctor_user_ptr_id_ba968804_fk_doctors_user_id" DETAIL: Key (user_ptr_id)=(1) is not present in table "doctors_user". From django document - https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project I realized I did 'python manage.py migrate' before changing AUTH_USER_MODEL in settings.py. So I tried to delete all tables and redo 'python manage.py migrate', but it still hit this problem. Following are my code settings.py AUTH_USER_MODEL='doctors.User' models.py class User(AbstractUser): mobile = models.CharField(max_length=30) fixtures_autodump = ['dev_users'] class Meta: db_table = 'doctors_user' def __str__(self): return self.username class Doctor(User): personal_id = models.CharField(max_length=255, blank=True) fixtures_autodump = ['dev_users'] class Meta: db_table = 'doctors_doctor' def __str__(self): return self.username dev_users.json [ { "model": "doctors.doctor", "pk": 1, "fields": { "date_joined": "2019-06-16T09:09:56.127Z", "email": "user1@localhost.dev", "first_name": "user1", "groups": [], "is_active": true, "is_staff": true, "is_superuser": true, "last_login": null, "last_name": "test", "password": "pbkdf2_sha256$36000$nITgYnD9lKzm$cXGlthNYJDrrihQikgyh7HO5hm2fNvH71+fiCoMyIpY=", "user_permissions": [] } }, { "model": "doctors.doctor", "pk": 2, "fields": { "date_joined": "2019-06-16T09:09:56.127Z", "email": "user2@localhost.dev", "first_name": "user2", "groups": [], "is_active": true, "is_staff": false, "is_superuser": false, "last_login": null, "last_name": "test", "password": "pbkdf2_sha256$36000$ohIbxnbyKjNm$smg+FvfhT1cF1kLt93EDz/n5KyfkDupIgkihsNIHQS8=", "user_permissions": [] } } ] I expect loading fixture data can be … -
How to deploy Django application using Django-background-tasks on AWS beanstalk?
I am using Django-background-tasks in my application, it worked fine for me on my local machine, I am trying to deploy the website to AWS elastic-beanstalk. I wanted to know how to mimic the 2 cmd prompt situation in windows( one with "python manage.py runserver" and the other with "python manage.py process_tasks") in AWS. This will be a kind of parallel situation where both commands need to run simultaneously. I tried adding the command as one of the container_commands in the config file in "./.ebextensions" but it didn't work (i consider AWS waits for such commands to end and it never ends, that's the case"). -
Django - Unpack dictionary in include
I want to unpack a dictionary in an include tag. # Python kwargs = {"dictionary": "vertical"} # Template {% include "test.html" with kwargs %} {# This should be turned into this #} {% include "test.html" with dictionary=vertical %} Is this possible using only an inclusing tag? -
pytest-django ModuleNotFoundError: No module named 'myproject.urls'
Hi I have a project using django, test module is pytest-django when I run pytest, it raise error some error project tree is seshat - pytest.ini - tox.ini - README.md - seshat - manage.py - conftest.py - __init__.py - settings.py - reviewer - test.py - views.py - __init__.py - models - __init__.py - user.py my django settings.py is import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'reviewer', ] pytest.ini [pytest] DJANGO_SETTINGS_MODULE=seshat.seshat.settings python_files = tests.py test.py is from .models import Reviewer from django.shortcuts import reverse def test_reviewer_model_object_create(): reviewer = Reviewer.objects.create_user( email='test@test.com', username='test_User', password='test123', ) assert bool(reviewer) == True def test_reviewer_create_view_get(client): req = client.get(reverse('reviewer')) assert req.status_code == 200 In these settings, when i run pytest command it raise error ModuleNotFoundError: No module named 'reviewer' but when I run python seshat/manage.py runserver, there's no problem :( So I change my settings.py reviewer -> seshat.reviewer, and run pytest command but it raise ModuleNotFoundError: No module named 'seshat.urls and runserver doesn't working too! I think it is path problem but where...? why pytest-django can't find my modules?? please somebody help me! thank you:) -
Django tenant unit test return 403 instead of 200
I have an application in django 2.1 and I am using a django-tenants package. I have application accounts there, which in settings.py is in SHARED_APPS. I want to write a unit test for the login view. Every time I get: AssertionError: 403 != 200 Here is my code: class LoginViewTests(TenantTestCase): def setUp(self): super().setUp() self.client = TenantClient(self.tenant) def test_login(self): response = self.client.get(reverse('accounts:login')) print(response) self.assertEqual(response.status_code, 200) -
How to prevent django from sorting keys JsonField
I have a model class Resource(models.Model): index = JSONField(blank=True, default=dict) The problem is that django sorts the json field alphabetically, how do I prevent this default behaviour, I've tried using " sort_keys=False " ps: Most fields have been stripped out for brevity -
How to make vue js ssr using the django framework
I want to make some part of my application capable of supporting server rendering. In the project, we actively use vuex and vue router. We receive all data using api queries. Tell me where to go or provide any working code snippet. Thank you in advance -
How to customize django-weasyprint view response
I would like to change a bit the behavior while generating pdf with django-weasyprint module. In my application, the objective is that the pdf is automatically saved then send it attached to an email. I built a CBV using the following class : class GeneratePDF(WeasyTemplateView): pdf_filename = 'resolutions_dj.pdf' template_name = 'polls/resolutions.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) return self.render_to_response(context) This works but shows me either the pdf or a dialog box to save the file. get_context_data() method is overriden but I do not think it has any importance. I would like to use this get() method to to more actions after rendering pdf. I tried this code but it does not work (no pdf generated, no dialog box) : class GeneratePDF(WeasyTemplateView): pdf_filename = 'resolutions_dj.pdf' template_name = 'polls/resolutions.html' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) response = self.render_to_response(context) return redirect('polls:event', event_slug=context['event'].slug) The key seems to be this line : response = self.render_to_response(context) I do not understand why it does not work. Finally, I found how to save pdf without showing it nor displaying a dialog box by overrinding rendered_content property (from WeasyTemplateResponse class) and adding response_class = PersoWeasyTemplateResponse in my GeneratePDF but it displays an empty pdf page … -
Djongo or MongoEngine to deal with mongodb for Django web app?
I am writing backend code for a web app, the database is already in MongoDB, what is the best way to use MongoDB with Django is it djongo or mongoengine? I found mongoengine a bit complicated and djongo easier for the intergration as it uses the same structure as Django but I'm still new in this can you please tell me the difference from your experience? thanks -
Why console is showing templates not defined error in django
I am new to django , I am facing one while django running server , I have copy and paste my code please tell me what is wrong with my code 'DIRS': [templates], NameError: name 'templates' is not defined in settings.py file , I have put templates in [] brackets TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [templates], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] this is my views.py from django.http import HttpResponse from django.shortcuts import render def index(response): return render(request,'index.html') this is urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('about', views.about, name='about'), ] -
Overriding settings.py email settings in view
The email settings that are used by a post request need to depend on logic within my view. As a result, I'd like to overwrite the following email settings within my view, which are typically set in settings.py: settings.py EMAIL_HOST_USER = 'user@website.com' EMAIL_HOST_PASSWORD = '****************' DEFAULT_FROM_EMAIL = 'user@website.com' SERVER_EMAIL = 'user@website.com' Based on my reading (https://docs.djangoproject.com/en/2.1/topics/settings/#using-settings-without-setting-django-settings-module), I believe the best way to do this is as follows: views.py from django.conf import settings def myview(request): profile = ..logic that grab's user's profile... settings.configure(EMAIL_HOST_USER = profile.email) settings.configure(EMAIL_HOST_PASSWORD = profile.email_password) settings.configure(DEFAULT_FROM_EMAIL = profile.email) settings.configure(SERVER_EMAIL = profile.email) Can you confirm that this is the most appropriate way to do this? Thanks! -
implement ajax to get checkbox items list from table in django
here i have a table and there is a checkbox and i want to send email to all the checked data of that table.For this i have tried the following. But it is not working .The problem is while returning the list of checked items. The items which are checked are not being returned. How to solve it? template <tbody> {% for contact in contacts %} <tr> <td> <input name ="messages" type="checkbox" id="contact-{{contact.id}}" value={{contact.id}}"> <label for="contact-{{contact.id}}">{{ forloop.counter }}</label> </td> <td>{{ contact.name }}</td> <td>{{ contact.email }}</td> <td>{{ contact.subject }}</td> <td>{{ contact.message }}</td> </tr> {% endfor %} </tbody> //modal <button class="btn btn-primary send-mail-to-selected-btn" type="button" data-toggle="modal" data-target="#item-unit-modal1"> Send Mail To Selected Email </button> <div class="modal" id="item-unit-modal1"> <div class="modal-body"> <form method="POST" action="{% url 'admin:send_mail_selected_contact' %}" class="unit-ajax-form"> {% csrf_token %} <p><label>Subject</label> <input type="text" name="subject" class="form-control required" placeholder="Enter subject" ></p> <p><label>Message</label> <textarea name="message" class="form-control required" placeholder="Enter message" ></textarea></p> <button class="btn btn-primary mt-30">Send Mail</button> </form> </div> views.py def send_mail_selected_contact(request): selected_contact = ContactForm.objects.filter(id__in=request.POST.getlist('messages')) print(selected_contact) form = SendMailContact(request.POST or None) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] for contact in selected_contact: send_mail(subject, message, ' <settings.EMAIL_HOST_USER>', [contact.email]) messages.success(request, 'Mail Sent') return redirect('admin:contact_message') ajax <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).on('click', '.send-mail-to-selected-btn', function(){ var messages = new Array(); $("input:checked").each(function() { messages.push($(this).val()); }); console.log(messages); … -
Double check e-mail validation at the Django backend
Considering that a user can disable JavaScript in the browser, how can I proceed with a "double check" for e-mail validation in the Django backend (specifically, to prevent register using Webmail [GMail, Hotmail and so on])? Thanks. -
create a relation between two models in third
I'm new to development, and I'm at a dead end. I'm trying to create a grant system for Python3 and Django I have models: class Grant(models.Model): id = models.AutoField(primary_key=True) program = models.ForeignKey('Program', on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=200, help_text="Enter name of the grant") budget = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00'),verbose_name="Total budget") grantee = models.ForeignKey('Grantee', on_delete=models.SET_NULL, null=True) description = models.TextField(max_length=1000) owner = models.ForeignKey(settings.AUTH_USER_MODEL,null=True, blank=True, on_delete=models.SET_NULL) class Report(models.Model): title = models.CharField(max_length=100) grant_name = models.ForeignKey('Grant', on_delete=models.SET_NULL, null=True) CAT_LIST = ( ('s', 'Salary'), ('e', 'Event'), ('t', 'Transportation'), ('p', 'Printing'), ('eq', 'Equipment'), ('of', 'Office'), ('o', 'Other') ) categories = models.CharField(max_length=2, choices=CAT_LIST, blank=True) spent = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00')) repbudget = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00'),verbose_name="Budget") comment = models.TextField(max_length=300, null=True) # Below the mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Installment(models.Model): id = models.AutoField(primary_key=True) grant_name = models.ForeignKey('Grant', on_delete=models.SET_NULL, null=True) amount = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00')) date = models.DateField(default=datetime.date.today) date_report = models.DateField(default=datetime.date.today) Now I need to create a model for Installment Report, and it should include Installment and Report’s categories for the same Grant. Something like this: class InstallmentReport(models.Model): id = models.AutoField(primary_key=True) title = models.ForeignKey('Report’, on_delete=models.CASCADE) spent = models.DecimalField(max_digits=12, decimal_places=2,default=Decimal('0.00')) installment = models.ForeignKey('Installment', on_delete=models.CASCADE) When I create this report, I can connect with "Installment", but I can’t image how … -
How to configure nginx, gunicorn to run 2 django servers with different domain names
I have DjangoServer1 and DjangoServer2 running a virtualenv, where gunicorn is installed. nginx is installed under user in Ubuntu. I make DjangoServer1 running under nginx, gunicorn. Server IP: 12.12.12.12 Web site domain for DjangoServer1 is mydomain1.com Web site domain for DjangoServer2 is mydomain2.com This is nginx server config for DjangoServer1. server { listen 8000; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/develop/DjangoServer1; } location / { include proxy_params; proxy_pass http://unix:/home/user/develop/DjangoServer1/DjangoServer1.sock; } } I start the DjangoServer1: 1) Under virtualenv, run gunicorn command to start DjangoServer1 gunicorn --daemon --workers 3 --bind unix:/home/user/develop/DjangoServer1/DjangoServer1.sock DjangoServer1.wsgi 2) Then, run: sudo service nginx restart 3) In router, I portforward port 80, 8000, to server 12.12.12.12 4) In browser, enter: 12.12.12.12. DjangoServer1 works. Enter: mydomain1.com, DjangoServer1 works. Now, I want to run DjangoServer2 under same server: 12.12.12.12 Question: How to configure DjangoServer1 and DjangoServer2 to different port? How to run gunicorn command to use different port? Following command uses port 8000? Why? gunicorn --daemon --workers 3 --bind unix:/home/user/develop/DjangoServer1/DjangoServer1.sock DjangoServer1.wsgi How to configure nginx file? -
What is the correctly way to pass an orientdb @rid as a parameter, to DELETE request in django rest framework?
I'm creating a delete method in a DRF API, by passing parameters, but I don't know how to pass correctly an orientdb @rid. I have a relationship in orientdb called "worksat", in OrientDB Studio i can see the @rid with the structure name like #:, i.e: "#33:1" is the @rid of a worksat relationship record. [![enter image description here][1]][1] So I need to pass that string in my DRF URL api relationship: http://127.0.0.1:8000/api/oworksat/ But passing like: http://127.0.0.1:8000/api/oworksat/#33:1 I see GET request, with the message below: Allow: GET, POST, HEAD, OPTIONS If a pass a simple number: http://127.0.0.1:8000/api/oworksat/1 Then I see DELETE request: Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS``` api.py: class OWorksAtViewSet(viewsets.ModelViewSet): queryset = graph.oworksat.query() serializer_class = OWorksAtSerializer permission_classes = [ permissions.AllowAny ] def destroy(self, request, *args, **kwargs): print ("destroy") urls.py: from django.conf.urls import include, url from rest_framework import routers from .api import (OWorksAtViewSet) from rest_framework_swagger.views import get_swagger_view router = routers.DefaultRouter() router.register('api/oworksat', OWorksAtViewSet, 'oworksat') schema_view = get_swagger_view(title='Swagger Documentation') urlpatterns = [ url(r'^swagger/$', schema_view) ] urlpatterns += router.urls The interesting thing is that by accesing from swagger api, in the DELETE method, if I a pass in the ID of the request "#33:1", it works, the api call to my destroy … -
How to lookup by field inherited from OneToOneField of another model
I am attempting to lookup UserProfile model using a field inherited from the User model. How can I access the username field from the User model in UserProfile view? I am using Django REST framework 3.9. And from my understanding, using the @property annotation in the Model definition allows you to serialize on that field. And I am using that serialized field as lookup_field in the view. This is the UserProfile model. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, null=True, blank=True) birth_date = models.DateField(null=True, blank=True) @property def username(self): return self.user.username This is the serializer. class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = [ 'user', 'username', 'bio', 'birth_date' ] This is the view. class UserProfileAPIView(generics.RetrieveUpdateAPIView): # permission_classes = [permissions.IsAuthenticated] serializer_class = UserProfileSerializer lookup_field = 'username' def get_queryset(self): return UserProfile.objects.all() def get_serializer_context(self, *args, **kwargs): return {'request': self.request} This is the API url. path('<str:username>/profile/', UserProfileAPIView.as_view(), name='profile'), I expected the API to return: username, bio, birth_date but I received this error: "Cannot resolve keyword 'username' into field. Choices are: bio, birth_date, id, user, user_id". -
Error on django-heroku install with pipenv
pretty new to Django here. Not sure the problem. elementary os 0.4.1 loki django 2.1 django-rest-framework 3.8.2 gunicorn python 3.7 So i'm in my pipenv shell and run pipenv install django-heroku. And I get this crazy error: An error occurred while installing psycopg2==2.8.2 --hash=sha256:00cfecb3f3db6eb76dcc763e71777da56d12b6d61db6a2c6ccbbb0bff5421f8f --hash=sha256:076501fc24ae13b2609ba2303d88d4db79072562f0b8cc87ec1667dedff99dc1 --hash=sha256:4e2b34e4c0ddfeddf770d7df93e269700b080a4d2ec514fec668d71895f56782 --hash=sha256:5cacf21b6f813c239f100ef78a4132056f93a5940219ec25d2ef833cbeb05588 --hash=sha256:61f58e9ecb9e4dc7e30be56b562f8fc10ae3addcfcef51b588eed10a5a66100d --hash=sha256:8954ff6e47247bdd134db602fcadfc21662835bd92ce0760f3842eacfeb6e0f3 --hash=sha256:b6e8c854cdc623028e558a409b06ea2f16d13438335941c7765d0a42b5bedd33 --hash=sha256:baca21c0f7344576346e260454d0007313ccca8c170684707a63946b27a56c8f --hash=sha256:bb1735378770fb95dbe392d29e71405d45c8bdcfa064f916504833a92ab03c55 --hash=sha256:de3d3c46c1ee18f996db42d1eb44cf1565cc9e38fb1dbd9b773ff6b3fa8035d7 --hash=sha256:dee885602bb200bdcb1d30f6da6c7bb207360bc786d0a364fe1540dd14af0bab! Will try again. 🐍 ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 8/8 — 00:00:04 Installing initially failed dependencies… [pipenv.exceptions.InstallError]: File "/home/andrew/.local/lib/python3.5/site-packages/pipenv/core.py", line 1874, in do_install [pipenv.exceptions.InstallError]: keep_outdated=keep_outdated [pipenv.exceptions.InstallError]: File "/home/andrew/.local/lib/python3.5/site-packages/pipenv/core.py", line 1253, in do_init [pipenv.exceptions.InstallError]: pypi_mirror=pypi_mirror, [pipenv.exceptions.InstallError]: File "/home/andrew/.local/lib/python3.5/site-packages/pipenv/core.py", line 859, in do_install_dependencies [pipenv.exceptions.InstallError]: retry_list, procs, failed_deps_queue, requirements_dir, **install_kwargs [pipenv.exceptions.InstallError]: File "/home/andrew/.local/lib/python3.5/site-packages/pipenv/core.py", line 763, in batch_install [pipenv.exceptions.InstallError]: _cleanup_procs(procs, not blocking, failed_deps_queue, retry=retry) [pipenv.exceptions.InstallError]: File "/home/andrew/.local/lib/python3.5/site-packages/pipenv/core.py", line 681, in _cleanup_procs [pipenv.exceptions.InstallError]: raise exceptions.InstallError(c.dep.name, extra=err_lines) [pipenv.exceptions.InstallError]: ['Collecting psycopg2==2.8.2 (from -r /tmp/pipenv-iaa8p0mr-requirements/pipenv-n1t1lb2p-requirement.txt (line 1))', ' Using cached https://files.pythonhosted.org/packages/23/7e/93c325482c328619870b6cd09370f6dbe1148283daca65115cd63642e60f/psycopg2-2.8.2.tar.gz'] [pipenv.exceptions.InstallError]: ['ERROR: Complete output from command python setup.py egg_info:', ' ERROR: running egg_info', ' creating pip-egg-info/psycopg2.egg-info', ' writing pip-egg-info/psycopg2.egg-info/PKG-INFO', ' writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt', ' writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt', " writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt'", ' ', ' Error: pg_config executable not found.', ' ', ' pg_config is required to build psycopg2 from source. Please add the directory', ' containing pg_config to the $PATH or specify the … -
How do you list all object with the same foreign key object?
I have a Department model with a name field, then User model with department field using foreignkey to Department. How can I list in a template all users in a Department? Is there a way without using many to many? class Department(models.Model): name = models.CharField(max_length=64,unique=True) description = models.TextField(blank=True) def __str__(self): return self.name class User(AbstractUser): department = models.ForeignKey(Department, on_delete=models.CASCADE, blank=True,null=True) def __str__(self): return self.username