Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rotate selfie image working in development but not working when saving to S3 bucket in production?
I'm trying to fix an image rotation error that I'm getting in production, but not getting in development. Been stuck on this for a few days and would really appreciate any help from anyone who has any insight into how to solve this! ==Context== I'm writing a Django web app with a profile pic upload feature. To get over the selfie EXIF problem (incorrect orientation), I've added a function that rotates the image using a post-save receiver. It works great in development (when the images are saved and stored locally), but now that I've moved to production (Heroku server; saving images in S3 bucket), the function throws a FileNotFound error -- [Errno 2] No such file or directory: 'https://db-devsite1.s3.amazonaws.com/media/uploadImage/81c01af5-030f-42ed-b413-91eb8941675b.JPG', even though it's the correct file path for the image. Everything else still works great. ==View== def rotateimage (request): if request.method == 'POST': form = uploadImageForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('rotateimage') else: form = uploadImageForm() ==Model== import os from django.db import models from catalog.utilities import rotate_image from django.urls import reverse from io import BytesIO from django.core.files import File from PIL import Image, ExifTags from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings class uploadImage(models.Model): uploadImage = models.ImageField(upload_to='uploadImage', … -
when i set SECURITY_SSL_REDIRECT = True in django settings my site doesnt work in browser
i set in django settings : SESSION_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO','https') CSRF_COOKIE_SECURE = True and if i set SECURE_SSL_REDIRECT= True my site cant load in browser -
i'm using django 1.1 with python 2.7. cant display pdf in browser it pops a notification for download
if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %(user_name) content = "inline; filename='%s'" %(filename) download = request.GET.get("download") return response return HttpResponse("Not found") this is the code views.py , a part of it. I have tried many things. Even the pdf stored on my pc locally can only be downloaded and does not display. I used also. -
Django how to do model1.model2_set.all() in template?
I'm building a website and I have two models, let's call them Model1 and Model2, with Model2 having a foreignKey attribute pointing towards Model1. I have a template in which I have access to the list of all entry in the Model1 table of the database. What I want is doing a for loop over all the entries model2 associated to a specific entry model1. In a view, I could do : for model2 in model1.model2_set.all(): but how can I do that in a template ? I've tried {% for model2 in model1.model2_set.all %} but that doesn't work. Thanks in advance ! -
Question on Django queryset searching across multiple models and fields
I have the following models within my Django code. class Card(models.Model): card_name = models.CharField(max_length=255) geography_choices = [('Africa', 'Africa'), ('Asia', 'Asia'), ('Australia', 'Australia'), ('Europe', 'Europe'), ('North America', 'North America'), ('South America', 'South America')] geography = models.CharField(max_length=255, choices=geography_choices, default='North America') type_choices = [('Creature', 'Creature'), ('Spell', 'Spell'), ('New Type', 'New Type'),('Undecided', 'Undecided')] card_type = models.CharField(max_length=255, choices=type_choices, default='Creature') class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) entry_date_time = models.DateTimeField(default=timezone.now, null=True) class Meta: ordering = ['-entry_date_time'] score_choices = [(-5,'-5'), (-4, '-4'), (-3,'-3'), (-2, '-2'), (-1,'-1'), (0,'0'), (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5')] score = models.FloatField(choices=score_choices, default=0) read_through_choices = [(-1, 'Competitive'), (0, 'No Effect'), (1, 'Industry-Wide')] read_through = models.IntegerField(choices=read_through_choices, default=0) cardvar = models.ForeignKey(Card, on_delete=models.CASCADE, null=True) I also had the following function as a query within my views as a search feature: def get_queryset(self): #new query =self.request.GET.get('q') results = Article.objects.filter( Q(cardvar__card_name__iexact=query) ).order_by('cardvar', '-entry_date_time') return results However, this search function only returns articles whose "card topic" is specifically the one searched. What I would like to do is by searching for a card name (cardvar) to return not only articles with that cardvar Foreignkey but ALSO articles which a) have the same card_type as card_var, as well as b) have an Article score … -
How to add additional help_text to a model
I have a standard model: class Book(models.Model) title = models.CharField( max_length=None, verbose_name='These are books', help_text='Provide a title for your book' ) Is there any way I can add a second help_text2 or placeholder_text so I can render an input placeholder as well as help text when displaying a model.Form? I want to do this inside the model, not inside the form (which I know I can do with Widgets). For example: class Book(models.Model) title = models.CharField( max_length=None, verbose_name='These are books', help_text='Provide a title for your book', placeholder='E.g. My First Book' ) -
Categories and subcategories in Django/Wagtail
I'm trying to implement categories and subcategories for question_answers snippet in Wagtail/Django. I have defined the categories as shown here: https://docs.djangoproject.com/en/3.0/ref/models/fields/. The problem is that I am finding it difficult to implement subcategories for the categories that I defined and I cannot find a proper way to show them in Wagtail admin, as I am not sure which of the available panel types I should use from the ones that are available (https://docs.wagtail.io/en/v2.5/reference/pages/panels.html). Also, preferably I want to use CharField for the names. Ideally, I want them to be available to choose from in the admin panel, so that for example when I choose one of the categories, I get the subcategories for each. What would be the best way to go about it? Here's the code: from django.db import models from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import ( FieldPanel, MultiFieldPanel, InlinePanel ) from wagtail.snippets.models import register_snippet class FaqPage(Page): max_count = 1 slug = 'faq' template = 'faq/faq.html' @register_snippet class question_answer(models.Model): CATEGORIES = ( ('GENERAL', 'General'), ('JOBS', 'Jobs'), ('LANGUAGES', 'Languages'), ('PROGRAM', 'Program'), ('REGISTRATION', 'Registration'), ('STUDIES', 'Studies'), ('SUPPORT', 'Support') ) category = models.CharField(max_length=30, blank=False, choices=CATEGORIES, default='Other'), question = models.CharField(max_length=150, blank=False) answer = RichTextField(blank=False) panels = [ … -
The serializer field might be named incorrectly and not match any attribute or key on the `Project` instance
i'm trying to work with django-rest-framework and serializers ,and i keep getting this error : AttributeError: Got AttributeError when attempting to get a value for field recruitment_date on serializer EmployeeSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Project instance. Original exception text was: 'Project' object has no attribute 'recruitment_date' models.py : class Employee(models.Model): f_name = models.CharField(max_length=50,default='') l_name = models.CharField(max_length=50,default='') telephone = models.CharField(max_length=15,default='') recruitment_date = models.DateField(auto_now_add=False) salary = models.DecimalField(max_digits=12,decimal_places=2) def __str__(self): return self.f_name +' '+self.l_name class Project(models.Model): name = models.CharField(max_length=255, default='') statuts = models.CharField(max_length=10,choices = STATUS,default= STATUS[0]) description = models.TextField(blank=True) leader = models.OneToOneField(Employee,on_delete=models.CASCADE,related_name = 'leader') p_employees = models.ManyToManyField(Employee) estimated_budget = models.DecimalField(max_digits=12,decimal_places=4) start_date = models.DateField(auto_now_add=False) end_date = models.DateField(auto_now_add=False) tasks = models.ManyToManyField(Task) materials = models.ManyToManyField(Materials) def __str__(self): return self.name serializers.py : class EmployeeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Employee fields=['id','f_name','l_name','telephone','recruitment_date','salary'] class ProjectSerializer(serializers.HyperlinkedModelSerializer): leader = EmployeeSerializer() p_employees = EmployeeSerializer(many =True) tasks = TaskSerializer(many =True) materials = MaterialsSerializer(many =True) class Meta : model = Project fields = ['name','statuts','description','leader','p_employees', 'start_date','end_date','tasks','materials'] -
how does django class based views know which context means what
Let's say I have a model of blog: #models.py class Blog(models.Model): title = models.CharField(max_length=100) content = models.TextField() def __str__(self): return self.title And in views I have a class based view: #views.py class BlogDetailView(DetailView): model = Blog And I refer that view as: urlpatterns = [ path('post/<int:pk>/', BlogDetailView.as_view(), name='blog-detail'), Now django DetailView accepts the context variable name to be 'object'. So in the html, I do something like: <<! blog_detail.html --> <p>{{ object.content }}</p> And that renders contents which I manually created using manage.py shell. Now, my question is, how does django know that 'object' explicitly means 'a' discrete blog? Like here I am only referring that primary key in url. So is it like django grabs that primary key from url and then passes that primary key as context and then when I refer 'object.content' then django grabs the object that has primary key as 1 from the model Blog and then displays the actual content? Is it like it or something else? I really can't understand. Any help with a detailed explanation about how it happens will be really be helpful. -
Django 2.2 : how to add a hidden input and populate it?
How do I add an arbitrary hidden input to a specific model's view and populate it with a value? I would like to get it from request.GET.get('my_input_name') on submit (e.g. "Save") . It's not a field that exist in the model, it's just a random value. Also: I am not trying to make some existing field hidden with widgets. If possible, without introducing a custom template. Thanks. -
How to fix "like" functional Django Rest Framework
Base url - api/v1/posts/. If we use GET request, we can see response with all objects from "posts". For example: { "count": 1, "next": null, "previous": null, "results": [ { "url": "http://127.0.0.1:8000/api/v1/posts/11/", "id": 12, "name": "Sample name", "type": "Футболка", "collection": "Winter 2020" "isFan": true } ] } isFan is a boolean value. Value equal true, if we liked post. For example, the url of post looks like api/v1/posts/6. For like some post, we need to do POST request to this url - api/v1/posts/6/like For this functional, my code looks like - My class PostSerrializer - def get_isFan(self, obj) -> bool: user = self.context.get('request').user if user.is_anonymous: print() else: return services.isFan(obj, user) Services - def add_like(obj, user): obj_type = ContentType.objects.get_for_model(obj) like, is_created = Like.objects.get_or_create(content_type=obj_type, object_id=obj.id, user=user) return like def remove_like(obj, user): obj_type = ContentType.objects.get_for_model(obj) Like.objects.filter(content_type=obj_type, object_id=obj.id, user=user).delete() def isFan(obj, user) -> bool: if User.is_authenticated: obj_type = ContentType.objects.get_for_model(obj) likes = Like.objects.filter(content_type=obj_type, object_id=obj.id, user=user) return likes.exists() Models.py - class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likes') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveSmallIntegerField() content_object = GenericForeignKey('content_type', 'object_id') Now, I want to filter, what posts I did like. Where isFan == true class PostViewSet(LikedMixin, viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer authentication_classes = (TokenAuthentication, SessionAuthentication, ) … -
Display Django model data in HTML table by grouping data by users
I want to display all the information from my models to this format in the HTML table and have followed this Django link: Name Start_time Stop_time Bobby Dec. 31, 2019, 5:39 a.m Dec. 31, 2019, 5:50 a.m Jan. 01, 2020, 9:00 a.m Jan. 01, 2020, 18:00 a.m Jan. 02, 2020, 6:00 a.m Jan. 02, 2020, 19:00 a.m ... ... Tina Dec. 31, 2019, 9:00 a.m Dec. 31, 2019, 10:00 a.m Dec. 31, 2019, 12:00 p.m Dec. 31, 2019, 15:00 p.m Jan. 01, 2020, 9:00 a.m Jan. 01, 2020, 11:00 a.m Jan. 02, 2020, 5:00 a.m Jan. 02, 2020, 9:00 a.m Jan. 02, 2020, 10:00 a.m Jan. 02, 2020, 12:00 a.m ... ... The information should be grouped according to each user and I tried the following: models.py: class Starttime(models.Model): user_id= models.ForeignKey(User, on_delete = models.CASCADE) start_time = models.DateTimeField() class Stoptime(models.Model): user_id= models.ForeignKey(User, on_delete = models.CASCADE) stop_time = models.DateTimeField() views.py: def interface(request): data = User.objects.filter(pk__gt=1) store_data = [] for user in data: if Starttime.objects.filter(user_id = user).exists(): sta_time = Starttime.objects.filter(user_id = user) sta_data = sta_time.values_list('start_time', flat=True) sto_time = Stoptime.objects.filter(user_id = user) sto_data = sto_time.values_list('stop_time', flat=True) store_data.append({'name': user.first_name, 'start_time':sta_data, 'stop_time': sto_data}) else: store_data.append({'name': user.first_name, 'start_time':sta_data, 'stop_time': sto_data}) return render(request, 'users/interface.html', {'data': store_data}) interface.html: <table> … -
Having problems with Jinja2 on windows
PS E:\Dropbox\rp-portfolio\personal_portfolio> Jinja2 --version Jinja2 : The term 'Jinja2' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + Jinja2 --version + ~~~~~~ + CategoryInfo : ObjectNotFound: (Jinja2:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
New field of custom AbstractUser not showing up in Django admin despite overriding the default admin
I have added the field introduction to my CustomUser model and made the proper migrations: class CustomUser(AbstractUser): introduction = models.CharField(max_length=5000, null=True, blank=True, default="") def get_absolute_url(self): return reverse('user_detail', args=[str(self.username)]) admin.py overrides the default admin for users: CustomUser = get_user_model() class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['username', 'introduction',] admin.site.register(CustomUser,CustomUserAdmin) forms.py: class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('username',) class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ('username', 'introduction',) Despite this, when I try to modify a user in the Django admin, the introduction field doesn't appear. I am using django 3.0.1. -
Create news website with data visualizations in Django
I'm trying to make a website that I can post articles to. The articles will have various d3.js visualizations or something like this: https://www.latimes.com/projects/star-wars-most-talkative-characters/ https://www.latimes.com/projects/rams-chargers-fan-map-la/ The site will have less than 500 visitors, and security is not a concern. I plan to upload articles once a day, so uploading should be simple. I'm currently planning on using Django for the backend, d3.JS for visualizations, and some database to store articles in, etc. I'm planning on using a rich text editor plugin such as TinyMCE to format the pages. My only Django experience is the tutorial series in the documentation, so I'm not sure if this is the right set of tools for the job. Is there a better way to store an article that contains graphs, images, interactive visualizations, etc. in a database? Is there a better way to structure what I'm trying to do? -
How to dynamically render vuejs directives in custom django template tags
I created a custom template tag in django called text_field @register.inclusion_tag('form_field_tags/text_field.html') def text_field(field, prefix=None, field_type=None, attr=None, **kwargs): return { 'field': field, 'prefix': prefix, 'field_type': field_type, 'placeholder': '', 'attrs': parse_attrs(attr) } Where parse_attrs is a function that takes as input something like this class=form-control mb-4, v-model=property_name. {% text_field form.property_name attr="class=form-control mb-4, v-model=property_name" %} parse_attrs then creates a dictionary of html attribute and value that can be looped over, so in my text_field.html i can loop over all the attrs passed in from the text_field custom template tag <label > {% if field.field.required %} <strong> {{ field.label }} <span> * </span> </strong> {% else %} {{ field.label }} {% endif %} </label> <input {% if field_type == "password" %} type="password" {% else %} type="text" {% endif %} {% for attr, val in attrs.items %} {{ attr }} = {{ val }} {% endfor %} name="{% if prefix %}{{prefix}}-{% endif %}{{ field.name }}" placeholder="{{ placeholder }}" id="{% if prefix %}{{prefix}}-{% endif %}{{ field.name }}" {% if field.field.required %} required="required" {% endif %} {% if field.value %} value="{{ field.value }}" {% endif %}> However when I try refresh the browser and see the rendered output what I get is <input type="text" class="form-control mb-4" name="property_name" … -
how to automatically take GeoPoint() from my model's latutude and longitude data when using search_index --rebuild from command line?
I have a model of Location which has the following fields: class Location(models.Model): latitude = models.CharField(max_length=255, null=True, blank=True) longitude = models.CharField(max_length=255, null=True, blank=True) how_to_reach = models.TextField(default='', null=True, blank=True) class Meta: abstract = True And another model City that inherits Location class City(Location): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255, null=True, blank=True) I am using elasticsearch 6.3.2 and accordingly using elasticsearch-dsl-py and elasticsearch library versions, I have already used in another project so I know it is not compatibility issue of libraries and elasticsearch version. My question in how to use GeoPoint() field. In my document.py file I have: from .models import City from django_elasticsearch_dsl import Document, fields, GeoPoint from django_elasticsearch_dsl.registries import registry @registry.register_document class CityDocument(Document): location = GeoPoint() class Index: name = 'cities' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = City fields = [ 'name', 'slug', 'id' ] The latitude and longitude fields I have in model, how will I get them indexed when I use: python manage.py search_index --rebuild from terminal. Currently if I do this, only textual fields 'name', 'slug' and 'id' get indexed with each City doc, no location field is there in those docs.However in mappings I can see the location field "location" : … -
TypeError at /posts/upvote/3/ vote_up() missing 1 required positional argument: 'vote_id'
I've been trying to add buttons for upvotes and downvotes, it's kinda new to me, I followed instructions from here & here, I also tried following this tutorial, but it was a bit over my level, I need more understanding of Django for this. Whenever I click like or dislike, I get Internal Server Error: /posts/upvote/3/ Traceback (most recent call last): File "C:\Users\...\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\...\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\...\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: vote_up() missing 1 required positional argument: 'vote_id' [31/Dec/2019 12:09:11] "GET /posts/upvote/3/ HTTP/1.1" 500 65961 I thought I needed to make a bit changes in my urls.py as said in a few of SO solutions, I tried out a few things, but ended up in more errors. In my urls.py: from django.urls import path,re_path from . import views app_name='posts' urlpatterns = [ ... ... re_path(r"upvote/(?P<pk>\d+)/$",views.vote_up, name="upvote"), re_path(r"downvote/(?P<pk>\d+)/$",views.vote_down, name="downvote"), path('vote_count/',views.vote_count,name='votecount'), ] In my views.py: def vote_up(user_id, vote_id,pk): user = User.objects.get(pk=user_id) vote = Vote.objects.get(pk=vote_id) rows = UserVotes.objects.filter(name=user, vote=vote) if rows.count() == 0: user_vote = UserVotes(name=user, vote=vote) user_vote.save() return 'ok' else: return 'fail' # /vote/down def vote_down(user_id, vote_id,pk): user = User.objects.get(pk=user_id) vote … -
How to configure AWS4 S3 Authorization in Django?
I configurred S3 bucket for Frankfurt region. Though my Django-based service is able to write files to the bucket, whenever it tried to read them there's InvalidRequest error telling to upgrate authorization mechanizm: <Error> <Code>InvalidRequest</Code> <Message> The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. </Message> <RequestId>17E9629D33BF1E24</RequestId> <HostId> ... </HostId> </Error> Is the cause for this error burried in my incorrect implementation of storage backend or is this caused by bucket not supporting older AWS3 method of authorization? How to configure S3Boto3Storage in Django to use AWS4 authorization? I can't find any definitive documentation on this issue. -
How to add custom field like phone number in User model in django so that it can be used in UserCreationForm?
I want to save user phone number upon sign up. How can i add phone number in user creation form? If i create a separate model known as UserContact, then how can i add this field in UserCreationForm so that when it is submitted it gets saved to the corresponding models? -
How can i authenticate a POST request in Django?
I built a custom view where, when the page is loaded, the view sends a request to an external Python script. This script should retrieve some data of the user who sent the request and send it back as a response to the Django view, which will show it to the user. The problem with my actual code is that i don't know how to authenticate the request sent from the external script to Django. In order for Django to accept the request and show the user their data, it needs to be authenticated with the user's crdeentials. The problem is that the external Python script doesn't have those credentials, unless the Django view sends it first. So, X user is using the view, the view sends a request to the external script, the external script should send a response with the user's data and the credentials of user X. Same goes if user Y is using the view and so on. Since this service is handling personal data, i would like it to be as safe as possible. Here is what i have: This is how the request is sent from the external script to the Django view import … -
How to perform actions on files stored in S3 bucket?
In a Django-based web sevrice I'm implementing storage for FileField objects in S3 bucket. Some of those files later are copied to temporary path in the service itself, generate some result archive and are instantly deleted from temporary storage. Here's simplified version of one of models I have: class MyModel(models.Model): some_image = models.ImageField(storage=PrivateMediaStorage()) some_file = models.FileField(storage=PrivateMediaStorage()) ... Where PrivateMediaStorage is very primitive S3Boto3Storage implementation: class PrivateMediaStorage(S3Boto3Storage): location = 'private' default_acl = 'private' file_overwrite = False custom_domain = False With this implmenetation files are being correctly uploaded to S3 bucket. At some point when service wants to use them (copy to temporary local storage): instance = MyModel.objects.get(...) shutil.copy2(instance.some_image.name, ***some_temporary_path_at_the_server***) shutil.copy2(instance.some_file.name, ***some_temporary_path_at_the_server***) This action raises FileNotFound exception: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.7/site-packages/rest_framework/views.py", line 502, in dispatch response … -
not able to run Django in windows 10
I have just installed Django in anaconda. I am running it in windows 10, right now i am trying to run the django server. For this when i manage.py runserver i get a popup window which asks me to chose how to open this site. The screenshot is below: Initially i chose windows explorer but since then i am getting a window which list the file as downloads. How can i run this file? I have also tried http://127.0.0.1:8000/ in chrome but i get "the site cannot be reached page". How can i fix this? -
django.db.utils.ProgrammingError: [42S22] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'xxx'. (207) (SQLExecDirectW);
I have added new fields to model and tried "python manage.py makemigrations" . It gave me below error. Can anyone help me? django.db.utils.ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'pm_comments'. (207) (SQLExecDirectW); [42S22] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'archived'. (207)") -
Python Django admin iterate and display
I am trying to find a way where I need to display the custom result in my Django admin section for that I have this dataset: Gist link to my data In my code section, I can get this data using this code in Django admin: def question_00(self, obj): return obj.data["0"]["question"] def answer_00(self, obj): return obj.data["0"]["answer"] And I am displaying that data using this code: fieldsets = ( (None, { 'fields': ( ('question_00','answer_00'), ) }), ) My whole code is like this: class SurveyAdmin(admin.ModelAdmin): list_display = ['user_id','question_answer'] def question_00(self, obj): return obj.data["0"]["question"] def answer_00(self, obj): return obj.data["0"]["answer"] fieldsets = ( (None, { 'fields': ( ('question_00','answer_00'), ) }), ) readonly_fields = ["question_00","user_id","answer_00"] Everything is fine all is working if I need to create this system through iteration how can I get a result like this: Where it create a functions like: def question_00(self, obj): return obj.data["0"]["question"] def question_01(self, obj): return obj.data["1"]["question"] ...... And answer like this: def answer_00(self, obj): return obj.data["0"]["answer"] def answer_01(self, obj): return obj.data["1"]["answer"] And it should populate data like this in fieldset: fieldsets = ( (None, { 'fields': ( ('question_00','answer_00'), ('question_01','answer_01'), ...... ) }), ) It looks simple but I am trying to do it admin.py file what …