Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django test framework token authentication — is there any way to log everyone out?
I understand that token authentication doesnt really have the concept of logging out— that a token merely identifies a user. Is there any way to invalidate all tokens? Maybe via the change of some variable from which all the tokens are generated— causing everyone to need to log in again? -
Query one more existing MSSQL DB from Linux
I have deployed django application running on Linux (Ubuntu) in VirtualBox. The settings file database section looks like this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } On the local network there is an MSSQL Server with database x and a few tables. I'd like to create a view with datagrid, which is able to work with the data from database x providing the basic CRUD functionality with possibility of filters. Could you refer me to the steps with corresponding documentation I need to fulfill? You don't need to go into much detail, only to refer me to what I need to edit and what I should be aware of to achieve a desired result. -
Django rest framework how to use path parameter in serializer
I am trying to create a API endpoint that outputs calculated data from the database. In this endpoint I have a path parameter which I would like to filter the data by. However I am not sure how to do it. urls.py path('v1/sets/<str:code>/breakdown', individual_set_breakdown.as_view(), name='individual_set_breakdown'), views.py class individual_set_breakdown(ListAPIView): serializer_class = SerializerSetsIndividualBreakdown def get_queryset(self): code = self.kwargs.get('code', None) qs = magic_sets.objects.filter(code=code.upper()) return qs serializers.py class SerializerSetsIndividualBreakdown(serializers.ModelSerializer): common = serializers.SerializerMethodField() class Meta: model = magic_sets fields = ['common'] def get_common(self): def average(lst): if not len(lst): return 0 else: return sum(lst) / len(lst) common = { 'unique': magic_sets_cards.objects.exclude(side='b').filter(set_id__code='LEA').filter(rarity='common').count(), } return common As you can see I try to filter the data in the view but that does not seem to filter the data the is returned from the endpoint. I would like filter(set_id__code='LEA') to be dynamic depending on what is passed into the endpoint. If I remove this part it gets the data for all sets. -
Django Re-Run Migrations on older DB
I've made some changes to my local Django project which has altered my DB structure. I ran my migrations on my local database and everything works fine locally. However my production SQL file does not have these changes made to it. How do I bring my production SQL file up-to-date with the new migrations? -
Straight forward modelform doesn't validate on submit of form
I have a fairly simple ModelForm which doesn't validate on submit. Not sure how to debug this. I tried different print statements in my view and everything seems to be proper. This is what I have: # views.py def render_entities(request): """View to render the entities overview page""" # Get the logged in user instance user = User.objects.get(username=request.user.username) user_cashpool = Cashpool.objects.get(company__user=user) # Get the info for the site visited dashboard_site = 'entities' if request.method == 'GET': # Return the form and populate with user's company company = user.company # Query all entities associated to the cashpool companies = Company.objects.filter(cashpool=user_cashpool).order_by('name') # Pass the queryset to the Select Form CompanyForm.base_fields['company'] = forms.ModelChoiceField( queryset=companies) # Return the form form = CompanyForm() context = { 'company': company, 'companies': companies, 'dashboard_site': dashboard_site, 'form': form } return render(request, 'dashboard/dashboard_entities.html', context) else: form = CompanyForm(request.POST) if form.is_valid(): # fails # Get the cleaned inputs company = form.cleaned_data['company'] ... # forms.py class CompanyForm(forms.ModelForm): """ A form to render a select widget with companies associated to a user """ company = forms.ModelChoiceField(queryset=Company.objects.exclude(name='exclude-all'), required=True) class Meta: model = Company fields = ['name'] # template <!-- Select Company --> <form action="entities" method="post"> {% csrf_token %} <label for="company">Select a Company</label> {{ form.company }} … -
django make multiple objects for each da with a user imput: start and end date
I'd like to know how i can make multiple object for each day in a Timespan. The users input is a start and end date. My curent moddel looks like this: from datetime import datetime from django.db import models from django.contrib.auth.models import User class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) desk = models.ForeignKey(to='Desk', on_delete=models.CASCADE) startingdate = models.DateField(default=datetime.now) endingdate = models.DateField(default=datetime.now) ... I probably have to change it to this: ... class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) desk = models.ForeignKey(to='Desk', on_delete=models.CASCADE) date = models.DateField(default=datetime.now) ... The user selects a start and end date on the website: <form"> <label for="starting_date">Start Date:</label> <input type="date" id="starting_date" name="starting_date"> <label for="ending_date">End Date:</label> <input type="date" id="ending_date" name="ending_date"> <input type="submit" value="Submit"> </form> As I said a user should have the posibility to canche a Booking for a day. but the problem here is if the user e.g. created a Booking from 21-12-2021 until 25-12-2021 and just want to canche/delete the booking on 23-12-2021 it get's a bit complecated. -
What is the recommended way of naming REST API urls? [closed]
I have a Django REST API. In my app there are users and the users have plans. For plans, I have GET, POST and PUT routes. Every plan has an id and a user_id linking it to a User. Should I use url parameters in my endpoints or should I just receive the params in the request body? For example, should I do: POST api/user/<uuid:user_id>/plan or POST api/plan and take the user_id from the request body? And if the number 1 is the better way, should I still require the user_id to be passed also into the request body? And with the update request, should I do: PUT api/user/<uuid:user_id>/plan/<uuid:plan_id> or PUT api/plan/<uuid:plan_id> and take the user_id from the request body, or PUT api/plan/ and take both id's from the body? And again, if I require the id's in the url, should I do it also in the body? -
Django_filters apply all chosen filter fields
Hej! :) I want to filter my data before I do some calculations with it with an AND operator. The chosen filter fields should ALL be applied. I added some fields of the mode to the filter function and I can filter (e.g.) for the name and the year seperate. But not combined. If I try to filter for both name AND year at the same time I would just get the results from year. In my model I got an M2M to another model in which the year is set: # models.py class Plant(models.Model): name = models.CharField( max_length=200 ) used_xducts = models.ManyToManyField( Xduct, through="UsedXduct", blank=True, related_name="used_in_plant" ) class UsedXduct(models.Model): plant = models.ForeignKey( Plant, on_delete=models.PROTECT, related_name="used_in_plant" ) xduct = models.ForeignKey( Xduct, on_delete=models.PROTECT, related_name="xduct" ) year = models.SmallIntegerField( validators=[validate_year], blank=True, null=True ) class Xduct(models.Model): code = models.CharField( max_length = 20, blank = True, null = True, unique = True ) name_english = models.CharField( max_length = 200, blank = True, null = True, unique = True ) description_english = models.TextField( max_length = 500, blank = True ) explanation_english = models.TextField( max_length = 4000, blank = True ) # filters.py class PlantsNameFilter(django_filters.FilterSet): name = ModelChoiceFilter(queryset=Plant.objects.all()) year = django_filters.NumberFilter(method='year_filter', label='Year') class Meta: model = … -
How to check if some datatype is string or list in python?
I'm trying to add a check here that if the receiver is just a string. then convert that into list else just pass. if type(receiver) == str: receiver=[receiver] error: TypeError: 'str' object is not callable -
How to access websocket from another function in another file
I'm trying to make a login page, and I want to access the websocket I've opened up. I'm assuming although I could be wrong, that you only want one websocket open at a time so I'm trying to use the one from earlier. But I'm having trouble accessing it. This is my main file that hosts what I have so far import React, { Component, useState, useEffect } from 'react'; import { render } from 'react-dom' import WebSocketStuff from './websocket'; import Navbar from './navbar'; import Login from './login'; import { BrowserRouter as Router, Switch, Route, Link, Redirect } from "react-router-dom"; function App() { return ( <div> <Navbar /> <WebSocketStuff /> <Router> <Switch> <Route path="/account/login" component={Login}></Route> </Switch> </Router> </div> ); } const appDiv = document.getElementById("app"); render(<App />, appDiv); This is the javascript file that has the websocket code. import React, { Component, useState, useEffect } from 'react'; export default function WebSocketStuff(props) { const [name, setName] = useState(''); console.log(window.location) var loc = window.location var socket; useEffect(() => { var wsStart = 'ws://' if (loc.protocol == 'https:') { wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname; socket = new WebSocket(endpoint); console.log(socket); socket.onmessage = function (e) { console.log("message", e) setName(e.data); … -
when I try to use SyncToAsync() using django and hit 3rd party API endpoint. I get 'SyncToAsync' object has no attribute 'get' error
Iam trying to use async functionality to django views with SyncToAsync(https://docs.djangoproject.com/en/3.2/topics/async/#sync-to-async). I have to hit a 3rd party API using request.get method. But when I hit my endpoint.I get the above error. Any idea how to resolve it... -
How to create models for friend system in django?
I haven't seen much talks about in the internet . I want to create a friend system for my personal project . I think if i can create it I will have better understanding of ORM which I don't I think . Please help me out guys :'( . And possibly explain in a nutshell of what you did . -
How do I make changes to my Django HTML view file that extends a base template?
I have a Django test project that I am working on, and have been working on it for hours now, and I am stuck. I can't add other html syntax into my html file that extends a base template into it. I have a base template that works on my html view, however, when I make changes inside the html view, it doesn't reflect. Looks like I am missing something between the HTML view, and the base template. Below is the HTML view <!DOCTYPE html> {% extends "base.html" %} <!--https://www.anwita-arun.in/ --> {% block head %} <html lang="en"> <head> <title>Test Project</title> </head> {% endblock %} {% block body %} <body> <h1 style="font-size: 250px"> Testing </h1> <p> aloha </p> <form method="POST"> <!-- Form creation with post. No method "post" needed --> {% csrf_token %} <!-- Insert token --> {{ form.as_p }} <!-- form variable --> <input type="submit"> <!-- Form input submission --> </form> </body> {% endblock %} Below is the base template <!DOCTYPE html> <!--https://www.anwita-arun.in/ --> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia"> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-social/4.10.1/bootstrap-social.css" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"> <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link href="https://fonts.googleapis.com/css?family=Rajdhani&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Lobster&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/coliff/bootstrap-rfs/bootstrap-rfs.css"> … -
I'm unable to accept friend request from other users in my Django social site
unable to accept friend requests in my web app below are the errors that I'm getting when I'm trying to accept the friend request. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/users/friend-request/accept/5/ Django Version: 2.1 Python Version: 3.8.10 Installed Applications: ['users.apps.UsersConfig', 'feed.apps.FeedConfig', 'crispy_forms', 'stdimage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py" in execute 296. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.users_profile__old) was the direct cause of the following exception: File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/rohan/ByteWalk-master/users/views.py" in accept_friend_request 88. user1.profile.friends.add(user2.profile) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py" in add 926. self._add_items(self.source_field_name, self.target_field_name, *objs) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py" in _add_items 1088. self.through._default_manager.using(db).bulk_create([ File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/query.py" in bulk_create 465. ids = self._batched_insert(objs_without_pk, fields, batch_size) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/query.py" in _batched_insert 1152. self._insert(item, fields=fields, using=self.db) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/query.py" in _insert 1133. return query.get_compiler(using=using).execute_sql(return_id) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/models/sql/compiler.py" in execute_sql 1285. cursor.execute(sql, params) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/utils.py" in execute 100. return super().execute(sql, params) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/utils.py" in execute 68. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/home/rohan/.local/share/virtualenvs/ByteWalk-master/lib/python3.8/site-packages/django/db/backends/utils.py" in … -
How to link my Django form selection to filtered database values
I am configuring a web page using Django in which I would like my form's dropdown options to filter the database options based on master ID. There are four options: allElements, oldElements, newElements, and testElements. My problem is that while I can create a for loop to iterate through the database based on any of the four variables I've defined, my form selection is not linked to the choices like I thought it would be. Can anyone help? My form: account_choices=[('allElements','All Elements'), ('oldElements','Old Elements'), ('newElements','New Elements'), ('testElements','Test Elements')] class SelectIdForm(forms.Form): Filter = forms.ChoiceField(choices = account_choices, error_messages={'required': ''}) My view: def metalist(request): form=SelectIdForm(request.POST) if account_choices == 'allElements': data = Metadata.objects.all().order_by('title') elif account_choices == 'oldElements': data = Metadata.objects.all().filter(metaMain = 1).order_by('title') elif account_choices == 'newElements': data = Metadata.objects.all().filter(metaMain = 2).order_by('title') elif account_choices == 'testElements': data = Metadata.objects.all().filter(metaMain = 3).order_by('title') else: data = Metadata.objects.all().order_by('title') return render(request, "Site/insights/metalist.html", {"allElements": Metadata.objects.all().order_by('title'), "oldElements": Metadata.objects.all().filter(metaMain = '423844416462').order_by('title'), "newElements": Metadata.objects.all().filter(metaMain = '689665504419').order_by('title'), "testElements": Metadata.objects.all().filter(metaMain = '542384344085').order_by('title'), "form": form, 'data': data }) My HTML page: <form method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Click to Filter"> </form> {% for list in data %} <li> Metadata List: <a href="{% url 'Site:insights/metalist' account.title %}"> {{ metadata.title }}</a> </li> {% endfor %} I've … -
Django - Run all tests inside of "test" sub-folder
So I've been running tests using the command python manage.py test to run every test inside the test folder and I'd like to run all test in a subfolder of the test folder. So I tried python manage.py test <app name>.test.<sub-folder>(path to the test sub-folder), but it doesn't work. I created an __init__.py file inside <sub-folder> that imports all the test files in <sub-folder>, but that didn't work. Every time I run python manage.py test <app name>.test.<sub-folder> the terminal outputs Run 0 tests in Xs. How do you run all tests inside of a sub-folder of the test folder in Django? -
Django virtual environment successfully installed. But when I run 'pip freeze' in command prompt it says 'No python at C drive'
Python is already installed and the version is 3.8. Could anyone help me? [1]: https://i.stack.imgur.com/44FSS.jpg -
I have a model with a many to many field. How can I display the information only if that field is selected?
I am making a recipe app. The model Recipe has a ManyToMany field favorites. On my favorites page I only want to display the recipes that are favorited. I can only figure out how to display all of the recipes. How can I set it to only display the recipes that has a user favorite it? models.py: class Recipe(models.Model): title = models.CharField(max_length=45) description = models.CharField(max_length=180) recipe_image = models.ImageField(upload_to=get_image_path, blank=True, null=True, default="/static/photos/food_default.jpg") favorites = models.ManyToManyField(User, related_name='favorite', default=None, blank=True) def __str__(self): return self.title views.py: def pinned_view(request): fav = Recipe.objects.all() model = { "fav": fav } return render(request, 'pinnedRecipes.html', model) pinnedRecipes.html: <div id="favoritedCollapse" class="collapse" aria-labelledby="favorited" data-parent="#accordion"> <div class="card-deck list-inline p-0"> <a href="#" class="card card-custom list-inline-item m-4"></a> {% for fav in fav %} {% for recipe in fav.recipes.all%} <img class="card-img-top img-thumbnail img-custom" src="{{ recipe.recipe_image.url }}" alt="Image Not Found" /> <div class="card-body"> <h5 class="card-title text-truncate"></h5>{{ recipe }} {% for recipe in fav.recipes.all%} <p class="card-text text-truncate">{{ description }}</p> {% endfor %} </div> </a> {% endfor %} {% empty %} <h3>No Favorites </h3> {% endfor %} </div> </div> -
Why is my else statement not working in django rest framework?
I have the following code: views.py @api_view(['DELETE']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def selected_job_delete(request,pk=None): if pk != None: job=Job.objects.get(pk=pk) jobdetail = Job_detail.objects.get(job=pk) jobtrack = Job_track.objects.get(job = pk) jr = Job_removed() jdr = Job_detail_removed() jtr = Job_track_removed() jr.jobname = job.jobname jr.owner = job.owner jr.enabled = job.enabled jr.start_date = job.start_date jr.start_time = job.start_time jr.date_added = job.date_added jr.version = job.version jr.save() jdr.job = jr jdr.json = jobdetail.json jdr.save() jtr.job=jr jtr.jobdetail= jdr jtr.save() operation = job.delete() data = {} if operation: data["Success"] = "Successfully deleted" else: data["Failure"] = "Unsuccessful" return Response(data) urls.py path('api/jobs/<int:pk>/delete', views.selected_job_delete), Lets say my database in Job have the only following id of 40. I want to delete it so i key the url of api/jobs/40/delete and the deletion will happen, followed by the task in the function. The output result in my postman will show it is successfully deleted . But if I key the url of api/jobs/41/delete, the id of 41 does not exist in my database, it does not run my else statement to show unsuccessful . Instead it shows me How can I make it to show unsuccessful instead of the whole chunk of the error that it does not exist? -
TransactionManagementError in Django when make migrate
I am new to programming , I have an issue when make migrate in Django 3.2.9. Here is my code, models.py from django.db import models from django.db.models.deletion import CASCADE, PROTECT # Create your models here. class Promotion(models.Model): description = models.CharField(max_length=255) discount = models.FloatField() class Collection(models.Model): title = models.CharField(max_length=255) class Product(models.Model): slug = models.SlugField() title = models.CharField(max_length=255) description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotions = models.ManyToManyField(Promotion) class Customer(models.Model): MEMBERSHIP_BRONZE = 'B' MEMBERSHIP_SILVER = 'S' MEMBERSHIP_GOLD = 'G' MEMBERSHIP_CHOICES = [ (MEMBERSHIP_BRONZE, 'Bronze'), (MEMBERSHIP_SILVER, 'Silver'), (MEMBERSHIP_GOLD, 'Gold') ] first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=255) birth_date = models.DateField(null=True) membership = models.CharField( max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE) class Order(models.Model): STATUS_Pending = 'P' STATUS_Complete = 'C' STATUS_Failed = 'F' STATUS_CHOICES = [ (STATUS_Pending, 'Pending'), (STATUS_Complete, 'Complete'), (STATUS_Failed, 'Failed') ] placed_at = models.DateTimeField(auto_now_date=True) payment_status = models.CharField( max_length=1, choices=STATUS_CHOICES, default=STATUS_Pending) customer = models.ForeignKey(Customer, on_delete=PROTECT) class Address(models.Model): street = models.CharField(max_length=255) city = models.CharField(max_length=255) customer = models.OneToOneField( Customer, on_delete=models.CASCADE, primary_key=True) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=PROTECT) product = models.ForeignKey(Product, on_delete=PROTECT) quantiy = models.PositiveSmallIntegerField() unit_price = models.DecimalField(max_digits=5, decimal_places=2) class Cart(models.Model): created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=CASCADE) product = models.ForeignKey(Product, on_delete=CASCADE) quantity = … -
How do I write a Django query to get distinct objects linked to another object?
I'm using Python 3.9 and Django 3.2. I have this class, which has a field for another ... class Transaction(models.Model): ... id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) account = models.ForeignKey('Account', on_delete=models.CASCADE) I woudl like to get the distinct set of Account objects, linked to certain transactions., so I treied this class TransactionManager(models.Manager): def get_accounts_with_pending_transactions(self): """ Returns acounts with pending transactions """ return Transaction.objects.filter(status=Transaction.Status.PENDING).values("account").annotate(n=models.Count("pk")) ... However, the above seems to return a list of dicts as opposed to objects. Thus, I don't have access to all the fields from my Account objects. Is there any way to write a query to get the Account objects such that they are already hydrated as actual objects? -
Django - What happens when you delete an entity in a table that has a foreign key ManyToMany relationship to another?
I've noticed that Django doesn't let you set the on_delete parameter for ManyToManyField. This made me curious what happens if you delete an entity in a ManyToMany relationship? So for example, let's say we have Book, which has a ManyToMany relationship to Author. Let's say that a book A has 3 authors: "Tom Lam", "Lam Tom" and "Britney Britney". Then let's say "Britney Britney" gets deleted from the Author table. Does "Britney Britney" get removed from the ManyToMany relationship with Book? Does an exception get thrown when trying to delete "Britney Britney?" What does Django do in the case that an entity is deleted when it exists in a ManyToMany relationship? -
Django-allauth: Redirect users post sign-up/sing-in to a specific page depending on the page they are coming from
Problem I have an invite system in my django app that allow users to invite other people (using their email) to join their team. When an invited user clicks on an invitation, they are redirected to an url that carries informations about the specific team the user was invited to. Such url calls a view called accept_invitation that handles the following use-cases: a) If a user is logged-in already AND they are also the invited user (i check the email of the invite), I add the user to the team and redirect them to the team's page. b) If a user is logged-in already BUT they are not the invited user, I redirect them to a page where I invite them to log-in with a different account. c) If a user is logged-out, I redirect them to a page where I invite them to log-in and/or sign-up to continue. Use-case a) works just fine but use-case b) and c) I had to figure out how to propagate the informations of the invite to the following screens and past the login. My initial idea was to add the parameters of the invitation to the request.session so that after the login-in I … -
Fix Django "Unresolved attribute reference" for prefetched field
Let's say I have the following Django models: class Toolbox(models.Model): name = models.CharField(max_length=255) tools = models.ManyToManyField("Tool") class Tool(models.Model): class Size(models.TextChoices): SMALL = "S" MEDIUM = "M" LARGE = "L" name = models.CharField(max_length=255) size = models.CharField(max_length=10, choices=Size.choices) I have a function to get all small tools for each toolbox. The @queries_disabled() comes from django-zen-queries to ensure the small tools have been prefetched and avoid N+1 performance problems. @queries_disabled() def get_toolbox_to_small_tools_mappings(toolboxes: list[Toolbox]) -> dict: return {toolbox: toolbox.small_tools for toolbox in toolboxes} The problem is my editor (PyCharm) is highlighting a warning: Unresolved attribute reference 'small_tools' for class 'Toolbox' I can fix this my changing the argument's type hint: def get_toolbox_to_small_tools_mappings(toolboxes: list[Toolbox] | QuerySet): ... This feels a little hacky to me. Is there a better way to fix this? -
In Django how I can create automatically a many to many entry based on a field found in two models
I have the following models example: class TestSet(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Class(models.Model): name = models.CharField(max_length=50) test_set_id = models.ForeignKey(TestSet) def __str__(self): return self.name class Test(models.Model): title = models.CharField(max_length=50) test_set_id = models.ForeignKey(TestSet) def __str__(self): return self.title class ClassTest(models.Model): class_id = models.ForeignKey(Class) test_id = models.ForeignKey(TestSet) memo = models.CharField(max_length=250) def __str__(self): return self.memo What I want to do is when a new Class or Test is created, it should also create automatically a ClassTest entry if their test_set_id matches with the currenct entries on the database. Example: Lets say I already have three Test objects with test_set_id = 1 I create a new Class object with test_set_id = 1 After creating the new Class object, the program should also create 3 new entries in the ClassTest model connecting classes to tests based on the match of the test_set_id field. It should work the same if a new Test object is added.