Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Multiple model forms in one template
So I think I have this almost working. I have it set up basically like this tutorial, but it wont display in my HTML template. Here is my code for the template: {% extends 'base_layout.html' %} {% load bootstrap4 %} {# Load CSS and JavaScript #} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {% block content %} <div class="container"> <h1>Patient Checkin</h1> <h2>{{patient.first_name}} {{patient.last_name}} {{patient.id}}</h2> </div> <div class="container"> <form action="{% url 'patientRecords:checkinsubmit' %}" method="POST" class="form"> <input type="hidden" name="patient_id" value="{{patient.id}}" /> {% csrf_token %} {% bootstrap_form updateForm %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Submit</button> {% endbuttons %} </form> </div> {% endblock %} Note that i am using the "bootstrap_form" to allow for bootstrap styling. Is this what is causing the issue? or something else? Anyone have any ideas? Thanks!! -
CORS header access control missing django on digital ocean NGINX and gunicorn
Response in Console:- Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blissedmaths.sgp1.digitaloceanspaces.com/media/topics/4276769703/4276769703.svg. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). I have user django-cors-headers, a Django App that adds CORS (Cross-Origin Resource Sharing) headers to responses. My setting.py file is INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'students', 'commons', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] I have added everything needed in setting.py by still header is not coming. I tries Jquery and AJAX also. But no use. How to fix this. Is it require some javascript also or only this is enough. Please provide a fix for this. The image that is giving me error coming from Digital ocean space is <script> function fetchXML(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.withCredentials = true; xhr.setRequestHeader('Access-Control-Allow-Origin' , '*'); console.log(xhr.getAllResponseHeaders) xhr.onreadystatechange = function (evt) { //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { callback(xhr.responseXML); } }; … -
Sort two zipped lists in django template
On a django template is there a way to use the template tag |dictsort:"key" to sort a zipped list? The key belongs to the first list (object_list) views.py ... def get_context_data(self, *args, **kwargs): ... context['zipped_list'] = zip(object_list, quantity_list) return context some_list.html {% for obj1, obj2 in zipped_list|dictsort:"ticker" %} {{ obj1.ticker }} {{ obj2.quantity }} ... {% endfor %} -
Checking to see if image field has validation errors
Does anyone happen to know how to check an image field within forms.py to see if it has on or more ValidationErrors on it? -
Django - Sorting in Template
I have the following in my template: {% for p in assignments.cap.all %} {{p.assignments.num}}-{{p.fy.year|dictsort:"fy" }} {{p.score}} {% endfor %} I want to order the results by year. I tried {{p.fy.year|dictsort:"fy" }} and {% for p in assignments.cap.all|dictsort:"fy" %} and a few other combinations. I it is not sorting by the year. These are my models: Models.py class Assignment(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) def __unicode__(self): return "id{},name{}, description{}".format(self.id,self.name, self.description) class Meta: ordering = ['id'] class Ratings(models.Model): id = models.CharField(primary_key=True, max_length= 255) rating = models.CharField(max_length=255, blank=True, null=True) yo = models.ForeignKey(Year, related_name="ycap", blank=True, null=True) assignment = models.ForeignKey(Assignment, related_name="cap") class Meta: ordering=['fy'] class Year(models.Model): year = models.CharField(max_length=5) cl_year = models.CharField(max_length=5) class Meta: ordering = ['id'] Views.py def task_page(request, Assignment_id): assignments = Assignment.objects.get(id=Assignment_id) context = { 'tasks' : tasks, } return render (request, 'index.html', context) How can I order this by year? -
Django RESTful Framework bundle multiple api calls into one
I need 3 apis, and I still need a big api to call these 3 apis at once. "task1": "http://localhost:8000/api/task1/", "task2": "http://localhost:8000/api/task2/", "task3": "http://localhost:8000/api/task3/", Can I make a big bundle api call to call those 3 tasks sequentially just in one request? "big_job": "http://localhost:8000/api/bigjob/" -
How do I make a partial update on a ManyToManyField? I also need it validated. Django Rest
I want to be able to partially-update instances through GET requests. urls.py urlpatterns=[ url(r'^classes/(?P<pk>\d+)/add_student/(?P<student_id>\d+)', views.add_student), ] models.py class Class(models.Model): students = models.ManyToManyField('Student', related_name='classes') max_capacity = models.PositiveIntegerField() ... class Student(models.Model): ... The following does not work, but what I want is to be able to partially-update a class_ instance. I want to add a student to this Class instance. Also, I want the validate code in my serializer to reject the update if it is not good. views.py def add_student(request, pk, student_id): class_ = get_object_or_404(Class, id=pk) student = get_object_or_404(Student, id=student_id) class_.students.add(student) serializer = ClassSerializer( class_, data={'students': class_.students}, partial=True ) if serializer.is_valid(raise_exception=True): serializer.save() return redirect('class-detail', pk=pk) serializer.py class ClassSerializer(serializers.ModelSerializer): ... def validate(self, data): students = data['students'] max_capacity = data['max_capacity'] if len(students) > max_capacity: msg = 'This class is full' raise serializers.ValidationError(msg) return data Please help, I really don't know what to do. I have no idea where to place my codes. I would accept any revision or replacement of code -
VSCode - messy unittest configuration for django project
I just switched to VSCode and it's already giving me a headache. I'm using python 3.6.5, django 2.0.3 and VSCode 1.21.1. In my project I have couple test files (test_*.py) in the following location app/tests/. I'm able to simply run them using cmd: python manage.py test app.tests. I wanted to use VSCode tests debugging so I decided to configure built-in unittest handler. First I edited workspace settings.json file adding following code: "python.unitTest.unittestEnabled": true, "python.unitTest.unittestArgs": [ "-s", "app.tests", "test_*.py", It turned out that __init__.py files are required both for app and tests folders in order to detect files containing tests. I recently switched to Python 3 and was really happy __init__.py files are no longer a requirement (PEP420). But yeah, I had to add them just to make test detection work. Then I found out that without calling django.setup() and setting DJANGO_SETTINGS_MODULE in the first place I still won't be able to run my tests. Therefore I had to add the following code at the beginning of every test file: import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyAwesomeWebApp.settings') django.setup() Is it all really required or there is some other way to configure unittest in VSCode? -
django.core.exceptions.ImproperlyConfigured: Field name `id` is not valid for model
I'm having troubles with one of my serializer. I'm trying to return all the data of a PriceUnit object but DRF refuses to serve the id. This id is automatically generated and I'm not modifying it. serializer.py class PriceUnitSerializer(serializers.ModelSerializer): product_id = serializers.SerializerMethodField() def get_product_id(self, obj): if obj.product is not None: return obj.product.id return None class Meta: model = PriceUnit fields = ('id', 'name', 'formula', 'product_id') urls.py url(r'^price_units/$', price_unit_view.PriceUnitCreateUpdate.as_view()), url(r'^price_units/(?P<pk>[0-9]+)/$', price_unit_view.PriceUnitList.as_view()), models.py class PriceUnit(models.Model): UNIT = 'Unit' SQUAREMATER = 'm2' CUBEMETER = 'm3' LINEARMETER = 'ml' KILOGRAM = 'kg' PRICE_UNITS_CHOICES = ( (UNIT, 'Unit'), (SQUAREMATER, 'm2'), (CUBEMETER, 'm3'), (LINEARMETER, 'ml'), (KILOGRAM, 'kg'), ) name = models.CharField(max_length=50, choices=PRICE_UNITS_CHOICES, default=UNIT,) formula = models.CharField(max_length=400, blank=True) product = models.OneToOneField(Product, on_delete=models.CASCADE, primary_key=True,) def __str__(self): return 'Price unit : ' + self.name + ' - Product #' + str(self.product.pk) price_unit_view.py class PriceUnitList(APIView): """ Retrieve a PriceUnit. """ permission_classes = (permissions.IsAuthenticated,) def get(cls, request, pk, format=None): price_unit_list = PriceUnit.objects.filter(pk=pk) if price_unit_list: serializer = PriceUnitSerializer(price_unit_list[0]) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(data={}, status=status.HTTP_204_NO_CONTENT) Request (using httpie) : http GET http://127.0.0.1/api/price_units/1/ "Authorization: Token ba4ee2628669a9cc0d6e715b12660003f748c674" Error : ERROR [django.request:135] Internal Server Error: /price_units/1/ Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in … -
Unknown field(s) Error: Trying to create Teacher / Student profiles from User Model?
So I have a Accounts model that extends AbstractUser model. I Also have StudentProfile and TeacherApplications that have a one to one relation with Accounts. I ALSO have two forms for teacher and student to fill out. Requirement: Enable students/teachers to register via their forms. Issue: In the student/teacher form I am asking for fields that the User model needs such as email, username, first and last name etc.. However I am getting this: django.core.exceptions.FieldError: Unknown field(s) (last_name, date_joined, first_name, email) specified for StudentProfile ISSUE: I need to register the user with user fields otherwise User fields would be null and generate error as well.. But is the best approach? Or what am I doing wrong? models class Accounts(AbstractUser): email = models.EmailField('email address', unique=True) first_name = models.CharField('first name', max_length=30, blank=True) last_name = models.CharField('last name', max_length=30, blank=True) date_joined = models.DateTimeField('date joined', auto_now_add=True) # asdd bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) class StudentProfile(models.Model): user = models.OneToOneField('Accounts', related_name='student_profile') # additional fields for students AMEB_Ratings = models.PositiveIntegerField(default=0) is_student = models.BooleanField('student status', default=False) class TeacherApplications(models.Model): user = models.OneToOneField('Accounts', related_name='teacher_profile') # additional fields for teachers instrument = models.TextField(max_length=500, blank=True) skill = models.CharField(max_length=30, blank=True) experience_in_years = models.PositiveIntegerField(blank=True) is_teacher = models.BooleanField('teacher status', … -
Django Serialize multiple models in a single view
Here's the scenario, i have two models Offre and Recruteur class Recruteur(models.Model): [...] entrepriseName = models.CharField(max_length=50) [...] class Offre(models.Model): [...] idRecruteur = models.ForeignKey(Recruteur,verbose_name = "idRecruteur", on_delete=models.CASCADE, default=None) [...] And I have the following serializers: class RecruteurByIdSerializer(serializers.ModelSerializer): class Meta: model = Recruteur fields = ( 'entrepriseName',) class OffreSerializer(serializers.ModelSerializer): recruteur = RecruteurByIdSerializer(many=True, read_only=True) class Meta: model = Offre fields = ( 'title', 'dateAjout', 'description', 'recruteur') i expected this result: but im getting this instead: what am i doing wrong ? -
Allauth Custom Provider Urls
Where/how does one hook up a custom provider url patterns? I can't find anywhere in the code that automatically installs the providers... e.g. allauth.socialaccount.providers.shopify urls. My custom provider worked on older versions like 0.2x.x but now I am getting reversal errors in the provider list template because the urls are not registered -
django - once extended block gets overridden
I am learning with django 2.0, in python 3.6, on windows. I would like to create page with three different blocks, and therefore, this can be seen in the base.html: base.html <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}My amazing site{% endblock %}</title> </head> <body> <div class='menu'>{% block menu %} start menu {% endblock menu %}</div> <div class="content">{% block content %} start content {% endblock content %}</div> <div class="buttons">{% block buttons %} start buttons {% endblock buttons %}</div> </body> </html> And this is, how my urls.py looks like: urls.py from django.urls import path from . import views urlpatterns = [ path('', views.MenuView.as_view(), name='menu'), path('folder<pk>/', views.FolderView.as_view(), name='folder'), path('picture<int:picture_id>/', views.picture, name='picture_url') ] When I come to localhost:8000/check_images, I call menu view, which should extend base.html. In the first block, I would like to display menu bar, which shows all folders. I would like to have this bar visible everywhere, on every page. This is called via following view: views.py class MenuView(generic.ListView): model = Folder template_name = 'check_images/menu.html' context_object_name = 'folders' def get_queryset(self): return self.model.objects.all() which renders into check_image/menu.html: menu.html {% block menu %} {% for folder in folders %} <a href="{% url 'folder' folder.id %}">{{ folder.id }} -- {{ folder.name }}</a> … -
python: CommandError: You appear not to have the 'mysql' program installed or on your path
I am working on a Mysql database for a Django app, so I created a database named maison, configure settings.py as bellow: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'maison', 'USER': 'root', 'PASSWORD': '1234', 'HOST': '127.0.0.1', 'PORT': '5432', } } And to verify if my database is connected to my app I run the command python manage.py dbshell But it throws that error : CommandError: You appear not to have the 'mysql' program installed or on your path. though I have installed all the requirement: Python: 3.6 Django: 1.11 MySQL: 5.7 mysqlclient Do you have any idea to fixe that error?? -
Django - Receive signal when model is created with get_or_create
I am trying to use either pre_save or post_save signals to run code when a specific model is created. This model is part of a third-party application and as such, is not created directly in my code. The third-party code uses get_or_create to create the object. Since get_or_create is wrapped in an atomic transaction, the pre_save and post_save signals are not received when an instance is initially created (only when it gets updated). I see that an on_commit method has been added, but it takes no arguments. As such, it looks like it is made to do something after every single SQL transaction is committed, not just when a specific model is saved. It is a bit confusing to me that django does not seem to have a signal that can be received when get_or_create is called, so it makes me feel like I am misunderstanding something. How can one run code when a new instance is created with get_or_create -
What are common practices using connection draining during deployments to prevent breaking long running websocket connections?
I have a Django app using Django Channels deployed to a single server in a large organization. Currently we use double forking to deploy code without breaking the long running websocket connections. These connections have complex objects in memory such as sockets and things that can't be persisted. They are very stateful. This works well for us now but I've refactored our code for Channels 2 and took out the double forking. It always seemed hacky to me. These connections are proxied through Nginx and run with the Daphne application server on a CentOS VM. What are the common tools used to manage multiple instances of an application and drain one instance's connections while sending new connections to another instance? I can get more servers if I need them. I looked at Circus. It seems like it might be able to accomplish what I'm looking for but it seems to be abandoned. Other than that I couldn't find much information on this topic that wasn't specific to something like EC2. -
Django CMS Placeholder alternatives for Django 2.0
I have a site in django 2.0. I would like to be able to edit various content -such as social media links, about text, site title, and much more- via the django admin. I understand that I could use the Django CMS placeholder in a model and connect that to the html and admin interface and database. However, django cms seems to only support up to django 1.9 and really all I need is the place holder aspect of it and nothing else of django cms. Is there any way I can accomplish this placeholder affect / user editable content in plain django / python? Or perhaps another django plugin that supports django 2.0? I am not really looking for anything elaborate. -
How to get user instance in some other function (outside view)
I am trying to create a Hotel Booking Portal. So, A person will enter the number of rooms he/she wants and then in the admin, that amount of admin.TabularInline fields will be formed. I am not able to get the number of rooms he wants from the model. After I get the number of rooms, my code will somewhat look like this. admin.py class BookingInfoInline(admin.TabularInline): model = Visitor extra = no_of_rooms Any idea, about how can I do this?? -
Grap external website with authentication inside of django
I grab the content of a website with this script: from requests import session cred = { 'action': 'login', 'email' : 'e@mail.com' , 'password' : 'topsecret' } with session() as c: c.post('https://website.com/login', data=cred) response = c.get('https://website.com/data') file = open('data.html','w') file.write(response.text) file.close When I run this code it works fine. When I run it with django the login works well but the https://website.com/data say's that I am not authorized. -
Passing instance values of a model to another different model instance in django
I am relatively new to django and have a problem regarding passing some information from one model to another. Its not quite inheritance but rather ensuring that a parent model passes certain information upon creating a child model. So I have two models, one for Events and another for Occurrences. The Events is run via admin and when you create an event it also creates occurrences for that event. My problem is that each event is in a specific city and I would like it to pass the city value to the occurrences it creates so that I can use that city value in a filter. It should be noted, an occurrence is not an Event so this is not simply just multi-table inheritance. How do I pass on this value? Models.py # The events are models that contain the what and where. class Event(models.Model): class Meta: verbose_name_plural = 'Events' verbose_name = 'Event' created = models.DateTimeField(auto_now=False, auto_now_add=True, blank = False, null = False, verbose_name = 'Creation Date') #Date Event was edited for the last time updated = models.DateTimeField(auto_now=True, auto_now_add=False, blank = False, null = False, verbose_name = 'Updated') #Name of the event name = models.CharField(max_length = 400, null=True, blank = … -
Django Multi-Conditional Statement
I have the following code working in a Django HTML template. However, it’s quite repetitive. How can this code be simplified? It translates to, "If you're not staff, you get to see nav.html. If you are staff, you only get to see nav.html if you're on these 4 pages." {% if not request.user.is_staff %} {% include ‘nav.html’ %} {% else %} {% if request.get_full_path == ‘/one/’ %} {% include ‘nav.html’ %} {% if request.get_full_path == ‘/two/’ %} {% include ‘nav.html’ %} {% if request.get_full_path == ‘/three/’ %} {% include ‘nav.html’ %} {% if request.get_full_path == ‘/four/’ %} {% include ‘nav.html’ %} {% endif %} {% endif %} -
Python Django manage.py shell Attribute error module 'ast' has no attribute 'AnnAssign'
So i'm working on this test app in django and i wanted to add some data to my sql tables through the python shell. I ran the following command from the CMD λ python manage.py shell Which gave me the following output: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Python\lib\site-packages\django\core\management__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Python\lib\site-packages\django\core\management__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Python\lib\site-packages\django\core\management\commands\shell.py", line 99, in handle return getattr(self, shell)(options) File "C:\Python\lib\site-packages\django\core\management\commands\shell.py", line 35, in ipython from IPython import start_ipython File "C:\Python\lib\site-packages\IPython__init__.py", line 55, in from .terminal.embed import embed File "C:\Python\lib\site-packages\IPython\terminal\embed.py", line 15, in from IPython.core.interactiveshell import DummyMod, InteractiveShell File "C:\Python\lib\site-packages\IPython\core\interactiveshell.py", line 109, in _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign) AttributeError: module 'ast' has no attribute 'AnnAssign' Im using Python 3 and django 2.0.3 Some things i tried on my own: I checked so ipython was up to date using pip, my database runs on SQL community server runs and works fine and the django server itself also runs without issues. Thanks alot in advance // New django fan ;) -
Wagtail User with Moderator role unable to log in to CMS Admin
I am using Wagtail 2.0 Wagtail 2.0 comes with default groups Editors and Moderators. Moderators group also has the checkbox "Can access wagtail admin" and is checked by default. I have created a user and set him as a moderator. When I am trying to log in with the moderator credentials. I am getting the error "You do not have permission to access the admin". But I want the moderator to access the CMS Admin interface. How can I accomplish this? Thanks in advance. -
Django Serializer Object is not JSON Serializable
so I'm working on a website that utilizes Django and having trouble with this one serializer. Here is the code: class DataPointSerializer(serializers.ModelSerializer): value = serializers.DecimalField(max_digits=30, decimal_places=15) sensor = serializers.ChoiceField(choices=list(Sensor.objects.all())) point = serializers.ChoiceField(choices=list(MapPoint.objects.all())) class Meta: model = DataPoint fields = ('__all__') def create(self, attrs, instance=None): return DataPoint(value=attrs['value'], sensor=attrs['sensor'], point=attrs['point']) My DataPoint model uses value as a decimal field, sensor as a foreign key, and point as another foreign key. I'm using the choice fields to fetch the objects that have been created but from the create function, I get a TypeError saying that (Sensor object) is not JSON serializable. I assume the same is happening for point but I am unsure of what to do. Any help would be appreciated! -
Django POST violates not-null constraint user_id
Having trouble finding the answer to my question even on here. I know there are posts like it but I am still not getting it. I get the error when trying to POST to my "user_profile" Below is the error and my code. django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint models.py which has a foriegnkey from django.contrib.auth.models import User from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.OneToOneField(User, on_delete=True) start_date = models.DateTimeField last_active_date = models.DateTimeField alias_name = models.CharField(max_length=30) city = models.CharField(max_length=30) state = models.CharField(max_length=30) zipcode = models.CharField(max_length=5, null=True) serializers.py from rest_framework import serializers from api.models import UserProfile class UserProfileSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) orientation = serializers.CharField(required=False, allow_blank=True, max_length=100) def create(self, validated_data): return UserProfile.objects.create(**validated_data) userprofile.py the get works fine but the post through the "violates not-null constraint" @csrf_exempt def user_profile_list(request): if request.method == 'GET': orientation = UserProfile.objects.all().values() list2 = list(orientation) return JsonResponse(list2, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = UserProfileSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400)