Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auth system checks superuser instead of custom user moel?
I created a custom authentication model. I am trying to authenticate custom user model but instead of that it checks for superusers(users that are created on python shell). Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(verbose_name='email address',max_length=255,unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) username =models.CharField(max_length=80,unique=True) Views.py class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) response = { 'message': 'User logged in successfully', 'token' : serializer.data['token'], } status_code = status.HTTP_200_OK return Response(response, status=status_code) def get(self, request, format=None): queryset = User.objects.all() serializer = UserRegistrationSerializer() return Response(serializer.data) Serializers.py class UserLoginSerializer(serializers.Serializer): email = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): email = data.get("email", None) password = data.get("password", None) user = authenticate(email=email, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password is not found.' ) try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) update_last_login(None, user) except User.DoesNotExist: raise serializers.ValidationError( 'User with given email and password does not exists' ) return { 'email':user.email, 'token': jwt_token } Basically i am trying to authenticate my custom created users (created from my custom registration form instead of user).Can somebody help? -
Accessing additional fields from a grouper in a Django group_by
How can I access fields other than the grouper in a Django group_by function? class dateEvent(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return "%s" % (self.event.title) def description(self): return "%s" % (self.event.description) class Event(models.Model): description = RichTextUploadingField(max_length=200) view: def my_view(request): events = dateEvent.objects.all() context = { 'events': events, } return render(request, 'view.html', context) template: <ul> {% for event in dateEvents_list %} <li><h5>Event: {{ event.grouper }}</h5> <h6>Description: {{ event.description }}</h6> #How can access the description of the main event? <ul> {% for dateEvent in event.list %} <li>date: {{ dateEvent.start_date_time }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> I'd like to have the title, which is the grouper so it's fine, but also the description. -
Set field default value from field in foreign key - Django
I have two models, Product & Order, and an intermediate model (OrderProduct). The intermediate has an FK to Product in a field called product, and one to Order in order, and an integer field max_quantity not related to them. What I want is set the default value of max_quantity to be product.inventory, But when attempting that, I get: "product" has no attribute "inventory", Even though I have a field called inventory in Product My question is: How can I make this work? max_quantity = models.IntegerField(default=product.inventory) -
TypeError: __init__() got an unexpected keyword argument 'required'
I am using django 3.0 I am new to django I face the error that shows TypeError: init() got an unexpected keyword argument 'required' . my models.py code : from django.db import models from django.utils import timezone from django.utils.text import slugify from django.utils.encoding import smart_text PUBLISH_CHOICES = [ ('private', 'Private'), ('public', 'Public'), ] class BlogPost(models.Model): title = models.CharField( max_length=2000, verbose_name='Post Title', unique=True, error_messages={ "unique": "Enter unique title." }) post_description = models.TextField(blank=True, null=True) post_images = models.ImageField(upload_to='pics') date_of_publish = models.DateField(default=timezone.now) published = models.CharField( max_length=250, choices=PUBLISH_CHOICES, default=None) author_name = models.CharField(max_length=250) slug = models.SlugField(max_length=1000, required=False) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(BlogPost, self).save(*args, **kwargs) class Meta: verbose_name = 'Blog Post' verbose_name_plural = 'Blog Posts' Ouptput error: init super().init(*args, **kwargs) TypeError: init() got an unexpected keyword argument 'required' -
Deploying Django website: SECRET_KEY must not be empty
I'm trying to host a website on Linode server. I'm actually following a Corey Schafer tutorial on youtube, but now I'm stuck. So at this point I'm running commands with SSH in the server, but when I run any manage.py commands, specifically python3 manage.py runserver 0.0.0.0:8000, I'm getting the error in the title. Here's the full error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/taufiq/trident_site/server_env/lib/python3.7/site-packages/django/conf/__init__.py", line 161, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. settings.py: """ Django settings for trident_site project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ … -
Display owner full name in field panel list
i want to edit the wagtail page model owner so it displays full names not just the username in the wagtail admin. I created a separate class that inherits from the page model so i'm more flexible in customizing the admin area. class PageAdmin(ModelAdmin): model = BlogPage menu_icon = "doc-full" menu_label = "All posts" list_display = ("title", "date", 'category', 'owner') modeladmin_register(PageAdmin) The field pannel content_panels = Page.content_panels + [ FieldPanel('owner'), Is there a way to edit the display value of the owner via hooks or any other method to display first and last name instead of just the username in the admin panel? Thank you! -
Custom Token Authenticating for external microservices in Django DRF
I am using a CustomTokenAuthentication class which extends Django rest framework's Token authentication. class CustomTokenAuthentication(TokenAuthentication): keyword = 'Bearer' def authenticate_credentials(self, key): # username = get_username() username = self._fetch_authorized_user(key) User = get_user_model() user = User(username=username) return user, key _fetch_authorized_user(key) uses an external login client to login users. Question: How do I extend this for external system authentication i.e. Allowing other microservices to authenticate and access these APIs as well. The external login client can't be touched so _fetch_authorized_user(key) will not find a valid username. I'm thinking of adding a fallback when that happens but what would that be? Is it Django's own authentication? (Creating a db and creating profiles for valid external microservices). Can both even work in parallel? Open to other suggestions -
django get filtered by parameter
The site I am building has 6 profiles (desks) and these are accessed via buttons at the top of the page using: path('home/<slug:slug>/', HomeView.as_view(), name='homepage') and is accessed by a button with: {% url 'homepage', slug=desk.slug %} So is filtered in the queryset. How can I access what that value so I can use it in the template for styling purposes? basically I want to highlight the desk button on the page so the user has visual feedback on where he is. Is there a way to do this nicely, as currently the only way I can think of doing this is to use: {% request.url %} and then split off the end of the url, but that seems like a nasty hack to me. Unfortunately google can't get past the word filter so all I get is django-filter documentation and issues. -
How to block requests from apps like postman, insomnia and allow only one origin - django rest framework
I try to block the possibility to send a post request to my app via postman or insomnia. I want to limit the source of a request to one domain www.sample.com. I did add this domain to the ALLOWED_HOSTS and CORS_ORIGIN_WHITELIST, and nothing more and still I can send a request and save the data in my django app. How can I limit the origin of a request to the one domain and block all others or return "Unauth msg"? Stack: DJANGO REST Framework -
Translated URLs in Django that work simultaneously for all languages
Given a view defined by a function about_us, I would like it to be accessible by either one of these URLs: /about/ /acerca-de/ In a way that requesting any of those activates the corresponding language and renders the view, but both URLs remain accessible at all times regardless of the currently active language. I would also like to reverse these URLs inside templates using the path name, so reverse('about_us') can give me the URL that corresponds to the currently active language. Django offers a mechanism for translating URLs by wrapping the string matchers for path objects in gettext_lazy so reverse URL resolution can return the one appropriate for the current language, but AFAIK only one of the URLs works at any given time, depending on the current language. If I instead define two path objects then I can point them to the same view wrapped by some view decorator that activates the given language first, but then I lose the ability to perform reverse URL resolution and I am forced to perform some ugly tricks to get links to respect the current language. Has anyone found a solution to this problem? -
Django 'str' object has no attribute 'field' context
I have a problem, i got this error: 'str' object has no attribute 'field' This is my views: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from .models import Company from .forms import NewCompanyForm # Sociétés def companies_index(request): companies_list = Company.objects.order_by('-id') context = { "companies_index": "active", 'companies_list': companies_list, } return render(request, 'companies/index.html', context) def companies_create(request): context = { "companies_create": "active", } if request.method == 'POST': form = NewCompanyForm(request.POST) if form.is_valid(): form.save() return redirect('companies_index') form = NewCompanyForm() return render(request,'companies/create.html',context,{'form': form}) def companies_delete(request, pk): company = get_object_or_404(Company, pk=pk) company.delete() return redirect('companies_index') The problem is with the "create" action i want to know how i can pass the context variable and the form variable to my template. Best regards. Thx. -
ContentType matching query does not exist. django=3.0.7
from django.contrib.contenttypes.models import ContentType def posts_detail(request,slug=None): instance = get_object_or_404(Post, slug=slug) if instance.publish > datetime.datetime.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated: c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, ) if created: print("yeah it worked") comments = instance.comments context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form":form, } return render(request, "post_detail.html", context) Showing following error ContentType matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/posts/gchgjvhbk/ Django Version: 3.0.7 Exception Type: DoesNotExist Exception Value: ContentType matching query does not exist. Exception Location: C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py in get, line 417 Python Executable: C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.6 Python Path: ['C:\Users\ANUPYADAV\Desktop\try19\src', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\Scripts', 'C:\Users\ANUPYADAV\Desktop\try19\src', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37', 'C:\Users\ANUPYADAV\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\lib\site-packages'] -
Passing parameters in URLs in Django
This is supposed to be a stupidly simple thing, nevertheless I can't get my head around it. I want to create a 'bulletin' page where I filter a few models by start- and end- date. path('bulletin/<int:startyear>-<int:startmonth>-<int:startday>/<int:endyear>-<int:endmonth>-<int:endday>/', bulletin_view, name="bulletin"), And the view: def bulletin_view(request, startyear, startmonth, startday, endyear, endmonth, endday): start_date= startyear + '-' + startmonth + '-' + startday end_date= endyear + '-' + endmonth + '-' + endday dateEvents = dateEvent.objects.filter(start_date_time__gte=start_date).filter(start_date_time__lte=end_date).order_by('start_date_time') context = { 'dateEvents': dateEvents, } return redirect('bulletin') When I go to this URL: /bulletin/2020-06-01/2020-06-30/ I keep getting: TypeError at /bulletin/2020-06-01/2020-06-30/ bulletin_view() got an unexpected keyword argument 'startyear' I've changed parameters names, replaced '-' with '/', taken the 'int:' out; nothing, I still get the error. What am I missing? -
how to get each id of each selected in M2M djnago
i want to get the ID of selected imeis class Mobile(models.Model): mobile = models.CharField(max_length=20,unique=True) quantity = models.IntegerField() imei = models.ManyToMany(Imei,on_delete=models.CASCADE) class Imei(models.Model): imei = models.CharField(max_length=13,unique=True) if i selected 10 imei's i want to get 10 ID's of selected imeis!? i tried this ways but no one worked ! instance.imei__id instance.imei.id instance.imei_id i appreciate your helps -
Generating HTML from AJAX
I am making an AJAX pagination in my Django project. First time using it and I am doing it step by step, debugging along the way. I want the user to paginate through its favorite products. Each product has it's picture, name, brand... What I have now is a functional AJAX that get a set of datas back. I have everything I need to display the list but I find it hard to display my HTML from AJAX. My AJAX $(".nav_button_2").on("click", function(event) { event.preventDefault(); var page = $(this).val(); console.log (page); var url = '/register/account/'; $.ajax({ url: url, type: "POST", data:{ 'page': page, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(resp) { $('#fav_list').html('') var resp = JSON.parse(resp); $.each(resp, function(i, val) { $('#fav_list').append('<h2>' + val.sub_pic + '</h2>') }); } }); }); My HTML: <div class='row d-flex justify-content-between'> <div class="card mb-3" style="width: 49%;"> <div class="row no-gutters"> <div class="col-md-2 my-auto"> <img class="mx-auto d-block" style="width:auto; height:auto; max-width:100px; max-height:100px; " src="{{ saved.original_product.picture }}"> </div> <div class="col-md-10"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'finder:detail' saved.original_product.id %}" class="aaccount">{{ saved.original_product.real_name }}/ {{ saved.original_product.real_brand }}</a> </h5> <img src="/static/finder/img/nutriscore-{{ saved.original_product.nutrition_grade}}.svg" style="width:70px;"><br> </div> </div> </div> </div> This HTML is for the first page displayed by django, for the other pages I will substitute all … -
Django annotations m2m duplication
I am trying to do an annotation with django, for some reason I am getting a weird result when I add the m2m of task: qs = qs.annotate(Sum('activitytime__cost'), Sum('tasks__tasktime__cost')) activitytime__cost = 600 ! WRONG ! When I do: qs = qs.annotate(Sum('activitytime__cost')) I get the correct value of 200, but it seems like it's multiplying by the amount of tasks I have when trying to sum the m2m of tasks. Any help is much appreciated. -
How to display extended user model extrafield at django-rest-auth registration endpoind
I am trying to use the django-rest-auth library on my django rest framework api. What I have done here, is extending my user model by using a one to one field to the basic user model, and adding an extra field role, which is going to be a choice between "Student" and "Teacher". Here is my model: from django.db import models from django.contrib.auth.models import User ROLES = [ ('Student', 'Student'), ('Teacher', 'Teacher'), ] class AxessUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=7, choices=ROLES, default="Student") The role field is displayed as an inline inside the admin site. In fact, the result is the following: So far so good. Now when I try to access the rest-auth endpoint for registration, obviously I am presented with a registration form for the generic django user model. So my question is, how do I implement this field inside the rest-auth registration endpoint? -
Why does my flask app error with "Permission Denied" when I try to deploy and run on AWS?
I created my flask web app in AWS so I could deploy it on the server. But, it won't let me run it. It keeps giving an error. This is my traceback. Traceback (most recent call last): File "/home/ec2-user/environment/qgen/helloworld/application.py", line 102, in <module> flaskrun(app) File "/home/ec2-user/environment/qgen/helloworld/flaskrun.py", line 29, in flaskrun port=int(options.port) File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 944, in run run_simple(host, port, self, **options) File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 1052, in run_simple File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 1005, in inner fd=fd, File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 848, in make_server host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 740, in __init__ HTTPServer.__init__(self, server_address, handler) File "/usr/lib64/python3.6/socketserver.py", line 456, in __init__ self.server_bind() File "/usr/lib64/python3.6/http/server.py", line 136, in server_bind socketserver.TCPServer.server_bind(self) File "/usr/lib64/python3.6/socketserver.py", line 470, in server_bind self.socket.bind(self.server_address) PermissionError: [Errno 13] Permission denied and this is my code #!flask/bin/python from flask import Flask, redirect, url_for, render_template, request from mainforqupld import * from outputtostring import storetheprintoutputasstring from VolumeQ1 import volumeQ1 from random import choice from mainforqupld import * from LinearEquationsQ1 import linearEquationsQ1 from ExponentialEquationsQ1 import exponentialEquationsQ1 from PercentageQ1 import percentageQ1 from ProbabilityQ1 import probabilityQ1 from CoordinateGeoQ1 import coordinateGeoQ1 from RadicalsQ1 import radicalsQ1 from SystemsQ1 import systemsQ1 from flaskrun import flaskrun app = Flask(__name__) @app.route('/') def home(): return render_template("qgenhtml.html") @app.route('/', methods=['GET','POST']) def my_form_post(): … -
Getting "Message.receiver" must be a "User" instance in Django forms
I get this error message and I don't know how to fix it, I tried every possible solution I could find in StackOverflow or I could think of. Cannot assign "'2'": "Message.receiver" must be a "User" instance This is my forms.py file : class SendMessageAuditorForm(forms.ModelForm): auditors = User.objects.filter(is_staff=True).values_list('id', 'username') message = forms.CharField( validators=[NOSPECIAL_CHARACTERS], widget=forms.Textarea(attrs={'maxlength': '500'}), required=True, label="Write your message" ) receiver = forms.ChoiceField( choices = auditors, required=True, label="Send to" ) class Meta: model = Message fields = ('message', 'receiver',) This is my models.py file: class Message(models.Model): date = models.DateTimeField( verbose_name="Date d'envoie" ) sender = models.ForeignKey( User, related_name='sender', on_delete=models.PROTECT, verbose_name="Sent from" ) receiver = models.ForeignKey( User, related_name='receiver', on_delete=models.PROTECT, verbose_name="Sent to" ) message = models.TextField( blank=False, null=False, verbose_name="Message" ) is_read = models.BooleanField( default=False, verbose_name="message is read" ) class Meta: ordering = ['-date'] verbose_name = "Message" verbose_name_plural = "Messages" def __str__(self): return "{} : {} - {} - {}".format(self.date, self.sender, self.message, self.receiver) and this is my view.py : @login_required def send_message(request): if user.profile.institution: institution = user.profile.institution else: institution = None user = request.user form = SendMessageAuditorForm(request.POST) if request.method == 'POST': if form.is_valid(): post_data = dict(request.POST.lists()) now = datetime.now() message = form.save(commit=False) message.date = now message.sender = user #*The problem might be here* receiver_id … -
Modify default queryset in django based on condition
assume the following table | id |policy_start_date| amount | is_renewed | original_policy |renewed_counter| | 10 | 01-06-2019 | 134 | 0 | NULL | 0 | | 12 | 05-06-2019 | 454 | 0 | NULL | 0 | | 35 | 04-06-2020 | 121 | 1 | 12 | 1 | My Issue is, when is_renewed is True , i want to show the a prefix R along with renewed_counter and original_policy instead of the original policy id. for example : for the third entry, i want to show id as R112 instead of 35 To achieve the above, I'm using ModelManager as below but unable to get the desired result in my model.py : class CustomManagerTest(models.Manager): def get_queryset(self): policies = super(CustomManagerTest,self).get_queryset().filter(is_renewal=True) for policy in policies: policy.id = str("R" + str(policy.renewal_counter) + policy.renewal_policy_id) return policies class Policy(models.Model): objects = CustomManagerTest() policy_start_date = models.DateField() amount = models.IntegerField() is_renewed = models.BooleanField(default = False) original_policy = models.IntegerField(Null = False) renewed_counter = models.IntegerField(default = 0) my function in views: def show_all_policies(request): policy_list = Policy.objects.all() return HttpResponse(policy_list) Error I'm getting: django.db.utils.OperationalError: (1054, "Unknown column 'myapp_policy.renewal_counter' in 'field list'") -
create a spare parts web API
I want to create a spare parts web API using Django, the question here is should I create my own spare parts database, or just use some API from professionals (like tecdoc), and how do i process in each method -
Nginx location doesnt workd
I have a Django app running with Nginx and Gunicorn on mysite.com. I would like it to be accessible only under mysite.com/myapp. This is my nginx configuration: server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } When I change location / to location /myapp/, I get "Not found error". Nginx error log doesn't seems to have anything. What could be the issue? -
how to have an "add another file" feature in a django form?
I have a Document model with a FileField. When creating a new Document , I can upload a file, submit and save the new Document. here is my code for a simple upload : models.py class Document(models.Model): document = models.FileField(upload_to='documents/') forms.py from .models import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) views.py from .forms import DocumentForm def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'journal/model_form_upload.html', { 'form': form }) I wish to alter this to enable the user to successively add multiple files. (not selecting multiple files with a unique submit button) example of process : 1) select a file, click on upload, 2) display : the name of the uploaded file, a button to remove this file if needed a button to upload another file 3) eventually click on submit to save the Document and its multiple files. -
Using same foriegn key in multiple tables django
I have a table named class student(models.Model): std_name= models.CharField(max_length=20 , blank=False, null=False) std_username = models.CharField(max_length=20 , blank=False, null=False) And another table named std_admission. Can I use the student fields in this table is foreign keys like this? And if so can I use it the same way in other tables as well? class std_admission(models.Model): admission_date= models.CharField(max_length=20 , blank=False, null=False) std_name = models.ForeignKey(student, default=1, on_delete=models.SET_DEFAULT) std_username = models.ForeignKey(student, default=1, on_delete=models.SET_DEFAULT) -
Django following system using many to many field
So I have the following model (a profile for the user where the user is the default django user): class Profile(models.Model): user=models.OneToOneField(get_user_model(), on_delete=models.CASCADE, null=True, related_name='getprofile') following=models.ManyToManyField(get_user_model()) Let's say I have a user Mark. Then I get who he is following like this: mark.getprofile.following.all() My question is how do I get a queryset of people that follow Mark? I think that since this is a many-to-many relationship this must be possible but I am quite new in Django so I don't know how to do it. Any help would be greatly appreciated!