Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I get HTTP 404 when I load static files in Django
I am trying to upload images. I configured the directory which stores the image but I got 404 error. look on this error on the console this is the configuration: URL file from django.conf.urls import url,include from django.contrib import admin # These 2 lines are for static files from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), # We isolated "Posts" app urls in its folder then we included them in the main project url file # Here decleared a namespace for the whole "post app URL file". This namespace is "postsAppURLs". url(r'^posts/',include("posts.urls", namespace="postsAppURLs")), ] if settings.DEBUG: urlpatterns = static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) # This is required for images urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is setting file: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") This is my model if you it will help you to understand this issue class Post(models.Model): title = models.CharField(max_length=121) image = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field" ) height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) content = models.TextField() updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=Tr -
DJANGO Form Clean
Model: class MyModel(models.Model): status = models.ForeignKey(Status, on_delete=models.PROTECT, null=True, blank=True) date = models.DateField() Form: class MyModelForm(ModelForm): class Meta: model = MyModel fields = '__all__' def clean_date(self): cd = self.cleaned_data status = cd.get('status') date = cd.get('date') if not date and status == 1: raise forms.ValidationError((mark_safe('<p class="text-danger">When status is .... You must add date </p>'))) return date My clean function not work. How is wrong ? Can you help me ? -
Integrate Django cms with Openedx
I am trying to Integration Django-cms with Openedx.. getting error while importing from cms.models import * its looking into openedx cms not in django-cms. I tried to renamed cms(django-cms) in virtualenv but its inappopirate way, how can i fix this issue. Thanx in Advance -
django 1.11 polls app not working
i am new to django and web frameworks. As said in the documentation of django 1.11.4, i changed polls/view.py as from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") after that i created polls/urls.py and write code in it as: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] finally changed mysite/urls.py as from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] when i run this project with: python manage.py runserver it shows error when go to "http://localhost:8000/polls/": Not Found: /polls/ [09/Aug/2017 12:01:36] "GET /polls/ HTTP/1.1" 404 1947 i add polls to installed apps. What else to do ?? -
Django NoReverseMatch and POST URL error
I am facing 2 issues NoReverseMatch and APPEND_SLASH . Issue #1. APPEND_SLASH Detail.html <form action="update-entry" method="post"> /* if I add '/' at the end of update-entry, it works fine. */ {% csrf_token %} {{ form }} <input type="submit" value="Edit"> </form> When I click on the Edit button, I get the error below, You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/genericviews/1/update- entry/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. This is the URL generated: http://127.0.0.1:8000/genericviews/1/update-entry I know URL should end with '/'. urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailsView.as_view(), name='detail'), url(r'^makeentry$', views.makeentry, name='makeentry'), url(r'^static/$', views.StaticView.as_view()), url(r'^new-entry/$', views.MakeEntryView.as_view(), name='new-entry'), url(r'^(?P<pk>[0-9]+)/update-entry/$', views.UpdateEntryView.as_view(), name='update-entry'), ] My confusion is why URL is not generating '/' at the end. Above URL pattern seems correct to me. Issue #2 NoReverseMatch When I try to change the hardcoded URL, I get the error below, NoReverseMatch at /genericviews/1/ Reverse for 'update-entry' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['genericviews/(?P<pk>[0-9]+)/update- entry/$'] Detail.html <form action="{% url 'genericviews:update-entry' %}" method="post"> {% csrf_token … -
Queryset filter: retrieve manytomany field as list of each object
I want to retrieve every object of a model with only their id and a list of ids they have in a many to many field. My models : class Wordlist(models.Model): words = models.ManyToManyField(Word) class Word(models.Model): word = models.CharField(max_length=256) I have this code : list(models.objects.all().annotate(w=F('words')).values_list('pk', 'w')) And it gives me this : [{'pk': 1, 'w': 7}, {'pk': 1, 'w': 13}, {'pk': 1, 'w': 17}, {'pk': 2, 'w': 29}, {'pk': 1, 'w': 42}, {'pk': 3, 'w': 52}, {'pk': 2, 'w': 65} ... ] What i want is : [{'pk': 1, 'w': [7, 13, 17, 42,...]}, {'pk': 2, 'w': [29, 65,...]}, {'pk': 3, 'w': [52,...]}, ... ] A simple solution would be to combine the dicts based on their ids but I don't think it's a good practice and very efficient, since we could have dozens of thousands dicts as a result. Also, I wondered if it was possible to do the opposite with a single request; retrieving a list of Wordlist a word is in for each word in a request on Word. -
Django - Authentication in Forms
I'm relatively new to Django and most of what I've done previously hasn't needed User Authentication so I am especially new to working with this. I have two of my own models, a company (linked to a django user), and employees (many to one relationship with a company). What I would like to do is find out how to create forms so that when a user is logged in, it can add new employees that are automatically tethered to the company relating to that user (and cannot tether them to others of course). I've seen things like self.request(user), but am unsure how this would work for me as the model I am trying to create with this form is not directly linked to the user that is logged in. Any advice or pointers towards places with solutions would be much appreciated. -
Additional routes are not visible after specifying additional paths to add a sub memo picture picture
Is there my code below and is there any wrong part? view.py class PhotoCreateView(CreateView): model = Photo template_name = "photo/photo_form.html" fields = ['description'] def get_form(self, form_class=PostForm): form = super (PhotoCreateView, self).get_form (form_class) form.fields['description'].widget = SummernoteInplaceWidget () return form -
NVD3 scatter plot not showing
I was trying to try the nvd3 scatter plot example myself. I am not getting any error, but the chart is not populating. I got a blank web page when I try to get to the screen. Even my existing other contents are gone. Did anyone manage to get the scatter plot up and running? I would really appreciate if you could share a working example. #html <script> $(document).ready(function(){ nv.addGraph(function() { var chart = nv.models.scatterChart() .showDistX(true) //showDist, when true, will display those little distribution lines on the axis. .showDistY(true) .color(d3.scale.category10().range()); //Axis settings chart.xAxis.tickFormat(d3.format('.02f')); chart.yAxis.tickFormat(d3.format('.02f')); var myData = randomData(4,40); d3.select('#chart svg') .datum(myData) .call(chart); nv.utils.windowResize(chart.update); return chart; }); /************************************** * Simple test data generator */ function randomData(groups, points) { //# groups,# points per group var data = [], shapes = ['circle', 'cross', 'triangle-up', 'triangle-down', 'diamond', 'square'], random = d3.random.normal(); for (i = 0; i < groups; i++) { data.push({ key: 'Group ' + i, values: [] }); for (j = 0; j < points; j++) { data[i].values.push({ x: random() , y: random() , size: Math.random() //Configure the size of each scatter point , shape: (Math.random() > 0.95) ? shapes[j % 6] : "circle" //Configure the shape of each scatter point. }); } … -
Using Scrapy DjangoItem but it won't save the item
I'm learning Python and Django and for my personal project, I'm just playing with Scrapy for scraping website data and links. It took me almost two days for setting up DjangoItem and writing spider but there is just one thing I can't solve by myself! When I run the spider by "scrapy crawl WebspiderSpider", it runs and end without any errors. But the problem is the crawled data is not saved...I checked pipeline, items, settings, but it seems alright. Please help me! So this is my webspider.py from zukkan_bot.items import WebItem import datetime from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class WebspiderSpider(CrawlSpider): name = 'WebspiderSpider' allowed_domains = ['example.com'] start_urls = ['http://example.com/'] xpath = { 'title': "//title/text()", } list_allow = [r''] list_deny = [r''] list_allow_parse = [r''] list_deny_parse = [r''] rules = ( Rule(LinkExtractor( allow=list_allow, deny=list_deny, ), follow=True ), Rule(LinkExtractor( allow=list_allow_parse, deny=list_deny_parse, unique=True ), callback='parse_items' ), ) def parse_items(self, response): item = WebItem() item['title'] = response.xpath(self.xpath['title']).extract()[0] item['link'] = response.url item['date'] = datetime.datetime.utcnow() + datetime.timedelta(hours=9) return WebItem(title=item['title'], link=item['link'], date=['date']) And here is the items.py from scrapy_djangoitem import DjangoItem from zukkan.models import ExampleDotCom, Spider class WebItem(DjangoItem): django_model = Spider This is the pipelines.py class ZukkanBotPipeline(object): def process_item(self, item, spider): item.save() return … -
(Django) Order by desc
I can not order my News table. I guess i did everything right but django shows me error! Please check my code maybe something went wrong class News(models.Model): news_title = models.CharField(max_length=255) news_text = models.TextField(max_length=1000) news_logo = models.ImageField(upload_to='uimages') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'News' verbose_name_plural = 'News' **News.objects.filter().order_by('-created_at')** -
Django rest framework filters and search not working when def list() is added to model viewsets
I am working on API written in Django rest framework. I have added Search filters and ordering filters in my ModelViewSet and were working fine. class bookviewset(ModelViewSet): queryset = Book.objects.all() serializer_class = book_serializer filter_class = bookfilter filter_backends = ( django_filters.rest_framework.DjangoFilterBackend,filters.OrderingFilter,filters.SearchFilter) ordering_fields = ('created_at', 'id','price_ids__price',) search_fields = ('name', 'description', 'tag_ids__tag_name', 'category_ids__category') But, When I override def list(self, request, *args, **kwargs): inside Modelviewset, all the filters have stopped working. Is there a way to enable all the filters again? Thank you. -
connect firebase with django
I want to connect my django app with firebase and I am trying to push the data into firebase, but it is not taking any data. Although my app is working correctly. Please help. my views.py file is here enter image description here -
JSONDecodeError : Sending file and json string to Django view in POST request
I am sending a file and json object in string format as in the POST request in multipart/form-data below. I am unable to identify what I am doing wrong here. Request, Django view code and the stacktrace - Request: curl -X POST \ http://127.0.0.1:8000/api/capshots/send-capshot-new-capset/ \ -H 'authorization: Token 534cec0c2d7f81808600fee15751b4de2b7c1bd1' \ -H 'cache-control: no-cache' \ -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \ -F media_file=@/Users/ankit/Desktop/logo.png \ -F thumbnail_image=@/Users/ankit/Desktop/logo.png \ -F 'payload='\''{"allow_capset_sharing": true, "description": "Bla blah", "media_type": 1, "content_type_list": ["group", "directmessagegroup", "temporarygroup"], "object_id_list": [3, 2, 4], "userprofiles_pk": [2, 4, 6], "direct": false}'\''' Code def send_capshot_new_capset(request): created_by = request.user.userprofile payload_json_str = request.data['payload'] payload_json = json.loads(payload_json_str) content_type_list = payload_json['content_type_list'] object_id_list = payload_json['object_id_list'] allow_sharing = payload_json['allow_capset_sharing'] description=payload_json['description'] media_type=payload_json['media_type'] . . . Stacktrace : ^[[BInternal Server Error: /api/capshots/send-capshot-new-capset/ Traceback (most recent call last): File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/rest_framework/views.py", line 483, in dispatch response = self.handle_exception(exc) File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/rest_framework/views.py", line 443, in handle_exception self.raise_uncaught_exception(exc) File "/Users/ankit/projects/indiez/capshot/capshot-be/venv/lib/python3.6/site-packages/rest_framework/views.py", line 480, in dispatch response = handler(request, *args, **kwargs) … -
manage.py runserver & migrate get stuck without showing any error
Here is commands to I use: python3 manage.py migrate python3 manage.py runserver After these commands I receive no error but not migarte nor the the runserver work. Although, It didn't work after removing warnings and I am pretty sure It's not due to warnings. I am using Linux-Mint Python 3.x Django 1.9 Can anyone please tell what's the problem is or where to look for??? -
How do I convert this string to an array of json objects? [duplicate]
This question already has an answer here: Deserializing a JSON into a JavaScript object 8 answers '[{"x": "y", "pk": 1, "f": {"l": 2, "d": "3"}}]' This is a object serialized to json using django. I need to convert it from a string to a an array of json objects which i can use in my ajax function. -
The django templates language judgement if is abnormality.
My code in the views.py: def home(request): return render(request, 'home.html', {'age':37}) This is the if templates judgement in the django templates example: <tr> <td> {% if age > 25 %} <span> >25 </span> {% elif age > 30 %} <span> >30 </span> {% elif age > 35 %} <span> >35 </span> {% else %} <span> other </span> {% endif %} </td> </tr> But however if I refresh the safira there all prints >25, not >35, why? -
Single ModelForm for model fields, updating just subset at time
I'm using Django 1.11. I'm currently solving the following problem: Currently I'm having multiple ModelForms for a single Model (different forms have different fields of the model in them, e.g. modelForm1 has fieldA, modelForm2 has fieldB, fieldC and fieldD, ...). This is because in the template I need to have the forms in different places (because of the UI). I was wondering if it is possible to have just one ModelForm with the union of all fields that would update only the fields it receives through request.POST, leaving the others as they are. For the sake of simplicity let's assume that all the fields are non-required and have no validations. (One possible solution is to encapsulate all the fields in template in the "big" form, but this does not work for me as there are more different non-model forms in the template as well and HTML s cannot overlap or nest.) Thank you. -
DRF serializer only works one way, output is OK, but input gives error
I am trying to follow this http://www.django-rest-framework.org/api-guide/fields/#custom-fields to serialize a Point in GeoDjango. But only get the exception below. Can't figure out where my mistake is. It outputs correctly, but get an error while inserting the same output. Got a `TypeError` when calling `Venue.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Venue.objects.create()`. You may need to make the field read-only, or override the VenueSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/rest_framework/serializers.py", line 916, in create instance = ModelClass.objects.create(**validated_data) File "/usr/local/lib/python3.5/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 394, in create obj.save(force_insert=True, using=self.db) TypeError: save() got an unexpected keyword argument 'force_insert' from django.contrib.gis.geos import Point class LocationField(serializers.Field): def to_representation(self, obj): return "%s,%s" % (obj.y, obj.x) def to_internal_value(self, data): lat,lng = [col for col in data.split(',')] return Point(float(lat), float(lng), srid=4326) -
How to convert the data types in the django templates language? [duplicate]
This question already has an answer here: Need to convert a string to int in a django template 4 answers This is the code of home.html: This code is in my views.py: def home(request): return render(request, 'home.html', {'age':'27'}) This is the templates html home.html: <td> {% if age > 25 %} <span>abc</span> {% elif age > 30 %} <span>def</span> {% elif age > 35 %} <span>ghi</span> {% else %} <span>others</span> {% endif %} </td> You know in the home.html, it will be others, not abc. How to convert the string to int in the django templates language? -
typeahead.js in Django project
There are examples on https://twitter.github.io/typeahead.js/examples/ I need to make a similar thing in my django app for searching hashtags. But I tried and it doesn't work. There is a similar question and got ansewred on stackoverflow, but i dont get it out how to do it. Using typeahead.js in Django project views.py class SearchTag(View): """ Search tags with autocomplete (live search) """ def get(self, request): form = SearchTagForm() context = {'searchtag' : form} return render(request, 'search_tags.html', context) def post(self,request): q = request.POST['q'] form = SearchTagForm() tags = HashTag.objects.filter(name__icontains=q) context = {'tags' : tags, 'searchtag' : form} return render(request, 'search_tags.html', context) class TagJson(View): """Search a hashTag with auto complete feature""" def get(self, request): q = request.GET['q'] taglist = [] tags = HashTag.objects.filter(name__icontains=q) for tag in tags: new = {'q' : tag.name} taglist.append(new) return HttpResponse(json.dumps(taglist), content_type="application/json") models.py class HashTag(models.Model): ''' HashTag model ''' name = models.CharField(max_length = 100, unique = True) post = models.ManyToManyField(Post) def __str__(self): return self.name forms.py class SearchTagForm(forms.Form): q = forms.CharField(widget=forms.TextInput(attrs={ 'size' : 30, 'class' : 'form-control search-tag-query typeahead', 'id' : 'typeahead' })) and in html it looks like this <input type="text" name="q" size="30" class="form-control search-tag-query typeahead" id="typeahead" required=""> i got the typahead.bundle.js connected and also a file search_tag.js … -
No handlers could be found for logger "silk.middleware"
I am following https://github.com/jazzband/silk#installation to setup django-silk but getting error in middleware.I have django silk middleware in the last also Do anyone have any solution please let me know -
How to incorporate server side authentication in a react-redux project with python/django backend?
I'm working on a project which has it's backend on python/django and front end in react and redux with client side routing using react-router. Please suggest me some ways of doing user login authentication/validation in react with the django token generated/stored at the backend. The login flow should be something like this: User table with email and password created in django, auth token generated by django. User logs in for the first time, api gets called by react, on successful validation server responds with a token which I'll be storing in a session. All the subsequent calls to the api will include this token for authorization. Secondly, I'm confused about how the secured client side routes will be authorised? On the basis of the user logged in state or what? PS: I'm only asking suggestions for the best ways to achieve this and nothing else. -
Django synchronous task queue to external system
I have Django application as a load balancer. It receives tasks and forwards them to available server. All communications handled as HTTP requests, i.e. django posts http request to external server and ext. server posts http request to django upon task completion. Unfortunately there's no way to check whether the ext. server is busy or not, so I need to wait for notification. As Django process requests asynchronously I need to build some synchronous task queue which will monitor free tasks and free servers and send tasks to all available servers and then will wait until any of them reports back. I tried using celery but not sure how to "wait" for server to report back. -
Django REST Framework, breaks image while uploading
I have model Product: class Product(models.Model): ... image = models.ImageField( upload_to=lambda instance, filename: 'images/{0}/{1}'.format(instance.id, filename), max_length=254, blank=True, null=True ) ... Then I have serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ( ... 'image', ... ) And then I have views: class ProductViewSet(BaseViewSet, viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer @detail_route(methods=['POST']) def upload_image(self, request, *args, **kwargs): upload = request.data['file'] print(upload.name) product = self.get_object() product.image.delete() upload = request.data['file'] product.image.save(upload.name, upload) return Response({'Location': product.image.url}, status=status.HTTP_201_CREATED) Problem is only with images. On uploading images changes 'source code', and I can't open it, in the browser black window. Mp3 and PDF formats works fine. Why does it happens? Thank you.