Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
serializer increases the query in django rest framwrork
I have an API that returns the data including ManyToMany relation's data as well, but when I see queries in Django Debug Toolbar so it's more than 100 queries at the backend which I think is not a good approach, even if the records increases so the queries also get increases. I just want fewer queries so the API can respond faster, is there any way to achieve it? models.py class Package(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, null=True, blank=True) project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) is_active = models.IntegerField(default=1, null=True) tags = models.ManyToManyField(Tag, related_name='packageroom') members = models.ManyToManyField(User,related_name='packages') account = models.ForeignKey(User, on_delete=models.CASCADE, null=True) class Meta: db_table = 'packages' serializers.py class PackageSerializer(serializers.ModelSerializer): tags = TagSerializer(read_only=True, many=True) # added to fetch tags details team_members = UserDetailSerializer(read_only=True, many=True) # added to fetch team members details class Meta: model = Package fields = ['id', 'name', 'description', 'project', 'tags', 'team_members'] views.py query = Package.objects.filter(project=project_id, is_active=1).prefetch_related('tags', 'team_members').select_related('project', 'account') packages = PackageSerializer(query, many=True).data return Response(packages) I just want fewer queries so the API can respond faster, is there any way to achieve it? -
Django - How to update the status of one model in the save method of another model
I have two models ''' class JobPosition(models.Model): ... position_status = models.CharField(choices=POSITION_STATUS) class Outreach(models.Model): ... outreach_status = models.CharField(choices=OUTREACH_STATUS, max_length=20) position = models.ForeignKey('action.JobPosition', on_delete=models.CASCADE, related_name='feelers') ''' I want the position_status of jobposition to be, at any time, the highest of the outreach_status of the outreaches that are related to it (feelers). Where "highest" is set by an arbitrary rule of mine that we can ignore. My thinking is to override the save method of the outreach model and make it so that when the status of the outreach changes, I trigger an update status in the jobposition model to update the status of the position. However, I am realizing that within the safe method, the status of the outreach is still not updated in the DB so if I trigger something on the jobposition model, it would not work. Any other idea? I can do everything in the outreach method but it would have to be an ugle function and I was hoping there was a better way within the jobposition model. -
Como sumar la columna de valores de los registros de una tabla clasificandolos por sus categorías que vienen heredadas de otro model django
Tengo un programa de contabilidad que recibe inputs (transacciones) del usuario, entre otros datos que tiene la tabla de transacciones llamada "Ingreso" está la columna de "Bolsillo_Afectado" y lo que quiero hacer es mostrarle al usuario sus bolsillos (o cuentas para que me entiendan mejor) y el total de dinero que tiene cada uno). Cabe recalcar que la columna de "Bolsillo_Afectado" está heredada de otra clase como ForeingKey, Aquí el codigo, espero puedan ayudarme, he batallado mucho con ello :´) models.py ------------------------------------------------------------- class Bolsillo(models.Model): Nombre = models.CharField(max_length=25, verbose_name='Nombre bolsillo', unique=TRUE) class Meta: #este va a ser la manera en la que se ordenen los datos al llamarlos desde el admin o desde las vistas ordering = ['id'] def __str__(self): #Esto será lo que devuelva el modelo al momento de mostrarse desde el administrador, se pueden poner varios campos return self.Nombre class Ingreso(models.Model): timestamp = models.DateField( default=timezone.now) Valor = models.DecimalField(null=FALSE, blank= FALSE,decimal_places=0, max_digits=10 ) Categoría = models.ForeignKey(Categoría_Ingresos, on_delete=models.PROTECT) #El tipo de relación many to many field permite u Bolsillo_Afectado = models.ForeignKey(Bolsillo, on_delete=models.PROTECT) #la propiedad PROTECT indica que no se puede borrar un registro de bolsillo si otra tabla lo está usando Nombre = models.CharField(max_length=30, blank=FALSE, null=FALSE) Usuario = models.ForeignKey(User, on_delete=models.CASCADE, related_name='form_ing' … -
consoling out django context in console
why am I getting output in console as {{request.num}} without the actual number? This is my code: def test(request): number = 4 context = {"num": number} javascript var number = "{{request.num}}"; console.log(number) -
Django get max length value from same model with Coalesce
I'm trying to write the following raw query with the ORM. I'm not sure is it possible or not. select first_name, middle_name, COALESCE(middle_name, ( select middle_name from contacts c2 where c2.first_name = c1.first_name and c2.last_name = c1.last_name and c2.middle_name is not null order by length(c2.middle_name) desc limit 1 ) ) expected, last_name from contacts c1 The expected result is like the following, if middle_name is null, get the middle name from another record that has the same first_name and last_name. id| first_name | middle_name | expected | last_name 1 | ahmet | <NULL> | burak | ozyurt 2 | ahmet | burak | burak | ozyurt DB: Postgres Django Version: 3.12 -
docker-compose django unable to connect to postgres
I'm trying to dockerize an existing django application. I've followed the example docker-compose and docker files on https://docs.docker.com/samples/django/ I've added the links and networks suggestion as see on other posts, to no avail. I've brought up the db by itself with docker-compose up db and run docker ps and confirmed it's up, accepting connections, and has the name db. I'm not sure what else to try. My docker-compose: version: '3' services: #octoprint: # image: octoprint/octoprint # restart: unless-stopped # ports: # - 16766:16766 # volumes: # - ./octoprint:/octoprint # logging: # driver: none db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: db networks: harpnetwork: harp: build: context: . dockerfile: docker/harp/Dockerfile volumes: - ./harp:/harp environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - 16765:16765 depends_on: - db networks: harpnetwork: links: - db:db networks: harpnetwork: My django db config: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } } and my Dockerfile to build the django project From python:3.10 COPY ./harp harp WORKDIR /harp RUN pip install -r requirements.txt RUN python manage.py migrate CMD ["python", "manage.py", "runserver", "0.0.0.0:16765"] -
How do I input an image that is already displayed on html?
I'm working with a webcam application and I am trying to integrate it into Django framework. This is the function that takes a photo(it's javascript in static folder): // play sound effect shutter.play(); // take snapshot and get image data Webcam.snap( function(data_uri) { // display results in page document.getElementById('results').innerHTML = '<img id="imageprev" src="'+data_uri+'"/>'; } ); document.getElementById("camera").outerHTML = ""; Webcam.reset(); } This is a fraction from my template: <div id="camera"></div> <button onclick="takeSnapShot()" type="button" id="button1" class="button-1">Take Picture</button> <form action="" enctype="multipart/form-data" method="POST"> {% csrf_token %} <div name="results" id="results"></div> <div class="button-2"> <button type="submit" href="/">Pateikti</button> </div> </form> So after picture taken, it displays an image inside < div > tag which id is "results" And now I want to save taken photograph. So I tried POST method, but when I do that, the template reloads, and the image gets lost. So I believe that's why I'm getting this error window. Also usually POST method used when you want to save files in your server which client uploads, so I'm not sure if this is the best way to do this So my question is: Is there a method to save an image to your server from a template? Or am I using POST method wrong? … -
How to permit only users with a particular domain to login? Django google authentication
I'm trying to limit the access to a page only to logged users. I used the google authentication, but it let every account to log in; instead i want to avoid every domains different from 'fermi.mo.it'. A google account like luca@gmail.com shouldn't be able to login, while an account like luca@fermi.mo.it should be able to. I noticed this code to make it, but it doesnt work. It says: "No module named 'social_core'" but i installed it. AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['fermi.mo.it'] These are all the modules that i installed: -
How Can I Create Array Form Input in Django
I have the following form input in my template that displays questions from the database. <input type="text" name="qus[{{ question.id }}]" id="qus" value="{{ question.quest }}" /> I created my Django form with: class QuestionForm(forms.Form): qus = SimpleArrayField(forms.CharField(max_length = 50)) Each time I submit the form, it does'nt work. It seems the form is not valid MyQuestionForm = QuestionForm(request.POST) if request.method == "POST" and MyQuestionForm.is_valid(): How can I create the form properly and loop through request.POST['qus'] to retrieve all the values when I submit the form? Please help. -
Problem with displaying and fitting requests in SelectMultiple, django forms
I'm having a problem displaying potential members in a select multiple select box. The usual logic is that the user submits an application for participation, and the admin approves his participation through select multiple. The problem is that in this field I have displayed all applications for all events, without any filter. I started trying other people's solutions, but even that doesn't work. These are the two forms involved class EventForm(forms.ModelForm): class Meta: model = Event fields = ('name', 'venue', 'event_date', 'participants', 'short_description', 'description') #"__all__"name widgets ={ 'name' : forms.TextInput(attrs={'class':'form-control'}), 'manager' : forms.Select(attrs={'class':'form-select'}), 'venue' : forms.Select(attrs={'class':'form-select'}), 'event_date' : forms.TextInput(attrs={'class':'form-control'}), #'participants': forms.SelectMultiple(attrs={'class':'form-control'}), 'participants' : forms.SelectMultiple( to_field_name="participants", queryset=Participant.objects.filter(attending__event=event_id, attending__is_attending=True), # error in "event_id" widget=forms.CheckboxSelectMultiple), 'short_description' : forms.Textarea(attrs={'class': 'form-control'}), 'description' : forms.Textarea(attrs={'class': 'form-control'}), } class ParticipantForm(forms.ModelForm): user = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.HiddenInput()) event = forms.ModelChoiceField(queryset=Event.objects.all(), widget=forms.HiddenInput()) class Meta: model = Participant fields = ['event', 'user'] and these are the functions def is_attending(request, event_id): """set user as attending an event.""" event = get_object_or_404(Event, id=event_id) attendance = Participant( participant = request.user, event = event, is_attending = True ) attendance.save() return redirect('show_event') in this function, one of the fields, the select multiply field, in which approval should occur only for those people whose event id matches def update_event(request, … -
Is there any way to prevent my bootsrap cards from getting nested by a django for loop?
The code is below: {% for task in tasks %} <div class="card text-center"> <div class="card-header"> <h5 class="card-title">{{ task.name }}</h5></div> <div class="card-body "> <h6 class="card-subtitle mb-2 text-muted"> Date due: {{ task.date }}. </h6> <p class="card-text"> {{ task.description }}</p> </div> {% empty %} <h4> Good to go!No tasks yet </h4> </div> <br/><br/> {% endfor %} When I run this, it nests the cards within each other as such: cards nested within each other -
Django Swagger integration not showing authenticated URls post clicking Authorize button
I am integrating Swagger with token based authentication for DRF APIs. Swagger displays documentation for all APIs when I use 'AllowAny' permission class for my API however once I start using 'IsAuthenticated' class, as expected, documentation for these APIs is not shown by default and I am presented with 'Authorize' button on UI. Once I click on it by adding valid 'Bearer JWT_Token' (which I get via calling token API via POSTMAN) it shows me 'Logout' and 'Close' button. With help of developer tools, I can see on clicking 'Authorize' button there is not server interaction, as a result of which I still unable to see documentation for these authenticated APIs. Below are settings I am using: SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { "api_key": { "type": "apiKey", "in": "header", "name": "Authorization" } } } # JWT Token Configuration SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } # REST Framework configurations REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 5, 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.AllowAny', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', … -
Django run management command from python code and fetch exit status
I'm looking for a way to run a django management command and fetch its exit status, so if sys.exit(1) is called, then I'm looking for the 1 value. Secondly, if I could fetch the output of the management command (so not return values, but the result of the print statements), that'd be also a big hit. I tried to use StringIO, but unfortunately it's not capable - imho - to fetch the exit status, and not the print statements. It's a shame, but it's still python 2.7 and django==1.11.16 . -
Create a link based on input in django
<form action="player_profile/" method="GET"> <div class="row"> <div class="col-12 col-md-9 mb-2 mb-md-0"><input class="form-control" type="text" name="nickname" placeholder="Enter player's nickname..." style="height: 48px;background: var(--bs-body-color);border: 2px solid var(--bs-yellow);font-family: Alata, sans-serif;color: white;"></div> <div class="col-12 col-md-3"><button class="btn btn-primary btn-lg" type="submit" style="background: var(--bs-body-color);border: 2px solid var(--bs-yellow);font-family: Alata, sans-serif;">Search</button></div> </div> </form> I want to create link based on nickname input. I saw the way of using javascript but how should it be done in django? -
How to bring for whom the product is ordered to on front in Django
I am more of a beginner in Django and I need some help. I have adjusted that when every order product is ordered, every vendor(staff user) can see his/her own order product but no one else's. But as an Admin I want to see to whom the order product goes to. Here is my code. class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) #many to one relation with Category title = models.CharField(max_length=150) image = models.ImageField(null=False, upload_to='images/') price = models.DecimalField(max_digits=12, decimal_places=2,default=0) amount = models.IntegerField(default=0) detail = RichTextUploadingField() slug = models.SlugField(null=False, unique=True) def __str__(self): return self.title class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() price = models.FloatField() amount = models.FloatField() def __str__(self): return self.product.title class OrderProductAdmin(admin.ModelAdmin): list_filter = ['user', 'product', 'status'] readonly_fields = ('user', 'code', 'product', 'price','quantity','amount') def get_queryset(self, request): qs = super().get_queryset(request) if request.user.is_superuser: return qs return super().get_queryset(request).filter(product__user=request.user) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "order": if request.user.is_superuser: kwargs["queryset"] = User.objects.all() else: kwargs["queryset"] = User.objects.filter(username=request.user.username) return super().formfield_for_foreignkey(db_field, request, **kwargs) -
submit button did not work after i click on that, if someone know the answer please answer me, I am actually new in django and want to solve this prob
The code i am using is on the git hub and i am trying to conver this website in django webapp. https://github.com/divanov11/StudyBud/tree/master/base facing a weird issue that after all why submit button did not work if any seniour here so please answer me... HTML Files: <div class="form__action"> <a class="btn btn--dark" href="{% url 'settings' %}">Cancel</a> <button class="btn btn--main" type="submit">Update</button> </div> This is the python file below and it looks like everythings is ok here PYTHON-models.py from django.db import models from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, ) image = models.ImageField( default='default.jpg', upload_to='profile_pics', ) class UserUpdateForm(forms.ModelForm): email = models.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): image = models.ImageField() class Meta: model = Profile fields = ['image'] This is another the python file below and it looks like everythings is ok here too PYTHON-views.py from django.shortcuts import render, redirect from .models import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators import login_required @login_required def profile(request): return render(request, 'users/profile.html') @login_required def settings(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.settings) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() return redirect('profile') else: u_form = UserUpdateForm(request.user) p_form = ProfileUpdateForm(request.user.profile) … -
Django-HTML: Prompt Asking For Password When Pressing A Button
i would like to add a prompt everytime someone tries to press the button to 'Delete' and to 'Download' a file (in my project, you can upload files with passwords, so that if someone want to delete/download the file, he needs to enter a password). the password itself is saved in the models.py using django - how would i be able to to so in my code (listing my viwes.py to the html code, urls.py, models.py, forms.py, HTML CODE Itself) Thanks a lot. @login_required(login_url='login') def My_Files(request): files = File.objects.all() return render(request, 'home/My Files.html', {"files" : files}) path("MyFiles", views.My_Files, name="my_files"), path("MyFiles/<int:pk>/", views.delete_file, name="delete_file"), {% extends 'layouts/base.html' %} {% load static %} {% block title %} {% endblock title %} <!-- Specific CSS goes HERE --> {% block stylesheets %}{% endblock stylesheets %} {% block content %} {% include "includes/footer.html" %} <h2>My Files</h2> <table class="table"> <thead> <tr> <th>File Name</th> <th>File Description</th> <th>Uploaded By</th> <th>Download</th> <th>Delete</th> </tr> </thead> <tbody> {% for file in files %} <tr> <td> {{ file.File_Name }}</td> <td> {{ file.File_Type }}</td> <td> {{ file.Uploaded_By }}</td> <td> <a href="{{ file.File.url }}" class="btn btn-primary btn-sm" target="_blank"> Download File </a> </td> <td> <form method="post" action="{% url 'delete_file' file.pk %}"> {% csrf_token %} <button … -
Problème lors du deploiement d'un application django sur heroku
Bonjour a tout le monde, j'ai un probleme lorsque je deploie mon application les images qui ajouter dynamiquement don cceux qui se trouvent dans le dossier media s'afficher quand je les ajoutent via le site deja heberger ce qui est tout en fait normale. mais quand j'applique certaines modifications a local et je fais un git push pour une mise en jour de l'application les images qui etait entrain de bien s'afficher n'arrive plus à se charger. Je tenter de mettre en comantaire 'DATABASES['default'] = dj_database_url.config()' et la les images s'affiche sauf que d'autres donnes des autres tables sont maintenant aussi introuvable, comme les utilisateur de la table Users, .... Aider moi a trouver une solution. Merci d'avance ce une application Django -
Django Gunicorn web-app returns 500 error for new objects via form if being not connected to the server via SSH
The problem described in the title is quite strange: I deployed my Django web-app using gunicorn and nginx. When I set up my production webserver and then start my gunicorn workers and leave the command prompt open afterwards, everything works fine. However, when I close the command prompt, I always get a 500 Internal Server Error when trying to create a new object using the normal Django ModelForm handling. This only occurs: In production. When creating new objects directly using Djangos ModelForms. When the command prompt with ssh access to the webserver is closed. This also appears when stripe tries to call the webhook when the command prompt is closed. I implemented error handling for every single part of my view functions, so I can be sure that this has nothing to do with my code. I would strongly appreciate any ideas on what to check next or where the error could come from. Thanks in advance -
flutter future builder keeps loading one-to-many relationship
im tring to view tasks on alone screen from data using rest api dart django with project_id its one-to-many relationship project has many tasks so i want to dispay the tasks when i click on project widget using future builder here is usagae future builder and task list import 'package:flutter/material.dart'; import 'package:project/model/task_model.dart'; import 'package:project/project_dtetailForTest.dart'; import 'package:provider/provider.dart'; import 'new_project.dart'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; class TaskById extends StatefulWidget { //const TaskById({ Key? key }) : super(key: key); final int project_id; //final Task task =Task(); TaskById({required this.project_id}):super(); @override State<TaskById> createState() => _TaskByIdState(); } class _TaskByIdState extends State<TaskById> { @override Widget build(BuildContext context) { final taskP= Provider.of<TaskProvider>(context); return Scaffold( backgroundColor: Colors.white, appBar: AppBar( elevation: 0, bottom: PreferredSize( child: Container( color: const Color(0xff94adb4), height: 2, width: 320, ), preferredSize: const Size.fromHeight(4.0)), centerTitle: true, backgroundColor:const Color(0xff076792), title: const Text( 'Project1', style: TextStyle(color: Colors.white, fontSize: 35, fontWeight:FontWeight.w700, shadows: [ Shadow( color: Color(0xa6A2B6D4), blurRadius:20), ] ), ), leading: IconButton( onPressed: () { Navigator.pop(context); }, icon: const Icon( Icons.arrow_back, size: 44, ), ), actions:[Container(padding: const EdgeInsets.fromLTRB(0, 0, 6, 3), child: IconButton( color:Colors.white , icon: const Icon( Icons.search, size: 44, ), onPressed: () {}, ), ),] ), //TaskProvider(){ // this.fetchTask(); // } body: FutureBuilder( future: TaskProvider().fetchTask(widget.project_id), builder: (context, … -
Django - why path is mentioned in different format for admin compared to our app
I am new to django , in urls.py why do we mention the path to our app as "path('appname/', include(appname.urls))" whereas for admin its mentioned as below "path('admin/', admin.site.urls)" Thanks. -
Access table in sqlite using django and query creation
I want to access data from table1, from my database and to make a query based on other table, using django. For example: access data from table1 (user, date, hour:minutes, city, check) and table 2 (user, date: hour:minute, latitude, longitudinal) and if the hour:minutes are the same in both table, I need to update the field check with the value True. I tried to access the data from table1 with objects.filter on user, date, but I think that it's not a good method, because it doesn't give me the values from the row. I read the documentation from https://docs.djangoproject.com/en/4.0/topics/db/queries/#copying-model-instances but I can not manage to do this correctly and finish it. And for the second part, I was thinking to make something with an if, but still not sure. In the beginning I need to access data from the table1. -
Best way to asynchronously send and receive using a socket with Django?
I've tried to use threading, background tasks, but neither work with sockets. I am looking into Django Channels but I can't find a tutorial where they use the sockets to connect to an external regular listening socket. What library should I use to use sockets asynchronously with Django? -
django app.models.VideoLibrary.DoesNotExist: VideoLibrary matching query does not exist
The problem is I can't type http://localhost:8000/1 to see spesific ViedoLibrary in my database. Can anyone help me to find the solution? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('main/', views.main, name='main'), path('create_view/', views.create_view, name='create_view'), path('list_view/', views.list_view, name='list_view'), path('<id>', views.detail_view), ] views.py def detail_view(request, id): context = {} context['data'] = VideoLibrary.objects.get(shop_id=id) return render(request, 'app/detail_view.html', context) models.py class VideoLibrary(models.Model): shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') Also if I type id=id in views.py the next error pops up : Cannot resolve keyword 'id' into field. Choices are: adress, attendance, equipment, films, genre, income, shop_id, shop_name, staff. This are all my classes in models.py but there are also adress, shop_id and shop_name that are from specific model -
How do I create a 'couple' relationship in Django?
I've got a model called Couple. Couple describes the relationship between two Auth.User records. class Couple(models.Model): created = models.DateTimeField(auto_now_add=True) partner_one = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='partner_one') partner_two = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name='partner_two') I'm having trouble referencing the partner in a reliable from their user model because now I need to know which is partner one, partner two. This is obviously not an elegant solution. Is there a better way to achieve what I'm trying to do here?