Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run a function multiple times and return different result python
Hello I'm having a problem I don't know if this is doable but what I wanted to do is call a function multiple times. The idea is I am generating a serial number for tickets I have a function that generates a number which is 16 in length def random_number_generator(size=16, numbers=string.digits): return ''.join(random.choice(numbers) for _ in range(size)) now if I run this function like this print(random_number_generator() * 4) it will return something like this 1234567890987654 1234567890987654 1234567890987654 1234567890987654 How do I make this to return different numbers instead of the same numbers? -
How to restrict date hierarchy to years in django administration?
I need to display some data from a table in django administration. Everything is set and working but I was wondering how I could do to restrict the date_hierarchy to years only. Not allowing to show in detail for months and date. Here's the view class HistorySummaryAdmin(admin.ModelAdmin): change_list_template = 'admin/history_summary_change_list.html' date_hierarchy = 'date_and_time' list_filter = ( 'device_type', ) def changelist_view(self, request, extra_context=None): response = super(HistorySummaryAdmin, self).changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'views': Count("date_and_time"), } selectpart = { 'week': "CONCAT(YEAR(DATE_ADD(date_and_time, INTERVAL - WEEKDAY(date_and_time) DAY)),'-',LPAD(WEEK(DATE_ADD(date_and_time, INTERVAL - WEEKDAY(date_and_time) DAY)),2,0))", } response.context_data['summary'] = list( qs .extra(select=selectpart) .values('week') .annotate(**metrics) .order_by('-week') ) summary_over_time = qs.extra(select=selectpart).values('week').annotate(**metrics).order_by('-views') high = summary_over_time.first()['views'] low = summary_over_time.last()['views'] summary_over_time = qs.extra(select=selectpart).values('week').annotate(**metrics).order_by('week') response.context_data['summary_over_time'] = [{ 'week': x['week'], 'views': x['views'], 'pct': x['views'] * 100 / high, } for x in summary_over_time] return response And my template <div class="results"> <h2> Views over time </h2> <div class="bar-chart-graph"> <div class="bar-chart"> {% for x in summary_over_time %} <div class="bar" style="height:{{x.pct}}%"> <div class="bar-tooltip"> <p>{{x.week}}</p> <p>{{x.views | default:0 }} views</p> </div> </div> {% endfor %} </div> </div> <table> <thead> <tr> <th> <div class="text"> <a href="#">Week</a> </div> </th> <th> <div class="text"> <a href="#">Views</a> </div> </th> </tr> </thead> <tbody> {% for row … -
How to count the number of employees based on age groups in Django
I have a problem with writing a code for employee count based on age groups. I have six age groups and would love to render out the total number of employees that falls in-between those ages. For instance: Baby Boomers | 20 Employees Gen Y | 15 Employees And so on... Can someone please help me out with this? I would so much appreciate it if the code can work on both SQLite (development) and Postgres (production). Thanks -
deploying django react on digitalocean with nginx gunicorn
i have bind react build inside django. its working fine on localhost but on server its static files not working. when i run this after activating virtualenv: gunicorn --bind 64.225.24.226:8000 liveimage.wsgi its admin panel working without css: this is my nginx default config: server { listen 80; server_name 64.225.24.226; access_log off; location /media/ { alias /root/liveimage/media/; # change project_name } location /static { autoindex on; alias /root/liveimage/build; } location / { proxy_pass http://127.0.0.1; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } my seetings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'build/static')] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/liveimage ExecStart=/root/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ liveimage.wsgi:application [Install] WantedBy=multi-user.target my project is in /root/liveimage and virtualenv at /root/venv i dont know what going wrong -
How to save array of values in django rest framework
How to save array of values in django rest framework ,can you help to solve this problem. example: { "user":test{ "category":cat1, "subcategories":sub1 }, { "category":cat2, "subcategories":sub2 } } models.py class SavingCategoryandPreferences(models.Model): user = models.ForeignKey(User, related_name='user') category = models.ForeignKey(Category) subcategories= models.ForeignKey(SubCategory, related_name='sub', default=1) sort_order = models.IntegerField(default=0) slug = AutoSlugField(populate_from='subcategories_id', separator='', editable=True) created_time = models.DateTimeField("Created Date", auto_now_add=True) serializer.py class SavecatsubSerialize(serializers.ModelSerializer): class Meta: model = SavingCategoryandPreferences fields = ('id', 'user', 'category', 'subcategories') views.py class Mobilesavecatsub(viewsets.ModelViewSet): serializer_class = serializers.SavecatsubSerialize queryset = SavingCategoryandPreferences.objects.all() -
Is it possible to use global pip installed modules in virtual environment? [duplicate]
This question already has an answer here: How to import a globally installed package to virtualenv folder 5 answers Is it possible to use global pip installed modules in virtual environment? I mean, I don't have an internet access all the time. So I wonder, if it is possible to use globally installed modules in new created virtual environment. I have somewhere read that, instead pip install it is possible to use pip download. Please help, what I have to do, and how I have to do? -
save raw html data to postgresql database
Can anyone please help me solve this issue. I want to save raw HTML data to the Django PostgreSQL database. I am currently new to both Django and programming and i have been spending lots of time and still could solve it. Any help will be grateful. my error This is the error I get at the web browser. NameError at / name 'models' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 2.2.8 Exception Type: NameError Exception Value: name 'models' is not defined Exception Location: D:\Django\TimeSheetProject\morabu_timesheet\views.py in create_timesheet_view, line 18 Python Executable: D:\Django\TimeSheetProject\morabu\Scripts\python.exe Python Version: 3.7.2 Python Path: ['D:\\Django\\TimeSheetProject', 'D:\\Django\\TimeSheetProject\\morabu\\Scripts\\python37.zip', 'D:\\Django\\TimeSheetProject\\morabu\\DLLs', 'D:\\Django\\TimeSheetProject\\morabu\\lib', 'D:\\Django\\TimeSheetProject\\morabu\\Scripts', 'c:\\program files\\python\\Lib', 'c:\\program files\\python\\DLLs', 'D:\\Django\\TimeSheetProject\\morabu', 'D:\\Django\\TimeSheetProject\\morabu\\lib\\site-packages'] Server time: Fri, 13 Dec 2019 16:55:22 +0900 this is the models.py file I have created. from django.db import models # Create your models here. class TimesheetDetails(models.Model): date = models.CharField(max_length = 10) day = models.CharField(max_length = 10) startTime = models.CharField(max_length =10) endTime = models.CharField(max_length =10) breakTime = models.CharField(max_length=3) normalTime = models.CharField(max_length=10) overTime = models.CharField(max_length = 10) holidayTime = models.CharField(max_length = 10) weekType = models.CharField( max_length = 10) attendance = models.CharField( max_length = 10) content = models.TextField( max_length = 10) my views.py code from . models import TimesheetDetails # … -
TypeError: hasattr(): attribute name must be string in djnago rest framework
class RemoveDependentViewSets(CustomModelViewSet): """ This view-set is used for Delete employee dependent """ http_method_names = ('delete',) queryset = EmployeeDependents.objects.filter() permission_classes = (IsAuthenticated, IsEmployeePermission) def destroy(self, request, *args, **kwargs): instance = self.get_object() dependent_del = EmployeeDependents.objects.filter(id=instance.id, created_by=request.user).first() if dependent_del: return instance.delete(dependent_del, request) return custom_error_response(status=status.HTTP_400_BAD_REQUEST, detail=ERROR_CODE['2016']) This is my views.py for deleting the dependent added by employee and employee. what am i doing wrong please tell me. what is up with this problem -
Contains null values during migration
I try to add a new field to my model, allowing to be null or blank. chapter = models.IntegerField(max_length=4, default=None, blank=True, null=True) Make migrations worked fine: python3 manage.py makemigrations But when I try to migrate, I get this error: return self.cursor.execute(sql, params) django.db.utils.IntegrityError: column "chapter" contains null values OK, I understand what the error tries to tell, there are records already...But I allow chapter field to be null. Aren't these 3 enough to set new rows as null? default=None, blank=True, null=True) Truncating database is the easy way, I want to understand how to do such migrations with existing data. What am I missing? -
How to create django app programmatically using call_command
In my project current scenario i am required to create app programmatically. What i have done so far, the steps are listed below. 1 - I have created a test app which is just simple text field crud. 2 - In Testapp model i am using post_save.connect method to run some custom app generation code. def model_created_or_updated(sender, **kwargs): the_instance = kwargs['instance'] if kwargs['created']: app_name = ''.join(the_instance.test_title.lower().split()) generate_app(app_name) generate_app_model(app_name) generate_settings(app_name) create_migration(app_name) post_save.connect(model_created_or_updated, sender=TestApp) 3 - Now the first generate_app method create app (see below), Below function will created the app def generate_app(self): management.call_command('startapp', self) 4 - After that i have generate_app_model, I have programmatically write the newly created app model to add some custom fields in it. def generate_app_model(self): app_name = self try: model_file_ = open(os.path.join(settings.BASE_DIR, app_name + '/models.py'), 'r+') except IOError: print("An error was found. Either path is incorrect or file doesn't exist!") finally: class_name = str(app_name).capitalize() title_field = app_name + '_title' file_field = app_name + '_file' timestamp_field = app_name + '_timestamp' line1 = 'from django.db import models \n\n' line2 = 'class ' + class_name + '(models.Model): \n\n' line3 = '\t' + title_field + ' = models.CharField(max_length=200) \n' line4 = '\t' + file_field + ' = models.FileField(upload_to="uploads/' + app_name + … -
Listing view will not filter based on captured URL value
With a given URL path, there is a variable portion that dictates which model instances are displayed depending on whatever uppercase letter is contained within it. As shown, the letter 'A' is set as the default for the view. However, if any other letter is passed to the path (such as 'B', "C", ...), the QuerySet is not filtered to what should be only those instances whose first letter matches that variable captured value. What can be done so that any letter from A-Z will return the correct QuerySet. As of now, any uppercase letter returns only a QuerySet where each model instances' first letter begins with 'A'. # urls.py from django.contrib import admin from django.urls import path, re_path, include from minerals import views mineral_patterns = ([ re_path("", views.filter_letter_list, name="letter_list"), re_path('(?P<query>([A-Z]))/', views.filter_letter_list, name="letter_list"), ], "minerals") urlpatterns = [ path('admin/', admin.site.urls), path('', include(mineral_patterns)) ] # views.py from random import choice from string import ascii_uppercase from django.shortcuts import render, get_list_or_404 from .models import Mineral # Create your views here. def filter_letter_list(request, query="A"): # import pdb; pdb.set_trace(); minerals = get_list_or_404(Mineral, name__startswith=query) random_mineral = choice(Mineral.objects.all()) return render( request, "minerals/list.html", context={ 'minerals': minerals, 'random_mineral': random_mineral, 'query': query, 'letters': ascii_uppercase } ) -
Django - Where IN with multiple columns
I have a query that needs to fetch from a table that meet two columns requirements exactly. So if I have users table with columns, age and score. SELECT * FROM users where (age, score) IN ((5,6), (9,12), (22,44)..) In my web app I am getting this pairs from an ajax request, and the number could be quite big. How do I construct a query for this in Django? I am working on postgres database -
Date picker is not initializing in django template
In my django template form it having one issue when I submitting the form I just checked the console it showing jquery-3.2.1.min.js:2 Uncaught TypeError: $(...).daterangepicker is not a function at HTMLDocument.<anonymous> (<anonymous>:4:37) at j (jquery-3.2.1.min.js:2) at k (jquery-3.2.1.min.js:2) I can understand the date picker initialising issue ... But its working fine in my local system but issue in the production ..... No idea why its showing like this in production only Here is my code <div class="modal-body"> <form method="post" id="new_form"> </form> </div> <script type="text/javascript" src="{% static 'assets/plugins/moment/moment.min.js' %}"></script> <link rel="stylesheet" href="{% static 'assets/plugins/daterangepicker/daterangepicker.css' %}"/> <script type="text/javascript" src="{% static 'assets/plugins/daterangepicker/daterangepicker.min.js' %}"></script> <script type="text/javascript"> $(document).ready(function() { $('input[name="joining_date"]').daterangepicker({ singleDatePicker: true, showDropdowns: true, joining_date: moment().startOf('hour'), "locale": { "format": "YYYY-MM-DD", "separator": "-" } }); }); -
Python contains and icontains both return case insensitive results
I have a very curious case that I'm not sure I understand. I am filtering data using field__contains but am getting case insensitive results. As an example: Entry Data: { "id": 2, "last_login": null, "is_superuser": false, "username": "slappy", "first_name": "don", "last_name": "sweeney", "email": "don@bruins.com", "is_staff": false, "is_active": true, "date_joined": "2019-12-09T09:07:11.897502Z", "groups": [], "user_permissions": [] } Search: query = { 'email__contains' : 'DON' } data_set = data_set.filter(Q(**query)) return data_set The results return the entry despite the casing clearly being wrong. I checked other filter types and they are working as expected: Search 2: query = { 'username__exact' : 'SLAPPY' } data_set = data_set.filter(Q(**query)) return data_set This search produces no results, as would be expected. Am I missing something here? Would could be the root cause of this? I would expect contains to be case sensitive and icontains to be case insensitive, otherwise why would the two exist? -
role of viewsets in django rest frameowrk when url is mapped to a method
Being new to drf , i am having slight issues in reading the code . In my urls.py of the app i see this . url(r'^ques', populate_health_questions) Now in views.py I see this . class QuestionViewSets(viewsets.ModelViewSet): #import pdb;pdb.set_trace(); queryset = HealthQuestions.objects.all() serializer_class = HealthQuestionsSerializer def get_permissions(self): print("self.action ", self.action) permission_classes = [] if self.action == 'create': import pdb;pdb.set_trace(); permission_classes = [IsAuthenticated, IsAdminUser] elif self.action == 'retrieve': permission_classes = [IsAuthenticated, IsAdminUser] elif self.action == 'update' or self.action == 'partial_update': permission_classes = [IsAuthenticated, IsAdminUser], elif self.action == 'destroy': permission_classes = [IsAuthenticated, IsAdminUser] elif self.action == 'list': permission_classes = [IsAuthenticated] return [permission() for permission in permission_classes] @api_view(['get']) def populate_health_questions(request): #import pdb;pdb.set_trace(); print("HealthQuestions",HealthQuestions.objects.all()) for data in HealthQuestions.objects.all(): print(data.ques) HealthQuestions.objects.all().delete() print("HealthQuestions after deleting",HealthQuestions.objects.all) questions = { "circulatory_issues" :"Heart Conditions or any other Blood or Circulatory Disorders except Hypertension?", "endocrine_issue" : "Other Endocrine Issues such as Hyperthyroidism or Pituitary / Parathyroid / Adrenal Gland Disorders?", } qlist = [] for key,ques in questions.items() : qlist.append({ "key" : key, "ques" : ques }) serializer = HealthQuestionsSerializer(data=qlist, many = True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now what i understand is that in order to get the ques route working , i look at the … -
What is the "best" way to build a Django Webapp frontend?
Thanks in advance! This is more a "philosophical" question then a direct request for opinions on code, though I would greatly appreciate anyone's input on code examples to look at. I've been a "traditional" developer for as long as I can remember, and now I work professionally as a data scientist. That being said, the one frontier I've never truly touched is web development. For a project I'm working on, I need to build (and in a somewhat expedited timeframe) a good-looking web application that functions somewhat similarly to a Wiki website (using existing codebases like Mediawiki is not an option here, so assume everything has to be built from the ground-up). In trying to do things the "right way", I've set things up as follows: Django models are built that seem to correctly capture the relational structure of data for the webapp, at least as tested by playing with Django's admin portal Django is hooked up to a Postgres database (1) and (2) are running inside Docker containers The most important piece here left, obviously, is the frontend. I've tried to ask several friends and acquaintances for advice, and have been pointed in the Bootstrap direction. From here, I … -
Why isn't my Django REST Framework URL resolving?
I am building an API with Django REST Framework, using: Viewsets Non-standard namespacing HyperlinkedModelSerializer URLPathVersioning I am trying to cut out a lot of what I perceive to be irrelevant aspects of my application as it is large, established, and closed-source. However, if you can think of anything I have missed I will provide additional information. I have configured my HyperlinkedModelSerializer to support my custom-namespaced Viewset. class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: fields = ["id", "url", "description", "source_id", "location", "test"] model = models.Item extra_kwargs = { "url": { "view_name": "api:v1:questions:item-detail", "lookup_field": "pk", } } My Viewset: class ItemViewSet(APIMixin, viewsets.ReadOnlyModelViewSet): queryset = models.Item.objects.all() serializer_class = serializers.ItemSerializer # This is largely inconsequential, except for maybe the versioning class. class APIMixin(SerializerExtensionsAPIViewMixin): authentication_classes = [authentication.SessionAuthentication] filter_backends = [ django_filters.DjangoFilterBackend, filters.OrderingFilter, ] ordering_fields = [] pagination_class = pagination.DefaultPageNumberPagination parser_classes = [ parsers.JSONParser, parsers.FormParser, parsers.MultiPartParser, ] permission_classes = [ permissions.IsAuthenticated, permissions.DjangoObjectPermissions, ] versioning_class = versioning.URLPathVersioning Loading a view from the viewset (list or detail) throws the following: Traceback: File "/usr/local/lib/python3.5/dist-packages/rest_framework/reverse.py" in reverse 41. url = scheme.reverse(viewname, args, kwargs, request, format, **extra) File "/usr/local/lib/python3.5/dist-packages/rest_framework/versioning.py" in reverse 88. viewname, args, kwargs, request, format, **extra File "/usr/local/lib/python3.5/dist-packages/rest_framework/versioning.py" in reverse 25. return _reverse(viewname, args, kwargs, request, format, **extra) File "/usr/local/lib/python3.5/dist-packages/rest_framework/reverse.py" in _reverse … -
How can I get parent model object from signal in django
I'm a beginner in python and django. Can you explain to me, how can I get parent model from signal in onetomany relations. For example, I have 2 models: class ModelOne(models.Model): name = models.CharField(max_length=20) class Modeltwo(models.Model): comment = models.CharField(max_length=20) mo = models.ForeignKey(ModelOne) And signal for post_save: @receiver(post_save) def post_save_model(sender,instance,**kwargs): print("Signal: ",instance.objects.all().last()) How can I get related object of ModelOne in post_save_model function when I save ModelTwo? -
using URL passed values, render different outputs in django template
views.py class citydetailview(generic.ListView): model = country def get_queryset(self): city_type = self.kwargs['city_type'] if city_type == 1: mytypes=city1.objects.all() ads=test1_ads.objects.all() context={'ads':ads,'mytypes':mytypes} return context elif city_type == 2: mytypes=city2.objects.all() ads=test2_ads.objects.all() context={'ads':ads,'mytypes':mytypes} return context elif city_type == 3: mytypes=city3.objects.all() ads=test3_ads.objects.all() context={'ads':ads,'mytypes':mytypes} return context return super().get_queryset() I am trying to render the the output from model: country and from the conditional context from query set. And i am trying how to makeup the template for this class view. To do so need your assistance.:) -
Encrypt Django Source Code information is still not there yet?
i have search some information about encrypt the django sourcode like ioncube for php and other. but for django i can't find the information, there are a few question for many years with negative answer. its still not there yet the encryptor for django ? and if its still not there yet, what the solution to protect the source code if we have to put the source code in the local client server. if you have the solution please to tell me how to or what you usually do to protect your source code if you have to put this in your client server, where your client can access and see it too. thanks before, -
How to have a button in Django template to add more form variable? Then how to process the multiple forms in views?
I have 2 questions: How to code a button to be able to add 1 or more duplicate form variable in template? I want to have a product_create page with a Product that may have multiple Color and Thickness. Then how to save the Product with multiple Color and Thickness in views.py to database? Do I need for loop? My 4 related models in models.py: class Product(models.Model): product_id = models.CharField(max_length=6) video = models.URLField(max_length=250, null=True, blank=True) class ColorParent(models.Model): name = models.CharField(max_length=50) class ProductColor(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) color = models.ForeignKey(ColorParent, on_delete=models.CASCADE) class ProductThickness(models.Model, MeasurementUnits): product = models.ForeignKey(Product, on_delete=models.CASCADE) dimension = models.PositiveIntegerField(verbose_name='Thickness in International SI unit', null=True, blank=True) dimension_unit = models.CharField(max_length=20, choices=MeasurementUnits.si_base_units, default=MeasurementUnits.millimetre, null=True, blank=True) alias = models.CharField(verbose_name='Thickness in Imperial unit', max_length=10, null=True, blank=True) alias_unit = models.CharField(max_length=20, choices=MeasurementUnits.imperial_base_units, default=MeasurementUnits.inch, null=True, blank=True) My forms.py: class ProductForm(ModelForm): class Meta: model = Product fields = ['product_id', 'video'] class ColorParentForm(ModelForm): class Meta: model = ColorParent fields = ['name'] class ProductColorForm(ModelForm): class Meta: model = ProductColor fields = ['color'] class ProductThicknessForm(ModelForm): class Meta: model = ProductThickness fields = ['dimension', 'dimension_unit', 'alias', 'alias_unit'] My views.py: def product_create_view(request): product_form = ProductForm(request.POST, prefix='product_form') color_form = ProductColorForm(request.POST, prefix='color_form') thickness_form = ProductThicknessForm(request.POST, prefix='thickness_form') if product_form.is_valid() and color_form.is_valid() and thickness_form.is_valid(): product = product_form.save() … -
How to store data in JSONField
I have a django model named Fixture class Fixture(models.Model): fixture = models.IntegerField(primary_key=True) league_id = models.ForeignKey('League',null=True, on_delete=models.SET_NULL, to_field="league") teams_h2h = JSONField(null=True) home_team_id = models.IntegerField(null=True) away_team_id = models.IntegerField(null=True) half_time_score = models.CharField(max_length=30,null=True) full_time_score = models.CharField(max_length=30,null=True)) The Fixture object in my app store the data of soccer match between to teams. Fixture model have teams_h2h field which is JSONField and i put there the data of previous soccer matchs between both commands. Here is my question. I have a list of fixture ids which i want to store inside teams_h2h field. In which data format i should put data into it?? List or dictionary?? -
Django upload file using get method
I would like to upload a single file or files at a time using get method. I have already done with the post method and working fine. But for some reason i would like to do the file upload using get method using command line. def home(request): if request.method == 'GET': varValue = request.GET.get('myfile', '') print(varValue) HTML code: <form method="GET" enctype="multipart/form-data"> <input type="file" name="myfile" accept="image/*" multiple> <button type="submit">Upload files</button> I can able to get the varValue as string. But wondering how to get the files using get method. -
Formated field on Django serializer breaks with CSV renderer
In my model I have a datetime field that is being formatted on my serializer with field_1 = serializers.DateTimeField(format="%d/%m/%Y - %H:%m") When a make a GET request to the endpoint /api/v1/myresource to fetch a JSON response it all works great. The problem happens when I try using a new endpoint to retrieve a CSV file. I created a new ViewSet and renderer as follows: class MyresourceCSVRenderer(CSVRenderer): header = ['Field 1', 'Field 2', 'Field 3',] class MyresourceCSVViewSet(viewsets.ModelViewSet): queryset = Myresource.objects.all() http_method_names = ['get'] serializer_class = MyresourceSerializer renderer_classes = (MyresourceCSVRenderer,) def get_queryset(self): myresources = Myresource.objects.all() content = [ { 'Field 1': myresource.field_1, 'Field 2': myresource.field_2, 'Field 3': myresource.field_3, } for myresource in myresources ] return content And when I call /api/v1/csv I get the following error: keyError at /api/v1/csv/ "Got KeyError when attempting to get a value for field `field_1` on serializer `MyresourceSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'field_1'." Please, what am I missing? -
Django UpdateView conflicting with AJAX in FormView
Recently added an AJAX progress bar to a VideoUploadView(FormView) to make the user aware of the progress of the upload. Just realized this has broken the VideoUpdateView but I cannot figure out why. What happens when the "update" button is clicked is the form is rendered with the instance data - ok, looks good. Then after updating a field (e.g. description) and clicking "save" the form is then repopulated with all of the data (as if it were going to give a validation error), including the new changes, though the file fields (video file and thumbnail/image file fields) are now blank. From here it gets a little more strange as if add a video to the video field and click save it will then save the changes of the other fields (description or title) but the video will remain as the first file. What I can take from this is that the AJAX is being called and not submitting the form data for the video/image fields (as if it is using the FormView to handle it all. Then it is redirecting to the FormView page (according to the URL) due to this return render(request, self.template_name, {'form': form}) line. My first …