Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display a dropdown for ForeignKey models on the PARENT admin page
Can't seem to figure this out. I have a model - Show, and Episode, which has a ForiegnKey relationship to Show. On the Show admin page, I want a dropdown display of all the Episodes, which will link to their admin model page... The only thing I can get is a collapsed form as a read only. I like the links to the admin page with this, but I just want it in a dropdown. ***models.py*** class Show(models.Model): title = models.CharField(_("title"), null=True, max_length=5000) slug = models.SlugField(_("slug"), max_length=5000, unique=True) class Episode(models.Model): show = models.ForeignKey(Show, verbose_name=_("show"), on_delete=models.CASCADE) title = models.CharField(_("title"), null=True, max_length=5000) ***admin.py*** class ShowAdmin(admin.ModelAdmin): list_display = ('title', 'get_latest_duration', 'get_latest_pub_date',) inlines = [ EpisodeInline, ] class EpisodeInline(admin.StackedInline): model = Episode fieldsets = ( ('Episodes', { 'classes': ('collapse',), 'fields': ('title',), }),) -
How Can I call all functions in class base views
I am new in django and used function based views till now. Now I started class base views but they are so confusing . like class Newrecord(View): greeting="Hi" def newPost(request): deyCat = Category.objects.all() def oldPost(request) deyold = OldCategory.objects.all() path('about/', Newrecord.as_view(greeting="G'day")), Now How From class based url I will access both functions ? Or I have to implement logic in class when to execute which function ? And How we can use them for inheritance ? -
Token Based Authentication in latest Django
I'm trying to solve problem described here but code provided in that answer not works for latest django==2.2 I have tried to port this code but failed with that settings.py: MIDDLEWARE = ['polls.mymiddleware.CookieMiddleware', mysite/polls/authbackend.py: from django.contrib.auth.backends import RemoteUserBackend, UserModel class Backend(RemoteUserBackend): def authenticate(**credentials): """We could authenticate the token by checking with OpenAM Server. We don't do that here, instead we trust the middleware to do it. """ try: user = UserModel.objects.get(username=credentials['remote_user']) print('__user exists') except UserModel.DoesNotExist: user = UserModel.objects.create(username=credentials['remote_user']) print('__user not exists') # Here is a good place to map roles to Django Group instances or other features. return user mysite/polls/mymiddleware.py: from django.contrib.auth import authenticate, login, ImproperlyConfigured class CookieMiddleware(object): """Authentication Middleware for OpenAM using a cookie with a token. Backend will get user. """ def process_request(self, request): if not hasattr(request, 'user'): raise ImproperlyConfigured() if "thecookiename" not in request.COOKIES: return # token = request.COOKIES["thecookiename"] # REST request to OpenAM server for user attributes. # token, attribute, role = identity_manager.get_attributes(token) # user = authenticate(remote_user=attribute['uid'][0]) user = authenticate(remote_user=1) # simplified for test request.user = user login(request, user) result of that: File "C:\Users\Administrator\Desktop\my_scripts\mysite\mysite\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\Users\Administrator\Desktop\my_scripts\venv\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "C:\Users\Administrator\Desktop\my_scripts\venv\lib\site-packages\django\core\handlers\wsgi.py", line 135, in __init__ self.load_middleware() … -
What Is the Best Way to Test Racing Condition of Django Model Data Operation?
I've implemented an API based on Django and Django REST framework and found it had some problems when it's work under great concurrency. So I was interested in write some Testing code to reproducing the problem, and improve the code to get it to thread safe later. I've tried the library before_after, and it's quite hard to use if the busy part of the code is not a function or is a function but contains arguments. I've also tried using ThreadPoolExecutor to generate a racing condition, but it raises django.db.utils.DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 4328317000 and this is thread id 4690485864. My implementation is like this: class TestOrderViewSet(APILiveServerTestCase, AuthRequestMixin): def test_replace_order_thread_safety(self): john_balance = self.john.wallet.balance jane_balance = self.jane.wallet.balance order_user_pairs = [(mommy.make_recipe('payments.tests.jane_order'), self.jane)] for i in range(10): order_user_pairs.append((mommy.make_recipe('payments.tests.jane_order'), self.jane)) order_user_pairs.append((mommy.make_recipe('payments.tests.john_order'), self.john)) random.shuffle(order_user_pairs) print(order_user_pairs) self.assertGreaterEqual(Order.objects.count(), 20) def replace_order(order, user, i): print(i, order.id) response = self.auth_post('order', {'pk': order.id}, user) print(i, user.wallet.balance) self.assertEqual(response.status_code, 200) user.wallet.refresh_from_db() print(i, user.wallet.balance) def count_done(): return sum(int(r.done()) for r in results) with ThreadPoolExecutor(max_workers=4) as e: results = [] for i in range(10): r = e.submit(replace_order, *order_user_pairs[i], i) results.append(r) r = e.submit(replace_order, … -
Django Nested Relation API response
I have two models District and BTS. i want to get the response like bellow. [{ "id": 15, "name": "Westen", "page": 1, "expanded": false, "selected": false, "children": [{ "id": 12, "name": "BTS2", "page": 1 }] }, { "id": 13, "name": "Noth", "page": 1, "children": [{ "id": 13, "name": "BTS2", "page": 2 }] }] I have two Serializer class BTSSerializer(serializers.HyperlinkedModelSerializer): def to_representation(self, value): return { 'id': value.id, 'name': value.bts_id, "page": 4, "expanded": False, "selected": False, } class Meta: model = BTS fields = ('bts_id', 'id') class DistrictSerializer(serializers.HyperlinkedModelSerializer): def to_representation(self, value): return { 'id': value.id, 'name': value.name, "page": 1, "expanded": False, "selected": False, "children": [] } class Meta: model = District fields = ('name', 'id') This is BTS model class BTS(models.Model): id = models.AutoField(primary_key=True) bts_id = models.CharField(max_length = 100, unique=True) district_id = models.ForeignKey(District, related_name='districts', on_delete=models.CASCADE, null=True) bts_type_id = models.ForeignKey(BTSType, related_name='types', on_delete=models.CASCADE, null=True) class Meta: db_table = "base_stations" def __str__(self): return self.bts_id How could i achieve this ? -
Javascript move the content of textbox to a box dynamically
I want to move the content of a textbox to a Box when the ADD button is pressed as in the picture. Also, this text should be removed with an X button in the above box. Picture Any help is highly appreciated. Thanks in advance. -
Extra data specific to usertypes
i have a usertype model with choicefield usertype i.e 1 and usertype i.e. 2 usertype is in one to one relation with usermodel. Now I need to create a specific field for usertype 2 only. How do I extend user profiles according to user types(role) USER_TYPE_CHOICES = ( (1, 'student'), (2, 'teacher'), ) user_type = models.IntegerField(choices=USER_TYPE_CHOICES) class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) location = models.CharField(max_length=140) gender = models.CharField(max_length=140) profile_picture = models.ImageField(upload_to='thumbpath', blank=True) def __unicode__(self): return u'Profile of user: %s' % self.user.username -
How to show sub-sub category of sub-category in Django?
I have the following models: class TutorialCategory(models.Model): category_title = models.CharField(max_length=150) category_summary = models.CharField(max_length=150) category_slug = models.SlugField(default=1, blank=True) class TutorialSeries(models.Model): series_title = models.CharField(max_length=200) series_maincategory = models.ForeignKey( TutorialCategory, default=1, on_delete=models.SET_DEFAULT) series_summary = models.CharField(max_length=200) class Tutorial(models.Model): tutorial_title = models.CharField(max_length=150) tutorial_content = models.TextField() tutorial_published = models.DateTimeField( "date Published", default=datetime.now()) tutorial_series = models.ForeignKey( TutorialSeries, default=1, on_delete=models.SET_DEFAULT) tutorial_slug = models.SlugField(default=1, blank=True) As shown above TutorialCategory is main category, TutorialSeries is sub category and Tutorial is sub-sub-category. I created a simple view that shows sub categories of main categories, but don't know how to show the sub-sub categories of sub category. Please check out views.py and urls.py if you can improve its quality and if there is an easy and better way of doing it. Anyway, this is view: def single_slug(request, single_slug): matching_series = TutorialSeries.objects.filter( series_maincategory__category_slug=single_slug) series_urls = {} for i in matching_series.all(): part_one = Tutorial.objects.filter( tutorial_series__series_title=i.series_title).earliest("tutorial_published") series_urls[i] = part_one.tutorial_slug return render(request, 'tutorial/sub-category.html', context={ "tutorial_series": matching_series, 'part_ones': series_urls }) urls here: urlpatterns = [ path('', views.home_page, name='home'), path('tutorial/<int:id>/', views.tutorial_detail, name='tutorial_detail'), path('<single_slug>/', views.single_slug, name='single_slug'), ] the template that shows sub-category of main category: {% for tut, partone in part_ones.items %} <div class="card"> <div class="card-body"> <h5 class="card-title">{{ tut.series_title }}</h5> <p>{{ tut.series_summary }}</p> <a href="{{ partone }}">Read more</a> </div> </div> … -
How to fetch an entire row from a model in django
I am having a model class dev(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) empid = models.CharField(max_length=10) companyid = models.IntegerField() projectid=models.IntegerField() teamid = models.CharField(max_length=1) specialization = models.CharField(max_length=200) email_address = models.CharField(max_length=30) I am having a login form with username and password , When the user login , after authentication , emailaddress in the django Users has to be checked with email_address in dev model. If both are same , then the I need the the entire row having the respective matched email address . -
How to send canvas data from javascript to django with ajax
I am working on a django application where the user can trigger the webcam and capture a photo. This photo is saved in a canvas. I want to send this image to django views, through which, the image can be saved inside the django server. I am using webrtc to trigger the webcam. I was having a hard time saving the data with js itself and read somewhere that this is not possible with js alone. So I am now trying to send te data to python using ajax but am not able to. I am a beginner with working with canvas and ajax so, a detailed explanation will be helpful. I tried working with these answers, but none of them seemed to help Send canvas image data (Uint8ClampedArray) to Flask Server via Ajax Can't send data back to Django from JS AJAX here is my code so far html template <center> <button type="button" name="button" class='btn btn-outline-dark btn-lg' id='start'>Start Video Capture</button> <div class="container-fluid mt-2"> <video id="video" width="640" height="480" autoplay></video><br> <button type="button" data-toggle="modal" data-target="#image_model" class="btn btn-lg btn-dark" id="snap">Snap Photo</button> </div> </center> <button type="button" class="btn btn-secondary" data-dismiss="modal">Retake</button> <form action="{% url 'img_submit' %}" method="post" class="image_submit_form"> {% csrf_token %} <input type="submit" value="Use Image" class="btn … -
Hosting recommendation for a Django website that allows user-uploaded images
I have a small-size Django e-commerce website that's hosted on Heroku(I paid 7USD/month hobby dyno plan). The database is not big at all. The domain for the website is at another service provider, but I finally managed to make it work after many failed attempts. However, I recently added a new feature according to my customer's request -- allow users to upload images, which seems troubling if I continue using Heroku for hosting. (Their dynos are not exactly friendly for such design) I'm looking for any recommendations about other Django hosting services that can meet the need. So far I've checked AWS, Digitalocean, and Bluehost but the price seems all around $20/month?(My clients want the price as little as possible) So I wonder if there's any suggestion on choosing the service and is it possible to continue using Heroku with additional database like S3(If so what's the price comparison)? -
POST Request to update an image's source and a variable in a h1 tag issue
I am sending a POST request to my server which contains as data an image's name and a distance. In my views, i then extract that data and render it to an imaging.html file in my templates folder. The issue that I am having is that the variables are being updated as seen in the html that i printed from the POST request but the webpage itself is not being updated. In fact, when I look at the webpage's html code the tags themselves do not even appear. I would really appreciate some help with this issue as I have been struggling with it for a while now. I am not that experienced with Django. Thanks! POST request sent to server: import requests payload = {'distance': '30', 'img': 'image.jpg'} r = requests.post('http://127.0.0.1:8000/imaging', data=payload) print(r.status_code) print(r.text) Html printed from POST request object: 200 <!-- --> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Forest's Fishy Friends</title> <link rel="stylesheet" type="text/css" href="/static/imaging/index.css"> </head> <body> <div class="Top"> <h1>Forest's Fishy Friends</h1> <h3>Imaging Server</h3> </div> <div class="Reading"> <p>The distance from the robot to this object is: </p> <div class="Cool"> <!-- --> <h1>30</h1> <!-- --> </div> </div> <div class="Picture"> <p>Images taken from pi:</p> <!-- --> <img src="/static/imaging/Pictures/image.jpg" … -
Django manager and staff Authentication
I have one Manager authentication system, I want to add staff authentication under Manager. I already created AbstractUser for manager, how can i manage staff authentication under manager. models.py class CustomAccountManager(BaseUserManager): def create_user(self, email, password): user = self.model(email=email, password=password) user.set_password(password) user.is_staff = True user.is_superuser = False user.save() return user def create_superuser(self, email, password): user = self.create_user(email=email, password=password) user.is_active = True user.is_staff = True user.is_superuser = True user.save() return user def get_by_natural_key(self, email_): # print(email_) return self.get(email=email_) class CustomUser(AbstractUser): alphanumeric = RegexValidator(r'^[A-Za-z- ]*$', 'Only alphanumeric characters are allowed.') FullName = models.CharField(max_length=100, validators=[alphanumeric]) CompanyName = models.CharField(max_length=50) Country = CountryField(blank_label='Select Country') # username = None email = models.EmailField(('email address'), unique=True) email_confirmed = models.BooleanField(default=False) force_logout_date = models.DateTimeField(null=True, blank=True) # randompwd = models.CharField(max_length=20) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): # __unicode__ on Python 2 return self.email #'{} {} {}'.format(self.email, self.FullName, self.CompanyName) # expected when manager add staff information, staff will get email with email id and password -
how to use Django widthratio tag dynamically?
I want to calculate percentage of amount. Amount and percentage is stored in models. for eg 25% of 1500, both these value are stored in models. I tried django widthratio tag, but its only taking {% widthratio 25 100 1500 %}. its gives me bug when i try {% widthratio {{ obj.percent }} 100 {{ obj.price }} %} I tried jquery also, but its working as expected. <p class="course-price" >{% widthratio {{ obj.percent }} 100 {{ obj.price }} %}</p> I need to get percentage dynamically(based on the object), i'm loading around 10 objects dynamically(in one page). -
Django media files doesn't work when debug=false
settings.py STATIC_URL = '/static/' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'data') MEDIA_URL = '/data/' urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = 'generic.views.invalid_request' When I set DEBUG=False and run the server using python manage.py runserver --insecure all static file are serve successfully but media files doesn't appear. In debug console media urls raise error 500. -
CSRF Verification fails in production for Cross Domain POST request
The HTTP_X_CSRFTOKEN header does not match what is inside the csrftoken cookie. How can I examine the cookie? Set-Cookie is not displayed in the Response header for Cross Domain requests. -
how to handle auto_now_add and auto_now in django models
I have this model where date of second installment and third installment are same whenever i update any of them.How can i update different dates to the second and third installments models.py class StudentFee(models.Model): student = models.CharField(max_length=250) total_fee = models.IntegerField(default=0) first_installment = models.IntegerField(default=0) date_first_installment = models.DateField(auto_now_add=True) second_installment = models.IntegerField(default=0) date_second_installment = models.DateField(auto_now=True) #updates the same date when third installment updated.HOw can update dufferently third_installment = models.IntegerField(default=0) date_third_installment = models.DateField(auto_now=True) remaining = models.IntegerField(default=0) -
Refer related model field in model layer
I am try to refer 'spot_price' of model 'Spot' in model 'Basis' in django model layer, How can I manage this? I have designed view.py to automaticaly render the templates. so I am not able to modifty any view.py to choose data like 'models.B.objects.get().field'. and more, str is set to indicate the date, so, in the django backstage admin, the 'spot' field display would be 'date' formate, how would be change to 'spot_price'? model Spot class Spot(models.Model): date = models.DateField(primary_key=True) spot_price = models.FloatField(blank=True, null=True) def __str__(self): return str(self.date) if self.date else '' need to refer the model Spot'spot_price by date, cause date is unique but spot_price is not class Basis(models.Model): date = models.DateField(primary_key=True) major_future_contract_close_price = models.FloatField(blank=True) spot = models.OneToOneField(Spot, on_delete=models.CASCADE) basis = models.FloatField(default=calculate_basis) def __str__(self): return str(self.date) if self.date else '' def calculate_basis(self): return abs(self.major_future_contract_close_price - self.spot.spot_price) I expect the Basis.query.data would to like 'date: 2019-04-25, major_future_contract_close_price: 100.0, spot: 96.5, basis: 3.5' -
On submitting the Form how to read file upload control data in view coming from ajax
when i submit the form i donot want page to be reload that why i use ajax , and get data on form submission to ajax and ajax will send request to corresponding view . but i am unable to find code for file upload control in view by these two method i am unable to get data 1) myfile = request.FILES['myfile'] 2)myfile =request.FILES['myfile'].read() but i am always getting error : if request.method == 'POST' and request.FILES['filename'] raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'filename' this is my form <form action="{% url 'process_file' %}" method="post" enctype="multipart/form-data" id="myform"> {% csrf_token %} <div class="col-md-3 col-sm-3 firstblock padMin"> <h3>Input Data</h3> <ul> <li><input type="file" name="files[]" required accept=".csv" id="file_data" ></li> <li class="checkboxIn"> <input type="checkbox" name="id" id="id" /> </li> <li> <input type="number" name="train_fraction" id="train_fraction" required value={% if post_data %} {{fiction}} {% else %} 0.7 {% endif %} min="0.1" step="0.1" > </li> </ul> </div> <button class="btn btn-primary btn-lg custom-process" type="submit">Process</button> and there are other control also </form> and here is my ajax code $(document).ready(function(evt){ $(document).on('submit','#myform',function(e){ e.preventDefault(); var thisForm=$(this).serialize(); var action=$(this).attr('action'); var method=$(this).attr('method'); var formData = new FormData($('#myform')[0]); console.log(formData); $.ajax({ url: action, type: method, data: formData, success: function (data) { alert(data) }, cache: false, enctype: 'multipart/form-data', processData: false }); }); }); here … -
How to use vueJs inside django framework?
do you guys ever use VueJs inside the django framework? how could you get the data from the backend? -
Django how to iterate querysets of two subclasses in template?
I am using django-model-utils for inheritance Managers. I want to get result of both sub-classes with one dictionary without getting duplicates . models.py class Images(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) objects = InheritanceManager() class Postimg(Images): user_img= models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True) class Postsms(Images): user_message = models.CharField(max_length=500,blank=True) views.py def home(request): all_post = Images.objects.all().order_by('-created').select_subclasses() return render(request, 'copybook/home.html',{ 'all_post':all_post}) copybook/home.html {% for foo in all_post %} <hr> <br> SMS by: <p>{{ foo.user}} __ {{ foo.created }}</p> <h2>{{ foo.user_message }}</h2> <hr> <br> IMAGE by: <p>{{ foo.user}} __ {{ foo.created }}</p> <img src="{{ foo.user_img.url }}"width="250"> {% endfor %} i expect the result when i upload an image or message that should get top at home page . but now when i upload an image, a blank message also get iterated. i think the problem is in my home.html , because i do not know how to iterate over two sub-classes with single for loop without getting duplicate. -
django_tastypie can't recognize url
I am starting a new project with Django and neo4j, and the most promising library for developing REST services is TastyPie (Django Rest Framework is to tied to ORM, and neo4j is not a relational database). I am following this tutorial in order to make TastyPîe to work with not relational databases, and I already override the get methods, but I get this error when trying to access the endpoint: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/api/items_manager/items/ Using the URLconf defined in AttractoraGraph.urls, Django tried these URL patterns, in this order: admin/ api/ general/ api/ items_manager/ items/ ^(?P<resource_name>item)/$ [name='api_dispatch_list'] api/ items_manager/ items/ ^(?P<resource_name>item)/schema/$ [name='api_get_schema'] api/ items_manager/ items/ ^(?P<resource_name>item)/set/(?P<pk_list>.*?)/$ [name='api_get_multiple'] api/ items_manager/ items/ ^(?P<resource_name>item)/(?P<pk>.*?)/$ [name='api_dispatch_detail'] The current path, api/items_manager/items/, didn't match any of these. This is my general urls.py: from django.contrib import admin from django.urls import path from django.urls import path, include api_url_patterns = [ path('general/', include('GeneralApp.urls')), path('items_manager/', include('ItemsManagerApp.urls')), ] urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(api_url_patterns)), This is my application's urls.py: from django.urls import path, include from ItemsManagerApp import resources urlpatterns = [ path('items/', include(resources.ItemResource().urls)), ] this is my resources.py: from tastypie import fields, utils from tastypie.authorization import Authorization from tastypie.resources import Resource from ItemsManagerApp import models … -
Apollo Websocket doesn't seem to ever connect
I am developing a mobile app with authentication and subscriptions with apollo graphql on the frontend and Django on the backend. I am not able to make the websocket work. The user is able to login (close the app and come back logged in) as well as able to run mutations/queries, yet when it does subscriptions, the websocket doesn't seem to connect. Furthermore, when running the subscribe() method of the subscription, the onDisconnected listener(?) fires, however, onConnected nor onReconnected never do, and onReconnecting only fires when connectionParams contains authToken: storage.getCookie() (which I believe is a wrong way to set it up anyway). Practically speaking, when using the messaging feature, the message is sent but the current user is not added as part of the context of the message sent and thus the subscription returns the message as if the user hadn't sent it (Django sees AnonymousUser which is default for no context user obtained). I feel like I have scraped the internet and I am consulting as a last resort/desperation. Any small tip/hint helps! If your require further information, I would be happy to share. I have the following configuration for my Apollo links (websocket and regular): import { ApolloLink … -
How to get a deferred attribute value?
I need to compare two ID values to see if they match. In this database, there are Areas, and Locations within them. I need to check which locations are in a certain area. Areas have an ID as the primary key, and locations have a foreign key in them pointing to area. if obj.area.id == self.id: For some reason, the foreign key always returns correct values, while self.id (is inside the Area class) always returns . I have tried Area.id, Area.pk, Area._get_pk_val, and everything using self instead of Area. How do I pull the value out of deferred attribute? -
Retrieve a user list from a manydomanyfield with information from an intermediate table
it's been a few hours since I tried to retrieve a list of users with the information of an intermediate table. So I have a workspace model that is a manytomanyfield with users There is also an intermediary table to differentiate the classic users and the workspace manager I would like to display the list of users and add a small icon symbolizing the managers in the list. But unfortunately it seems difficult for Django, to display both the list of users of the workspace with the information of the intermediate table. In any case I look at the documentation of Django I have not managed to find how to do. models.py class Workspace(models.Model): name = models.CharField(max_length=250, verbose_name="Nom du workspace") members = models.ManyToManyField(User, through='Membership', verbose_name="Membres du workspace") token = models.CharField(max_length=500) # token statique join_token = models.CharField(max_length=500) # token dynamique join_token_date = models.DateTimeField(auto_now_add=False, null=True, blank=True) payday = models.DateField(max_length=10, verbose_name="Jour de paye", null=True, blank=True) planning_image = ProcessedImageField(upload_to='planning', null=True, blank=True, processors=[ResizeToFill(1299, 937)], format='JPEG', options={'quality': 100}) planning_thumbnail = ImageSpecField(source='planning_image', processors=[ResizeToFill(280, 202)], format='JPEG', options={'quality': 100}) def __str__(self): return self.name def get_absolute_url(self): return reverse('create-workspace') class Membership(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) workspace = models.ForeignKey(Workspace, on_delete=models.CASCADE) is_manager = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) views.py @login_required def workspace_detail(request, token): ins_workspace …