Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
display list[0] list[1] in template form default value
I have a tag_list passed to template context = {"tags": ["python", 'django']} I want to retrieve them respectively as the input default value <input type="text" class="form-control" name="q" placeholder="Search ..." value="[{{ tags[0] }}] [{{ tags[1] }}]"> I intent id displayed as [python] [django] in the search bar but get error noticed. -
import views.py from app directory
In setting up Django app, I want to import main_app/views.py in the url.py of the main project folder. main_app folder is located parallel to the main project folder. Here is how I am referencing to import views.py in main project folder\url.py: > import sys > sys.path.append('../main_app') > > from django.conf.urls import url > from django.contrib import admin > from django.urls import path > from main_app import views > > urlpatterns = [ > path('admin/', admin.site.urls), > url(r'^', 'main_app.urls'), ] However, I am receiving ModuleNotFoundError: No module named 'main_app' -
Passing variables into extends template?
I have a template named base.html. As the name suggests, it is where the header and footer reside. In between these 2 elements, is a {block content} where the child template can extend this template and add content inside block content. However, inside header I want the user's name to be shown. For example, {user.username} but Django can't seem to recognize this when I extend this template to a child template. Is there a way I can pass in objects to the extends template? That way the logged in user's name is shown? -
Arbitrary depth of filter chains
I'd like to select articles which have multiple tags; url(r"^tagged/(?P<tags>[+]*\w+)$", views.tagged, name="tagged"), the request acts like "article/tagged/python+django" In the views.py, determine the length of tags and find qualified articles def tagged(request, tags): tags = tags.split("+") if len(tags) == 1: articles = Article.objects. .filter(tags__name=tags[0]) if len(tags) == 2: articles = Article.objects. .filter(tags__name=tags[0]) .filter(tags__name=tags[1]) if len(tags) == 3: articles = Article.objects. .filter(tags__name=tags[0]) .filter(tags__name=tags[1]) .filter(tags__name=tags[2]) if ... the multiple seems unwieldily, how could I solve the problem with a general function to handle arbitrary length the tags. -
Setting Up S3 with Heroku and Django with Images
so I currently have my static files (js and css) just being stored on Heroku which is no biggie. However, I have objects that I need to store multiple images too and be able to get those images on request. How would I store a reference to those images? I was planning to use a S3 Direct File Upload using these steps on Heroku here. Is this also going to be the best way for me to do so? Thank you in advance. -
Django Rest Framework: HTTP 401 Unauthorized error
I am django rest framework jwt token package. For some reason, it is not receiving the token credentials. I am sure I am using axios in the correct format to store a token. I am unsure if the error is frontend or backend. Settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } Frontend handleFormSubmit(e) { e.preventDefault(); if (this.getValidationState() == 'error') { this.setState({invalidFormSubmit: true}) return; } axios.defaults.headers.common['Authorization'] = 'Token ' + this.props.auth.getToken(); console.log(this.props.auth.getToken()); var capsule = new MyForm(); capsule.append("user", this.state.userUrl); capsule.append("dateToPost", this.state.dateToPost.format()); capsule.append("image", this.state.image); capsule.append("caption", this.state.caption); capsule.append("dateToDelete", this.state.dateToPost.add(1, "d").format()); axios.post(this.props.auth.domain + "/snapcapsule/", capsule) .then(() => { this.setState({redirect: true}) }).catch(err =>{ alert(err); }) } Error {"detail":"Authentication credentials were not provided."} -
Convert [python] [django] in search bar to python+django in url
When I input [python] [django] to search bar, it will convert automatically to 'python+django' in the url https://stackoverflow.com/questions/tagged/python+django I am trying this function but have no idea where to start from, Could you please provide any hints? -
nginx invalid number of arguments in "proxy_pass" directive
nginx: [emerg] invalid number of arguments in "proxy_pass" directive in /etc/nginx/sites-enabled/django_direct:12 My nginx conf file: server { listen 80; server_name 94.154.13.214; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/django_direct/main_app/; } location / { include proxy_params; proxy_pass unix: /root/django_direct/django_direct.sock; } } What do I do? -
Issue with django-paypal encrypted button
I have been trying to encrypt a paypal button so that it can't be tampered with via html. I've followed the steps outlined here in the docs to the best of my knowledge, but on calling the view that generates the form, I'm met with the following django error: X509Error at /cart/payment/ no start line I generated a private and public key as usual and was able to upload the public key to paypal ok to get a certificate, but I've noticed that in the docs it refers to the certificate supplied by paypal as a .pem file when the file they supply me with is a plain txt file. Is there something I need to do to this file before I can use it to encrypt the button? If anyone has been down this route before I'd be very grateful if you could share your knowledge. Thanks in advance -
django, static files not found 404
I am getting an error with static files in nginx custom_main.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) THis is my nginx config: server { listen 80; server_name 94.154.13.214; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/django_direct; } location / { include proxy_params; proxy_pass unix:// root/django_direct/django_direct.sock; } } What do I do? -
dc.js charts not working in django
I have a Django URL which generates the JSON data for the charts which works (see url(r'^report/get_issues_json/$', get_issues_json, name='get_issues_json'), in issues/urls.py) but when I call that URL from my javascript file (static/js/graph.js) it doesn't render anything (no errors or anything in the console) in my html page (issues/templates/report.html) the code is in this github branch here: https://github.com/jordandaly/issue_tracker/tree/dashboard -
searching images on the internet by hash
I have a selection of 13970 corrupted images, each named after its own MD5 hash. Ideally I want to conjure up a tool that can search the internet matching the corrupt image with a clean undamaged version online, using this hash, and restore the image. At the moment I am trying to find a means to search online by hash. I have been able to find online services offering hashes of images you don't want on your website for blacklisting purposes, if it is possible to check what users are posting to your website against a blacklist, it must be possible to match a corrupt image against it's original source or a repost online. -
can not able to add favicon in my django app
I'm using django 2.06 to develop an application. I'm trying to add Favicon but it's not working in my app. <link rel="shortcut icon" href="{% static 'favicon.ico' %}" type='image/x-icon' > <link rel="icon" href="{% static 'favicon.ico' %}" type='image/x-icon'> I have mentioned {% load static %} at base.html file as well. How can i fix this?? -
Celery get() works in python shell but not in Django view
I want to check basic Celery functionality inside official demo Celery project for django with code available here. My modification is the demoapp/views.py (and of course urls.py to point to this view): from __future__ import absolute_import, unicode_literals from django.http import HttpResponse from demoapp.tasks import add, mul, xsum def home(request): return HttpResponse("Your output is: %s" % mul.delay(22,4).get(timeout=1) ) which always gives timeout error, though the terminal of running Celery worker shows that task was received and displays correct return value. However, if I start python shell python ./manage.py shell and then run from demoapp.tasks import add, mul, xsum mul.delay(22,4).get(timeout=1) I immediately get the expected result. What may be the problem? Rabbitmq server is running, I use Celery 4.2.1, django 2.0.6. demoapp/tasks.py: from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def add(x, y): return x + y @shared_task def mul(x, y): return x * y @shared_task def xsum(numbers): return sum(numbers) proj/celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' … -
Django REST Framework: Is the top-level JSON array on an empty ListView a security risk?
Django REST Framework returns what appears to be an empty array when querying a ListView that does not have any objects. Is this a security risk? -
Django UpdateView is not working
My question is when I use an UpdateView, it doesn't update the record. Besides this it also doesn't give any error. When I debug code, the form_valid() function is not called after the HTTP POST request. But my form class (AdvertisementDetailForm) is correctly working. I couldn't find what I'm doing wrong. Console outputs like that: GET /advertisement/publish/adv1_3ad5f56a-d99d-4ed4-b878-1327b9fa1bf8/1/ HTTP/1.1 POST /advertisement/publish/adv1_3ad5f56a-d99d-4ed4-b878-1327b9fa1bf8/1/ HTTP/1.1 1st App views.py: class PublishAdvertisement(LoginRequiredMixin, generic.UpdateView): login_url = '/' redirect_field_name = '/' model = AdvSummary form_class = AdvertisementDetailForm template_name = 'advertisement/publish_advertisement.html' success_url = reverse_lazy('brand:brand_home') def form_valid(self, form): pk = self.kwargs.get('pk') obj = get_object_or_404(AdvSummary, pk=pk) obj.advertisement_image = form.cleaned_data['advertisement_image'] obj.adv_max_follower = self.request.POST['adv_max_follower'] obj.adv_min_follower = self.request.POST['adv_min_follower'] obj.adv_desc = self.request.POST['adv_desc'] selected_categories = Category.objects.filter(pk__in=self.request.POST.getlist('categories')) obj.categories.add(*[cat for cat in selected_categories]) obj.publish_date = timezone.now() obj.save() return super().form_valid(form) urls.py: urlpatterns = [ path('publish/<slug:slug_name>/<int:pk>/', views.PublishAdvertisement.as_view(), name='publish'), path('delete/<slug:slug_name>/<int:pk>/', views.DeleteAdvertisement.as_view(), name='delete'), ] 2nd app views.py: class BrandHomePage(LoginRequiredMixin, generic.View): login_url = '/' redirect_field_name = '/' def post(self, request, *args, **kwargs): view = CreateAdvertisement.as_view() return view(request, *args, **kwargs) def get(self, request, *args, **kwargs): view = PublishedAdvertisementList.as_view() return view(request, *args, **kwargs) urls.py: urlpatterns = [ path('', views.BrandHomePage.as_view(), name='brand_home'), ] -
How to translate category names in Django
I do not want to use third-party module for this.. I only need to translate category names. Here is my category model: class Category(models.Model): name = models.CharField(_('Category Name'), max_length=50) slug = models.SlugField(_('Link')) class Meta: verbose_name = _('Category') verbose_name_plural = _('Categories') def __str__(self): return self.name def get_absolute_url(self): return reverse('abc:category', args=[self.slug]) I just want to translate "name" field of the Category model instances. Let's say I added category called "General". When a user views my website with x language, the "General" text should be translated into x language. How can I achive this? Doesn't Django has a built-in way to do this? (I can use choice field instead of a model for categories, but in this case, they can't be dynamic, I need to update models.py file every time that I want to add a category.) -
Django: Serializers filtering out undeclared fields
Here is my MSV: models.py import mongoengine class PersonAddressModel(mongoengine.DynamicEmbeddedDocument): country = mongoengine.fields.StringField() town = mongoengine.fields.StringField() class PersonModel(mongoengine.DynamicDocument): name = mongoengine.fields.StringField() age = mongoengine.IntField() is_married = mongoengine.fields.BooleanField() address = EmbeddedDocumentListField(PersonAddressModel) serializers.py from rest_framework_mongoengine import serializers from .models import PersonInfoModel, PersonAddressModel import mongoengine class PersonAddressSerializer(serializers.EmbeddedDocumentSerializer): class Meta: model = PersonAddressModel fields = '__all__' class PersonSerializer(serializers.DynamicDocumentSerializer): class Meta: model = PersonModel fields = '__all__' views.py from rest_framework_mongoengine import viewsets from .serializers import PersonSerializer, PersonAddressSerializer from rest_framework.response import Response from rest_framework import status import djongo from .models import PersonModel class PersonView(viewsets.ModelViewSet): lookup_field = 'id' serializer_class = PersonSerializer def create(self, request): serializer = self.serializer_class(data=request.data) try: serializer.is_valid() serializer.save() except djongo.sql2mongo.SQLDecodeError: return Response( status=status.HTTP_503_SERVICE_UNAVAILABLE ) return Response( status=status.HTTP_201_CREATED ) I'm sending the following json object: { "name": "Helmut", "age": 21, "is_married": true, "address": [{"country": "Germany", "town": "Berlin", "street": "Wolfstraße 1"}] } However when I check the database I see the following object: { "_id" : ObjectId("5b5e201c540d1c3b7a4491e8"), "name" : "Helmut", "age" : 21, "is_married" : true, "address" : [ { "country" : "Germany", "town" : "Berlin" } ] } That's to say, Helmut's street is missing. I wonder why! My bet is that it has something to do with the serializers but I can't figure out what it … -
New to Python: "ModuleNotFoundError: No module named 'django'"
I'm currently working on a tutorial to create an app using Python and Django and am fairly new to the whole process. I keep getting the message: "ModuleNotFoundError: No module named 'django'" when running my manage.py file in python I'm working on a mac if that makes a difference: Python 3.7 Django 2.0.7 Using virtualenvwrapper My virtual environment is active dir: my project myproject myproject manage.py venv Here's my manage.py file: from django.db import models from django.contrib.auth.models import User class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics') starter = models.ForeignKey(User, related_name='topics') class Post(models.Model): message = models.TextField(max_length=4000) topic = models.ForeignKey(Topic, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name='posts') updated_by = models.ForeignKey(User, null=True, related_name='+') I've also changed the top line from "from django.db import models" to "from django.urls import models" as I've read this was recommended on some other posts but have had no success. What am I missing? Thanks for the help! -
Python manage.py test error
I am trying to run a manage.py test on my application and I am getting the following error: ERROR: test_was_published_recently_with_future_question (samples.tests.QuestionModelTests) Traceback (most recent call last): File "/Users/developer/dev/everest/everest-web/web-app/samples/tests.py", line 17, in test_was_published_recently_with_future_question future_question = Question(pub_date=time) File "/anaconda3/lib/python3.6/site-packages/Django-2.2.dev20180728041048- py3.6.egg/django/db/models/base.py", line 485, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Question() got an unexpected keyword argument 'pub_date' I am not sure where to look to fix this error. -
Unable to save file: Permission denied in atom while working on django
guys what is the solution of this problem or error even if I try to save it out of atom or anywhere it gives me the same error -
Django progress bar update by view
I have a progress bar in my html, I want to send the percentage from a view function and so update it. I should use a while in the view function but to pass the variable to html I should use: return render(request, 'Progress.html', {'ProgressBar':ProgressBarPercentage}) this will break the while loop, How should I pass the variable to the html without returning? -
django-rest-framework ModelSerializer fields whose names are invalid Python identifiers
If I have a serializer thus: class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) then the dictionary returned by serializer.data will have keys "email" and "content". But I need to include fields whose names are not valid Python identifiers: "type" "@context" Is there an idiomatic way of doing this? -
django system with signup and login features
I am trying to build a django system with signup and login features and I also want that the logged in user should be able to add notes to his profile. What approach should I take up for building my models?...creating a OneToOneField for User or creating a custom Django User model. Please help! -
Creating and annotating simple geographical maps in Django
I am looking for a simple way to create geographical maps in Django, in which I could then select, highlight and annotate countries or groups thereof. "Annotate": insert a label displaying textual information about said country. Is there anything that comes to mind? Many thanks