Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query Create - the field is determined by a string
I'm try create a object with django with string: my model: class Example(models.Model): user_id = models.IntegerField(blank=True, null=True) field_1 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) field_2 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) field_3 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True) Code for Create: real_field = "field_"+str(level) example = Example( user_id=user_id, real_field=value_1, ...... ) example.save() how create this..please thanks ..!! -
In Django Admin Form - How do I call Save with redirect from JS?
Let's say I have a standard Django ModelAdmin class without a custom form, only some JS code which I attached using the Media class. This JS code needs to call submit() on the form to do a "save" operation. The problem is: the save will redirect to the admin list view. Can I invoke save and then redirect back to the same object's edit form? -
Getting a list from Django into Javascript as an array
I have a python list generated by my views.py in Django, and I would like to pass it to javascript in my HTML template. I cannot seem to get it into javscript as an array... I need to evaluate if the list/array contains certain numbers, but it is coming over as a string. I am passing the list to my HTML template like this: def get_context_data(self, **kwargs): context = super(dashboardView, self).get_context_data(**kwargs) mylist = [10,22,33,45] context['mylist'] = mylist return context When I use: <h1 id = "list"> {{mylist}}</h1> it shows up on the browser as it shows up as [10,22,33,45] Then in my template I am using javascript I have: var mylist = document.getElementById("list").innerHTML; for(i = 0; i < mylist.length; i++){ console.log(mylist[i]) }; this returns in the console: ' [ 1 0 , 2 2 ........ I want: 10 22 33 45 I have tried to convert to JSON in python, and parse it in javascript, but can't seem to convert this string to an array, or keep getting errors. Any ideas for the best method here? -
Understanding relationships in django
I'm new to django. I'm struggling with relationships. I have 4 apps (app1, app2, app3, app4). App2, 3 and 4 have the same fields. And those fields have to be in app1. How can i write my models? Please help. For example app1 is movies(with title and location), app2 is music(with title and location) and app3 is ballet(with title and location). App1 has to be cinema where we have movies, music performances and ballets. -
django-debug-toolbar: 503 Service Unavailable when SQL Panel is active
I want to use django-debug-toolbar to optimize my queries, the problem is that I get a "503 Service Unavailable by Daphne" on every view when the SQL panel is active, including the admin views. Note: everything loads instantly when I disable the SQL panel. Sometimes the server is able to load the page (Debug Toolbar in that case), Why is the server having problems to load if there are only 6 queries related to this view? Checking my debug.log I've found that the server throws a VariableDoesNotExist [2018-10-25 20:34:19,677] base DEBUG Exception while resolving variable 'trans_status' in template 'debug_toolbar/panels/sql.html'. Traceback (most recent call last): File "/home/ubuntu/workspace/.env/local/lib/python2.7/site-packages/django/template/base.py", line 903, in _resolve_lookup (bit, current)) # missing attribute VariableDoesNotExist: Failed lookup for key [trans_status] in u'{u\'rgb_color\': [256, 0, 0], u\'stacktrace\': u\'<span class="djdt-path">/home/ubuntu/workspace/.env/local/lib/python2.7/site-packages/channels/management/commands/</span><span class="djdt-file">runserver.py</span> in <span class="djdt-func">run</span>(<span class="djdt-lineno">164</span>)\\n <span class="djdt-code">worker.run()</span>\\n<span class="djdt-path">/home/ubuntu/workspace/.env/local/lib/python2.7/site-packages/channels/</span><span class="djdt-file">worker.py</span> in <span class="djdt-func">run</span>(<span class="djdt-lineno">119</span>)\\n <span class="djdt-code">consumer(message, **kwargs)</span>\\n<span class="djdt-path">/home/ubuntu/workspace/.env/local/lib/python2.7/site-packages/channels/</span><span class="djdt-file">handler.py</span> in <span class="djdt-func">__call__</span>(<span class="djdt-lineno">344</span>)\\n <span class="djdt-code">for reply_message in self.handler(message):</span>\\n<span class="djdt-path">/home/ubuntu/workspace/.env/local/lib/python2.7/site-packages/channels/</span><span class="djdt-file">handler.py</span> in <span class="djdt-func">__call__</span>(<span class="djdt-lineno">214</span>)\\n <span class="djdt-code">response = self.get_response(request)</span>\\n<span class="djdt-path">/home/ubuntu/workspace/.env/local/lib/python2.7/site-packages/channels/</span><span class="djdt-file">staticfiles.py</span> in <span class="djdt-func">get_response</span>(<span class="djdt-lineno">57</span>)\\n <span class="djdt-code">return super(StaticFilesHandler, self).get_response(request)</span>\\n<span class="djdt-path">/home/ubuntu/workspace/.env/local/lib/python2.7/site-packages/django/contrib/sessions/</span><span class="djdt-file">middleware.py</span> in <span class="djdt-func">process_response</span>(<span class="djdt-lineno">58</span>)\\n <span class="djdt-code">request.session.save()</span>\\n<span class="djdt-path">/home/ubuntu/workspace/.env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/</span><span class="djdt-file">db.py</span> in <span class="djdt-func">save</span>(<span class="djdt-lineno">87</span>)\\n <span class="djdt-code">obj.save(force_insert=must_create, force_update=not must_create, using=using)</span>\', u\'vendor\': u\'unknown\', u\'form\': <SQLSelectForm bound=False, … -
Django middleware to change language depending on domain, work on localhost, but uwsgi+nginx it doesnt work
I have a middleware for django to detect the domains and serve a specific local. It worked fine developind and testing on window trought localhost, but now on vps with uwsgi and nginx it doesnt work. How can I make it work now ? from django.contrib.sites.shortcuts import get_current_site from django.utils import translation #manage.py makemessages -l pt_BR #manage.py compilemessages -l pt_BR class SetLanguageToDomain: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): current_site = get_current_site(request).domain if current_site == 'www.doutorlandivar.com': user_language = 'pt_BR' elif current_site == 'www.doctorlandivar.com': user_language = 'es_ES' else: user_language = 'en' translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language response = self.get_response(request) return response -
OneToOne relationship not linking
I have these models: class Article(TimestampedModel): title = models.CharField(max_length=255) ... class Event(models.Model): article = models.OneToOneField( Article, on_delete=models.CASCADE, related_name='event', ), .... However, when I look at the generated events table in my database, there is no foreign key (I would have expected on). Furthermore, I have a record in Article: article = Article.objects.find(1) And then when I try to access the event: event = article.event I will get this error: 'Article' object has no attribute 'event' This is how I save the records: if not id: form = SimpleArticleForm(request.POST) eventform = EventForm(request.POST) else: form = SimpleArticleForm(request.POST, instance=info) eventform = EventForm(request.POST, instance=event) if form.is_valid(): info = form.save(commit=False) info.site = request.site info.save() event = eventform.save(commit=False) event.article = info event.save() Saving the records works well and it inserts both records (event and article), but when I later try to access the event I can not do so. -
Can this be done with django __str__ method?
I have 2 models with foreignkey to a model class MyModel(models.Model): description = models.CharField(max_length=50) type = models.CharField(max_length=10) def __str__(self): return self.description class Model1(models.Model): mymodel = models.ForeignKey(MyModel) class Model2(models.Model): mymodel = model.ForeignKey(MyModel) In the drop down list in the admin for mymodel field the str method returns description of MyModel How do I change what is returned for each model Model1,Model2 example in the str method to return 'type' if the model is Model2 or 'description' if model is Model1 -
Django - type object 'HttpRequest' has no attribute 'method'
I'm getting an attribute error type object 'HttpRequest' has no attribute 'method' but HttpRequest has the attribute 'method' as per Django docs. My views.py: from django.http import HttpRequest, HttpResponse import myapp.pyfile def function(self): request = HttpRequest if request.method == 'GET': return HttpResponse(pyfile_function()) Thanks!! -
DRF use regex to match multiple fields in serializer
I am trying to implement django-modeltranslation in my existing Django app that uses DRF. That package adds a translation field per language in the objects representation, and I need them to be write_only. Is there any way to match all field at once using a regex or anything? Ie: extra_kwargs: { "write_only": regex(match_required_fields) } If it is not doable, do you know if django-modeltranslation can do it on its own? -
Why are django.utils.timezone.make_aware and pytz.localize returning different results when dealing with DST?
I'm using django 1.11 and pytz 2018.6 I'm having some problems understanding how django is dealing with DST. My main problem is localizing the date 2018-11-04 00:00:00 in the America/Sao_Paulo timezone. According to the latest pytz version this is the date when DST starts in this timezone in 2018. Well, on my application I started seeing the pytz.exceptions.NonExistentTimeError exception when trying to localize the mentioned date. The following code reproduces this exception: import os import datetime import django import pytz os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") django.setup() from django.utils.timezone import make_aware sp = pytz.timezone('America/Sao_Paulo') dst_start_date = datetime.datetime(2018, 11, 4, 0, 0, 0) make_aware(dst_start_date, sp) # Exception raised: pytz.exceptions.NonExistentTimeError: 2018-11-04 00:00:00 However, if I try to localize using pytz.localize instead of make_aware I get different results: sp.localize(dst_start_date) # Returns 2018-11-04 00:00:00-03:00 I expected to receive the same exception when trying to localize. But it didn't raise the exception and actually returned a wrong result (the -03:00 offset is when we're not on DST. On the specific date I was expecting the 2018-11-04 00:00:00-03:00 date to be converted to 2018-11-04 00:00:00-02:00). This confuses me, because reading the make_aware code in django.utils.timezone I understood the same pytz.tzinfo.localize method is called. # django.utils.timezone def make_aware(value, timezone=None, is_dst=None): """ … -
Bootstrap 4 Dashboard with Django
Trying to set up a Bootstrap 4 Dashboard theme with Django. If I double click any .html file in the downloaded theme folder, I get a properly displayed webpage with the graphs and everything working. However, when I try to run the same theme through Django, I only get the text from the html file. I am quite new to Django and especially Bootstrap so not sure where to go from here. Just to be sure all the static files are in the correct position, I have copied the whole theme folder into my static folder. I also think my settings files are configured correctely. INSTALLED_APPS = [ 'django.contrib.staticfiles', ] STATICFILES_DIRS = [os.path.join(BASE_DIR, '/static')] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/ Here is the partial output from the Command Prompt: System check identified no issues (0 silenced). October 25, 2018 Django version 2.1.2, using settings 'DataBooth.settings ' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [25/Oct/2018 "GET /dolcegusto/line HTTP/I.I" 200 9722 [25/0ct/2018 21:29:18] "GET / static/ vendor/datatab1es/dataTab1es.bootstrap4.css HTTP/I.I" 404 1753 Not Found: /dolcegusto/vendor/jquery/jquery . min. js [25/0ct/2018 21:29:18] "GET / static/ vendor/ fontawesome-free/css/all.min.css HTTP/I.I" 404 1741 Not Found: /dolcegusto/vendor/bootstrap/js/bootstrap. bundle. min. js [25/Oct/2018 "GET /static/css/sb-admin.css HTTP/I.I" 404 1672 … -
Django css isn't working, even though the css file is found
So in my html i have this link <link href="/static/css/style.css" rel="stylesheet"> I already set up all my static files: settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), #'/var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') urls.py: if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I already ran python manage.py collectstatic So when I load this page with the link, the bootstrap css loads and it doesn't say it can't find the style.css file, so I'm pretty sure its not an issue with my static directory because the files are registering and when it doesn't find the file it will say in the command shell as you load the page. This is a snippet of what style.css looks like. I won't show you the whole thing cause it's long: html, body, header, .view { height: 100%; } .icon-1 { font-size: 75px; } @media (max-width: 740px) { html, body, header, .view { height: 1000px; } } @media (min-width: 800px) and (max-width: 850px) { html, body, header, .view { height: 600px; } } @media (min-width: 800px) { .music-margin-top { margin-top: 140% !important; } .music-just2{ left: .4%; } .music-just4{ left: .3%; } So basically none of my custom css is showing up, but the file seems to … -
How do I handle tracing back to Segmentation Fault killing my workers?
so I have my app running and every now and then I get a Segmentation fault and my worker is killed off :[. I was wondering how I should go about fixing this issue? Here is the error log: !!! uWSGI process 8996 got Segmentation Fault !!! *** backtrace of 8996 *** /opt/django/www/bin/uwsgi(uwsgi_backtrace+0x2e) [0x4650ee] /opt/django/www/bin/uwsgi(uwsgi_segfault+0x21) [0x4654b1] /lib/x86_64-linux-gnu/libc.so.6(+0x36d40) [0x7ff6d0b86d40] /opt/django/www/local/lib/python2.7/site-packages/numpy-1.10.4-py2.7- linux-x86_64.egg/numpy/core/multiarray.so(+0x2eec8) [0x7ff6cbd5eec8] /opt/django/www/local/lib/python2.7/site-packages/numpy-1.10.4-py2.7- linux-x86_64.egg/numpy/core/multiarray.so(npy_aquicksort+0x218) [0x7ff6cbe32938] /opt/django/www/local/lib/python2.7/site-packages/numpy-1.10.4-py2.7- linux-x86_64.egg/numpy/core/multiarray.so(+0x878c3) [0x7ff6cbdb78c3] /opt/django/www/local/lib/python2.7/site-packages/numpy-1.10.4-py2.7- linux-x86_64.egg/numpy/core/multiarray.so(+0x8a09b) [0x7ff6cbdba09b] /opt/django/www/local/lib/python2.7/site-packages/numpy-1.10.4-py2.7- linux-x86_64.egg/numpy/core/multiarray.so(+0xcb642) [0x7ff6cbdfb642] /usr/lib/x86_64-linux- gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x4bd4) [0x7ff6d10a20d4] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x80d) /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(+0x1c36d0) [0x7ff6d10d86d0] /opt/django/www/local/lib/python2.7/site- packages/pandas/lib.so(+0x1468f) [0x7ff6c9f9d68f] /opt/django/www/local/lib/python2.7/site- packages/pandas/lib.so(+0x10be3) [0x7ff6c9f99be3] /opt/django/www/local/lib/python2.7/site- packages/pandas/lib.so(+0x2f843) [0x7ff6c9fb8843] /usr/lib/x86_64-linux- gnu/libpython2.7.so.1.0(_PyObject_GenericGetAttrWithDict+0xb1) [0x7ff6d105be81] /usr/lib/x86_64-linux- gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x2611) [0x7ff6d109fb11] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x80d) [0x7ff6d10a354d] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(+0x1c36d0) [0x7ff6d10d86d0] /opt/django/www/local/lib/python2.7/site- packages/pandas/lib.so(+0x1468f) [0x7ff6c9f9d68f] /opt/django/www/local/lib/python2.7/site- packages/pandas/lib.so(+0x10be3) [0x7ff6c9f99be3] /opt/django/www/local/lib/python2.7/site- packages/pandas/lib.so(+0x2f843) [0x7ff6c9fb8843] /usr/lib/x86_64-linux- gnu/libpython2.7.so.1.0(_PyObject_GenericGetAttrWithDict+0xb1) [0x7ff6d105be81] /usr/lib/x86_64-linux- gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x2611) [0x7ff6d109fb11] /usr/lib/x86_64-linux- gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x4b59) [0x7ff6d10a2059] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x80d) [0x7ff6d10a354d] /usr/lib/x86_64-linux- gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x48d8) [0x7ff6d10a1dd8] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x80d) [0x7ff6d10a354d] /usr/lib/x86_64-linux- gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x48d8) /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x80d) [0x7ff6d10a354d] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(+0x1c37a5) [0x7ff6d10d87a5] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyObject_Call+0x43) [0x7ff6d1044d43] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0xeb1) [0x7ff6d109e3b1] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x80d) [0x7ff6d10a354d] /usr/lib/x86_64-linux- gnu/libpython2.7.so.1.0(PyEval_EvalFrameEx+0x48d8) [0x7ff6d10a1dd8] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyEval_EvalCodeEx+0x80d) [0x7ff6d10a354d] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(+0x1c36d0) [0x7ff6d10d86d0] /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0(PyObject_Call+0x43) [0x7ff6d1044d43] *** end of backtrace *** DAMN ! worker 1 (pid: 8996) died :( trying respawn ... Respawned uWSGI worker 1 (new pid: 8999) This is shown exactly in my err.log and happens every now and then. I have no idea as why it might be happening. Please help a noobie out. There is one function that … -
Invalid HTTP_HOST header: The domain name provided is not valid -- requests to dockerized django app using container name
Within an app composed of multiple microservices run via docker-compose, I need a way to make a request from one container (app via flask & requests), directly to the other (chart/django): This is a simplified version of what I'm attempting. routes.py: @APP.route('/post_data', methods=['POST']) def post_data(): post_data = request.get_json() response = requests.post('http://chart_app_1:8080/json/', data=post_data) return response.text The response I get is an error message: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: 'chart_app_1:8080'. The domain name provided is not valid according to RFC 1034/1035 I'm able to make exactly this kind of request to other containers running flask apps, with no problems. I don't have any control over whether or not we use Django for this particular microservice though. It seems that this might be because the hostname has an underscore in it: see this post. Is there a way around this? It seems like it must be possible to make a simple request between containers. -
Django app - incorrect asset urls while serving via S3/CloudFront
I want to store my static assets and media in AWS S3 and serve them via CloudFront. My configuration (borrowed from this) are as following but for certain assets the app is concatenating localhost & CloudFront urls. I am not sure if my configs are correct. I have spent hours trying to figure this out. Any help is much appreciated! Concatenated url: http://127.0.0.1/static/https://dl4a98tlihsia.cloudfront.net/media/liirn_landing/Digiday_kcqijyq.jpeg http://127.0.0.1/static/https://dl4a98tlihsia.cloudfront.net/media/liirn_landing/Havas_Logo_NB88lg9.jpg http://127.0.0.1/static/https://dl4a98tlihsia.cloudfront.net/media/liirn_landing/Digiday_kcqijyq.jpeg settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ..... ...... INSTALLED_APPS = ( ... 'storages', ... ) ...... ...... STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), './static/', './static-assets/' ] # AWS custom storage steup AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME'] AWS_CLOUDFRONT_DOMAIN = os.environ['AWS_CLOUDFRONT_DOMAIN'] STATICFILES_LOCATION = 'static' # STATIC_ROOT = '/%s/' % STATICFILES_LOCATION STATIC_URL = 'https://%s/%s/' % (AWS_CLOUDFRONT_DOMAIN, STATICFILES_LOCATION) STATICFILES_STORAGE = 'docker_django.aws_s3.StaticStorage' MEDIAFILES_LOCATION = 'media' # MEDIA_ROOT = '/%s/' % MEDIAFILES_LOCATION MEDIA_URL = 'https://%s/%s/' % (AWS_CLOUDFRONT_DOMAIN, MEDIAFILES_LOCATION) DEFAULT_FILE_STORAGE = 'docker_django.aws_s3.MediaStorage' aws_s3.py from django.conf import settings from storages.backends.s3boto import S3BotoStorage class StaticStorage(S3BotoStorage): """uploads to the '/static' folder in S3 bucket, serves from cloudfront""" location = settings.STATICFILES_LOCATION def __init__(self, *args, **kwargs): kwargs['custom_domain'] = settings.AWS_CLOUDFRONT_DOMAIN super(StaticStorage, self).__init__(*args, **kwargs) class MediaStorage(S3BotoStorage): """uploads to the '/media' older in S3 bucket, serves from cloudfront""" location = settings.MEDIAFILES_LOCATION def __init__(self, *args, **kwargs): kwargs['custom_domain'] = settings.AWS_CLOUDFRONT_DOMAIN super(MediaStorage, … -
Whats the difference between .conf and .config files
I am running a Django Project in PyCharm and deploying it to EC2 in AWS. The guide tells me to use nginx I have to create a file called nginx_someName.conf however no matter how much I try I can't get create a .conf file and write in it. I tried to download Scala to Pycharm using the question below IntelliJ IDEA plugin to fold .conf files? but somehow the Scala plugin is no longer available on Pycharm. (Scala was supposed to be a plugin that allows .conf files) However I am able to create .config files So I named my file nginx_someName.config Is it the same thing -
Different setter and getter for django model field
I have a null boolean mysql field in django: class Invoice(models.Model): ... status = models.NullBooleanField() However, when I call it, I want it to return the following: @property def status(self): return "Pending" if self.status is None else "Paid" if self.status == 1 else "Failed" What would be the correct way to (1) set the data as a boolean; but then (2) when calling it receive the text? For example: >>> invoice = Invoice() >>> invoice.status = True >>> invoice.save() >>> invoice.status "Paid" -
Why am I getting 403 error with CSRF Token - Django - Vue Ressource
I'm new on Django and Vue.js. I have an application and I'm trying to post data but I get 403 error (even with CSR token). Currently, I wrote the following code: Base template: I get the CSRF token <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script type="text/javascript"> window.csrftoken = Cookies.get('csrftoken'); </script> My template where the form is displayed: <form @click.prevent="addtoCart({{article.id}})" method="post" action="{% url 'cart_add' article.id %}"> {% csrf_token %} {{ cart_product_form }} <input type="image" src="{% static 'img/icones/shopping-cart.png' %}" alt="shopping-cart" /> <input type="hidden" name="next" value="{{ request.path }}"> </form My Vue file : methods: { addtoCart: function(id) { csrftoken = window.csrftoken; this.$http.post('http://127.0.0.1:8000/commander/add/' + id +'/', {headers: {'csrfmiddlewaretoken': csrftoken}}); console.log(csrftoken); } } My view: def cart_add(request, product_id): product = get_object_or_404(Variations_Articles, id=product_id) cart = Cart(request) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data next = cd['next'] var = cart.add(product=product, quantity=cd['quantity']) return HttpResponseRedirect(next) My URL: path('add/<int:product_id>/', views.cart_add, name='cart_add') I can get the CSRF token in the console, but I still get a 403 error. It has been a couple of days that i'm looking for a mistake but i don't figure out where it is. Thanks in advance for your help. Singertwist -
Wagtail Tinymce - ModuleNotFoundError: No module named 'wagtail.wagtailadmin'
I'm trying to install the package "wagtailtinymce" already downloaded it, however, the repository tutorial is completely bad. I do not know if it's because of some update or something. I'm using the latest version of wagtail and I already have a project created (obvious). The error is in every import the package tries to make, and since I'm starting in Django and Wagtail, I do not know what to do. I have not been able to migrate the application yet because of this error. File "/mnt/sda3/Development/Projetos/blog-wagtail/env/lib/python3.7/site-packages/wagtailtinymce/wagtail_hooks.py", line 37, in <module> from wagtail.wagtailadmin.templatetags.wagtailadmin_tags import hook_output ModuleNotFoundError: No module named 'wagtail.wagtailadmin' File "/mnt/sda3/Development/Projetos/blog-wagtail/env/lib/python3.7/site-packages/wagtailtinymce/wagtail_hooks.py", line 29, in <module> from django.core.urlresolvers import reverse ModuleNotFoundError: No module named 'django.core.urlresolvers' The import of django passed when I changed to "from django.urls import reverse" but the rest I do not know what to do, and I believe it will continue to give error every import -
TemplateDoesNotExist at / home_page.html
When I run python manage.py runserver I get the error "TemplateDoesNotExist at / home_page.html". My folder structure is included in the screenshot below. How do I get my template to display when I run the server? Folder Structure Screenshot TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] -
How I can upload the complete directory Django?
I would like to upload the complete directory but I do not know how to do it. Currently, I am able to opload more files at the same time. But my wish is to copy and paste the reiter to my media directory in django. How can I do this? Here is my form: from django import forms class FileFieldForm(forms.Form): file_field = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True})) vocii my view: def FileView(request): if request.method == 'POST': form = FileFieldForm(request.POST, request.FILES) if form.is_valid(): for f in request.FILES.getlist('file_field'): liens = str(settings.MEDIA_ROOT) myfile = f a = myfile.name b = myfile fs = FileSystemStorage(liens + "photo/") filename = fs.save(a, b) return render(request, 'photo/upload.html', {'form': form}) here is my template: <form method="post" enctype="multipart/form-data" id="fileupload" type="file" name="file_field" multiple> {% csrf_token %} {{ form.as_p }} <button class="btn btn-warning btn-lg" type="submit">Upload</button> </form> -
Break long {% with %} assignment into multiple lines in a Django template
I'd like to improve my Django's template readability by breaking a very long {% with ... %} multi-assignment tag into multiple lines (without having to use multiple % with % tags). I have a very long {% with ... %} statement in my code (3 assignations), and it'd be nice if I could break it into multiple lines, but every combination I try ends in a TemplateSyntaxError at /products/ Invalid block tag on line 132: 'endwith'. Did you forget to register or load this tag? In order words, I have this: {% with is_ratable=is_ratable|default:False|logical_or:product.is_ratable is_heartable=is_heartable|default:False|logical_or:product.is_heartable is_customizable=is_customizable|default:False|logical_or:product.is_customizable %} and I'd like to break it into something like {% with is_ratable=is_ratable|default:False|logical_or:product.is_ratable is_heartable=is_heartable|default:False|logical_or:product.is_heartable is_customizable=is_customizable|default:False|logical_or:product.is_customizable %} Is it possible? I'm using Django 2.0.3 and Python 3.6.5 Thank you in advance -
Browser sources css file but does not apply it
I am trying to host a django web application using nginx as a reverse proxy and waitress as the application server. I am running this on windows. Static javascript assets load correctly on the page, but css does not. I have tried clearing my cache before refreshing the page, but that is not the problem as developer tools show the page correctly fetching the css file from the server. Additionally, I have tried navigating directly to "http://localhost:8888/static/css/styles.css" directly, and I can see the contents of the file. Does anyone have any idea why the browser would correctly fetch the file but not display it on the page? nginx.conf server { # Running port listen 8888; # Settings to serve static files location ^~ /static { alias "C:\\Users\\username\\Desktop\\django-dev\\appname\\static\\"; } # Proxy connections to the application servers # app_servers location / { proxy_pass http://127.0.0.1:8081; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } Request I am making: http://localhost:8888/static/css/styles.css html stylesheet reference <link rel="stylesheet" type="text/css" href="/static/css/styles.css"> -
How can I use use multiple objects in 1 table inside my Django template without breaking the layout or displaying incorrect data?
Inside my DetailView, I have 3 objects that are very similar with slight differences in the what is being filtered. # views.py def get_context_data(self, **kwargs): # all sales for all products with a specified title sales = Sales.objects.filter(publication__title=self.object) # filters print sales for a specified title print_sales = Sales.objects.filter(publicaton__title=self.object, line_item=1) # filters digital sales for a specified title digital_sales = Sales.objects.filter(publicaton__title=self.object, line_item=2) Ideally, I would like to display a table that has all sales separated by product and month like so: | Month | Print Sales | Digital Sales | | --------------- | ----------- | ------------- | | January | 2,000 | 3,000 | | February | 1,000 | 2,000 | | --------------- | ----------- | ------------- | | Total: | 3,000 | 5,000 | | Combined Total: | | 8,000 | However, I have not been able to figure out a way to properly format the table AND provide the correct filtered data within my template. The snippet below displays the properly formatted table (similar to above) but with the combined sales data displaying in each month. {% for item in sales %} <tr> <td>{{ item.issue }}</td> {% for obj in print_sales %} <td>{{ obj.net_sales}}</td> {% endfor %} {% …