Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use different SQL data depending on url in Django
If i have a url that is "someurl/report/1/" where "report" is an app and "1" corresponds to a certain id of a model in my SQL database, how would i substitute the variables in the template with that specific models data? In my case I am writing a website that displays a surf report for different beaches. I have set it up so each SQL model id corresponds to a different beach. So if I wanted to use the data of beach "3" in the template, how would i display those in the html template? #MY TEMPLATE <!DOCTYPE html> <html> {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'report/css/style.css' %}"/> <link href="https://fonts.googleapis.com/css?family=Biryani:300,400,800" rel="stylesheet"/> <head> <title>REALSURF</title> </head> <body> <h1> <form id="search"> <input id="search" type="text"> </form> </h1> <div class="container"> <div class="column"> <div class="text">Wind</div> <div class="number">{{Break.wind}}</div> </div> <div class="column"> <div class="text">Wave Height</div> <div class="number">{{Break.low}}-{{Break.high}}</div> </div> <div class="column"> <div class="text">Tide</div> <div class="number">{{Break.tide}}</div> </div> </div> <h2> REALSURF </h2> <h3> A simple site by David Owens </h3> </body> </html> #MY MODEL from __future__ import unicode_literals from django.db import models # Create your models here. class Break(models.Model): name = models.CharField(max_length=50) high = models.SmallIntegerField() low = models.SmallIntegerField() wind = models.SmallIntegerField() tide = models.DecimalField(max_digits=3, decimal_places=2) def __str__(self): return … -
Include urls for django-registration
So i just installed django-registration and got the templates from https://github.com/macdhuibh/django-registration-templates I'm getting a problem with the URL resolver, I get Reverse for 'auth_password_reset' with arguments '()' and keyword arguments '{}' not found. as well as many others.... urls.py: #Other stuff, url(r'^accounts/', include('registration.backends.hmac.urls')), Exactly as the docs specify. Furthermore here's the html that throws the error. It's from login.html from the github. It's the one that threw this error but it seems i get something similar every time i try doing a reverse match on a url from the auth_url.py of django-registration. {% extends "main/header.html" %} {% load i18n %} {% block content %} <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans 'Log in' %}" /> <input type="hidden" name="next" value="{{ next }}" /> </form> <p>{% trans "Forgot password" %}? <a href="{% url 'auth_password_reset' %}">{% trans "Reset it" %}</a>!</p> <p>{% trans "Not member" %}? <a href="{% url 'registration_register' %}">{% trans "Register" %}</a>!</p> {% endblock %} Thanks in advance. -
Set field's value during migration, based on another table value
I have 3 models in my Django project: class A(models.Model): id = models.AutoField(primary_key=True) ... class B(models.Model): id = models.AutoField(primary_key=True) a = models.ForeignKey(A, on_delete=models.CASCADE) ... class C(models.Model): id = models.AutoField(primary_key=True) b = models.ForeignKey(B, on_delete=models.CASCADE) ... So the relations are A->B one-to-many, B->C one-to-many. What I want to do is add field a = models.ForeignKey(A, on_delete=models.CASCADE) to model C, and during migration I want to set values of c equal b.a__id value. So I achieve new relation A->C one-to-many. How can i do this? I use PostgreSQL. -
Django REST framework - Getting data instead of links
I have taken a look around, and I didn't find an answer to this question. Serializers.py class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Post fields = ['title', 'body', 'comments', 'user', 'date'] class CommentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Comment fields = ['body', 'user', 'date'] class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['id', 'user'] Models.py class Post(models.Model): # Children comments = models.ManyToManyField('Comment', blank=True) # Content title = models.TextField(default="-->Title here<--") body = models.TextField(default="-->Body here<--") # About user = models.ForeignKey(User) date = models.DateTimeField(auto_now=True) object_id = models.PositiveIntegerField(default=0) content_type = models.ForeignKey(ContentType, default=0) content_object = fields.GenericForeignKey() def __str__(self): return str(self.title) class Comment(models.Model): comments = models.ManyToManyField('Comment', blank=True) # Content body = models.TextField(default="-->Body here<--") # About user = models.ForeignKey(User) date = models.DateTimeField(auto_now=True) object_id = models.PositiveIntegerField(default=0) content_type = models.ForeignKey(ContentType, default=0) content_object = fields.GenericForeignKey() def __str__(self): return str(self.body) Views.py class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer def index(request): return render(request, 'index.html', []) The index template is a "homepage" that loads the latest posts. Under each post, I'm showing the comments. In the JSON those are links, and I found out how to load them trougth the links (so it's working). Someone told me … -
python manage.py migrate [add new model to database]
I am doing the tutorial on djangogirls.org website for creating a blog. I am attempting to add a new model to the database and I did the following: $ python manage.py makemigrations blog I get list of errors as such: Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/marty/swapper/venv/local/lib/python2.7/site-packages/django/core/management/init.py", line 367, in execute_from_command_line utility.execute() File "/home/marty/swapper/venv/local/lib/python2.7/site-packages/django/core/management/init.py", line 341, in execute django.setup() File "/home/marty/swapper/venv/local/lib/python2.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/marty/swapper/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/marty/swapper/venv/local/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/home/marty/swapper/blog/models.py", line 4, in from django.util import timezone ImportError: No module named util I am stuck. Proud noob. thanks, Marty -
django-websocket-redis development server not working
I'm working on a Django app that's using the django-websocket-redis app to publish events from the server side. I've successfully configured a test server using nginx and uWSGI to route both HTTP and WS requests correctly to my Django app, but on my local development environment I cannot get this working. According to the django-websocket-redis documentation, it's enough to start the Django development server and everything should work fine, but it seems like this is far away from reality. Here is what I've checked: redis is running on localhost:6379 and is responding to PING requests tried to run the server on different ports (80, 8080, 8000) to check if the django-websocket-redis makes any assumption about the development server's port, but nothing changed searched for solution online, but there is nothing about this topic On my local environment on the client side I see a 404 error when my app tries to connect to the local WebSocket. My settings.py sets the WEBSOCKET_URL to the correct URL (on test server it's working, but locally isn't). Anyone has an idea what am I doing wrong? Thanks! -
How to link between views of different apps django 1.10
In Django 1.10 they have seemingly changed a lot of things about urls and there are very little examples outside of the official documentation of its new usage. All I want to be able to do is when a user clicks on a link in the navbar, they will be directed to a view in a different app which renders a different template (like a link in index.html going to newpage.html). I know it is such a simple thing to do in basic html, but it feels like the new updates in Django 1.10 have made it nearly impossible to do. -
django and bootstrap carousel - use offline
I am using bootstrap offline with {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} in my template, but the code for the first carousel shown here http://www.w3schools.com/bootstrap/bootstrap_grid_basic.asp does not work unless I have the CDN links: link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> what {% %} do i need to make carousel work? -
Setting model user to current user when using inlineformset_factory in Django
I've hit a roadblock that I've spent hours trying to overcome, and I would appreciate some guidance. I have two models: Listings and Addresses, with the following structure: class Listings(models.Model): created_date = models.DateTimeField(auto_now_add=True) pub_date = models.DateTimeField(auto_now_add=True) address = models.ForeignKey(Addresses) user = models.ForeignKey(User, on_delete=models.CASCADE) is_active = models.BooleanField(default=1) class Addresses(models.Model): address1 = models.CharField(max_length=100) address2 = models.CharField(max_length=100) address3 = models.CharField(max_length=100) address4 = models.CharField(max_length=100) postcode = models.CharField(max_length=8) I also have these: class AddressForm(ModelForm): class Meta: model = Addresses fields = ['address1', 'address2', 'address3', 'address4', 'postcode'] class ListingForm(ModelForm): class Meta: model = Listings fields = ['user'] I'm trying to create a form which will add a new listing, however the only information to be entered are the fields in the Addresses model. When the form is submitted, I need a new Listings object and a new Addresses object to be created, but the Listings object must have the 'user' foreign key equal to the id of the current logged-in user. This is the view: @login_required(login_url='share:login_view', redirect_field_name='share:addlisting') def addlisting(request): ListingInlineFormSet = inlineformset_factory(Addresses, Listings, form=ListingForm, can_delete=False, extra=1) if request.method == 'POST': address_form = AddressForm(request.POST) if address_form.is_valid(): new_address = address_form.save() listing_formset = ListingInlineFormSet(request.POST, request.FILES, instance=new_address) if listing_formset.is_valid(): listing_formset.save() return HttpResponseRedirect(reverse('/listing_added/')) else: address_form = AddressForm() listing_formset = ListingInlineFormSet() return … -
Where to define Celery subtask queues
I have a pluggable app I'm developing for a Django system. In it, I have a task for creating notifications that looks something like so: installable_app.tasks @app.task(name='tasks.generate_notifications') def generate_notifications(...): I have a pluggable app I'm developing for a Django system. In it, I have a task for creating notifications that looks something like so: installable_app.tasks @app.task(name='tasks.generate_notifications') def generate_notifications(...): clients = get_list_of_clients() for client in clients: client_generate_notification.delay(client['name'], client['id']) return "Notification Generation Complete" @app.task def client_generate_notification(client_name, client_id): ... return result Now I want this to run periodically which can be accomplished with Celery Beat using settings. I also want it to be on its own queue: settings.py: CELERYBEAT_SCHEDULE ={ {'generate_schedule_notifications': { 'task': 'tasks.generate_notifications', 'schedule': crontab(hour=6, minute=0), 'options': {'queue': 'notification_gen'}, 'args': ('schedule', 'Equipment', 'HVAC')}, } } The first task, generate_notifications is run correctly on the queue notification_gen but the client_generate_notification subtasks are run on the default queue. I know I can specify the queues specifically in the @task decorator but since this is a django app, I would rather they be specified where it is actually run. I've looked into using the CELERY_ROUTES option but when I tried it, it seemed to overwrite the queues for other tasks I was running. Is the … -
500 error when requesting data from Django-rest API from other Django app
I built a small API using the Django rest framework and deployed it on elastic beanstalk. It works great when querying it from a script or the browser, but I cant seem to get it to work when requesting from another django app, using the requests library. I can obtain a token without issue, but I get a 500 Server Error whenever actually asking for data. I'm not sure how to debug this. Here is the request from views.py: token = blahblahblah324y92432489320ffiweojf239208 header = { "Authorization": 'Token {var}'.format(var=token) } payload = { 'fromDate':from_date, 'toDate':to_date } req = requests.post("http://www.blahbllahblah.com/api/blah/blah/", headers=header, json=payload) I just cant find much info on how to resolve this error, nor on whats actually going wrong. Has anyone else experienced this? Any tips on how to get more info? Happy to post any code/logs that might be useful. -
shopify_auth multi store session handling
I am using Django with the shopify_auth package to connect with Shopify. Does anyone have any examples of how to handle multi store sessions/connections? So far, I am thinking of modifying shopify_auth's @login_required decorator with the following, but am unsure if I will miss anything with this: In shopify_auth/decortaors.py: def login_required(f, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): @wraps(f) def wrapper(request, *args, **kwargs): if request.user.is_authenticated(): # Extract the Shopify-specific authentication parameters from the current request. new_request_d = [ ... get request.GET params ('shop', etc.) ... ] # Compare current active request.user with new reqeust.GET's 'shop' if request.user != new_request_d['shop']: [ ... do something to change session to the other shop ...] [ ... redirect as necessary .... ] return f(request, *args, **kwargs) In the shopify_auth module their is an unresolved issue about this. It hints at using the ruby implementation. Any help in the right direction would be appreciated. -
Dynamic field values are save and update
I have created one model file where i have defined table and under the table i have created some fields like:-teacher(foreign key),id(primary key),title,location etc. Now i have created one Django's API which saved data into the database. The problem statement is that we don't know which field will be update and insert by the User. Example:- if the first time i have saved the title filed into the database and then i want to save location. How i can handle to save and update the location value without effecting the title. For User interaction we are using angular1.x. -
Unable to increase Gunicorn Timeout
I am getting a 502 Bad Gateway error and am realizing it is probably a timeout from Gunicorn. I'm attempting to increase Gunicorn's default timeout from 30 seconds to something higher, probably 5 minutes, but despite my config file change, the time out is still happening at 30 seconds. I realize the first order of action is to resolve the server-side process so it doesn't take longer than 30 seconds. In this case, however, I'm running a large sql sproc report and it sometimes takes longer than 30 seconds because of the amount of data being churned. Below are my nginx and gunicorn config files. Thanks for any help! gunicorn.conf: description "Gunicorn application server handling formManagement django app" start on runlevel [2345] stop on runlevel [!2345] respawn setuid ubuntu setgid www-data chdir /home/ubuntu/AARC-ServiceManager/ServerSide/formManagement exec ve/bin/gunicorn --timeout 300 --workers 3 --bind unix:/home/ubuntu/AARC-ServiceManager/ServerSide/formManagement/formManagement.sock formManagement.wsgi:application nginx.conf: user www-data; worker_processes 4; pid /run/nginx.pid; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## # set client body size (max http request size) # client_max_body_size 50M; #upping the timeouts to allow time for the DB to return from a long running sproc proxy_connect_timeout 300s; proxy_read_timeout 300s; sendfile on; tcp_nopush on; … -
django-rest-framework:- how to display custome phonenumber instead of username
I am using phone number and password for authenticating user. But my django-rest auth is showing me username instead of phone number. Entering phone number works just fine How can i get rid of the username placeholder and replace it with phone number. -
Error in starting new project in Django
So I am starting up with Django. I installed python, and when I run python in the CMD, it runs well. Next, I downloaded and installed Django, went into the python shell, imported django and outputed its version successfully. Finally I made a new directory for my project, entered: django-admin.py startproject mysite and I got the following error: Type 'django-admin.py help <subcommand>' for help on a specific subcommand. Available subcommands: [django] check compilemessages createcachetable dbshell diffsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate runserver sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). Did I do something wrong in Django's installation? -
Django slug link edit page not found
I'm having trouble, when I use slug for my url. it said no post matches the query. The troubles occuring in edit and delete page, it turns out still working fine within the detail page. But the weird thing is the 404 error was raised by post.views.post_detail, not post_update. my urls inside the post app urlpatterns = [ url(r'r^$', post_list, name='list'), url(r'^create/$, post_create, name='create'), url(r'^(?P<slg>[\w-]+)/$, post_detail, name='detail'), url(r'^(?P<slg>[\w-]+)/edit/$, post_edit, name='edit'), url(r'^(?P<slg>[\w-]+)/delete/$, post_delete), ] the views def post_detail(request, slg=None): instance = get_object_or_404(Post, slg=slg) context = { "title":intance.title, "instance":instance } return render(request, "post_detail.html", context) def post_update(request, slg=None): instance = get_object_or_404(Post, slg=slg) form = PostForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(instance.get_absolute_url()) message.success(request, "Saved", extra_tags = 'some-tags') context = { "title":instance.title, "instance":instance, "form", form, } return render(request, "post_form.html", context) the get_absolute_url function also already return slg. the only problem is the post not found in edit page, even the slg title has a match with the current available posts. thank you. -
Django map Urls
Hello I am new to django, I have created a simple app for category wise product. for that I wanted to display as below url patterns. / -> Home page /product -> category page /product/product_name -> product page to achieve this I have wrote a below code. myapp/urls.py file import product urlpatterns = [ url(r'^manage/', admin.site.urls), url(r'^', include(product.urls)), url(r'^product/', include(product.urls)), ] in myapp/product/urls.py (I am managing app wise urls) from views import product_name, product_root urlpatterns = [ url(r'^', product_root, name="ProductRoot"), url(r'^product_name/', product_name, name="ProductName"), ] Now when I runs the app and browse the page it gives me below result. / -> product category page /product -> product category page /product/product_name -> product category page (but it should be product page) /product/product_name/any_value -> product category page (Should return 404) Can anyone guide me what I am doing wrong? -
TypeError: __str__ returned non-string (type PhoneNumber)
I am using PhoneNumberField in my django-rest-api application class User(AbstractBaseUser, PermissionsMixin): phone_number = PhoneNumberField(_('phone number'), unique=True) i was successful creating superuser with phonenumber and password.But each time am running the server i get error TypeError: __str__ returned non-string (type PhoneNumber) Can someone please help me -
django - underscoring foreign keys - pros and cons
As PEP8 states, one should name classes that have several words with camelcase (e.g. ProfileAttributeGroup), and use underscores for variables (profile_attribute_group). However when it comes to django and reverse relations (and templates), we are forced to use lowercased name of classes. For example, if our ProfileAttributeGroup has a one-to-one key to a Profile model, the reverse lookup would be profile.profileattributegroup. Also, this lowercasing happens in DetailView and UpdateView templates and in sql joins (e.g. someattr.filter(profileattributegroup__isnull=False)). This makes me think that it makes sense to just lowercase foreign key names, without adding any underscores there. This way I won't have to remember when to use profile_attribute_group or profileattributegroup. But explicit ignoring of underscores contradicts PEP8. My question is, has anyone else had my doubts? And are there any future downsides of ignoring underscores that I haven't thought about? -
Django - AttributeError: 'module' object has no attribute 'TEMPLATE_CONTEXT_PROCESSORS'
I have got a python App on production that crashed. When trying to open the website I get a 502 bad gateway. After trying to restart the django app using python manage.py restart I got the following error. Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 316, in execute settings.INSTALLED_APPS File "/usr/lib64/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/usr/lib64/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/lib64/python2.7/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/ringier/expat/expat/expat/expat/settings/__init__.py", line 12, in <module> from expat.settings.production import * File "/ringier/expat/expat/expat/expat/settings/production.py", line 4, in <module> from expat.settings.base import * File "/ringier/expat/expat/expat/expat/settings/base.py", line 89, in <module> TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + ( AttributeError: 'module' object has no attribute 'TEMPLATE_CONTEXT_PROCESSORS' I didn't change anything on the code nor the configs, I don't know why this is happening. I checked similar errors but they didn't resolve this issue. Thanks -
Django error when trying to edit an entry - Cannot resolve keyword 'count' into field
I am getting a FieldError when I try to edit certain models in the Django admin. As far as I can tell, this started happening after I started using .annotate() in some of my ModelAdmin classes. The error shows up if I try to edit a Profile or a Photo. It also shows up if I try to edit a token (I am using Django REST Framework). What's confusing me though is why Token is also breaking; I have't touched that model at all. Here are the relevant models: class User(AbstractBaseUser, common_models.EditMixin, PermissionsMixin): age = models.PositiveSmallIntegerField(blank=True, null=True) avatar = models.ImageField(upload_to=common_models.get_uploaded_file_path, blank=True, null=True) email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=64, blank=True, null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False, verbose_name='staff account') last_name = models.CharField(max_length=64, blank=True, null=True) username = models.CharField(max_length=255, unique=True) USERNAME_FIELD = 'email' class Profile(models.Model): user = models.ForeignKey(User) bio = models.TextField(blank=True, null=True) cover_image = models.ImageField(upload_to=common_models.get_uploaded_file_path, blank=True, null=True) gear = models.TextField(blank=True, null=True) class UserAction(models.Model): ACTION_CHOICES = ( ('photo_click', 'Photo Click'), ('photo_imp', 'Photo Impression'), ) user = models.ForeignKey(account_models.User) action = models.CharField(max_length=32, choices=ACTION_CHOICES) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class PhotoClassification(models.Model): CLASSIFICATION_TYPE_CHOICES = ( ('category', 'Category'), ('tag', 'Tag') ) classification_type = models.CharField(max_length=32, choices=CLASSIFICATION_TYPE_CHOICES, default='tag') name = models.CharField(max_length=64) public = models.BooleanField(default=True) class … -
Python/Django - Where do I have to make methods that perform like DML?
'Methods that perform like DML' means methods that change data in the database. Is there a standard or guideline for that? Below are my own guesses. Collect all functions in file of which name is like 'data_access.py' Contain functions in each class of models.py There is no standard. No one will blame even if I make them in views.py Above all are wrong. -
Django - combine DetailView and ListView
I am new to Django and I want to build a web app that shows you a list of your events. You can have several different lists (like for sport events, birthdays...). I have made two models - Calendar (list of events) and Event. On my page I have nav menu, where you can see a list of your "calendars". When you click on one calendar you can see a list of events for that calendar, but also I want to keep a list of calendars in the side bar. As I understand Django I need two views for that - ListView (for sidebar calendars) and DetailView (for events on each calendar). Here are my views: class DetailView(generic.DetailView): model = Calendar template_name = 'koledarji/detail.html' class CalendarsView(generic.ListView): template_name = 'koledarji/calendars.html' context_object_name = 'calendars_list' def get_queryset(self): return Calendar.objects.all() With that approach my details on every specific calendar are ok, but I lose my list of calendars on the sidebar nav menu. My url for specific calendar: url(r'^(?P<pk>[0-9]+)$', views.DetailView.as_view(), name='detail'), and a part of my template: {% extends 'prijavljen/calendar.html' %} {% block cal_name %} {% for calendar in calendars_list %} {% if request.path == '/prijavljen/'|add:calendar.id %} {{calendar.name }} {% endif %} {% endfor … -
OnetoOneField Django query
so I have this two models: class Patient(models.Model): patientID = models.CharField(max_length=200 , default='Enter PatientID') age = models.IntegerField(default='-') gender = models.CharField(max_length=200,choices=Gender_Choice, default='UNDEFINED') class RiskFactor(models.Model): patient = models.OneToOneField(Patient, on_delete=models.CASCADE) hypertension = models.BooleanField(default=False) diabetes = models.BooleanField(default=False) PAVK = models.BooleanField(default=False) nicotin = models.BooleanField(default=False) So I've changed from ForeignKey to OnetoOneField because of reasons. So with the ForeignKey everything was easypeasy and I can show the data of the RiskFactor model in my Patient detail template. Now I have problems to change the query. I just don't know how to change this: <ul> {% for rfac in patient.riskfactor_set.all %} <li>Hypertension: {{ rfac.hypertension }}<br/> Diabetes: {{ rfac.diabetes }}<br/> PAVK: {{ rfac.PAVK }}<br/> Nicotin: {{ rfac.nicotin }}<br/> </li> {% endfor %} </ul> into sth that shows the riskfactor data from the patient with a OneToOneRel. Thanks for your help!