Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make field unique with other models
I have 3 different models, and they all have index field (small positive integer number). How to make them unique with each other? I was trying to override save model in models.py, and this is work pretty good, except ValidationError exception. It redirect me to the error page, and if i turn Debug=False, it will nothing show me at all, just "error 500" or something like that. It would be great if this validation show message in admin's page, without refreshing. Maybe someone know how to validate this properly, or how to make this in other way? -
Python + Django: Trouble with setting up mkvirtualenv on macOS
I’m trying to dabble around with Python and Django and am getting stuck on what is probably a dumb issue. I’m using macOS and have installed Python v 3.6.4 I'm trying to follow the instructions per this Mozilla article: [https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/development_environment][1] I only know enough terminal commands to be dangerous (which is why I'm learning) and I'm very much a Python n00b, so please be nice. :) My process: 1 which python » /usr/local/bin/python note, somewhere along the way I did a Symlink ln -s /usr/local/bin/python3 /usr/local/bin/python 2 python3 -V » Python 3.6.4 3 sudo -H pip3 install virtualenvwrapper » Requirement already satisfied: virtualenvwrapper in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages Requirement already satisfied: stevedore in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from virtualenvwrapper) Requirement already satisfied: virtualenv in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from virtualenvwrapper) Requirement already satisfied: virtualenv-clone in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from virtualenvwrapper) Requirement already satisfied: pbr!=2.1.0,>=2.0.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from stevedore->virtualenvwrapper) Requirement already satisfied: six>=1.10.0 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from stevedore->virtualenvwrapper) 4 nano .bash_profile » Add following: » export WORKON_HOME=$HOME/.virtualenvs export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3 ## is this the issue? export PROJECT_HOME=$HOME/Devel source /usr/local/bin/virtualenvwrapper.sh 5 mkvirtualenv my_django_environment » Running virtualenv with interpreter /usr/local/bin/python Using base prefix '/usr/local/bin/../../../Library/Frameworks/Python.framework/Versions/3.6' New python executable in /Users/myuser/.virtualenvs/my_django_environment/bin/python ERROR: The executable /Users/myuser/.virtualenvs/my_django_environment/bin/python is not functioning ERROR: It thinks sys.prefix is '/Library/Frameworks/Python.framework/Versions/3.6' (should be '/Users/myuser/.virtualenvs/my_django_environment') ERROR: … -
python virtual environment change
I am a beginner for django framework. I am working on multiple tutorial projects. According to best practices , I use different virtual environments for different projects. I have a problem. When I want to switch to another project , even through I deactivate virtual environment of closed project , my browser still looks to the virtual environment that I deactivated. So , I can not display my new project at http://127.0.0.1:8000/ . It still display the older one. Can you please show me the way? Thanks. -
How to make related dropdown search filter with Django
So for a while I had trouble with this... I have more models like: Faculty, Department, Study Programme and Courses. Now, based on these models I want to show specific courses. Like for faculty of biology, department of sciences, study programme of science, I want to list all courses in that study programme, specific to the department, specific to faculty. I want to make each of this in a dropdown and then to display results on page. I did some research and found something about using Ajax, but I don't know how to use that thing. Considering the attached models, how should I do this ? class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) slug = models.SlugField(max_length=140, unique=True) class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "PhD Studies"), (3, "Integrated Studies")), default=0) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) class Department(models.Model): faculty = models.ForeignKey('Faculty', on_delete=models.CASCADE) name = models.CharField(max_length=50) class Faculty(models.Model): name = models.CharField(max_length=50) -
Data intensive application with Django?
I am trying to build a data intensive web application in Django. When I start this django application, I want it load a large amount of data (a few Gigabytes) into memory, and then whenever I receive a request, I will use the preloaded data to do some computation and generate a response based on the complicated calculations. I am wondering what might be the best way to organize this application. What will be the best way to build another layer that running purely on Python and Django can interact with the isolated running Python program for the calculation results. -
Django forms not sh
For some reason, my forms.py doesn't view any of the fields, instead, it only shows the 'Add' button and I don't know what to do anymore. I'd really appreciate if someone who knows what they're doing could tell me what I did, or didn't do. Please note that I'm new to Django, thank you. Here's my views.py: from django.shortcuts import render from django.utils import timezone from .models import Measurement from .forms import MeasurementForm from django.views import generic class IndexView(generic.ListView): model = Measurement context_object_name = 'measurement_list' template_name = 'index.html' queryset = Measurement.objects.all() def new_measurement(request): if request.method == "POST": form = MeasurementForm(request.POST) if form.is_valid(): measurement = form.save(commit=False) measurement.measurement_date = timezone.now() measurement.save() else: form = MeasurementForm() return render(request, 'index.html', {'form': form}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ] forms.py: from django import forms from .models import Measurement class MeasurementForm(forms.ModelForm): class Meta: model = Measurement fields = ('measurement_value', 'measurement_unit') index.html: {% extends "base.html" %} {% block content %} <h1>Climate Measurement Tool</h1> <h2>Add a new measurement</h2> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save">Add</button> </form> <h2>Measurements</h2> {% if measurement_list %} <ul> {% for measurement in measurement_list %} <li> <p>{{ measurement }}</p> </li> … -
How do I insert or create data with Django ORM programmatically? Or how do I specific Model field name with a string?
If I have: class Tag(models.Model): number = models.IntegerField() config = { "data": 1, "field": "number" } How do I do the following? record = Tag(config["field"], config["data"]) record.save() -
Django REST Framework- how can I create or update a foreign key object when POSTing parent
I am currently working on an API view, for a Job Planning system. Each Job, has a single JobPlan (which has a start and end date) and each JobPlan, may have several JobPlanManagers, users assigned to manage said Job. User one might be in charge of one month, and User two might overlap User 1, but extend the job by a couple of weeks. Thus, when User 2 POSTS their new JobPlanManager instance, they need to either create a new JobPlan (if no plan yet exists) or update the existing JobPlan, to extend the start and end appropriately. The user's POST data would include their user ID, the Job ID, and a start and end date, something like: { "manager": (User ID), "job_plan": { "id": null, "job": { "id": (existing Job ID) }, "start": "2018-02-01", "end": "2018-02-28" } } Additionally, I would like the return of this POST call to include all fields for JobPlan and Job, nested: e.g.: { "id": (created JobPlanManager instance ID) "manager": (User ID), "job_plan": { "id": (New or existing JobPlan ID) "job": { "id": (Existing Job ID), "name": "Existing Job Name" } "start": "2018-01-02", "end": "2018-02-28" } } My models look like: class Job(models.Model) name … -
How to use bootstrap styling in django project
I have downloaded bootstrap files (css, js) and put in the static folder of my project and made changes in header section of index.html as shown in the below code. But still django can't locate bootstrap.min.css as shown in the error "GET /static/css/bootstrap.min.css HTTP/1.1" 404 1687 Project Structure Project |---Project |---static |---css |---js |---templates |---index.html |---manage.py index.html <head> {% load staticfiles %} <link rel='stylesheet' href="{% static 'css/bootstrap.min.css' %}" type='text/css' /> </head> I followed tutorials and read documentation But could not locate the problem can anybody help, thanks in advance. -
Django: running a python shell in a sandbox environment, similar to rails console --sandbox
Inside my Django project, I want to fire up a python shell wherein I can make simple changes to my database (saving new records, updating old ones, etc.) which are then automatically reverted back when I exit the shell. Essentially the same functionality as running "rails console --sandbox" in a Ruby on Rails project. I'm not looking for all the features of a traditional sandbox such as blocking web-service calls, just the basic database rollback. Is this--or something similar--possible in Django? I want to use this for testing purposes. I know I can use Django's testing infrastructure to do this, but there are some basic instances where this would be very useful (e.g. quickly confirming that a specific model functions the way I expect it to). -
How do I use a CSS attribute's value of an html element as input when submiting a form with Django?
Please first click the link to the image below to understand my question/situation. If the text below a particular species icon (circle with animal image inside it) is bold, I would like that to be used as input criteria for getting information from a database. In other words, I want to use the font-weight CSS property of a element as an input. Only one "species text" can be bold at a time. For example, if I have "D. rerio" selected (its font is bold) and I click the "search" button, I would like for the back-end to know that it needs to pull information from the "D. rerio" database specifically. Click here to see the picture of the situation I described above -
How could I extend my user model with field profile_image = models.FileField()?
I have created a form and have all criterias of name, email, password but not the image. In order to create "upload image" option, I am in need to extend my user model with field profile_image = models.FileField() Do help. -
Pre-populating dropdown menus with ViewFlow Material Forms
I am using Django and am trying to get a dropdown menu to prepopulate. This is how I am currently trying to do it in the form: {% if asset.id|stringformat:"s" == pageID|stringformat:"s" %} {% attr form.assetID "option" selected %}"selected"{% endattr %} {% endif %} As you can see, I am trying to select the asset from the dropdown menu if it's ID matches the ID that was passed into the page and change it's selected attribute to "selected" if it matches. I know this isn't the right way to do it but I haven't been able to figure it out otherwise. I have tried overriding {% part form.assetID control %} and putting this code in there but that just removes the dropdown field entirely. Is there a way to do this without just writing the whole field myself? -
Django REST: Automatically update connected model (After POST)
I would like to create an ability for users to exchange 1-to-1 messages. To do this, I would like to update fields in my Django models, depending on actions taken by the Message model. For example, I would like to update the last_message in Conversation model, each time a new message is posted. I have 2 main models: Conversation and Message, where each conversation can have many messages. Models.py class Conversation(models.Model): last_message = models.CharField(max_length=50, blank=True) class Message(models.Model): body = models.TextField(max_length=500, blank=False) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) I figured that I need to use the override the save() method in the Message class. def save(self, *args, **kwargs): super(Message, self).save(*args, **kwargs) # something that I need self.conversation.last_message = self.body In the end, I would like to send a POST request to my API endpoint e.g. /api/conversation/<id>/messages/ and it will update the Conversation object with every new latest message. -
How Could I Add Image Upload Option To The Registration Form?
My forms.py is this. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm,UserChangeForm class RegistrationForm(UserCreationForm): email= forms.EmailField(required = True) class Meta: model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' } def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() And, i have to add "upload image" option for the user so that user could upload their image from any file and load it on the profile. -
Linking two django fields in two different models
I am going slightly crazy as I am sure this is a super simple question. I have two models in django: class Play(models.Model): gid = models.IntegerField() pid = models.IntegerField(primary_key=True) off = models.CharField(max_length=5) deff = models.CharField(max_length=5) type = models.CharField(max_length=10) class FGXP(models.Model): pid = models.IntegerField() fgxp = models.CharField(max_length=5) fkicker = models.CharField(max_length=10) This is a football database and when there is a Play that scores there is another table where additional data about the extra point is held: FGXP. So in Play pid is the primary_key. In FGXP there is a link between pid and the pid in play. In my Django model should I link them? I will end up needing to join the data when I do a query. Thanks - an apologies if a duplicate. -
CreateView doesn't save related objects
I have two models: Student and Group. A group consists of multiple students and a student can be in only one group. Here are the models: class Group(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) section = models.PositiveSmallIntegerField(default=1) group = models.ForeignKey( Group, on_delete=models.SET_NULL, null=True, blank=True ) I am trying to build a form where I can select multiple students to create a group. class CreateGroupForm(forms.ModelForm): students = forms.ModelMultipleChoiceField( required=True, queryset=Student.objects.all() ) class Meta: model = Group fields = ('students', ) I am using the following view for the form: class SelectGroup(CreateView): model = Group form_class = CreateGroupForm template_name = 'selection.html' success_url = reverse_lazy('test') When I submit the form, it creates a group but the group's student_set is empty. I am guessing this is because I cannot add students to a group without saving the group first. Is there a way for me to modify this view to save the students or should I use something else? -
AWS S3 and Django - An error occurred (AccessDenied) when calling the PutObject operation
I am trying to set up media and static files storage in an AWS S3 bucket, in a Django app, and am getting the following error when I try to run python manage.py collectstatic to put the static files into the bucket: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied I am running boto3 and django storages. Have trawled through the other answers on here and tried the ideas in there first. My access key etc is correct as I can connect to SES OK. I have CORS configured in the bucket. My bucket policy is { "Id": "Policyxxx", "Version": "2012-10-17", "Statement": [ { "Sid": "Stmtxxx", "Action": "s3:*", "Effect": "Allow", "Resource": [ "arn:aws:s3:::bucketname/*", "arn:aws:s3:::bucketname" ], "Principal": { "AWS": [ "arn:aws:iam::xxxx:user/xxxx" ] } } ] } My IAM user has AmazonS3FullAccess as below: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:*", "Resource": "*" } ] } I have also tried creating my own policy and attaching that to the IAM user as follows: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:*", "Resource": [ "arn:aws:s3:::bucketname", "arn:aws:s3:::bucketname/*" ] } ] } None of these work so I am clearly missing something. Can anyone help please? -
SyntaxError: invalid syntax - Python/Django
I am trying to simply display data from my database in Django. I am getting the following error; Syntax Error My code in views.py is as follows; def InputDisplay(request): input_info = Input.objects.all() args = {"input_detail" : input_info} print args return render_to_response('Project/display.html', args, context_instance=RequestContext(request)) My if statement in display.html; {% block head %} <title> Display Measurements</title> {% endblock %} {% block body %} <div class="container"> <h1> Input Details </h1> {% for detail in input_detail %} {{ detail.id }} {{ detail.waist }} {{ detail.height }} {% endfor %} </div> {% endblock %} Any help is greatly appreciated. -
Save filled form data in Django if user is not logged in?
I search Django-way to do some non tipical feature (I think). My env is Django 2.0.2, PostgreSQL 9.6 and Python 3.6.4. So, I have model and form like: # ./app/models.py class SubscribeModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=80) # ./app/forms.py class SubscribeForm(forms.Form): phone = forms.EmailField(label='Phone Number', max_length=100) Also, my view for this model like: # ./app/views.py from django.contrib.auth.mixins import LoginRequiredMixin from users.models import User class SubscribeView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' template_name = 'app/subscribe.html' form_class = SubscribeForm def post(self, request): user = get_object_or_404(User, id=request.user.id) form = self.form_class(request.POST, instance=user) if form.is_valid(): form.save() return redirect('/') return render(request, self.template_name, {'client': user, 'form': form}) Would be great to understand what to do that logic after save form: Anonymous user fill the form and click Save; He is redirecting to login page (because LoginRequiredMixin); After enter to the site, all data which he filled — saved to his account (automatically). This feature we can see when online shopping: we choose goods, add to our cart and only later, site ask us for login to site, if we are not (for save our order). I think, my question solve saving data to request.session and re-save to DB after logged in, but I have … -
How to test without hitting database
I want to test this code without hitting the database and using pytest and pytest-mock: from django.db.model import Q from orders.models import Order def get_orders_without_comment(): return Order.objects.filter(Q(comment__exact='') | Q(comment__isnull=True})) Here is my test: import pytest from django.db.models import Q from pytest_mock import mocker from .utils import get_orders_without_comment def test_get_orders_without_comment(mocker): orders_mock = mocker.patch('orders.models.Order.objects') orders = get_orders_without_comment() orders_mock.filter.assert_called_with(Q(comment__exact='') | Q(comment__isnull=True)) Here is the pytest exception: E AssertionError: Expected call: filter(<Q: (OR: ('comment__exact', ''), ('comment__isnull', True))>) E Actual call: filter(<Q: (OR: ('comment__exact', ''), ('comment__isnull', True))>) E E pytest introspection follows: E E Args: E assert (<Q: (OR: ('p...ll', True))>,) == (<Q: (OR: ('pi...ll', True))>,) E At index 0 diff: <Q: (OR: ('comment__exact', ''), ('comment__isnull', True))> != <Q: (OR: ('comment__exact', ''), ('comment__isnull', True))> E Use -v to get the full diff What am I doing wrong? -
Why django is not accepting spaces in template?
{% %} means that this is a django template delimiter. So inside {% %} the space should not matter I guess. Now in the example: <a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a> This is showing expected output whereas <a href="{% url 'post_detail' pk = post.pk %}">{{ post.title }}</a> is showing error. Why this is sensitive to whitespace? -
Django Attribute Error: object has no attribute '__state' and removing __init__ from Class
I'm trying to create a model for a sample Django application "webshop", and I'm having trouble at understanding what my problems stem from. The models.py I have is: from django.db import models class Product(models.Model): def __init__(self, title, quantity, description, image_url=""): title = models.CharField(max_length=255) self.quantity = quantity self.title = title self.description = description self.image_url = image_url def sell(self): self.quantity = self.quantity - 1 and what I want to be able to do with it is to initialize it with something like: toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10) I can call it with print(toy1.quantity) print(toy1.title) toy1.sell() and so on fine, but doing toy1.save() returns the error AttributeError: 'Product' object has no attribute '_state' Upon googling about the problem, I came across the fact that it's not advised to use init here, but the offered alternatives in https://docs.djangoproject.com/en/1.11/ref/models/instances/#creating-objects both utilize a logic where the first call of the class function is different from the initial call. If the problem I'm facing is due to relying in __init__, how can I get rid of it while still being able to initialize the objects with toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10) or is my problem something completely different? -
Join related models in django rest framework
Trying to create an API method for getting user profile. The problem is that there are two tables related to user: built in django User and SocialAccount from allauth framework. I guess the joining part should be in serializers so after a research I came up with this: from rest_framework import serializers from django.contrib.auth.models import User from allauth.socialaccount.models import SocialAccount class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'first_name', 'last_name') class SocialSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = SocialAccount fields = ('uid', 'provider', 'user') It works but it outputs it as nested objects: { "uid": "", "provider": "", "user": { "pk": 5, "first_name": "", "last_name": "" } } I would like it to be as one object: { "uid": "", "provider": "", "pk": 5, "first_name": "", "last_name": "" } -
Django_hosts Not Working With Django's Default Authentication
I'm using this package called django_hosts to re-route urls for some apps. Everything is working fine except for the fact that django_hosts is not working with Django Authentication. I hosted this url api.example.com, so on this page with the url api.example.com:8000/add_post, I want users to add post but before doing that you must be authenticated. So after I logged in, I still can't submit post via the form talkless of posting. But when I go back to example.com, it shows that I'm logged in but api.example.com is telling me otherwise. How do I make django authentication work with this package?