Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSONField Django template doesn't show me what I went
after a lot of research, I still have not found how to do it: my purpose is to be able to separate my json in keys/values to only display what it seems to me necessary (for example the title, the authors, ...). It's a Django Site web. That I have done : In models.py class Production(models.Model): titre = models.CharField(max_length=255, blank=True) publis = JSONField() def __str__(self): return '%s' % (self.titre) class Meta: db_table = 'Production' In Views.py def post_json(request): posts = Production.objects.all() return render(request, 'appli/post_json.html', {'posts': posts}) *And the template : post_json.html * This show me fully my json data {% for post in posts %} <div> <p>aa = {{ post.publis }}</p> </div> {% endfor %} And this it's what I'm trying to show only the authors <h1>Publications lalala</h1> {% for post in posts %} aa = {{ post.publis }} <p> Num : {{ aa.UT }}</p> <p>Auteur : {{ aa.AU }} </p> {% endfor %} The display on my web page : enter image description here Thank you in advance for your help (sorry if there are mistakes of english I am french) -
Django QuerySet: filter by the value of another field
I have a model I wish to filter by its attribute a. The model also has another attribute b. I am trying to filter entries where a is 0 or a has the value of the b attribute (for each row, obviously). How can I filter by the value of another column? Here is what I have tried, and the missing piece: MyModel.objects.filter(Q(a=0) | Q(a=???)) # ??? is to be the value of the `b` column I am using Django 1.4 and I know it is an old version that is no longer supported but unfortunately performing the upgrade is not up to me. -
Django: how to access inline fields from parent model form?
Here is a simple multiple choice application. A Question can have 4 choices. In the admin panel, when save new question, I want check number of choices that are empty(no words) but I don't know how to access the 4 choices. How can I access choices' values inside QuestionForm's clean() function? #model.py class Question(models.Model): question = models.CharField(max_length = 250) class Choice(models.Model): question = models.ForeignKey(Question) choice = models.CharField(max_length = 250) #admin.py class ChoiceInline(admin.TabularInline): model = Choice extra = 4 can_delete = False max_num = 4 # fix to have 4 choices class QuestionForm(forms.ModelForm): class Meta: model = Question fields = '__all__' def clean(self): """ HERE, i want to access the 4 choices model """ return self.cleaned_data class QuestionAdmin(admin.ModelAdmin): form = QuestionForm inlines = [ChoiceInline] admin.site.register(Question, QuestionAdmin) admin.site.register(Choice, ChoiceAdmin) -
django & nguni on digitalocean
I try to setup django and its environment on ubuntu using this tutorial I do the following sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=django Group=www-data WorkingDirectory=/home/django/django_project ExecStart=/home/django/django_project/django_project/bin/gunicorn -- workers 3 --bind unix:/home/django/django_project/django_project.sock m$ [Install] WantedBy=multi-user.target sudo systemctl start gunicorn sudo systemctl enable gunicorn sudo nano /etc/nginx/sites-available/django_project server { listen 80; server_name 1.1.1.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django/django_project; } location / { include proxy_params; proxy_pass http://unix:/home/django/django_project/django_project.sock; } } sudo ln -s /etc/nginx/sites-available/django_project /etc/nginx/sites-enabled sudo nginx -t sudo systemctl restart nginx sudo ufw delete allow 8000 sudo ufw allow 'Nginx Full' User name on system is django. Inside home/django there is django_project folder with django files But in return I get 502 error. What am I doing wrong ? -
How to host Django 1.10 Web Application on WHM via cpanel?
I want to host my Django 1.10 web application on WHM(VPS). for that i have installed Django and another necessary tools on WHM(VPS) by ssh login. and i also have uploaded my Django application code through cpanel in public_html directory. When i run python manage.py runserver <ip_address:8000> from ssh terminal, i am able to access that application. but when i close the ssh terminal, it terminates all the running process. so could not access application after that. So, Is there any way that without running python manage.py script i can access Django application? Any help would be highly appreciated. Thank you. -
Django timezone's now, what am I missing?
I'm having a hard time understanding how timezones works in django, so I looked at the source code in django/utils/timezone.py and I found the following code: def now(): """ Returns an aware or naive datetime.datetime, depending on settings.USE_TZ. """ if settings.USE_TZ: # timeit shows that datetime.now(tz=utc) is 24% slower return datetime.utcnow().replace(tzinfo=utc) else: return datetime.now() And I don't really understand why the provided tzinfo doesn't depend on settings.py's TIME_ZONE. Shouldn't it be something like that instead? return datetime.utcnow().replace(tzinfo=get_default_timezone()) This way timezone.now() will really be time zone aware, doesn't it? -
Django: How to fix template rendering?
THIS IS MY views.py: views.py: from django.views import generic from django.shortcuts import render, get_object_or_404 from .models import medicines,details_post,Post from django.http import JsonResponse def index(request): detailsposts=details_post.objects.all() medicine=medicines.objects.all() blog=Post.objects.all() return render(request,'aptool/index.html',{'my_dis':detailsposts,'my_data':medicine,'blogposts':blog}) def search(request): searchdata=request.GET.get('searchtext') queryset=details_post.objects.filter(disease_name__startswith=searchdata).values_list('disease_name') return JsonResponse({'result':list(queryset)}) class MedicineView(generic.ListView): template_name='aptool/medicine.html' def get_queryset(self): return medicines.objects.all() class DiseaseView(generic.ListView): template_name='aptool/disease.html' def get_queryset(self): return details_post.objects.all() class BlogView(generic.ListView): template_name='aptool/blog.html' def get_queryset(self): return Post.objects.all() def meddetail(request, med_id): medicine=get_object_or_404(medicines,pk=med_id) return render(request,'aptool/meddetail.html',{'medicine':medicine}) def disdetail(request, dis_id): detailsposts=get_object_or_404(details_post,pk=dis_id) return render(request,'aptool/details_post.html',{'detailsposts':detailsposts}) def searchdetail(request): searchtext=request.POST['searchtext'] try: detailsposts=details_post.objects.get(disease_name__startswith=searchtext) except: return render(request,'aptool/details_post.html',{'error_message':True}) else: return render(request,'aptool/details_post.html',{'detailsposts':detailsposts}) def blogdetail(request,blog_id): blog= get_object_or_404(Post,pk=blog_id) return render(request,'aptool/blog_post.html',{'blog':blog}) WHILE urls.py LOOKS LIKE THIS: ***urls.py*** from django.conf.urls import url, include from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^medicine/$',views.MedicineView.as_view(),name='medicine'), url(r'^disease/$',views.DiseaseView.as_view(),name='disease'), url(r'^blog/$',views.BlogView.as_view(),name='blogview'), url(r'^disease/(?P<dis_id>[0-9]+)/$',views.disdetail, name='disdetail'), url(r'^medicine/(?P<med_id>[0-9]+)/$', views.meddetail, name='meddetail'), url(r'blog/(?P<blog_id>[0-9]+)/$', views.blogdetail, name='blogdetail'), url(r'^disease/detail$',views.searchdetail,name='searchdetail'), url(r'^search/$',views.search,name='search'), ] The problem that arises while I try to load the index.html is: NoReverseMatch at /index/ Reverse for 'blog' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I just cannot figure out what is wrong with the codes. Any help would be marvelous. -
PyCharm not detecting python3 interpretor
I've created a python3 virtual env. However when I try start a new Django project in PyCharm, it doesn't show up in the list of interpreters. Any idea why? -
Different Django admin pages in runserver and with apache+mod_wsgi
I created an app 'blog' in project 'mysite' and updated the admin.py but the change in the admin page only reflects when I run ./migrate runserver command but not when I use apache to deploy it. I ran makemigrations, migrate, collectstatic commands and chown www-data for 'blog' folder but to no avail. Any explanation and fix for this disparity? settings.py: ... INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'blog', 'django.contrib.admin', ] ... STATIC_URL = '/static/' apache2_enable="YES" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] DIRNAME = os.path.dirname(__file__) STATIC_ROOT = DIRNAME + '/static/admin/' blog/admin.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from . import models admin.site.register(models.Entry) models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class EntryQuerySet(models.QuerySet): def published(self): return self.filter(publish=True) class Entry(models.Model): title = models.CharField(max_length=200) body = models.TextField() slug = models.SlugField(max_length=200, unique=True) publish = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) objects = EntryQuerySet.as_manager() def __str__(self): return self.title class Meta: verbose_name= "Blog Entry" verbose_name_plural = "Blog Entries" ordering = ["-created"] apache example.com.conf: ... WSGIScriptAlias /mypath/ /home/myuser/mysite/apache/wsgi.py <Directory "/www/data/example.com/mysite/mysite/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /media /www/data/example.com/mysite/media/ Alias /static/admin /www/data/example.com/mysite/static/admin <Directory /www/data/example.com/mysite/static> Require all granted </Directory> <Directory /www/data/example.com/media> Require all … -
Django forms for filtering search results?
I want to add some checkbox filters to a car sales website. My model categories to filter by are 'Brand', 'Model', and 'Price'. Within django what would be the best method to create a search function based on the above? Thank you. -
Initializing fcm_server_key in Django project using fcm-django
I am trying to use fcm-django package to send push-notification from my Django 1.10 REST app to an Android app. What I've done so far is: Successfully installed the package using pip command Ran migrate command in order to let Django create necessary tables in my DB Created a Firebase account and added a project Also, I have a Firebase account Now I am stuck trying to figure out what api key is, and where ti find it. I mean, the api_key which I must to set in the settings.py file as described in the documentation of the package: Edit your settings.py file: .. code-block:: python INSTALLED_APPS = ( ... "fcm_django" ) FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "[your api key]" } Any help with? Is it something that I should look for in my Firebase account ? And if yes, where this api key info is stored in the Firebase project account ? -
Django Reverse for 'birthday_cards' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['unsubscribes/birthdays/$']
Hello Firstly here is the error message in full just in case you find it relevant to issue. Error - Reverse for 'birthday_cards' with arguments '()' and keyword arguments '{'end_date': '2017-04-30', 'start_date': '2017-04-01'}' not found. 1 pattern(s) tried: ['unsubscribes/birthdays/$'] My Problem is from what i can understand from reading other questions is that it cannot match the url or it is matching the url but the incoming url doesn't know what to do with the argument. Problem: I'm on with a challenge and the code i was given to start with had a url like the below, I had to take this code which would display the birthday cards to send in between dates supplied and change it so that instead of typing dates in url a form would display url(r'^birthdays/(?P<start_date>\d{4}-\d{2}-\d{2})/(?P<end_date>\d{4}-\d{2}-\d{2})$', BirthdayCardListView.as_view(), name='birthday_cards_range'), These are just snippets of the related sections for this so there won't be any imports showing. birthday_cards.html: {% extends "base.html" %} {% load static %} {% block title %}Birthday Cards{% endblock %} {% load pagination_tags %} {% block content %} <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Birthday Cards to Send</h1> </div> <!-- /.col-lg-12 --> </div> {% if customers.count %} <div class="row"> <div class="col-lg-12"> <div class="table-responsive"> <table class="table … -
Django with docker doesn't run custom app's migrations
I have create a custom app named bay in my project's root directory, structure looks like below - My app/ - bay/ - migrations/ - __init__.py - 0001_initial.py - models/ - __init__.py - document.py - ... (other model files) When I am trying to save a new model instance from one of my custom app's models, I get the following error - postgres_1 | ERROR: relation "bay_brand" does not exist at character 13 postgres_1 | STATEMENT: INSERT INTO "bay_brand" ("name") VALUES ('xyz') RETURNING "bay_brand"."id" Thus, the migration for the given model hasn't been run. So, I try to migrate with - sudo docker-compose -f dev.yml run django python manage.py migrate which results in Postgres is up - continuing... Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount, users Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying users.0001_initial... OK Applying account.0001_initial... OK Applying account.0002_email_max_length... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying sessions.0001_initial... OK Applying sites.0001_initial... OK Applying sites.0002_alter_domain_unique... OK Applying sites.0003_set_site_domain_and_name... OK Applying socialaccount.0001_initial... OK Applying socialaccount.0002_token_max_lengths... OK Applying socialaccount.0003_extra_data_default_dict... OK … -
Django Rest Framework - timezone for datetime field
I am using DRF > 3.0; I want to control the serialization of a DateTime field in my model. Specifically, I want the date-time to be output in ANY timezone (not just in settings.TIME_ZONE; which is the default). The timezone i want to use is received as a keyword argument when i create an instance of my serializer. However I get an AttributeError when i try to set the timezone on the MySerializer.deployment_time.timezone = self.timezone code line. How can I set the "timezone" attribute on the "deployment_time" instance. Or is there another way of achieving this? class MySerializer(serializers.ModelSerializer): deployment_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', input_formats=['%Y-%m-%d %H:%M']) def __init__(self, *args, **kwargs): self.timezone = kwargs.pop('timezone') if 'timezone' in kwargs else None super(MySerializer, self).__init__(*args, **kwargs) if self.timezone: MySerializer.deployment_time.timezone = self.timezone AttributeError: type object 'MySerializer' has no attribute 'deployment_time' -
Django Model for mandatory/excatly one cross table relations
I am quite new to python django, so I am trying to find guidance on how to build a model representing the following: We have IT environments (consisting of multiple components, like webservers, databases, etc.) each environment must have at least one or more SLA(s) associated From all SLAs associated to an environment exactly one must have the state "effective" SLAs are not specific to one environment, it's more a set of general contracts a concrete environment references to ( aka should be a separate table) I implemented a model sufficiently reflecting the first two points (At least I think ;)), but especially the last point seems to be cumbersome. Sufficiently meaning, using this impl. the relation using the cross table is "optional" not mandatory. This is ok currently, but not in the long run. class Environment(models.Model): fullname = models.CharField(max_length=45) ... sla = models.ManyToManyField(SLA, through='EnvironmentSLA') creation_date = models.DateTimeField(auto_now_add=True) class Meta: unique_together = (('fullname', 'projectid', 'regionid', 'account'),) class SLA(models.Model): description = models.CharField(max_length=255) reaction_time = models.CharField(max_length=45) service_level = models.CharField(max_length=45) creation_date = models.DateTimeField(auto_now_add=True) class EnvironmentSLA(models.Model): PLANNED = 'pl' EFFECTIVE = 'ef' DEPRECATED = 'dp' SLA_STATE = ( ( PLANNED, 'planned' ), ( EFFECTIVE, 'effective'), ( DEPRECATED, 'deprecated'), ) environment = models.ForeignKey('Environment', on_delete=models.CASCADE) sla … -
tango with django "Like Button" Not working
I followed this Tutorial http://www.tangowithdjango.com/book17/chapters/ajax.html#add-a-like-button but my like count is not incrementing after clicking it. Here's my code views.py def like_post(request): post_id = None if request.method == 'GET': post_id = request.GET['post.pk'] likes = 0 if post_id: post = Post.objects.get(id=int(post_id)) if post: likes = post.likes + 1 post.likes = likes post.save() return HttpResponse(likes) urls.py url(r'like_post/$', views.like_post, name='like_post'), Models.py class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) likes = models.IntegerField(default=0) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title post_deatil.html <strong id="like_count">{{ post.likes }}</strong> people like this category {% if user.is_authenticated %} <button id="likes" data-post_id="{{post.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-thumbs-up"></span> Like </button> {% endif %} blog-ajax.js $('#likes').click(function(){ var postid; catid = $(this).attr("data-post_id"); $.get('/blog/like_post/', {post_id: postid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); Console message Internal Server Error: /blog/like_post/ Traceback (most recent call last): File "/home/bharat/.local/lib/python3.5/site-packages/django/utils/datastructures.py", line 83, in __getitem__ list_ = super(MultiValueDict, self).__getitem__(key) KeyError: 'post.pk' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/bharat/.local/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response … -
when i use the pagination, encountered the following questions,Is it not suitable for Python3?
SyntaxError at / invalid syntax (pagination_tags.py, line 225) Request Method: GET Request URL: http://www.zhangpengpeng.cn/ Django Version: 1.8.3 Exception Type: SyntaxError Exception Value: invalid syntax (pagination_tags.py, line 225) Exception Location: /usr/local/lib/python3.4/importlib/init.py in import_module, line 109 Python Executable: Python Version: 3.4.3 Python Path: ['/usr/workspace/blog_sae/1', '/usr/local/lib/python34.zip', '/usr/local/lib/python3.4', '/usr/local/lib/python3.4/plat-linux', '/usr/local/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/site-packages'] Server time: Wed, 19 Apr 2017 05:34:00 +0000 -
custom filter on contact by dates
I have a table in which I display information about organizations and I have a mechanism who is triggering next action date on the organization, that is manually set on the organizations. Now I've added a custom datepicker field on top of my table so I can filter it for the wanted date and show all next action date for that organization on selected date, so I'm passing a value to Controller so I can catch in the restAPI, and in the rest I want to filter the date to be before or equal to now so I can show organizations by next action date. My question is how to filter the date to be before or equal to now, I really lost here so can someone help me and explain how can I do that in my ModelViewSet. ModelViewSet: from rest_framework import viewsets, permissions, filters from cms.restapi.pagination import StandardResultsOffsetPagination from cms_sales.models import LeadContact from cms_sales.restapi.permissions.lead_contact_permissions import LeadContactPermissions from cms_sales.restapi.serializers.lead_contact_serializer import LeadContactSerializer class LeadContactViewSet(viewsets.ModelViewSet): def get_queryset(self): queryset = LeadContact.objects.none() user = self.request.user if user.has_perm('vinclucms_sales.can_view_full_lead_contact_list'): queryset = LeadContact.objects.all() elif user.has_perm('vinclucms_sales.can_view_lead_contact'): queryset = LeadContact.objects.filter(account_handler=user) return queryset serializer_class = LeadContactSerializer filter_backends = (filters.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter) filter_fields = ('account_handler',) ordering_fields = ( 'first_name', 'last_name', … -
Django-like button is not updating the likes
I am nearing completion of the Tango with Django tutorial, I'm near homestretch, in the process of making a 'like' button: http://www.tangowithdjango.com/book17/chapters/ajax.html#add-a-like-button What is supposed to happen is: when the button is clicked an AJAX request is made, given our url mapping, this invokes the like_category view which updates the category and returns the new number of likes. When the AJAX request receives the response it updates parts of the page, i.e. the text and the button. The #likes button is hidden. My button is there, can be clicked, but does not hide after being clicked, nor does it actual increment the number of likes, and I'm not sure why, I successfully created buttons in the previous introductory chapter. These are the relevant code snippets (but let me know if there is something that I missed which could be helpful: views.py @login_required def like_category(request): cat_id = None if request.method == 'GET': cat_id = request.GET['post_id'] likes = 0 if cat_id: cat = Post.objects.get(id=int(cat_id)) if cat: likes = cat.likes + 1 cat.likes = likes cat.save() return HttpResponse(likes) rango-ajax.js $('#likes').click(function(){ var catid; catid = $(this).attr("data-catid"); $.get('/rango/like_category/', {category_id: catid}, function(data){ $('#like_count').html(data); $('#likes').hide(); }); }); about.html {% extends 'base.html' %} {% load static %} {% … -
django rest framework: Get url path variable in a view
I have to pass the product_id (which is a string) in to a view. There I have to do some db operations based on the product id. How can I get that product id in that view. Actually what should be the parameter in the "class ProductDetailConfiguration" view ? Now am passing "viewsets.ModelViewSet". Actually this api call is not completely related to any model. urls.py url(r'^product-configuration/(?P<product_id>[\w-]+)/$', views.ProductDetailConfiguration, name='product-configuration'), views.py class ProductDetailConfiguration(viewsets.ModelViewSet): queryset = Product.objects.all() def get_queryset(self, **kwargs): queryset = Product.objects.all() product_id = self.request.get('product_id', None) #filter query set based on the product_id return queryset serializer_class = ProductConfigurationSerializer -
python eval assignment error
item = Table.objects.get(user_id=user_id) area_dict ={'grade':'test','name':'name_test'} s = area_dict['name']+'_grade1' eval("item."+s+" = area_dict['grade']") I am trying to update the database in python_django, above is the code I want to realize my need, but I meet the error item.name_test = area_dict['grade'] SyntaxError: invalid syntax ^ I don't know where I am wrong,can you tell me? -
Django Ajax Comment is updating and displaying but content is not removing from the comment form
When i used to Comment it is displaying on the div perfectly well but the value is not being removed from the comment form and for commenting again i have to refresh the page to do so. Kindly refer the view function and Main JS part. Please help in this regard, Thanks views.py def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) comments = Comment.objects.filter(post=post, parent=None) if request.method == 'POST': if not request.user.is_authenticated(): raise Http404 comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): content = comment_form.cleaned_data['content'] parent_id = request.POST.get("parent_id") print("Parent ID: ", parent_id) parent_qs = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id).first() print("Parent QS: ", parent_qs) new_comment, created = Comment.objects.get_or_create( user=request.user, post=post, content=content, parent=parent_qs ) else: comment_form = CommentForm() context = { "post": post, "comments": comments, "comment_form": comment_form, } if request.is_ajax(): return render(request, 'posts/partial_post_detail.html', context) else: return render(request, 'posts/post_detail.html', context) post_detail.html {% extends 'base.html' %} {% block title %}{{ post.title }}{% endblock %} {% block content %} {{ post.title }}<br> Published by {{ post.user }}<br><br> {{ post.content|linebreaks }}<br> {% if post.user == request.user %} <a href='{% url "posts:post_edit" slug=post.slug %}'>Edit</a> <a href='{% url "posts:post_delete" slug=post.slug %}'>Delete</a> {% endif %} <hr> <h1><b>Comments</b></h1> <div id="div1"> {% include 'posts/partial_post_detail.html' %} </div> {% endblock %} Partial_post_detail.html: {% for … -
The best Way to implement ReactJS in Django App
I have worked in Django for sometime and i am trying to learn ReactJS. I was wondering what is the best way to use ReactJS with Django. Having ReactJS within the Django Project to act as a template system. Having ReactJS as a separate front-end app and interact with Django through a REST API. What is your experience in either of those 2 methods ? -
Django forms - editing data in ClearableFileInput
i am working with Django forms and i came across the problem with ClearableFileInput field - i don't know how to update it from view. In the view, when the user doesn't upload any file, i want it to set manually - but i cant override any form methods, because the form is 3rd party app. I know i can edit data like this: if 'POST' == request.method: form = FormClass(request.POST, request.FILES) if form.is_valid(): form.cleaned_data['some_field'] = some_new_data When the some_field is CharField, i know the some_new_data should be string. But i don't know what to put in some_new_data when the field is ClearableFileInput. I want to set image which is stored on the website at MEDIA_ROOT folder. Can anyone guide me how to do that? -
I can't see django markdown editor with django 1.10v
I'm using django 1.10 / python 3.6. and I'm new at django. I followed up all the details with django_markdown github First, I have a trouble with urls.py in django_markdown, but I found the answer (I'm not sure it's right, anyway) in django_markdown github issue I solve the url problem but then I can't see my editor either admin or development page. this is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'django_extensions', 'social_django', 'multiselectfield', 'django_markdown', 'blog', ] also I add my urls.py url('^markdown/', include('django_markdown.urls') I make my models with MarkdownField too. from django_markdown.models import MarkdownField class Entry(models.Model): title = models.CharField(max_length=50) #.. md_content = MarkdownField() Also adding in admin.py, too class EntryAdmin(MarkdownModelAdmin): ... admin.site.register(Entry, EntryAdmin) But I can't find markdown editer in admin, just seeing default page. Is there anything wrong with my code? Or there's no more support django 1.10 in django_markdown?