Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom Django Model Form Field that Aggregates Multiple Instances of an Input
I have created a custom field in a model form that I want to use to enable users to enter multiple instances of inputs into. For example, the custom field is a series of values that corresponds to multiple dates. Once the form is submitted I want to consolidate all of those values into a string and store them in a single database field. See code below. The cleaned_data fields are empty when I add multiple values to the inputs. I think I need to access the input data before it is passed to cleaned_data, but I'm not sure how. Any assistance would be appreciated. #forms.py class UpdateModelForm(forms.ModelForm): custom_field = forms.CharField() class Meta: model = Model def clean_custom_field(self): custom_field = self.cleaned_data['custom_field'] return custom_field def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #I've tried to access the input fields here without success #views.py class ModelView(UpdateView): model = Model form_class = UpdateModelForm template_name = 'model_edit.html' def form_valid(self, form): #not sure what to put here #model_edit.py <body> <form action="" method="post">{% csrf_token %} <table> <thead> <tr> <th>Amount</th> </thead> <tbody> {% for i in '12345'|make_list %} <tr> <td> {{form.custom_field}} </td> </tr> {% endfor %} </tbody> </table> </form> </body> -
How to build chained filter in django admin dashboard
I want chained filter in django-admin dashboard,Please help me to achieve it. I have 3 models:- Board, Grade and Chapter. Initially when dashboard loads then only board filter should appear and after selecting board filter the selected boards all filter should appear and after selecting grade all chapters of that grade should appear. I have tried RelatedDropdownFilter, but thats just normal, it does not modify the view part of dropdownfilter, It shows all results. My models:- class LmsBoard(models.Model): name = models.CharField(max_length=240) class LmsGrade(models.Model): name = models.CharField(max_length=240) board = models.ForeignKey(LmsBoard, models.DO_NOTHING) class LmsSubject(models.Model): name = models.CharField(max_length=240) grade = models.ForeignKey(LmsGrade, models.DO_NOTHING) board = models.ForeignKey(LmsBoard,models.DO_NOTHING) class LmsChapter(models.Model): name = models.CharField(max_length=240,default='None') subject = models.ForeignKey(LmsSubject, models.DO_NOTHING) My admin.py:- @admin.register(MyModel) class MyModel(admin.ModelAdmin): list_display = ( 'board', 'grade', 'chapter',) list_filter = ( ('board',RelatedDropdownFilter), ('grade', RelatedDropdownFilter), ('chapter', RelatedDropdownFilter), I am expecting the filter should appear one by one and should contain the filter list of last selectected item. -
'DeferredAttribute' object has no attribute 'startswith'
I keep on getting this error message and do not know how to fix this,.. This message shows up when I log in with stored id and password. Please help! dfasfsfsfdsfsfsfsdfasfsfdsfsdfsd dfsfdsfasdfsafsfdsafdsfsdfdsfsdsdf dsfdsfsdfsdafsafdsdfsafsdf sdafasfdsafsdafsdfdsfds models.py from __future__ import unicode_literals from django.db import models # Create your models here. class seanyorder(models.Model): customer = models.ForeignKey('seany_user.seanyuser', on_delete=models.CASCADE, verbose_name='customer') product = models.ForeignKey('seany_product.seanyproduct', on_delete=models.CASCADE, verbose_name='product') def __str__(self): return str(self.customer) + ' ' + str(self.product) class Meta: db_table = 'seany_order' verbose_name = 'order' verbose_name_plural = 'order' url.py from django.conf.urls import url from django.contrib import admin from seany_user.views import index, registerview, loginview urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', index), url(r'^register/$', registerview.as_view()), url(r'^login/$', loginview.as_view()) ] view.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.views.generic.edit import FormView from django.shortcuts import render from seany_user.forms import registerform,loginform # Create your views here. def index(request): return render(request, 'index.html', { 'email': request.session.get('user') }) class registerview(FormView): template_name = 'register.html' form_class = registerform success_url = '/' class loginview(FormView): template_name = 'login.html' form_class = loginform success_url = '/' def form_valid(self, form): self.request.session['customer'] = form.email return super().form_valid(form) error message AttributeError at /login/ 'DeferredAttribute' object has no attribute 'startswith' Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 2.2.5 Exception Type: AttributeError Exception Value: 'DeferredAttribute' object … -
Reload only MultipleChoiceField of dajngo on jquery load
I have a popup-modal in the page to add new data with ajax, after the data is added i have to bring it to the django multichoicefield widget if I try it to bring it in selected portion it is dispalyed and works on submission but after that if user select and bring another data to selected side the one i have added will get destroyed it doesn't compile with the original data that are loaded. I also try to refresh only that portion to again load whole data so that it compile with js function. But now the multichoicefield will not construct through JS and will not display properly. Both of my method I can't work properly, I have changed little js of admin SelectFilter2 to load it in my popup-modal while ajax call that has worked but i didn't get what is causing js not to work on jquery load or addition of new data. Method 1: I append the data to selected side on ajax success $('#id_Course_Group_to').append(`<option value="`+ response.pk + `" title="` + id_InningGroup_Name + `" selected>` + id_InningGroup_Name + `</option>`); This data will not function like other data which are preloaded it will just disappear if … -
What does '|' in {{ services|pprint|safe }} mean in django?
I know that in views.py file: def index(request): person= {'firstname': 'Craig', 'lastname': 'Daniels'} weather= "sunny" context= { 'person': person, 'weather': weather, } return render(request, 'Articles/greeting.html', context) Then we can do in greetings.html: <h1>Hi {{ person.firstname }} {{ person.lastname }}</h1> <h1>Today it is {{ weather }}</h1> where {{ person.firstname }} is a variable defined in context. But what does '|' mean? {{ services|pprint|safe }} -
Is it possible to deploy django 2.2 on Google cloud engine?
I just began to learn Django recently. I am trying to deploy a django project on google cloud engine. But I stuck when following tutorial on google: https://cloud.google.com/python/django/appengine when I type: python manage.py makemigration I got: following error: mysqlclient 1.3.13 or newer is required; you have 0.9.3. After short research, aparently, I can't install mysqlclient 1.3.13 on Django 2.2 yet?? Is this a mistake? Am I missing something? Can I use mysqlclient 1.3.13 on django 2.2 ? Thank you for your time. -
assertEqual fails in Django test view
I'm testing whether the view returns in the context object all the database models that I've saved. The models actually render in the templates when the site is running but having had problems rendering them in the past, I need the view test to help with debugging. So the test collects then saves the site url to the variable resp using Client. I then assertTrue that the key value passed in the context exists. Then - and this is where the problem lies - i attempt to assetEqual that what's in the context object matches whats in my database and this is the resulting traceback: File "/Users/Sol/src/projects/portfolio/python_website/main/tests_models.py", line 24, in check_context_obj self.assertEqual(resp.context['projects'], Project.objects.all()) AssertionError: <Quer[20 chars] App>, <Project: Folium Web Map>, <Project: Personal Webiste>]> != <Quer[20 chars] App>, <Project: Folium Web Map>, <Project: Personal Webiste>]> You'll notice after the AssertionError the the values either side of the != operator are actually exactly the same (I actually checked that their types are the same). Here are my files: tests_views.py from django.test import TestCase from main.models import Project from django.urls import reverse def check_context_obj(self): url = reverse('site_index') resp = self.client.get(url) self.assertTrue(resp.context['projects']) self.assertEqual(resp.context['projects'], Project.objects.all()) views.py from django.shortcuts import get_object_or_404, render from main.models import … -
What is the difference between “return my_view” and “return redirect(my_view)” and how to get a mixed result?
I have a home in which I have a form that I get some info from students to suggest them some programs to apply to. The home view is as below: def home(request): template_name = 'home.html' home_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some stuff return programs(request) else: my_form = MyModelForm() home_context.update({'my_form': my_form, }) return render(request, template_name, home_context) In the second view, I have the same form and I want this form to be pre-occupied with the information I entered in the home page. That is why in the above, I passed my POST request to programs view that is as below: def programs(request): template_name = 'programs.html' programs_context = {} if request.POST: my_form = MyModelForm(request.POST) if my_form.is_valid(): # do some other stuff else: my_form = MyModelForm() programs_context.update({'my_form': my_form, }) return render(request, template_name, programs_context) The drawback of this strategy (passing the POST request in the home view to the programs_view) is that the url in url bar does not change to 'example.com/programs' and stays as 'example.com' . I will have some problems including problems in pagination of the programs. The alternative is that I do this: def home(request): template_name = 'home.html' home_context = {} if request.POST: … -
error on sending mail while test sending mail successfully in Django
I'm coding about Forget Password feature on Django. Reset mail will be sent when user fill out form and click Reset button. But I have a trouble here, mail isn't sent after user click button. I use sendtestmail command, sending mail successfully. And more, the content and mail subject that I define is not in the email it sent when I check by sendtestmail command. It took me all yesterday to fix above error but didn't work. Can somebody help me. settings.py ... EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER', 'vuthehuy.hus@gmail.com') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD', 'my_password_app') EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = os.getenv('DEFAULT_FROM_EMAIL', 'Colo Shop <no-reply@localhost>') app.urls urlpatterns = [ path('password_reset/', auth_view.PasswordResetView.as_view( template_name='account/password_reset_form.html', form_class=EmailForgotPassword, email_template_name='account/password_reset_email.html', subject_template_name='account/password_reset_subject.txt' ), name='password_reset'), path('password_reset/done/', auth_view.PasswordResetDoneView.as_view( template_name='account/password_reset_done.html' ), name='password_reset_done'), path('password_reset/confirm/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view( template_name='account/password_change.html' ), name='password_reset_confirm'), path('password_reset/complete/', auth_view.PasswordResetCompleteView.as_view( template_name='account/password_change_done.html' ), name='password_reset_complete'), ] -
Django Prefetch Related Using View Table in Database
I have make query set: queryset = Cart.objects.filter(deleted_at__isnull=True)\ .filter(status__in=['sent', 'inbound'])\ .annotate(**self.get_annotated_fields)\ .select_related('agent', 'agent_buyer')\ .prefetch_related('agentcost_set','viewcartdetail_set') the code not working with error message Cannot find 'viewcartdetail_set' on Cart object, 'viewcartdetail_set' is an invalid parameter to prefetch_related() when I execute this code to show all relations for this object. >>> from apps.models_helper.cart import Cart >>> a = Cart.objects.get(pk=3682) >>> a._meta.get_fields() The results of the code above, I found a viewcartdetail relations, but why I can't make prefetch_related of viewcartdetail_set? what's wrong my code? Note: viewcartdetail is model of view table in database (<ManyToOneRel: apps.cart>, <ManyToOneRel: apps.viewcartdetail>,...) -
error 'str' object has no attribute '_meta' appear when i call login
when i call login() this error appear to me, I think the error is in request but i don't know how to fix it... AttributeError at /login/ 'str' object has no attribute '_meta' Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 2.2.5 Exception Type: AttributeError Exception Value: 'str' object has no attribute '_meta' Exception Location: D:\python\Django\arablinks\lib\site-packages\django\contrib\auth\__init__.py in login, line 126 Python Executable: D:\python\Django\arablinks\Scripts\python.exe Python Version: 3.7.1 Views.py class Login(View): def get(self, request): forms = LoginForm() return render(request, 'arablinks/login.html', context={'forms': forms}) def post(self, request): forms = LoginForm(request.POST) error = forms.non_field_errors if forms.is_valid(): data = forms.cleaned_data login(request, data.get('user')) return render(request, 'arablinks/login.html', context={'forms': forms, 'error':error}) -
Django 2.2 static files not showing/processing
I'm trying to deploy my Django instructor's (Udemy) 'real estate' project. Here is Brad Traversy’s gist. I've followed Brad’s guide for deploying Django. I kinda got it to run but the static files (CSS, JS and images) are not being served. It's an issue with my configuration and it is not clear to me what I'm doing wrong here or what exactly I am missing. Here is what the end result it should look like: Here is what mine actually looks like: Exploring other questions and answers on SO, inside my settings.py, I've tried swapping in (and out) different paths into STATIC_ROOT, MEDIA_ROOT, STATICFILES_DIRS using the join method. I’ve also tried adding a number of different list items into the urlpatterns variable inside urls.py. After trying each new potential change, I enter python manage.py collectstatic and then I run the server. Sometimes there would be a trace back preventing the server from running. In these situations, I just rolled back the change to a setting which was known to work or alternatively, I just tried something else entirely which would enable the server to run without a trace back. Here are some of the other questions on SO which I … -
(1049, "Unknown database 'face-detection-database'") issue in django when deploying to aws through elasticbeanstalk
If I try to do any database related task in django , it's show me this error even though I have the database exists. It prints the "face-detection-database" line too. if 'RDS_HOSTNAME' in os.environ: print("has rds", RDS_DB_NAME) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } I have deploy my application on aws through Elastic beanstalk. It shows me the following error: InternalError at /registration/process_registration/ (1049, "Unknown database 'face-detection-database'") Request Method: POST Request URL: http://face-detection-env.qdnyceb2ug.us-west-2.elasticbeanstalk.com/registration/process_registration/ Django Version: 2.2.5 Exception Type: InternalError Exception Value: (1049, "Unknown database 'face-detection-database'") Exception Location: /opt/python/run/venv/local/lib/python3.6/site-packages/pymysql/err.py in raise_mysql_exception, line 109 Python Executable: /opt/python/run/venv/bin/python3 Python Version: 3.6.8 Python Path: ['/opt/python/current/app', '', '/opt/python/run/venv/local/lib64/python3.6/site-packages', '/opt/python/run/venv/local/lib/python3.6/site-packages', '/opt/python/run/venv/lib64/python3.6', '/opt/python/run/venv/lib/python3.6', '/opt/python/run/venv/lib64/python3.6/site-packages', '/opt/python/run/venv/lib/python3.6/site-packages', '/opt/python/run/venv/lib64/python3.6/lib-dynload', '/usr/lib64/python3.6', '/usr/lib/python3.6'] Server time: Fri, 13 Sep 2019 14:44:30 -0700 And the line where this error is occurring, when I try to retrieve user from the enrollment. : def ValidateData(self, request): try: username = str(request.POST['enrollment']) print(type(username), username) user = User.objects.get(username=str(request.POST['enrollment'])) print("user exists", user) return False except User.DoesNotExist: print("user not exists") return True I think I'm getting this error as I haven't run migrate command on linux server at the time of deploying. Hence I even follow the docs form … -
Passing name to a hidden field in Django form
I am trying to pass string to a hidden field scenario of a form whose data is stored in a database. The goal is to be able to retrieve extra information on client side without having it as another field of the form. This is my Model: class Person(models.Model): INDUSTRY_CHOICES = (('whatever','whatever'), ...) REGION_CHOICES = (('Europe', 'Europe'), ...) region = models.CharField(max_length=30, choices=REGION_CHOICES) industry = models.CharField(max_length=30, choices=INDUSTRY_CHOICES) uuid = models.CharField(max_length=50, blank=True, unique=True, default=uuid.uuid4) scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE,) def __str__(self): return "{}".format(self.uuid) My Form class PersonForm(forms.ModelForm): class Meta: model=Person scenario = forms.CharField(widget=forms.HiddenInput()) fields=['industry', 'region','scenario'] widgets = { 'scenario': forms.HiddenInput(), } My View def personforms(request): persons = Person.objects.all() if request.method == 'POST': filled_form = PersonForm(request.POST) if filled_form.is_valid(): created_person = filled_form.save() print(filled_form.cleaned_data['region']) created_person_pk = created_person.id filled_form = PersonForm() return redirect('/scenariopage', {'persons':persons}) else: created_person_pk = None return render(request, 'core/scenario-landing-page.html', {'personform':filled_form, 'created_person_pk':created_person_pk}) else: form = PersonForm() return render(request, 'core/scenario-landing-page.html', {'personform':form}) And my template <form action="{% url 'personform' %}" method="post" class="custom-form"> {% csrf_token %} {% for field in personform %} {% render_field field.industry class="form-control" %} {% render_field field.region class="form-control" %} {% render_field field.scenario value='{{ scenario.name }}' %} {% endfor %} <input type="submit" class="btn color-btn" value="Go to Scenario page" data-dismiss="gallery-item"/> </form> Questions I have: What I am doing … -
Modal form not submitting Django
I have a modal which does not submit. I'm using the Django base model. I think it could be a problem with the CSRF token since it's been throwing that error. I'm not even making it to the 'something went wrong' error message. I added something to catch form.errors, but it doesn't show any errors. The variables are being passed, but for some reason - it's not working. def voting(request): if request.method == 'POST': user=request.user if user.is_authenicated: price, created = Voting.objects.get_or_create( user=request.user, anonymous_user=False, object_id = Object.objects.get( objectid=request.POST.get('objectid') ), thumbs_up=request.POST.get('thumbs_up'), thumbs_down=request.POST.get('thumbs_down'), comments=request.POST.get('comments') ) price.save() else: pass response_data = 'success' return HttpResponse(json.dumps(response_data), content_type="application/json") else: return HttpResponse(json.dumps({"message": "Something went wrong"}),content_type="application/json") Here is the html code: <div class="voting text-right"><small>See a problem?</small> <a onclick="thumbsup('{{ data.object.objectid }}'> <i class="fas fa-thumbs-up"></i> </a> <a data-toggle="modal" data-target="#feedback" data-object-id="{{ data.object.objectid }}"> <i class="fas fa-thumbs-down"></i> It does not work and does not submit. I keep getting a problem with the CRSF token as well. Here is the modal: <!-- Modal --> <div class="modal fade" id="feedback" tabindex="-1" role="dialog" aria-labelledby="feedback" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Feedback</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="feedback-form" action="/api/voting/" method="post"> {% csrf_token %} <input type="hidden" name="objectid"> <input type="hidden" … -
TemplateDoesNotExist on Django custom management command tests
I have the following custom management command: from django.template.loader import render_to_string from django.core.management.base import BaseCommand class Command(BaseCommand): args = "" help = """Validates models.""" def handle(self, *args, **options): ... message = render_to_string( "validation_email.html", context ) ... When I run it from the command line, it works as expected without an issue. However, when I try to test it with the following test case: from io import StringIO from django.core import mail from django.core.management import call_command from django.test import TestCase from my_app.management.commands import validate_models class TestValidateModels(TestCase): def test_successful_call(self): out = StringIO() cmd = validate_models.Command() call_command(cmd, stdout=out) self.assertEqual(len(mail.outbox), 1) It gives me the following error: django.template.exceptions.TemplateDoesNotExist: validation_email.html Am I missing something? Why the command works just fine from the command line, but generates template problems while running unit tests? Is there any tweak needed about the templates to be able to test Django custom management commands? -
ImportError: No module named skeleton.settings
I'm using django 1.8 and satchmo project. But after successful installation of satchmo project when I try to start the server it's showing me this error `Traceback (most recent call last): File "manage.py", line 25, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python@2/2.7.16_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named skeleton.settings` -
django form save but not redirect
I'm make a store using django, I want when a add a new product not redirect to the cart page, only want that after save the item , I can see the same page How I can make this -
Showing related instance on readonly popup in django admin
When you see the control (e.g. a dropdown) for a related field in a Django admin create/edit form for a Model, by default it comes with 2 icons, one for add a new instance and one for editing the selected instance. I know that the formfield's widget can be tweaked with the can_add_related and can_change_related flags to not show those icons, but I wonder: is there any out-of-the-box way to have a "view" icon that would display a pop-up just like the edit one but with all fields being displayed as readonly? (There's a can_view_related flag, but that's not what it's for) So far the "easiest" way I can think of is extending the admin/change_form.html template and seeing if I can somehow force all controls to be readonly when is_popup is set to true. -
AttributeError: 'NoneType' object has no attribute 'split' in Firefox only
I have recently started a project in Django and I don't have too much experience in this framework. However, everything is working fine so far, but I am getting these errors when I open the project's site in the browser. I am not sure what it is about, but I have noticed that this happens only in Firefox and only after opening any other site (particularly in my case Facebook or Gmail) in new tab, while navigating to any page on my project. Prior to the visit of these websites, everything is working fine without any error in the console. If I clear the cache of the browser after this happen and close the additional tabs, everything is back to normal until I reopen any of the websites again. Also, I have checked if this would be a case in Chrome and I have noticed that everything is working fine there, even when the mentioned websites are opened in new tab. Can anyone provide me more information on what would be the reason for these errors? Thanks Traceback (most recent call last): File "C:\Users\Varangian\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Varangian\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Varangian\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 274, … -
Django form not submitting without forms.py
I have a Django form that does not submit. I'm using the Django base model. The following is the view for the model. I think it could be a problem with the CSRF token since it's been throwing that error, but the form itself does not submit. I'm not even making it to the 'something went wrong' error message. def voting(request): if request.method == 'POST': user=request.user if user.is_authenicated: price, created = Voting.objects.get_or_create( user=request.user, anonymous_user=False, object_id = Object.objects.get( objectid=request.POST.get('objected') ), thumbs_up=request.POST.get('thumbs_up'), thumbs_down=request.POST.get('thumbs_down'), comments=request.POST.get('comments') ) price.save() else: pass response_data = 'success' return HttpResponse(json.dumps(response_data), content_type="application/json") else: return HttpResponse(json.dumps({"message": "Something went wrong"}),content_type="application/json") Here is the html code: <div class="voting text-right"><small>See a problem?</small> <a onclick="thumbsup('{{ data.object.objectid }}'> <i class="fas fa-thumbs-up"></i> </a> <a data-toggle="modal" data-target="#feedback" data-object-id="{{ data.object.objectid }}"> <i class="fas fa-thumbs-down"></i> It does not work and does not submit. I keep getting a problem with the CRSF token as well. -
django: how to download a dataframe that is returned from a view
I have a form that takes an api key and an id and retrieves some data with a "load" button. That data is served as html in a template. Once the user sees the data that was retrieved, I would like them to be able to download the data as a CSV file by clicking a "download" button. What I've been trying to do is pass data as a context variable into a template, and then send that data on to another view that returns a download response from a view called "export". Perhaps there's a better way to do this? Sorry if this is a really dumb question. views.py def myview(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = WorkbenchForm(request.POST) # check whether it's valid: if form.is_valid(): context['form'] = form # Retrieve data from api [...] context['data'] = pandas_dataframe.to_html() context['file'] = pandas_dataframe.to_csv() return render(request, 'app/data.html', context) def export(request): response = HttpResponse(request, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=' + 'test.txt' return response data.html <body> <h1>Data</h1> <form action= "" method="post"> {% csrf_token %} {{ form.as_ul }} <input type="submit", value="Load"> </form> {% if data %} <h4>Data</h4> {{ data | safe }} <form … -
ㅁㄴㄹThe format is different when copying the input using django summer note
enter image description here For example If I copy this The result is output like this The problem is that the tab spacing line spacing is different =================================================================== const LOG_IN = 'LOG_IN' const LOG_OUT = 'LOG_OUT' const loginAction = { type : LOG_IN, data: { nickname:'제로초', }, } const logoutAction = { type:LOG_OUT, } =================================================================== this is code <div id="select-textarea-{{p.id}}" style="width:900px;">{{p.content2 | safe}}</div> ==================================================================== To copy and paste in its original format what should I do? -
What is the django rest framework suggested way, to render a serializer html template using Response() with Class Based View?
I'm defining a Class based view CRUD using Response() method, where I need to return my serialized data to a html template, but I haven't found a functional example using CBV (class based view) instead of FBS (function based view). I have read the DRF documentation about viewsets, requests and Response, and I found some ways to do that, but I'm not sure what is best suggested way according to my context. My project structure is as below: api core fixtures logs static templates users web In api folder I have my serializer and my api class: serializers.py class CustomDictionarySerializer(serializers.ModelSerializer): class Meta: model = CustomDictionary fields = ('__all__') api.py class CustomDictionaryViewSet(viewsets.ModelViewSet): queryset = CustomDictionary.objects.all().filter( is_active=True, is_deleted=False ).order_by('id') permission_classes = [ permissions.AllowAny ] serializer_class = CustomDictionarySerializer pagination_class = StandardResultsSetPagination urls.py router.register('api/customdictionary', CustomDictionaryViewSet, 'customdictionary') Then, in my web folder, I needed to render my serialized data, so I tried as below: views.py class CustomDictionaryView(View): def get(self, request, *args, **kwargs): queryset = CustomDictionary.objects.all() serializer = CustomDictionarySerializer(self.get_queryset, many=True) return Response(serializer.data,status=status.HTTP_200_OK,template_name='web/dictionary_get.html') ... (post,put and remove) But CustomDictionaryView didn't work by reason of this error: .accepted_renderer not set on Response My intention is to use CBV instead of FBV, so I can't use @api_view (that is … -
How to get all related objects from a reverse foreign key Django serializer (one-to-many)?
I have been trying to create a Trello-like clone and storing my 'Lists' and 'Applications' as separate models with a foreign key on my 'Applications' model to create a One-To-Many between Lists and Applications. I usually use Node and Sequelize and have been unsuccessful in trying to query my Lists and also returning all the Applications with the List's ID as the Applications foreign key. I suspect I am just missing something silly on my Serializers. I've tried a few things that broke the code, but now I just have it returning the List's fields like this: [ { "title": "My First List" }, { "title": "My Second List" }, ] when in reality what I really want back is something like: [ { "id": 1, "title": "My First List", "applications": [ { "id": 1, "company_name": "Spotify", "position": "Web Engineer", "date_applied": "2019-09-09", "application_id": "xv112_cv", "priority_level": "High", "company_contact_email": "jg@spotify.com", "notes": "Seems promising", "location": "New York", "status_list": "1" }, { "id": "2", "company_name": "Foursquare", "position": "Client Solutions Engineer", "date_applied": "2019-10-09", "application_id": "fsq_app_1", "priority_level": "High", "company_contact_email": "jdwyer@foursquare.com", "notes": "Interview on 9/29/19", "location": "New York", "status_list": "1" }, ] }, { "id": "2" "title": "My Second List", "applications": "applications": [ { "id": "3", "company_name": …