Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / making clone of reddit comment system
I try to make clone of reddit. For now I can get comments and sub comments. I couldn't make comment/subcomment/sub_sub_comment. How should I get the comment and childrens with tree structure without using mptt or any library. I want to make with generic relations. models.py class Comment(models.Model): entry_comment = models.TextField(max_length=160) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.entry_comment def descendants_comments(self): ct = ContentType.objects.get_for_model(self) childs = Comment.objects.filter(content_type=ct, object_id=self.pk) result = [] for child in childs: result.append(child) result.append(child.descendants_comments()) return result post_detail.html <section> <h1>Comments</h1> <div class="comments-bg"> {% for comment in comments %} <div class="comment-per-style"> <div class="comment-style">{{ comment.entry_comment }}</div> <ul> {% for subcomment in comment.descendants_comments %} <li>{{ subcomment.entry_comment }}</li> {% endfor %} </ul> </div> <button type="button" class="btn btn-success btn-sm reply-button">Reply</button> <form class="comment-form" action="{% url 'sub-comment' comment.id %}" method="post"> {% csrf_token %} <input id="entry_comment" class="form-input" type="text" name="entry_comment" maxlength="100" required /> <input type="submit" value="Submit comment"> </form> {% endfor %} </div> -
Django template doesn't load
Am following the Django Website's tutorial, currently on Pt3(https://docs.djangoproject.com/en/1.11/intro/tutorial03/) Tutorial states: "This code should create a bulleted-list containing the “What’s up” question from Tutorial 2. The link points to the question’s detail page." After adding the template and running the server I still only see this previous page and no updated template , what's wrong here? Thanks for your help! django_proj/mysite/polls/urls.py from django.conf.urls import url from . import views urlpatterns = [ #ex: /polls/ url(r'^$', views.index, name='index'), # ex: /polls/5/ url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'), # ex: /polls/5/results/ url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'), # ex: /polls/5/vote/ url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'), ] django_proj/mysite/polls/views.py from django.shortcuts import render from django.http import HttpResponse from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) def index(request): return HttpResponse("At Polls Index") /django_proj/mysite/polls/templates/polls/index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> … -
Sync App-Backend user table with wordpress login
I programmed a Backend for an app. In the Backend is of course the login/registration endpoint. The problem is that my client had the new idea of synchronizing his Wordpress Blog with the app. And now he wants that when an user registers himself in the App, then he can log in the Wordpress and when an user registers himself in the Wordpress Blog, he can log in the App. My problem is that I'm not specialized either in Wordpress nor in PHP. I was watching the wp-login.php file, but didn't find a good result. I'm thinking of using the Backend Endpoint with Wordpress, I can guess that Wordpress could work as a client. Then I could use the same Login-Backend-Function with the App and with Wordpress and it should work. I was reading this kind of post in Internet, but is not that way, I don't want to register an user in Wordpress from the app, but the other way, I would like to register an user in the App or in Wordpress and log him in the App or Wordpress, but using the Django Endpoints of the Backend. I did't think that it would be so complicated. Maybe … -
object that was saved with commit=False, still saved
I have a very big model, with steps form. So I decided on each page get previous object and update his attributes in form. In first form I do: def save(self, commit=False): obj = super(FirstForm, self).save(commit=False) obj.id = 999999999 self.request.session['obj'] = pickle.dumps(obj) self.request.session.save() return obj Id is requires for mtm. So I set default one. Then on last step in view I do: obj = self.request.session.get('obj') obj = pickle.loads(obj) obj.id = None # remove temporary id obj.save() But Django save two objects. One normal object and one empty with id 999999999 . Why ? I tried do: obj = super(FirstForm, self).save(commit=False) obj.id = 999999999 self.request.session['obj'] = pickle.dumps(obj) self.request.session.save() obj.delete() But it didn't help. -
how does django-rest-framework- javascript web token work with django to auth users?
How does the Django-rest-framework-jwt work with django? It seems that the token is not part of the database which doesn't make sense. What is the behind the scenes when we add JWT to our settings? -
data labels stacked diagram d3
I am creating charts with D3 in Django and I would like to include data labels in one of my stacked bar diagrams. This is the code for the data labels that I have so far: bars.append("text") .text(function(d) { return d3.format(".2s")(d.y1-d.y0); }) .attr("x", function(d) { return x(d.y1)+(x(d.y0) - x(d.y1))/2; }) .attr("y", y.rangeBand()/3) .style("fill", '#ffffff'); I found this in a similar thread but it does not seem to work for my case. The whole code for the diagram is here: https://www.dropbox.com/s/y5v5z7ism39ibyo/stacked%20diagram%20code.rtf?dl=0 And this is the result: https://www.dropbox.com/s/w26ui3pqkwdkr3k/stacked%20bar%20chart.png?dl=0 As you can see, it displays "NaN" instead of the data. I would like to have 3 data labels per chart for each part of the bars. The data that I'm using is in csv format and looks like this: country,1 year prevalence ,3 year prevalence ,5 year prevalence Albania,4.3,11.9,18.2 ... Any suggestions? Thanks in advance! -
adding an extra context while passing data to serializer
I am trying to add an extra field auth_token in my table with the request.data but it is giving errors. THe error is -- "data['auth_token_id'] = auth_token TypeError: list indices must be integers or slices, not str " my code is given below: serializers.py class AppSerializer(serializers.ModelSerializer): class Meta: model = ThirdPartyApps fields = ('app_name', 'package_name', 'auth_token_id') views.py @api_view(['POST']) def add_apps(request): data = request.data auth_token = request.META.get('HTTP_AUTHTOKEN', '') data['auth_token_id'] = auth_token serializer = AppSerializer(data=data, many=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors) I am looking for a way to pass extra data through the serializer. I just want to add auth_token to my model like the request.data nut it is giving this error --- data['auth_token_id'] = auth_token TypeError: list indices must be integers or slices, not str -
Listing Tags of a Post in Django CMS and Aldryn NewsBlog
I am trying to figure out how to display tags belonging to an article created within Aldryn NewsBlog plugin. Unfortunately, I cannot find any documentation on how do it. I was able to display categories using the following code. <span style="margin: 0; display: block"> <h4 style="display:inline-flex">Categories:</h4> {% for category in article.categories.all %} <a href="/articles/category/{{category.name|lower}}">{{ category.name }} {% if not forloop.last %}, {% endif %}</a> {% endfor %} </span> For tags, I am using this code: <span style="margin: 0; padding-bottom: 0; display: block"> <h4 style="display:inline-flex">Tags:</h4> {% for tag in article.tag %} <a href="/articles/tag/{{tag.name|lower}}">{{ tag.name }} {% if not forloop.last %}, {% endif %}</a> {% endfor %} </span> What am I doing wrong? Could anyone tell me how to display tags? -
ModuleNotFoundError: No module named 'django'
I'm trying make online a project but there is an error i can't solve myself. I already installed django but the server give me this error. Virtualenv is also active. 2017-09-25 20:10:27,471: *************************************************** 2017-09-25 20:10:30,892: Error running WSGI application 2017-09-25 20:10:30,893: ModuleNotFoundError: No module named 'django' 2017-09-25 20:10:30,893: File "/var/www/asd1_pythonanywhere_com_wsgi.py", line 17, in <module> 2017-09-25 20:10:30,893: from django.core.wsgi import get_wsgi_application 2017-09-25 20:10:30,893: *************************************************** 2017-09-25 20:10:30,893: If you're seeing an import error and don't know why, 2017-09-25 20:10:30,894: we have a dedicated help page to help you debug: 2017-09-25 20:10:30,894: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2017-09-25 20:10:30,894: *************************************************** Wsgi file is it: import os import sys path = '/home/asd1/mysite' if path not in sys.path: sys.path.append(path) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Hosting is pythonanywhere.com -
custom user auth in django how to hook up
So the django docs are great but I am confused, it would be great to have a mentor right now. I want to create a custom user model and authentication system the user model will have -name -password -email -JWT (javascript web token) a permissions and a venue (place of entertainment) will be connected to this user model via a many to many relation via an association table. Here is the problem, even with the docs I am confused how I override the current out of box implementation for authorization. Additionally I'd like to use https://github.com/GetBlimp/django-rest-framework-jwt for the token auth but I have no idea how to hook it up. I guess I am looking for a walk through. -
django-filter | updating search results without refreshing the page
I'm using django-filter to allow users to search and filter through my blog posts. I have a search form with the method=GET and a couple of filters set up. It works by refreshing the entire page. I don't want that. I want it to refresh only the div that contains my results. Doing some research I found out I may need to use AJAX for that. Problem is, I don't know JS. I'll provide snippets of my code to show you what I would need. If anyone would be so kind to help me out, it would be apprecaited. filters.py class ClassFilter(django_filters.FilterSet): title = django_filters.CharFilter( lookup_expr='icontains', widget=forms.TextInput(attrs={'class': 'list_of_class_search', 'placeholder': 'Search by Class or University', 'id': 'list_of_post_search_box_id'}), ) category = django_filters.ModelChoiceFilter( queryset=Category.objects.all(), widget=forms.RadioSelect(attrs={'class': 'list_of_class_university_filter_btn_input'}), empty_label=None ) class Meta: model = Post fields = ['title', 'category',] views.py def list_of_post(request): post = Post.objects.filter(status='published') categories = Category.objects.all() class_filter = ClassFilter(request.GET, queryset=post) search_template = 'blog/category/list_of_post_by_category.html' template = 'blog/post/list_of_post.html' context = { 'posts': posts, 'categories': categories, 'search_template': search_template, 'filter': class_filter, [...] } return render(request, template, context) template <form id="list_of_post_search_form" method='GET' action='/blog/' autocomplete="off" /> <div class="col-xs-12 col-md-4 col-md-offset-4"> {% for radio in filter.form.category %} <!-- Shows my category filters --> {% endfor %} </div> </form> <div id="list_of_post_search_results_id"> … -
Get the logged in user when there is request is not defined
I am having trouble to find a way to make it work; I need to get the queryset with a list of the team created by the current logged in user. My form look the following : from django import forms from django.contrib.auth.models import User from registration.models import MyUser from .models import Project, Team from django.contrib.auth import get_user_model User = get_user_model() class EditSelectTeam(forms.Form): team_choice = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=Team.objects.all().filter(team_hr_admin=request.User)) #team_id = forms.ChoiceField(queryset = Team.objects.filter(team_hr_admin= MyUser)) def team_select(self): data = self.cleaned_data['team_choice'] return data I get the error that request is not define -
Sending Data between Django and HTML using AJAX
Im new to AJAX and am having difficulty in understanding how the code works. Im trying to request a string containing a player name from a Database in Django called Game. Once it gets the name i would like it to return to the HTML, then repeat the process so that as players join their name is appended to the list and shown on the screen. Below is the code i currently have in views.py: # Host Client class HostGame(View): template_name = 'mainsite/hostclient.html' def get(self, request, gameCode, gamePassCode): if str(request.user) == "AnonymousUser": return(redirect(index)) return render(request, self.template_name, {'user': request.user, 'gameCode': gameCode, 'gamePassCode': gamePassCode}) def post(self, request,gameCode, gamePassCode): # Return the Player String from DB(Game) player = Game.objects.all().filter(hostPlayer=request.user).values('command') return render(request, self.template_name, {'user': request.user, 'gameCode': gameCode, 'gamePassCode': gamePassCode}) Below is the code i currently have in mainsite/hostclient.html: {% extends 'basicSet.html' %} {% block content %} <body> <div class="container"> <div class="page-header"> <h1 align="center">Join the Game Now!</h1> </div> <h4 align="center" class="break">Game Code: {{ gameCode }}<br>Game Pass Code: {{ gamePassCode }}</h4><hr width=90%><br> <div class="well"> <p>Insert Player Usernames</p> </div> </div> </body> {% endblock %} Any help would be greatly appreciated :) -
How to run Flask function that triggers on user's action and add content to the page?
The idea is that user push the button and Flask should add some content on the page. In my case python and Flask is not an aleatory choice, because python make a lot of backdoor work (that for example js can't). And perfectly it should be just one page without redirection on another page. So my question is: 1) How to get the moment when user push the button and run the function I want 2) How to make this function add some generated content on the page without reloading. -
Django migration returns unexpected name
I am trying to migrate a database, but every time I try it returns the error below. My app name is 'helloservice', but the table is 'customer' in the database 'pulse'. How do I tell Django not to use the helloservice prefix? If needed I followed a tutorial here, and am now trying to adapt the results to my own needs. django.db.utils.ProgrammingError: (1146, "Table 'pulse.helloservice_customer' doesn't exist") -
Error with Digital Ocean Droplet for Django
I have been following along with this tutorial to deploy my django site on Digital Ocean. I have just uploaded all my files and restarted gunicorn. The site is giving my this error: ImportError at / No module named braces.views And here is the traceback: Traceback Switch to copy-and-paste view /usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py in inner response = get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _legacy_get_response response = self._get_response(request) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py in _get_response resolver_match = resolver.resolve(request.path_info) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py in resolve for pattern in self.url_patterns: ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/functional.py in __get__ res = instance.__dict__[self.name] = self.func(instance) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/utils/functional.py in __get__ res = instance.__dict__[self.name] = self.func(instance) ... ▶ Local vars /usr/local/lib/python2.7/dist-packages/django/urls/resolvers.py in urlconf_module return import_module(self.urlconf_name) ... ▶ Local vars /usr/lib/python2.7/importlib/__init__.py in import_module __import__(name) ... ▶ Local vars /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__ result = _import(*args, **kwargs) ... ▶ Local vars /home/django/django_project/django_project/urls.py in <module> from blog import views ... ▶ Local vars /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__ result = _import(*args, **kwargs) ... ▶ Local vars /home/django/django_project/blog/views.py in <module> from braces.views import SelectRelatedMixin ... ▶ Local vars /usr/lib/python2.7/dist-packages/gevent/builtins.py in __import__ result = _import(*args, **kwargs) ... ▶ Local vars I … -
Django - custom non-model form field in admin panel
I would like to find a way to add another choice field next to actions form in my django admin panel. Here is my admin class: class InactiveSiteAdmin(SiteAdmin): change_list_template = 'admin/change_list_inactive.html' list_display = ('is_active', 'thumb', 'name', 'show_url', 'get_desc', 'keywords','category', 'subcategory', 'category1', 'subcategory1', 'group') fields = ('name', 'url', 'id', 'category', 'subcategory', 'category1', 'subcategory1', 'description', 'keywords', 'date', 'group', 'user', 'is_active', 'date_end',) readonly_fields = ('date', 'date_end', 'id') list_display_links = ('name',) actions = [activate_sites, activate_sites1, ] def get_queryset(self, request): return Site.objects.filter(is_active=False) def response_change(self, request, obj): return redirect('/admin/mainapp/site/{}/change/'.format(obj.id)) def has_add_permission(self, request): return False Here is top of my admin panel page: I am looking for way to add another choice field next to admin actions button. Something like: New form field is not related to any model. Choices are stored in database (I use django-constance). I tried to create new form in forms.py - for example with simple charfield: class EmailForm(forms.Form): email_form = forms.CharField(max_length=20) but I don't have any idea how can I use it in my admin template. -
Python traceback parts in Sentry event list
I am getting traceback parts in exception list on sentry.io using Raven 6.1.0 with Django 1.6 and Celery 3.1. Where should I look to make them reported properly? They are triggered only from periodic tasks (celery beat). -
Is there a Django way of comparing the results of a test to a fixture?
I'm trying to understand fixtures and unit tests in Django. I can successfully load a fixture and use the data in my unit test. What I want to do is compare the results of the test to a second fixture, fixture_2, which represents how the data should look. Here's a step-by-step of what I am talking about: Import fixture_1, generating the initial test data. Run the test on the data, changing it. Somehow compare the results of the test to fixture_2. Is there a way to do step 3? Should I somehow overwrite the test database with fixture_2 and do the assertions from there, or is there a way of comparing the test database to a fixture? -
Django 1.10 Template Renders Nested HTML Tags Outside Their Parent
I am a bit puzzled by the following behavior of the Django templates, which prevents me from successfully styling the output. Namely, I have the following template: <article class="article {% if article.is_featured %} featured{% endif %} {% if not article.published %} unpublished{% endif %}"> {% if not detail_view %} <div class="post-preview"> <a href="{% namespace_url 'article-detail' article.slug namespace=namespace default='' %}"> <h2 class="post-title"> {% render_model article "title" "" "" "striptags" %} </h2> {% if article.lead_in %} <h3 class="post-subtitle"> {% if not detail_view %} {% render_model article "lead_in" "" "" "truncatewords:'20'|striptags" %} {% else %} {% render_model article "lead_in" "" "" "striptags" %} {% endif %} </h3> {% endif %} </a> <p class="post-meta" style="margin-bottom: 0;"> Posted by {% include "aldryn_newsblog/includes/author.html" with author=article.author %} on {{ article.publishing_date|date:"F d, Y" }} </p> <p class="post-meta" style="margin: 0"> <h4 style="display:inline-flex">Categories:</h4> {% for category in article.categories.all %} <a href="/articles/category/{{category.name|lower}}">{{ category.name }} {% if not forloop.last %}, {% endif %}</a> {% endfor %} </p> <p class="post-meta" style="margin: 0"> <h4 style="display:inline-flex">Tags:</h4> {% for tag in article.tag %} <a href="/articles/category/{{tag.name|lower}}">{{ tag.name }} {% if not forloop.last %}, {% endif %}</a> {% endfor %} </p> </div> <hr> {% endif %} {% if detail_view %} <!-- <h3>Testing template! (from article with detail_view=True)</h3> --> … -
How to make a website work with Django development server?
I understand that this is never to be done. But I have a situation where I need to get something done real quick. I have to do a website where may be 200 people would register for an event. I need to present a simple registration form. Very basic functionality, register and view list of registrants. Very few hits. It would be live for about a month or so. I know a little bit of Django which can allow me to put together this thing quickly. However, I have only worked with the Django development server. My problem is setting up Apache to work with Django. I understand that, for Django, I need mod_wsgi installed. I have a VPS but mod_wsgi is not installed. I have asked my hosting provider to install it for me. Even if I can get mod_wsgi installed, it appears that it may take me some time to configure it and it may take a while. I have the following questions. Can I run this website on the Django development server? Will it hold up for very light traffic? If I do, how do I get traffic to go from port 80 to the development server … -
trouble using python requests to POST to django 1.8 server
I tried using session and grabbing the cookie. s = requests.Session() s.get(myurl) csrf = s.cookies['csrftoken'] The get had status_code 200 as expected. Then I first tried just a post on the session hoping that the session would do magic. (yeah I know better) r = s.post(myurl, json=mydata) which gives a status_code of 405. And yes, before I forget I have the django settings CSRF_HEADER_NAME='HTTP_X_CSRFToken' CORS_ORIGIN_ALLOW_ALL = True and my view function is marked with @csrf-exempt as well. The view function is known to accept post from my Angular frontend as long as I have 'X-CSRFToken=csrf' where csrf is as in the above setting. So I tried r = s.post(myurl, json=mydata, headers={'X-CSRFToken':csrf}) as well with the same result of 405. I read that it might help to set the referer to the url so I tried that as well. r = s.post(myurl, json=mydata, headers={'X-CSRFToken':csrf, 'Referrer: url}) and still got 405. So what is the correct way to make this work? -
[Django + Chart.js ]Uncaught ReferenceError: temperature is not defined
I tried to use Python Django make a ajax chart from database by javacript I used API VIEW in django restframwork retrieved the field temperature and send to ajax to render in the javascript. But the browser always said Uncaught ReferenceError: temperature is not defined This is my base.html This is my base.js This is my js block in the status.html This is my views.py I referenced this source code But I don't know what my cod get that above error. -
Login Using Microsoft Graph API
I used the following tutorial to create a login with Office365 - https://docs.microsoft.com/en-us/outlook/rest/python-tutorial#implementing-oauth2 It works, except I am allowed to access the http://localhost:8000/tutorial/mail page without having to login. Additionally, even after I logout( I added a log out function), The mail is still displayed, no matter what I do(e.g restart the server,etc.). Any help to solve this would be appreciated. Thanks. -
django-allauth mutli step signup form
I'm using pydanny/coockiecutter-django for a custom project, and I needed to build a custom multi-step signup for customers. django-allauth is a custom authentication tool inside cookiecutter so after some researching and reading the docs I found out how to customize allauth SignupForm and allauth-SignupView so it will fit my needs, but I have some problems, but please bare with me it's a long question. This custom signup needs to use some custom fields for state, zip-code and phonenumber. For this I'm using django-localflavor and for phonenumber-field I'm using django-phonenumber-field. Process of extending signup in django-allauth is a bit different. You can not define normal ModelForm field with class Meta rather you need to do it like this. This is two-step custom signup form. from django import forms from allauth.account.forms import SignupForm from localflavor.us.forms import USStateSelect, USPSSelect from ..models import User class CompanySignupStepOneForm(SignupForm): """ TODO: Custom Signup. :returns: TODO """ company_name = forms.CharField(max_length=225, required=True, strip=True) company_street_address = forms.CharField(max_length=225, required=True, strip=True) city = forms.CharField(max_length=225, required=True, strip=True) state = USStateSelect() zip_code = USPSSelect() def save(self, request): user = super(CompanySignupStepOneForm, self).save(request) company_user = User( step_one=user, company_name=self.cleaned_data.get('company_name'), company_street_address=self.cleaned_data.get('company_street_address'), city=self.cleaned_data.get('city') ) company_user.save() return company_user.step_one Step-two custom Signup Form: from django import forms from allauth.account.forms import SignupForm …