Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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": … -
How do I automate this sendinblue api?
Trying to automate the adding of contacts to sendinblue's api. The example given on their site shows adding a email and then adding it to a list in your account. I have tried fstrings and .format(email, industry, role) but for some reason it keeps throwing back errors. Heres what their website shows which works. import requests url = "https://api.sendinblue.com/v3/contacts" payload = "{\"email\":\"someonesEmail97@gmail.com\",\"listIds\":[1,4],\"updateEnabled\":false}" headers = { 'accept': "application/json", 'content-type': "application/json" } response = requests.request("POST", url, data=payload, headers=headers Here's what I tried import requests url = "https://api.sendinblue.com/v3/contacts" payload = "{\"email\":\f"{email}"\",\"listIds\":[f"{industry}",f"{role}"],\"updateEnabled\":false}" headers = { 'accept': "application/json", 'content-type': "application/json" } response = requests.request("POST", url, data=payload, headers=headers) I want this in the signup part of my site so it will grab their email thats been authenticated and add it to the appropriate list that I have set up. But what I get back from using fstrings is invalid syntax in the terminal pointing to the email field. I then tried .format and that didn't show any errors on the terminal but on the webpage I got this error back payload = "{\"email\":\{}\",\"listIds\":[{},{}],\"updateEnabled\":false}".format(email, industry, role) KeyError at /accounts/signup/activate/ "'email'" points to line that the payload is on. What am I missing? Thanks for reading -
How to handle return render in django function
def url_filter(request,x): if x<10: url=request.path[1:-9] elif x<100: url=request.path[1:-10] elif x<1000: url=request.path[1:-11] else: url=request.path[1:-12] return url def form_valid(form,request,url): if form.is_valid(): form.save() if request.user.is_staff: messages.success(request, f''+url+' List has been updated!') else: messages.warning(request, f'You do not have Admin access!') else: print(form.errors) context={ "form":form, "form_name":url, } return render(request,'movies_list/list_create.html',context) @login_required def Award_list_update(request,award_id): obj=get_object_or_404(Award_list,award_id=award_id) url=url_filter(request,award_id) form=Create_Award_list_form( data=(request.POST or None), files=(request.FILES or None), instance=obj, ) form_valid(form,request,url) I want to use same template for multiple views so,i decleared a seprate function form_valid for this but i dont know how to handle the return render function. -
How to download a csv file from django docker container
I have an mounted django app using docker-compose. I also have generated a csv file in the server django app directory and inside the docker container. server django directory /restapi |*filename.csv |*app1 |*app2 inside docker container directory /django |*filename.csv |*app1 |*app2 i already tried setting up a static absolute path for both server and docker directory, but i still couldn't download the csv file. response = HttpResponse(content_type='text/csv') django_root_path = '/django' file_path = '{}/myfilename.csv'.format(django_root_path) logger.info(file_path) response['Content-Disposition'] = 'attachment; filename=file_path' response.write(u'\ufeff'.encode('utf8')) return response -
Django ValueError: Missing staticfiles manifest entry, but the manifest appears to show the entry
On a Django 1.11 app deployed to Heroku. When loading the root URL / (and I presume when Django gets to {% static 'angular/angular.min.js' %} in the homepage.html template) I get the following error: ValueError: Missing staticfiles manifest entry for 'angular/angular.min.js' File "django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "homepage/views.py", line 87, in homepage "latest_python3": Version.objects.filter(supports_python3=True).select_related("package").distinct().order_by("-created")[0:5] File "django/shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "django/template/loader.py", line 68, in render_to_string return template.render(context, request) File "django/template/backends/django.py", line 66, in render return self.template.render(context) File "django/template/base.py", line 207, in render return self._render(context) File "newrelic/api/function_trace.py", line 60, in dynamic_wrapper return wrapped(*args, **kwargs) File "django/template/base.py", line 199, in _render return self.nodelist.render(context) File "django/template/base.py", line 990, in render bit = node.render_annotated(context) File "django/template/base.py", line 957, in render_annotated return self.render(context) File "django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "newrelic/api/function_trace.py", line 60, in dynamic_wrapper return wrapped(*args, **kwargs) File "django/template/base.py", line 199, in _render return self.nodelist.render(context) File "django/template/base.py", line 990, in render bit = node.render_annotated(context) File "django/template/base.py", line 957, in render_annotated return self.render(context) File "django/template/defaulttags.py", line 411, in render return strip_spaces_between_tags(self.nodelist.render(context).strip()) … -
Django category didn't work corrctly href not work
I have made a script to display all posts in a categroy so, when I try to open the single category it didn't open the page and show the article page, I've followed a tutorial for makeing this code, the link is: https://www.youtube.com/watch?v=o6yYygu-vvk . Can someone help me plz? Models.py from django.db import models from django import forms from django.contrib.auth.models import User from django.urls import reverse # Categorie class Category(models.Model): class Meta: verbose_name = 'category' verbose_name_plural = 'categories' name = models.CharField('Titolo', max_length = 250) slug = models.SlugField(max_length = 250, unique = True) desc = models.TextField('Descrizione', max_length=10000, blank=True) def get_absolute_url(self): return reverse("blog:CategoryList", args=[self.slug]) def __str__(self): return self.name # Articles class Article(models.Model): class Meta: verbose_name = 'Articolo' verbose_name_plural = 'Articoli' ''' Classe per creare articoli generali con media ''' title = models.CharField('Titolo', max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE,) category = models.ForeignKey (Category, on_delete=models.CASCADE) desc = models.CharField('Descrizione', max_length=10000, blank=True) text = models.TextField('Testo', max_length=10000, blank=True) image = models.ImageField('Foto', blank=True, upload_to="img") data = models.DateTimeField('Data di pubblicazione', blank=True) slug = models.SlugField(max_length = 250, null = True, blank = True, unique=True) class Meta: # Order post by date ordering = ['-data',] def __str__(self): return "Crea un nuovo articolo" Views.py from django.shortcuts import render, get_object_or_404 from django.shortcuts import render …