Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Wagtail psycopg2 error Expected in: flat namespace
I finished my website, and about to deploy it. I was following this guide to deploy my Django/wagtail site https://wagtail.io/blog/wagtail-heroku-2017/ . I was following along until the Using Postgres section. I did exactly what the article said, but I got an error when I try to createdb project_title_db Referenced from: /Users/jerrylee/Desktop/my_site/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so Expected in: flat namespace If you know how to solve this, please help me out. Much appreciated. -
Using mongodb with class-based view django
I try to use class-based view like below class DetailBookVIew(DetailView): model = Book template_name = 'book/detail_book.html' with model Book is a mongodb model, so how can I use that class-based view with mongodb model, because it will cause error like AttributeError: type object 'Book' has no attribute '_default_manager', the _default_manager attribute only available for sql model. -
Difference between django send_mail and bash mail command
I'm trying to set-up my web server for sending mail. I did apt install mailutils, if I understand correctly it also apt install postfix, when prompting for the configuration, I chose robertvandeneynde.be, beeing my domain name. I did months ago some modifications to config files but I ran apt purge postfix such that the /etc/postfix/ directory was deleted (and re-created). Now what I have is that the mail command from the command line doesn't send mail whereas the send_mail from django does. This doesn't send mail nor prints anything : echo "Test" | mail -s "Subject" myemail@myuniversity.com Whereas this, does : from django.core.mail import send_mail import django.conf django.conf.settings.configure() send_mail( 'Hello', 'World', 'noreply@robertvandeneynde.be', ['myemail@myuniversity.com'] ) The server is running Ubuntu 16.04.2 LTS (from lsb_release -a). -
Implement a REST API and Web interface in Djago
Is there a correct/proper approach to implementing a RESTful API and a user interface that uses that API in Django? I have an application that I'd like to create a REST API for and also have a web interface, but I don't know the best approach. Lets say I want to implement the following endpoint: /1.0/transactions. I can create a view for the API from .models import Transactions from django.core import serializers from django.http import HttpResponse from django.shortcuts import render from django.views.generic.base import View class TransactionApiView(View): def get(self, request): data = serializers.serialize('json', Transactions.objects.all()) return HttpResponse(data, content_type="application/json") Now I want to actually render an HTML page with my transactions. I'm thinking there are 3 approaches: Call my API which returns a JSON payload and render a template with the data from the payload. Duplicate the code from the API in the view that renders the template. Implement both an API and user interface in a single class (I don't know if this is even possible). The first approach would require me to somehow call my view within another view (something I know you shouldn't do), the second approach violates the DRY policy. Provided, in this example there isn't that much code … -
Form post redirect to 404 page Django error
Im doing one udemy course of django, but the course works with django 1.1 or something like that, Im tryng to do it with django 2 and i have no problem with it in general, BUT when i try to send a post with author, tittle and text, the app redirect to 404 error. the view.py code to create the post class CreatePostView(LoginRequiredMixin, CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' form_class = PostForm model = Post the url.py on the blog app folder from django.urls import path, re_path, include from blog import views urlpatterns = [ re_path(r'^$', views.PostListView.as_view(), name='post_list'), re_path(r'^about/$', views.AboutView.as_view(), name='about'), re_path(r'^post/(?P<pk>\d+)$',views.PostDetailView.as_view(),name='post_detail'), re_path(r'^post/new/$', views.CreatePostView.as_view(),name='post_new'), re_path(r'^post/(?P<pk>\d+)/edit/$',views.PostUpdateView.as_view(),name='post_edit'), re_path(r'^post/(?P<pk>\d+)/remove/$',views.PostDeleteView.as_view(),name='post_remove'), re_path(r'^drafts/$',views.DraftListView.as_view(),name='post_draft_list'), re_path(r'^post/(?P<pk>\d+)/comment/$',views.add_comment_to_post,name='add_comment_to_post'), re_path(r'^comment/(?P<pk>\d+)/approve/$',views.comment_approve,name='comment_approve'), re_path(r'^comment/(?P<pk>\d+)/remove/$',views.comment_remove,name='comment_remove'), re_path(r'^post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'), ] the form.py class PostForm(forms.ModelForm): class Meta(): model = Post fields = ('author', 'title', 'text') widgets = { 'title':forms.TextInput(attrs={'class':'textinputclass'}), 'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea postcontent'}) } the html <form action="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button class="save btn btn-default" type="submit">Guardar</button> </form> the error: django debug page pointing the error -
How do I connect Django to MySQL database and server in windows?
I am having problems connecting Django to MySQL to create my database. Note I have MySQL workbench downloaded and also the package for MySQL connector. Thanks. -
GraphQL support with django-saleor Ecomm platform
I need to know to what degree saleor supports GraphQL? My understanding is that the front end is just django templates, but I see a graphql folder there, so what is it? I was told by the moderators to take a look into the demo branch. I need to know how different is it compared to the master branch. -
Django custom filter not registering in tag library
I've written the following filter (in templatetags/custom_errors.py): from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter def custom_errors(bound_field): return mark_safe(f'<span id="{bound_field.id_for_label}-error" class="error">{", ".join(bound_field.errors)}</span>' if bound_field.errors else '') which I'm trying to use in a template as follows: {% load widget_tweaks %} {% load custom_errors %} {% load label_with_classes %} {% csrf_token %} <div class="row"> <div class="input-field col s12"> {{ form.session_number|add_error_class:"invalid" }} {{ form.session_number|custom_errors }} {{ form.session_number|label_with_classes }} </div> </div> However, I'm getting a TemplateSyntaxError: 'custom_errors' is not a registered tag library: What puzzles me, however, is that some of the tags that are registered, such as label_with_classes, are done so in the same way. Here is a tree view of dashboard/templatetags: dashboard/templatetags ├── active_page.py ├── custom_errors.py ├── edit_view_family_heading.py ├── google_analytics.py ├── label_with_classes.py ├── order_link.py ├── paginator.py └── profile_badge.py showing that label_with_classes.py is in the same directory as custom_errors.py. Here are the contents of label_with_classes.py: from django import template from django.forms import ChoiceField, BooleanField, DateField from titlecase import titlecase register = template.Library() def pretty_name(name): """Convert 'first_name' to 'First Name'.""" return titlecase(name.replace('_', ' ')) @register.filter(is_safe=True) def label_with_classes(bound_field, contents=None): '''Extend Django's label_tag() method to provide the appropriate Materialize CSS classes''' # The field should have the 'active' class if it … -
Pycharm can't find path to template after django upgrade
Recently I upgraded my project from Django 1.11.6 to Django 2.0. It all works like a charm after little editing, but there is one thing that makes me mad. Pycharm can't find a path to templates and highlights them on: render function, {% extend ... %} etc., and in settings.py on INSTALLED_APPS it can't find app. Here are some examples from my project: return render(request, 'panel/central_stock.html', {'stocks': stocks}) INSTALLED_APPS = [ 'panel.apps.PanelConfig', ] It did not happen in 1.11. I searched google for that, but no solution. Maybe there is some new way to adress it? -
Weird Django requests - is someone trying to hack my server?
I just saw my logs for a site on staging and I saw some weird requests: django-configurations version 2.0, using configuration 'Local' Performing system checks... System check identified no issues (0 silenced). February 21, 2018 - 16:30:01 Django version 1.11, using settings 'config' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [21/Feb/2018 19:51:54] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [21/Feb/2018 19:51:54] " c" 400 - [21/Feb/2018 23:55:30] code 400, message Bad request syntax ('\x00\x00\x00TZ\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x04\x010I\x00\x00\x00\x00\x80\x0b¨À\x00\x0c)t F\x07\x00tsXrcsXYs9\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00bbXcsXctst\x00\x00\x00\x00\x00\x00') [21/Feb/2018 23:55:30] "TZ0I ¨À)t FtsXrcsXYs9bbXcsXctst" 400 - [22/Feb/2018 04:42:19] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [22/Feb/2018 04:42:19] " c" 400 - [22/Feb/2018 06:58:13] "GET http://www.google.com/ HTTP/1.0" 404 1662 [22/Feb/2018 06:58:41] "GET http://www.google.com/ HTTP/1.0" 404 1662 [22/Feb/2018 06:59:25] "GET /status HTTP/1.1" 404 3724 [22/Feb/2018 06:59:25] "GET /status HTTP/1.1" 404 3724 [22/Feb/2018 15:43:40] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [22/Feb/2018 15:43:40] " c" 400 - [22/Feb/2018 17:20:24] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [22/Feb/2018 17:20:24] " c" 400 - [22/Feb/2018 18:49:40] code 400, message Bad HTTP/0.9 request type ('\x00\x00\x00') [22/Feb/2018 18:49:40] " c" 400 - [22/Feb/2018 19:39:14] "GET / HTTP/1.1" 500 142024 [22/Feb/2018 19:39:25] "GET / HTTP/1.1" 500 142024 [22/Feb/2018 19:39:26] "GET /favicon.ico HTTP/1.1" 404 3742 [22/Feb/2018 … -
How to use URL names in views?
I have been following this Django tutorial, and I am trying to remove hardcoded URLs, but I can't make the reverse function work. That's my detail view: def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") # How it was before: # return render(request, 'polls/detail.html', {'question': question}) return HttpResponse(reverse('polls:detail', kwargs={'question': question})) path('<int:question_id>/', views.detail, name='detail') And this is the template for the detail view: <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> <a href="{% url 'polls:index' %}">Index</a> </form> Can somebody help me with that or give any tips? Thanks in advance. -
custom RegisterSerializer doesn't work with django-rest-auth
I'm using django-rest-auth and I want to add registration with my own User model. So I add allauth and create my own RegisterSerializer as it was mentioned in docs. serializers.py class RegisterSerializer(serializers.Serializer): email = serializers.EmailField(required=True) password = serializers.CharField(write_only=True) def validate_email(self, email): email = get_adapter().clean_email(email) if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email def validate_password(self, password): return get_adapter().clean_password(password) def get_cleaned_data(self): return { 'password': self.validated_data.get('password', ''), 'email': self.validated_data.get('email', '') } def save(self, request): user = get_user_model() cleaned_data = self.get_cleaned_data() user.create_user(**cleaned_data) return user settings.py REST_AUTH_SERIALIZERS = { 'REGISTER_SERIALIZER': 'users.serializers.RegisterSerializer', } AUTH_USER_MODEL = 'users.User' Unfortunately still uses the default serializer -
Having trouble with django inlineformset_factory
Doing a little project, that has parties and info how people fly to them. Been banging my head on the forms for three days now. Cannot wrap my head around the inlineformset_factory. models.py class Party(models.Model): name = models.CharField(max_length=32) slug = models.SlugField() class Journey(models.Model): party = models.ForeignKey(Party,related_name='journeys') person = models.CharField(max_length=32) class Flight(models.Model): journey = models.ForeignKey(Journey, related_name='flights') departure_datetime = models.DateTimeField() etc... Party must exist before Journeys can be made, Parties are created elsewhere. urls.py, in urlpatterns[] path('<slug:slug>/add/', AddFormSet.as_view()), views.py class AddFormSet(generic.CreateView): template_name = 'party/formset.html' model = Party fields = ('name',) def get_success_url(self): return reverse('party:party-detail', **self.kwargs) def get_context_data(self, **kwargs): context = super(AddFormSet, self).get_context_data(**kwargs) if self.request.POST: context['formset'] = JourneyFormset(self.request.POST) else: context['formset'] = JourneyFormset() return context def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super(AddFormSet, self).form_valid(form) forms.py class BaseJourneyFormset(BaseInlineFormSet): def add_fields(self, form, index): super(BaseJourneyFormset, self).add_fields(form, index) # save the formset in the 'nested' property form.nested = FlightFormset( instance=form.instance, data=form.data if form.is_bound else None, files=form.files if form.is_bound else None, prefix='flight-%s-%s' % ( form.prefix, FlightFormset.get_default_prefix()) ) def is_valid(self): result = super(BaseJourneyFormset, self).is_valid() if self.is_bound: for form in self.forms: if hasattr(form, 'nested'): result = result and form.nested.is_valid() return result def save(self, commit=True): result = super(BaseJourneyFormset, … -
How exactly configure Django to send emails with bug reports?
everyone! I am really novice with Django, and I am having troubles in configuring property my app to send me emails with the bug reports. I already set on the settings file the required variables as I saw on the Django documentation, like this: DEBUG = False ... ADMINS = [('myname', 'myemail@server')] # For server errors MANAGERS = [('myname', 'myemail@server')] # For missing pages errors I provoked a error for testing, but nothing happened, no email. What should I do? -
For loop in Django template not processing
I create a dictionary, and pass it to my Django template: my_dict = {'boo': {'id':'42'}, 'hi': {'id':'42'}} t = get_template('delta.html') html = t.render(delta_dict) print(html) return HttpResponse(html) My Django template looks like this: <html> <body> Out of Dictionary <div> {% for key in my_dict %} <span>{{ key }}</span> {% endfor %} </div> After dictionary </body> </html> My output in the browser looks like this: Out of Dictionary After dictionary The HTML looks like this: <html> <body> Out of Dictionary <div> </div> After dictionary </body> </html> -
Combine 2 Django Querysets
I want to merge two queryset in Django using operand "|" but it don't work. I know that to do it you must have querysets from the same model. This is exactly what I'm trying to do. The loop is because I want to get random objects and merge it into one. Anyone have idea why Django throw "TypeError: unsupported operand type(s) for |: 'Sentence' and 'Sentence'" error? According to below source this is how to make it happen: https://simpleisbetterthancomplex.com/tips/2016/06/20/django-tip-5-how-to-merge-querysets.html from random import randint from sentences.models import Sentence sentence_number = 3 first_pk = Sentence.objects.first().pk last_pk = Sentence.objects.last().pk for i in range(sentence_number): next_pk = randint(first_pk, last_pk) sentence_qs = Sentence.objects.get(pk=next_pk) type(sentence_qs) if i > 1: sentence_qs = sentence_qs | Sentence.objects.get(pk=next_pk) -
How do I customize the display of radio buttons in a Django template?
In my forms.py, I have this, where supbplansTuple is a tuple of tuples: class RegisterForm(UserCreationForm): subChoices= forms.ChoiceField(label=_("Choose plan"), widget=forms.RadioSelect, choices=subPlansTuple) subplansTuple looks something like this: (("plan_1234","$5 a month"),("plan_2345","$10 a month")) register.html has this: <form id="register-form" name="regForm" method="post"> {% csrf_token %} {% for field in registration_form %} <p>{{ field }}</p> {% endfor %} </form> Problem is, Django displays the radio buttons widget like this: <p></p> <ul id="id_subChoices"> <li> <label for="id_subChoices_0"><input id="id_subChoices_0" name="subChoices" type="radio" value="plan_1234" required=""> $5 a month</label> </li> <li> <label for="id_subChoices_1"><input id="id_subChoices_1" name="subChoices" type="radio" value="plan_2345" required=""> $10 a month</label> </li> </ul> <p></p> I do not want the radio buttons to display this way. How do I customize the HTML, maybe to look something like Boostrap's inline radio buttons. -
Django formset not saving my files
So I have these two models Lecture and FileUpload. I want that the user to be able to add a lecture to a specific course and also upload multiple files for that lecture. Thing is that after I submit the form the information gets saved except for the uploaded files, so I am guessing something is wrong with my formset. Please have a look: FileFormset = inlineformset_factory(Lecture, FileUpload, exclude=[]) def classroom(request): if request.method == 'POST': form1 = LectureForm(request.POST) if form1.is_valid(): lecture = form1.save() formset = FileFormset(request.POST, request.FILES, instance=lecture, prefix='files') if formset.is_valid(): formset.save() else: print(formset.errors) formset.save() return redirect('courses:index') else: form1 = LectureForm() formset = FileFormset() context = {'teacher_data': TeacherData.objects.all(), 'teachers': Teacher.objects.all(), 'courses': Course.objects.all(), 'form1': form1, 'formset': formset, } return render(request, 'courses/classroom.html', context) <form method="post" action=""> {% csrf_token %} {{ form1.as_p }} {{ formset.management_form }} {% for form in formset %} {{ form }} <br> {% endfor %} <br> <button type="submit">Add Lecture</button> </form> class LectureForm(forms.ModelForm): class Meta: model = Lecture fields = ('course', 'lecture_title', 'lecture_category', 'content') class FileForm(forms.ModelForm): class Meta: model = FileUpload fields = ('files',) class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures',) lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses',) lecture_title = models.CharField(max_length=100, blank=True, null=True) … -
Django. How to get fields from child model in views.py?
How to get fields from child model in views.py? For example, I've parent model BasicOrder and child model (who extends BasicOrder) TouristVisa. I'm using Django 2.0.2 and Python 3.6.1. My models.py is: class BasicOrder(models.Model): user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE) status = models.PositiveIntegerField(_('Status'), choices=ORDER_STATUS, default=0) def __str__(self): return 'Order #{}'.format(self.id) class TouristVisa(BasicOrder, models.Model): citizenship = models.ForeignKey( Citizenship, verbose_name=_('Citizenship'), on_delete=models.PROTECT ) invitation_entry = models.PositiveSmallIntegerField( _('Invitation entry'), choices=INVITATION_ENTRY ) class Meta: ordering = ['id'] Would be great to have access to field invitation_entry from child model (TouristVisa). I try this way in views.py: order = BasicOrder.objects.get(user=request.user.id) print(order.invitation_entry) But it's show error: AttributeError: 'BasicOrder' object has no attribute 'invitation_entry' -
Issue with SSL, nginx, gunicorn, and Django in production
I'm having an issue getting nginx to pass over control of routing to my django server. By default it checks '/' path and if the user isn't logged in redirects to '/login' and then upon login passes it back to '/'. The login page works fine until you submit then it throws an 'Internal server error'. The server is ubuntu 16.4. Also the python is 3.5 and inside a virtualenv. Let me know if I need to provide the gunicorn service config. My nginx is as follows: server { server_name example.com; rewrite ^(.*) https://www.example.com permanent; } server { listen 80; server_name www.example.com; rewrite ^(.*) https://www.example.com permanent; } server { listen 443 ssl; server_name www.example.com; ssl on; ssl_certificate /etc/nginx/12345678.crt; ssl_certificate_key /etc/nginx/ssl.key; location = /favicon.ico { access_log off; log_not_found off; } location /static/ {root /home/ubuntu/app; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/app/app.sock; } } -
How to load the Django application module?
How to load the Django application module? This error is shown when I squeeze the django server compressed by pyinstaller. hook-sistema.apps.py from PyInstaller.utils.hooks import collect_submodules hiddenimports = collect_submodules('sistema') ERROR: (PythonLib): dist\AGTRAN.exe runserver Unhandled exception in thread started by <function check_errors..wrapper at 0x05F03738> Traceback (most recent call last): File "site-packages\django\utils\autoreload.py", line 225, in wrapper File "site-packages\django\core\management\commands\runserver.py", line 113, in inner_run File "site-packages\django\utils\autoreload.py", line 248, in raise_last_exception File "site-packages\django\core\management_init_.py", line 327, in execute File "site-packages\django\utils\autoreload.py", line 225, in wrapper File "site-packages\django_init_.py", line 24, in setup File "site-packages\django\apps\registry.py", line 89, in populate File "site-packages\django\apps\config.py", line 116, in create File "importlib_init_.py", line 126, in import_module File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 941, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'sistema' -
Django model with 'order_with_respect_to': how to get object order?
I have two models with an order_with_respect_to relationship: class Book(models.Model): pass class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) class Meta: order_with_respect_to = 'book' I know I can get the order of chapters like this: my_book.get_chapter_order() But given a chapter, I need to know its position. I know there's a generated _order field, but it's suposed to be private, so I'd prefer not to use it. My first approach would be something like this: my_chapter = Chapter.objects.get(pk=WHATEVER) chapters = my_book.get_chapter_order() for position, chapter_id in enumerate(chapters): if chapter_id == my_chapter.id: break print(position) But it feels very dirty: I must get the whole order list each time I want to know a chapter's order. I think this should be just a chapter's property. Is there any cleaner way to do this? -
How to restrict user acces to see/modify objects created by other users with Django
I'm making a hobby project with Django to store my ideas seperated by idea groups as the following: class Idea(models.Model): name = models.CharField(unique=True, max_length=50) description = models.TextField() in_process = models.BooleanField() is_done = models.BooleanField() group = models.ForeignKey(Group, on_delete=models.CASCADE, blank=False) class Group(models.Model): name = models.CharField(unique=True, max_length=25) description = models.CharField(max_length=50, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) Is there any way to restrict the currently logged in user from being able to see or modify ideas and idea groups created by other users using generic class based views? class GroupDelete(LoginRequiredMixin, generic.DeleteView): model = Group pk_url_kwarg = "id" success_url = reverse_lazy('ideas:list') ...and a url for example: urlpatterns = [ path('<int:id>/delete', views.GroupDelete.as_view(), name='delete'), ] I'm using Django 2.0. -
Django Custom model authentication and ACL (Access Control List) with Angular
I have a custom user model with onetoone relationship with django user model, I have migrated data from Odoo to django database. My Odoo password hash is different from django user password. I would like suggestion about how to make custom user model that will be helpful in all scenario for my Odoo data as well as Django data. Which will authenticate user easily in both way. Secondly i have overlooked in django documentation for Custom user authentication. So i have added custom authentication for both django and Odoo. How would i send response to Angular that my user can be authenticate every time on different views for django. How would i will implement ACL on different user roles in this point of view. Any more better example if you could share and better suggestion. Kindly put some good and simple examples would be appreciated. If you need code i will edit my question and put it as well. -
Trouble accessing object
I've been working on an issue all day and am at my wits end. I have two models with a manytomany relationship (bookmark, and boomark group). I am trying to access the bookmarks accosiated with the bookgroup in my view. When print the context to take a peak I get None returned. I've pasted the code below in a gist...any help would be so greatly appreciated. https://gist.github.com/colonelrascals/4bf4e4f98c47d64706b504646346bbd5