Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - extract filtered data excel
I have a django-filter (OrderFilter) to display a filtered table,next step is to export this table to excel. The export is working but I have only the header ... Can you check my code and tell me where is the problem Views.py def Order(request): filter= OrderFilter(request.GET, queryset=Order.objects.all()) orders= filter.qs.order_by('-Date') """ Don't work Category_query = request.GET.get('Category') qs = Order.objects.filter(Category= Category_query) """ if request.GET.get('Export') == 'Export': response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="data.xlsx"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Data') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Date', 'Category', 'Item'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows=qs.values_list('Date', 'Category', 'Item') for row, rowdata in enumerate(rows): row_num += 1 for col, val in enumerate(rowdata): if isinstance(val,datetime.date): val = val.strftime('%d/%m/%Y') ws.write(row_num, col, val, font_style) wb.save(response) return response return render(request, 'template.html',{'orders':orders,'filter': filter}) template.html <form method="get"> {{filter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> <form method="GET" > <button class="btn btn-warning" type="submit" value="Export" name="Export"> Export</button> </form> -
How i can create multi form like TCS form for student?
How i can create a multi form like first personal information then education and more, every page having save,submit and exit button after save go to the next form and at the end submit button to submit all information ? Using Django Python. -
Weasyprint cant load images when rendering html string
I am working on weasyprint library with python, scenario is i wrote a simple function which first renders html template to html_string with dynamic data and a logo then i am converting that html_string to pdf but the issue is when i am converting the html_string to pdf it doesn't show the image(logo), i went through different solution in which they solved the issue through request.build_absolute_uri() but i don't have request parameter because my function is not a django view, can anyone guide me how can i render the html_template with logo def generatepdf(data): html = render_to_string('template.html', {"test": data}) filename = data['version'] + ".pdf" try: # pdfkit.from_string(html.content.decode('utf-8'), filename, options=options) HTML(string=html).write_pdf(filename) return filename except Exception as e: print(e.__str__()) return False -
Wht is missing in this python django model? What is wrong?
Hello, I got an error when I try to migrate in my django model. It looks like something is missing there, like 'to' but what this 'to' mean?: class Planificare_concedii(BaseModel): class Meta: verbose_name = _('planificare concedii') verbose_name_plural = _('planificare concedii') persoana = models.ForeignKey( on_delete=models.CASCADE, null=False, blank=False, verbose_name=_('persoana') ) magazin = models.ForeignKey( on_delete=models.CASCADE, null=False, blank=False, verbose_name=_('magazinul') ) marca = models.ForeignKey( on_delete=models.CASCADE, null=False, blank=False, verbose_name=_('marca') ) an = models.ForeignKey( on_delete=models.CASCADE, null=False, blank=False, verbose_name=_('anul') ) data_inceput = models.ForeignKey( on_delete=models.CASCADE, null=False, blank=False, verbose_name=_('data inceput') ) data_sfarsit = models.ForeignKey( on_delete=models.CASCADE, null=False, blank=False, verbose_name=_('data sfarsit') ) tip_concediu = models.ForeignKey( on_delete=models.CASCADE, null=False, blank=False, verbose_name=_('tip concediu') ) This is the error that I got and I don't know exactly what is missing there or what is wrong... TypeError: __init__() missing 1 required positional argument: 'to' -
{ "detail": "Invalid signature." } in JWT using postman
models.py from django.contrib.auth import get_user_model # from accounts.models import User User = get_user_model() class Friend(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # who sent the request friend = models.ForeignKey(User, on_delete=models.CASCADE, related_name='friends') # who will receive the request # sender = models.CharField(max_length=20, default='requested') status = models.CharField(max_length=20, default='requested') created_at = models.DateTimeField(default=now) serializers.py class UserfSerializer(serializers.ModelSerializer): class Meta: model = Friend fields = "__all__" views.py class FindFriendsListView(generics.ListAPIView, APIView): # queryset = Friend.objects.all() # serializer_class = UserDetailSerializer serializer_class = UserfSerializer permission_classes = [IsAuthenticatedOrReadOnly] authentication_classes =[TokenAuthentication,JSONWebTokenAuthentication] def get_queryset(self): current_user_friends = self.request.user.friends.values('id') sent_request = list(Friend.objects.filter(user=self.request.user).values_list('friend_id', flat=True)) print(sent_request) users = User.objects.exclude(id__in=current_user_friends).exclude(id__in=sent_request).exclude(id=self.request.user.id) return users urls.py url('^f/$', views.FindFriendsListView.as_view()), but when i tried to trigger this particular url { "detail": "Invalid signature." } im getting this error it's an AUthorized GET Request but i dont understand what exactly the issue is -
Multiple django apps in wamp with custom domain
Please help i have struck with this I want to deploy django apps in wamp with two separate domains but unable to do, both domains routing to same django app Eg: abc.com and xyz.com both redirecting to abc.com Any how both are same code but i want deploy as one for production and one for testing -
Django: Calculate with "models.TimeField"
Good day and a happy easter-weekdend, in Django I'm trying calculate inside my "models.py" with the amounts of multiple TimeField. For example: class Times(models.Model): ... time_from = model.TimeField() time_to = model.TimeField() time_break = model.TimeField(default='00:00:00') time_all = ... ... Let's say my times look like... time_from: 08:00:00 time_to: 14:30:00 time_break: 00:30:00 ... I want to achieve the time of "06:00:00" inside my variable "time_all" Does anyone have an idea? Thanks! -
Django REST, append new field from values in a list
In a view, I get the result of an image classifier as a dictionary containing the name of an animal as key and the probability of it being the correct animal as value. {'dog': 0.9, 'wolf': 0.1} From here I send a Response containing all the animals of the dictionary that are also in the Animal Model. [ { 'common_name': 'dog', 'scientific_name' : 'Canis lupus familiaris', }, ] I would like to add the probability value for each occurrence contained in the dictionary : [ { 'common_name': 'dog', 'scientific_name' : 'Canis lupus familiaris', 'probability' : 0.9, }, ] What would be the best strategy for that? Here I am so far: Views.py: class AnimalListCreateAPIView(APIView): def get(self,request): classifier_result={'dog': 0.9, 'wolf': 0.1} list_animals=list(classifier_result.keys()) animals = Animal.objects.filter(common_name__in=list_animals) serializer = AnimalSerializer(animals, many=True) return Response(serializer.data) Serializers.py: class AnimalSerializer(serializers.ModelSerializer): class Meta: model= Animal fields= [' common_name ',' scientific_name '] Models.py class Animal(models.Model): common_name = models.CharField(max_length=50) scientific_name = models.CharField(max_length=50) def __str__(self): return self. common_name -
Verifying a Google ID Token in Django
I have a React Native Android app which uses Google Sign-In to get the users profile and email information and produces an ID token (using https://github.com/react-native-community/google-signin). The sign in works and I am displaying the users name, email, photo etc on the app. I am then trying to send the ID token to a Django + DRF backend so that it can be validated and a relevant user account created and/or logged in. I am following the instructions here: https://developers.google.com/identity/sign-in/web/backend-auth Here is my code for the endpoint. For now I have just been copying the ID token produced by the app and sending it to the backend via Postman. class GoogleView(APIView): def post(self, request): token = {'idToken': request.data.get('idToken')} print(token) try: idinfo = id_token.verify_oauth2_token(token, requests.Request(), MY_APP_CLIENT_ID) print(idinfo) if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise ValueError('Wrong issuer.') return Response(idinfo) except ValueError: # Invalid token content = {'message': 'Invalid token'} return Response(content) When I send the POST request, the first print statement runs confirming that the token was received correctly. However the second print statement never runs and I always get the 'Invalid token' response. So, I believe verify_oauth2_token is failing somehow but it doesn't give me anymore information. I have never used … -
setup domain for django web server
Say I have the domain mydomain.com and I want www.mydomain.com to display my Django site I have looked at the django docs but the answers they provide are confusing what DNS records do I need to set to allow this? and are there any changes that have to be made to the config note: I'm using ipv4 and am running ubuntu -
Djngo Formset: ['ManagementForm data is missing or has been tampered with']
I tried to implement inline forms using Django's formsets. To explain what I've tried to do is, I've tried to take multiple orders for a particular customer. I'm sharing the code for the same. views.py def create_customer_order(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status')) customer = Customer.objects.get(id=pk) if request.method == 'GET': formset = OrderFormSet(instance=customer) context={'customer': customer, 'formset': formset} return render(request, 'customer_order_form.html', context=context) elif request.method == 'POST': formset = OrderFormSet(request.POST, instance=customer) if formset.is_valid(): formset.save() return redirect('/') and my customer_order_form.html is, {% extends 'main.html' %} {% load static %} {% block content %} <h3>Orders for {{ customer.name }}</h3> <br> <form method="POST" action="."> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} {{ form }} <hr> {% endfor %} <input type="submit" name="Submit"> </form> {% endblock %} But when I'm making a POST request, i.e. to save the multiple forms (in the formset), I'm getting the following error. Traceback (most recent call last): File "C:\Users\Bagga\Documents\Django\Projects\crm\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Bagga\Documents\Django\Projects\crm\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Bagga\Documents\Django\Projects\crm\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Bagga\Documents\Django\Projects\crm\accounts\views.py", line 65, in create_customer_order if formset.is_valid(): File "C:\Users\Bagga\Documents\Django\Projects\crm\venv\lib\site-packages\django\forms\formsets.py", line 308, in is_valid self.errors File "C:\Users\Bagga\Documents\Django\Projects\crm\venv\lib\site-packages\django\forms\formsets.py", line … -
Django Saving Calculated Value to Model
:) I'm a Django beginner and I'd like to ask for some help from you beautiful people. Here's what I'm trying to accomplish: I have a model - shown below -that I would like to contain a score for each symbol. class Stock_Score(models.Model): Symbol = models.CharField(max_length=20, null=True) Score = models.FloatField(null=True) To calculate that score, I'd like to use a second model which contains a list of stocks and a value called Yrs for each symbol: class Stock_Data(models.Model): Symbol = models.CharField(max_length=20, null=True) Yrs = models.FloatField(null=True) So what I was thinking was to import the Stock_Data model in my views.py, loop through the Symbols, check a simple if/else and then save the result to my first model under the "Score" field. Something like this: data = Stock_Data.objects.all() for i in data: if i.Yrs > 10: Score = 1 else: Score = 0 Score.save() Apologies for this garbage code, but I'd love some ideas about how I would be able to accomplish this :) Thanks in advance. -
Django not loading images from css file
Good Morning I have my HTML file wich links to the css and it is working fine <link rel="stylesheet" href="{% static '/Website/css/bootstrap.min.css' %}" /> <link rel="stylesheet" href="{% static '/Website/css/style.css' %}" /> <link rel="stylesheet" href="{% static '/Website/css/ionicons.min.css' %}" /> <link rel="stylesheet" href="{% static '/Website/css/font-awesome.min.css' %}" />e here Then I have several images in the HTML file which are loading fine <link rel="shortcut icon" type="image/png" href="{% static '/Website/images/fav.png' %}"/> One div element id <div id="lp-register"> obviously links to above style.css selector as per below #lp-register{ background: linear-gradient(to right, rgba(0,0,0, 0.7) , rgba(0,0,0, 0)), url('../images/test.png') fixed no-repeat; background-size: cover; background-position: center; position: absolute; top: 0; width: 100%; min-height: 100vh; } the images are in the static folder structured as this static - images - test.png and the setting.py has the correct static file definition STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] When I load the HTML page that particular image is not being loaded, and no error I see in the Django server, furthermore if I inspect the element I see that url('../images/test.png') remain with the old settings linear-gradient(to right, rgba(0,0,0, 0.7) , rgba(0,0,0, 0.7)), url("http://placehold.it/1920x1280") fixed no-repeat and does not change no matter what. In addition to that if I … -
User dashboard on django?
I will explain my final degree project. I want to make a web app that have a public area (front web enterprise), admin dashboard (using jet adming or argon admin panel) and user dashboard. The thing is that... I want to make this enterprise web app and need a user web or dashboard. Django got a public area and admin, but no user. How could make a user interface that uses jet admin template? or simply how could make a user dashboard? This is a test project for my degree but dont know if i can do this on django Thanks a lot of! -
I have a problem with my Django URL pattern naming
For whatever reason when I give a name="..." - argument to a URL pattern and I want to refer to it by using the name it does not seem to work. That's my 'webapp/urls.py' file: from django.urls import path from .views import PostListView, PostDetailView, PostCreateView from .import views app_name = 'webapp' urlpatterns = [ path("", PostListView.as_view(), name="webapphome"), path("post/<int:pk>/", PostDetailView.as_view(), name="postdetail"), path('post/new/', PostCreateView.as_view(), name="postcreate"), path("about/", views.About, name="webappabout"), ] And that's my 'webapp/views.py' file: from django.shortcuts import render from django.views import generic from django.views.generic import ListView, DetailView, CreateView from .models import Post def Home(request): context = { 'posts': Post.objects.all() } return render(request, "webapp/home.html", context) class PostListView(ListView): model = Post template_name = 'webapp/home.html' context_object_name = 'posts' ordering = ['-date'] class PostDetailView(DetailView): model = Post template_name = 'webapp/detail.html' class PostCreateView(CreateView): model = Post fields = ['title', 'content'] template_name = 'webapp/postform.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def About(request): return render(request, "webapp/about.html", {'title': 'About'}) And that's my 'webapp/models.py' file: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField(max_length=300) date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse("postdetail", kwargs={'pk': self.pk}) As you can … -
Django User uploaded JPG not being visualized
OK, I've wasted a lot of time on this one and read a lot of other threads on this: I want to visualize a user uploaded profile pic. I'm still on a development server on windows. I can visualize static jpg without any issues. The uploading goes correctly: the jpg is stored in the media folder, but when I try to visualize the jpg, I only get the default jpg icon and a 404 error. I have no idea what's going wrong. Django version 3.0.4 Settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' url.py urlpatterns = [ path('', views.index, name='index'), url(r'^creategroup/', views.Groupnew, name='creategroup'), url(r'^createchallenge/', views.NewChallenge, name='createchallenge'), url(r'^updateprofile/', views.UpdateProfile, name='updateprofile'), #url(r'^showprofpic/', views.ShowProfPic, name='showprofpic'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Resulting HTML code /media/profilepics/filename.jpg The actual file is stored in C:(local path)(projectname)\media\profilepics. I also copied the file to C:(local path)(projectname)(appname)\media\profilepics. Anybody has any idea? I feel like I'm not getting the correct path to the file. -
Is there a way to avoid recalculating some values in a recursive many-to-many relationship using django and graphene?
Let's say I have a recursive a many-to-many relationship on one of my Django models, and I'm using graphene_django to query a tree. Something like this: query getTree{ tree{ id active percentage children{ id active percentage children{ ... } } } } Where 'percentage' is a value based on how many of the node's children are active. I could calculate the percentage on each node on their own, but then a bunch of nodes would be calculated multiple times. Is there a way to avoid this? -
Python Django log in with encrypt/decrypt messages
I've used this source code https://github.com/sibtc/simple-django-login. Before logging in I want to display encrypted messages on the log in page, and when logged in I want these messages to be decrypted. I also want the user who is logged in to be able to post another message to these already displayed messages. I will have txt files that will consist of the messages that will be displayed, so when a user posts a new message it will be added to this. I know each time the program is run them posts will be lost but thats okay for what I am currently looking for. The file system the program simple-django-login has slightly confused me as I'm unsure where I should put my python encrypt.py file which will handle the encryption. Any help with this project would be helpful like a drafted encrypt.py file and where it should be placed. Or inputting a form on the html and referencing when a message is posted where should the submit button redirect you. Thanks in advance -
Can't configure Docker + Django with Nginx and Gunicorn
I am trying to run the Django project inside Docker container using nginx and gunicorn. It seems that wsgi server running successfully but when I navigate to localhost (127.0.0.1:8000) the page is not loading. Here is my docker-compose.yml configuration: version: '3' services: app: build: context: . ports: - "8000:8000" env_file: - django.env volumes: - ./app:/app command: > sh -c "python3 manage.py migrate && python3 manage.py wait_for_db && gunicorn -w 4 "app.wsgi -b 0.0.0.0:8000 environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgres - DB_PASS=supersecretpassword depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgres - POSTGRES_PASSWORD=supersecretpassword ports: - "5432:5432" nginx: build: context: . dockerfile: nginx/Dockerfile ports: - 80:80 and nginx configuration: server{ listen 80; server_name localhost; location / { proxy_pass http://app:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } finally console: db_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | db_1 | 2020-04-13 10:22:22.719 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2020-04-13 10:22:22.719 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2020-04-13 10:22:22.833 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2020-04-13 10:22:23.150 UTC [20] LOG: database system was shut down at 2020-04-13 … -
Django translation returns page not found (404) for all secondary languages
I am using Django 3.0.4. I am trying to setup multiple languages in my project but for some reason only the default language is accessible. Here's my setup: settings.py: MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGES = ( ('en', _('English')), ('el', _('Greek')), ) LANGUAGE_CODE = 'en' USE_I18N = True USE_L10N = False USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) urls.py: from django.conf.urls.i18n import i18n_patterns urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), path('superadmin/', admin.site.urls), ] # Enable debug toolbar if settings.DEBUG: import debug_toolbar urlpatterns = [ path('__debug__/', include(debug_toolbar.urls)), ] + urlpatterns urlpatterns += i18n_patterns( path( 'dashboard/', include('fusers.dashboard_urls'), name="usersDashboard" ), ) And the result is that I cannot access the dashboard/ without the default language as a prefix: /en/dashboard/ --OK /dashboard/ --404 /el/dashboard/ --404 -
How can I change the returned field metadata type in the json returned by OPTIONS using the Django REST Framework?
I am currently writing an automated script to extract metadata types from my models in Django endpoints which I am trying to hook up to swift. How to pass information about the field data type to the frontend when using Django Rest Framework? The previous question on stack exchange explains how the OPTIONS field can be used to extract the metadata from my models; however, I run into a problem in that not all fields returned are detailed. Particularly, foreign key fields do not specify the correct metadata type. for instance, "created_by_merchant": { "type": "field", "required": false, "read_only": true, "label": "Created by merchant" } "item_size_selection": { "type": "field", "required": false, "read_only": false, "label": "Item size selection" } Both are foreign keys. Created by merchant should be an integer, item_size_selection should be a charfield. Is there any way I can specify the type for particular fields in my OPTIONS? -
why when I add select to <option> django automatically add ="" next to it?
I have this code in template: <option value="{{elem.0}}" {% if elem.0 == def_choice %} selected {% endif %} > {{elem.1|capfirst}} </option> when it is rendered have this result : <option value="profile/images/batata.jpg" selected=""> Batata </option> what is adding the ="" is it django rendering? -
'User' object has no attribute
I just tried to select my API but I got this error. My API http://127.0.0.1:8000/api/user/ My model=> class User(models.Model): userid = models.AutoField(primary_key=True) username = models.CharField(max_length=50,null=False,blank=False,unique=True) phno = models.CharField(max_length=20,null=True,blank=True) image = models.ImageField(upload_to='user', blank=True) email = models.EmailField(null=False,blank=False) pwd = models.CharField(max_length=20,null=False,blank=False) created_date = models.DateTimeField(auto_now_add=True) created_usr = models.IntegerField(blank=False,null=False) lastmodified_date = models.DateTimeField(null=True,blank=True) lastmodified_usr = models.IntegerField(null=True,blank=True) class Meta: db_table= 'user' def image_tag(self): # used in the admin site model as a "thumbnail" if len(self.image) <=0 : return '' else: return mark_safe('<img src="%s%s" width="150" height="150" />' % (settings.MEDIA_URL,self.image)) # return mark_safe('<img src="{}" width="150" height="150" />'.format(self.url()) ) image_tag.short_description = 'Image' image_tag.allow_tags = True My Serializer => class Base64ImageField(serializers.ImageField): """ A Django REST framework field for handling image-uploads through raw post data. It uses base64 for encoding and decoding the contents of the file. Heavily based on https://github.com/tomchristie/django-rest-framework/pull/1268 Updated for Django REST framework 3. """ def to_internal_value(self, data): from django.core.files.base import ContentFile import base64 import six import uuid # Check if this is a base64 string if len(data) <= 0 : return '' if isinstance(data, six.string_types): # Check if the base64 string is in the "data:" format if 'data:' in data and ';base64,' in data: # Break out the header from the base64 content header, data = data.split(';base64,') # … -
Unable to import 'misaka' - Django
I am following a tutorial about how to build a social network. I run into this error: IntegrityError at /posts/new/ NOT NULL constraint failed: posts_post.user_id Complete traceback (please note the lines in bold): The above exception (NOT NULL constraint failed: posts_post.user_id) was the direct cause of the following exception: C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\handlers\base.py in _get_response response = self.process_exception_by_middleware(e, request) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\core\handlers\base.py in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\base.py in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\contrib\auth\mixins.py in dispatch return super().dispatch(request, *args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\base.py in dispatch return handler(request, *args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\edit.py in post return super().post(request, *args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\edit.py in post return self.form_valid(form) … ▶ Local vars C:\Users\Tommaso\Django rest framework\Udemy Django\simplesocial\posts\views.py in form_valid return super().form_valid(form) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\views\generic\edit.py in form_valid self.object = form.save() … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\forms\models.py in save self.instance.save() … ▶ Local vars C:\Users\Tommaso\Django rest framework\Udemy Django\simplesocial\posts\models.py in save super().save(*args, **kwargs) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\models\base.py in save force_update=force_update, update_fields=update_fields) … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\models\base.py in save_base force_update, using, update_fields, … ▶ Local vars C:\Applicazioni_Tommaso\Phyton\lib\site-packages\django\db\models\base.py in _save_table result … -
Get _meta of model through relationship
I have two models. I would like to pass one of the models to a function, and then have the function traverse the ManyToManyField to display the related model's fields. class Email(models.Model): subject = models.CharField(max_length=50) body = models.TextField() time_sent = models.DateTimeField(null=True, blank=True) recipients = models.ManyToManyField(Email, related_name='emails') class Contact(models.Model): email_address = models.EmailField() contact_name = models.CharField(max_length=50, null=True, blank=True) The end result would be something like: >>> get_fields_of_related_model(Email) {'recipients': {'email_address': 'EmailField', 'contact_name': 'CharField'}} >>> get_fields_of_related_model(Contact) {'emails': {'subject': 'CharField', 'body': 'TextField', 'time_sent': 'DateTimeField', 'recipients': 'ManyToManyField'}}