Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Templates - block inside an include, the block displays above or below, not in the block
I have inserted a block inside an include in hopes that I could references that block and add extra links to it if needed. site_page.html: {% extends 'home/sbadmin_base.html' %} {% load extras %} {% load static %} {% block content %} {% include 'sites/site_tabs.html' %} {% block extratabs %} <li {{ active_sims|safe }}> <a href="{% url 'sites:site_overview' SiteID %}">Edit Site</a> </li> {% endblock %} site_tabs.html {% load extras %} <!-- Nav tabs --> <ul class="nav nav-tabs"> <li {{ active_ip|safe }}><a href="{% url 'sites:site_overview' SiteID %}">Overview</a> </li> <li {{ active_files|safe }}><a href="{% url 'sites:site_detail_files' SiteID %}">Files and Photos</a> </li> {% block extratabs %} {% endblock %} </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane fade in active" id="ip"> <div class="row"> When my page is rendered, the "extratabs" just appear below the include and outside the list as per the below: <!-- Nav tabs --> <ul class="nav nav-tabs"> <li class="active"><a href="/sites/site/7">Overview</a> </li> <li ><a href="/sites/site/files/7">Files and Photos</a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div class="tab-pane fade in active" id="ip"> <div class="row"> <li > <a href="/sites/site/7">Edit Site</a> </li> -
Assign auto manager foreign key when submit the order form in Django
I am working on Order model where the order assigned_to manager after saving the model. There are more than two Users.One who creates the order and one manager, who assigned automatically after order created. Then manager decides the next Users or stack_user to assign the work.There is only one manager now. user = models.ForeignKey(User, on_delete=models.CASCADE, editable=False) assigned_to = models.ForeignKey(Manager, on_delete=models.CASCADE, blank=True, null=True) assigned_to_stackuser1 = models.ForeignKey(StackUser1, on_delete=models.CASCADE, blank=True, null=True, related_name='assigned_to_stackuser1') assigned_to_stackuser2 = models.ForeignKey(StackUser2, on_delete=models.CASCADE, blank=True, null=True, related_name='assigned_to_stackuser2') I want to that when I submit the form. The Manager will be assigned automatically to the order. Then manager will add the StackUser1 or StackUser2 as he wants. I am trying to add this field with signals but failed. My question is that how assigned manager when I submit the form? -
Operational error with database on Django
I've uploaded a Django project to Digital ocean but I'm getting an operational error with the database on my Django project. OperationalError at /blog/ FATAL: Peer authentication failed for user "myprojectdbuser" Request Method: GET Request URL: http://178.62.41.209/blog/ Django Version: 1.8.7 Exception Type: OperationalError Exception Value: FATAL: Peer authentication failed for user "myprojectdbuser" Exception Location: /usr/lib/python2.7/dist-packages/psycopg2/__init__.py in connect, line 164 Python Executable: /usr/bin/python Python Version: 2.7.12 Python Path: ['/home/django/django_project', '/home/django/django_project', '/usr/bin', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Server time: Fri, 12 Jan 2018 09:28:48 +0000 Error during template rendering In template /home/django/django_project/blog/templates/blog/blog.html, error at line 3 FATAL: Peer authentication failed for user "myprojectdbuser" 1 {% extends "personal/header.html" %} 2 {% block content %} 3 {% for post in object_list %} 4 <h5>{{ post.date|date:"Y-m-d" }}<a href="/blog/{{post.id}}"> {{ post.title }}</a></h5> 5 {% endfor %} 6 {% endblock %} 7 The rest of the message can be viewed here: http://178.62.41.209/blog/ The site at Github: https://github.com/Karl2018/myWebsite -
How to judge the request.user whether is AnonymousUser? [duplicate]
This question already has an answer here: How do I check whether this user is anonymous or actually a user on my system? 3 answers How to jundge the request.user is AnonymousUser in Django? class UserListAPIView(ListAPIView): serializer_class = UserSerializer permission_classes = [] queryset = User.objects.all() def get(self, request): if request.user: print("not AnonymousUser" ) # there I tried return Response(data="200", status=HTTP_200_OK) You see, I tried request.user to check the user whether exist, but failed, always print the not AnonymousUser. How to check it? -
how to embed IPython in webpage?
I want to prepare an education site similar to Codeacademy or Datacamp. Especially I want it to look like Datacamp. I can now write code in ACE editor , I can get it but I want to know , can I embed IPython in my Django Template and make it run the code which I get through ACE editor? I have checked most of the docs and i am not experienced enough about this subject. How can I embed IPython inside? do i have to use prompt_toolkit? Thanks -
Django: How to set default model.charfield using enum?
I am having an issue with trying to migrate across the default value shown in the model. I get the error below. I followed what was write on here, however, it appears they did not have the same issue. error message field=models.CharField(choices=[('BIG','Larger'), ('MID','Normal'), ('SMALL','Small')], default=library.models.FontSize('Normal'), max_length=10), AttributeError: module 'library.models' has no attribute 'FontSize' model class Book(models.Model): class FontSize(ChoiceEnum): BIG = 'Larger' MID = 'Normal' SMALL = 'Small' #Other fields font_size = model.CharField(max_length=10, choices=FontSize.choices(), default=FontSize.MID) choices.py class ChoiceEnum(Enum): @classmethod def choices(cls): return tuple((x.name, x.value) for x in cls) -
AttributeError: 'WSGIRequest' object has no attribute 'user'
guys I'm running my Django code, but get this error AttributeError: 'WSGIRequest' object has no attribute 'user' My Django version is 1.8.2, and here is my middleware class of setting.py MIDDLEWARE_CLASSES = ( 'khxia.middlewares.PeeweeConnectionMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'subdomains.middleware.SubdomainURLRoutingMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'referral.middlewares.ReferralRecordMiddleware', 'common.middlewares.ExceptionMiddleware', ) -
Get the REMOTE_ADDR in Django-Rest-Framework?
How to get the request's remote_addr? I have a BileModelListAPIView as bellow: class BileModelListAPIView(ListAPIView): serializer_class = BModelSerializer permission_classes = [] queryset = BileModel.objects.all() def get(self, request): print(request) # there I debug the point return Response(data="ok", status=HTTP_200_OK) I read a article says the HttpRequest have a META property, in META there is the REMOTE_ADDR. But in my scenario how to get the REMOTE_ADDR ? -
Python Django open huge file
I want to build a json service with python. Program will read a json file then return. My file size 1 GB. When I run the program, I have error that "MemoryError". My code is; def homepage(request): file = open("file.json") json_file = json.load(file) return JsonResponse(json_file) Can anybody help me. Thanks... -
Django cant see file cms_apps.py
Hi I have application in Django and I want do apphook by http://docs.django-cms.org/en/release-3.4.x/how_to/apphooks.html So I have create file named cms_apps.py in my application directory # -*- coding: utf-8 -*- from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ class Aktualnosci(CMSApp): name = _('Aktualnosci') urls = ['aktualnosci.urls'] app_name = 'aktualnosci' apphook_pool.register(Aktualnosci) reload the server of course and django cant see my cms_apps.py I can write so random rubbish in my cms_apps.py and Django is silent. -
Allowing users edit their profile in Django Admin
I'm working in this Django project where exists three different roles: Hospitals, Doctors and Patients. Hospitals can add, edit or delete Doctors and Patients. Doctors can add, edit or delete patients. And patients should only be allowed to enter the profile that the doctor or hospital created for them and be able to edit their information. I read another kind of questions being answered but the different thing in here is I have to do this through the Django Administration Panel ¿Why? Is the first phase of the project so we're doing a basic demo ¿is this possible? I can restrict the role of patients in Django Admin but this gives a user power to edit the profiles of the other patients created. -
can you change the way get method makes links for django?
I'm using django for a website that has a searchbar setup with a simple form: <form method="get" action="/browse"> <div class="input-group col-md-12"> <input type="text" name="searchquery" class="form-control input-lg" placeholder="Search" style="margin-right:1vw; border-radius: 5px;"/> <span class="input-group-btn"> <button class="btn btn-primary btn-lg" type="submit"> {% fontawesome_icon 'search' color='white' %} </button> </span> </div> </form> This creates url's like this: http://127.0.0.1:8000/browse/?searchquery=<searchquery> However I've setup my django url like this: http://127.0.0.1:8000/browse/<searchquery>/ I would like to use the second url (as it just looks a lot better in my opinion). Is there a way I can make my form do this? -
Celery exception in case Redis didn't start or stoped , also similar for worker
I Celery you can use exception and retry if something is failing The below code is just a simple example: @task(name='add', max_retries=5, bind=True) def add(self, x, y): try: x+ y except Exception as e: self.retry(exc=e, countdown=exponential_backoff(self)) This let's say it work if I'm connecting to an emails/social media provider and is failing. But what if a server like Redis is failing ot the worker didn't start. What I want if the exception is because of my fault retry 5 and they call a send email function to the admin if the exception is because Redis stopped send an email without retrying if the worker is not active send an email without retrying -
Django 2 versions of german
I'm developing website with 2 versions of german (Default and Austrian). My problem is that template do not differ them, so in select django displays them both as Deutsch(de). Languages in settings.py: ('en', _('English')), ('de', _('German')), ('de-at', _('Austrian')) template code: <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <select style="border:1px dotted black" name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input class="btn-primary" type="submit" value="{% trans 'Change' %}" /> </form> Code is from documentation. Translation in Austrian language doesn't work, because django in select defines Austrian as default Deutsch select it and do not translate. So, are there any ways to display sublanguage in template, like (Deutsch(de-at)) or just (Austrian instead of Deutsch), or are there any other ways to solve it? Tried to change all languages in settings: ('en-us', _('English')), ('de-de', _('German')), ('de-at', _('Austrian')) Then created .po and .mo files to them. But still template defines them as same languages. Also I thought … -
Update User + Extend User together by using @detail_route in Django Rest Framework
I want to write a viewsets @detail_route in order to update User + Extend User. Please help me if you know. Extend User Model class Profile(models.Model): user = models.OneToOneField(User, unique=True) nickname = models.CharField(max_length=50, null=True, blank=True) gender = models.CharField(max_length=100, choices=GENDER_CHOICES, blank=True, null=True, default='MALE') Urls.py urlpatterns = [ url(r'^(?P<user__username>[\w-]+)/$', UserDetailAPIView.as_view({'get': 'retrieve'})), url(r'^account/edit/$', UserDetailAPIView.as_view({'post': 'edit_profile'})) ] Views.py: from rest_framework.decorators import detail_route class UserDetailAPIView(ReadOnlyModelViewSet): # renderer_classes = (JSONRenderer, ) queryset = Profile.objects.all() serializer_class = UserSerializer lookup_field = 'user__username' @detail_route(methods=['PATCH']) def edit_profile(self, request): ................. ????? Serializers.py class UserSerializer(ModelSerializer): username = serializers.CharField(source='user.username') first_name = serializers.CharField(source='user.first_name') last_name = serializers.CharField(source='user.last_name') email = serializers.CharField(source='user.email') gender = serializers.ChoiceField(choices=GENDER_CHOICES, default='1') class Meta: model = Profile fields = [ 'id', 'username', 'first_name', 'last_name', 'email', 'gender', ] -
Adding a new url gives error
In my urls.py I have this. from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from events import views as eviews urlpatterns = [ url(r'^user/', include('accounts.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^$', eviews.events_list, name='events_list'), url(r'^(?P<o_type>[-\w]+)/$', eviews.events_list, name='events_list_by_org'), url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', eviews.event_detail, name='event_detail'), ] when I add the "user" url which is at first line in urlpatterns, it shows error on line 26 which is "events_list_by_org" url. When I comment out or remove 'user' url it works fine but shows error when it's included. -
How can I write a custom fields serializer only update specified fields?
How can I write a custom fields serializer only update specified fields ? I have a Model: class TodoList(models.Model): content = models.CharField(max_length=64) user = models.ForeignKey(to=User, related_name="todolists") is_finish = models.BooleanField(default=False) ctime = models.DateTimeField(auto_now_add=True, null=True, blank=True) uptime = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.name def __unicode__(self): return self.name I only want to update the is_finish field: class TodoListUpdateIsFinishSerializer(ModelSerializer): class Meta: model = TodoList fields = ["id", "is_finish"] In my view: class TodoListUpdateIsFinishAPIView(RetrieveUpdateAPIView): serializer_class = TodoListUpdateIsFinishSerializer permission_classes = [] queryset = TodoList.objects.all() But when I access this view, there comes issue: Expected view TodoListUpdateIsFinishAPIView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. I tried add lookup_field = "id" or lookup_field = "pk", but still not work. EDIT My urlpatterns is bellow: url(r'^todolist/update_isfinish/$', TodoListUpdateIsFinishAPIView.as_view(), name='todolist-update_isfinish') -
Error: CSS only takes effect when words are in visible quotes. Django.
The body section of the css files works fine, but for some reason, h1 only shows any change when the word 'Sentiment Analysis' is literally in quotes, and these quotes show up on the page. If I take it out of quotes, no changes are reflected on the page. I am also using Django. Is there a way to fix this so I don't need quotes showing up on my page if I want to style anything? index.html <!DOCTYPE html> <html> <head> <meta charset ="utf-8"> {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}"> <title></title> </head> <body> <header> <h1>'Sentiment Analysis'</h1> <hr> <a href="/add">Add Stock</a> </header> <ul> The 10 most recently searched stocks: {% for scs in sc%} <li>{{scs.ticker}} {{scs.points}} {{scs.created_at}}</li> {% endfor %} </ul> </body> </html> styles.css body { height: 100%; margin: 0; background-repeat: no-repeat; background-attachment: fixed; background-color: red; background-image: linear-gradient( to top right, #C3E4ED, #00BFFF ); } h1 { text-align: center; } -
SearchForm is not shown in category.html
SearchForm is not shown in detail.html. I wrote in views.py def top(request): content = POST.objects.order_by('-created_at')[:5] form = SearchForm() return render(request,'top.html',{'content':content,'form':form}) class DetailView(generic.DetailView): model = Detail template_name = 'detail.html' form = SearchForm() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context in category.html <div class="search_box"> <form action='/app/search/' method="POST"> <table> {{ form.as_table }} </table> <button class="btn btn-secondary search" type="submit">SEARCH</button> {% csrf_token %} </form> </div> div> <h2>{{ object.title }}</h2> <a href="{% url 'detail' content.pk %}">SHOW DETAIL</a> </div> I think if I wrote DetailView class like top method which is return render(request,'top.html',{'content':content,'form':form}),I can show SearchForm() in detail.html.But DetailView class is generic view, so i cannot understand how I can read SearchForm() in DetailView class.I wrote context['search_form'] = SearchForm() but form is not shown.How should I fix this?What is wrong in my codes? -
Django - How to save files to STATIC_ROOT from views?
I have made a Django app that takes arguments from the form and makes an image using Pillow. views.py: file_name = "{}.png".format(random.randint(1, 255)) image1.save(file_name) pretty simple stuff, right? Now when I try to render that image with HttpResponse as: return HttpResponse("<img src='" +file_name + "' alt='image here'>") apparently, it will throw an error. Can you please tell me what to do in order to save it properly and show in HttpResponse? Django==1.11.8 Pillow==5.0.0 Python 3.6.2 Thank you! -
OSError: [Errno 22] Invalid argument: "C:\\xxxx\\xxx\\xxx\\{'query'
I am working on a Django project from my laptop that runs Windows 10. I've set the environment with pip install and everything seems to work fine, since, for example, python manage.py migrate working properly. The server starts fine with python manage.py runserver, however, when I open the URL http://127.0.0.1:8000/restaurants in my browser I get the following error: OSError at / [Errno 22] Invalid argument: "C:\\xxxxx\\xxxxx\\templates\\{'query': <QuerySet [<RestaurantModels: BIS>, <RestaurantModels: Sangam>, <RestaurantModels: IBIS>, <RestaurantModels: CCR>]>}" Request Method: GET Request URL: http://127.0.0.1/ Django Version: 1.11.7 Exception Type: OSError Exception Value: [Errno 22] Invalid argument: "C:\\xxxxx\\xxxxx\\templates\\{'query': <QuerySet [<RestaurantModels: BIS>, <RestaurantModels: Sangam>, <RestaurantModels: IBIS>, <RestaurantModels: CCR>]>}" Exception Location: C:\Users\fly\AppData\Local\Programs\Python\Python36\lib\site-packages\django\template\loaders\filesystem.py in get_contents, line 28 Python Executable: C:\Users\fly\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.4 Python Path: ['C:\\xxxxx\\xxxxx', 'C:\\xxxxx\\xxxxx', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\fly\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2017.3.1\\helpers\\pycharm_matplotlib_backend'] Here is the View, Model, Template of my project view.py template.py Kindly let me know what is causing this? I am sure it's not the code. -
What is the proper process for validating and saving data with with Django/Django Rest Framework regardless the data source?
I have a particular model that I'd like to perform custom validations on. I'd like to gaurantee that at least one identifier field is always present when creating a new instance such that its impossible to create an instance without one of these fields, though no field in particular is individually required. from django.db import models class Security(models.Model): symbol = models.CharField(unique=True, blank=True) sedol = models.CharField(unique=True, blank=True) tradingitemid = models.Charfield(unique=True, blank=True) I'd like a clean, reliable way to do this no matter where the original data is coming from (e.g., an API post or internal functions that get this data from other sources like a .csv file). I understand that I could overwrite the models .save() method and perform validation, but best practice stated here suggests that raising validation errors in the .save() method is a bad idea because views will simply return a 500 response instead of returning a validation error to a post request. I know that I can define a custom serializer with a validator using Django Rest Framework for this model that validates the data (this would be a great solution for a ModelViewSet where the objects are created and I can guarantee this serializer is used … -
Django model fields not appearing in admin
I have a relatively simple model in my Django project (I should note that the wording is weird in that the app itself is called 'games' and within it the model is Game but I'll change this later): from django.db import models class Game(models.Model): player_turn = models.IntegerField(), game_state = models.BooleanField(), rolled = models.BooleanField(), rolled_double = models.BooleanField(), last_roll = models.IntegerField(), test_text = models.CharField(max_length = 200), with a settings.py file in the main folder of the project showing INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'games.apps.GamesConfig', ] and games/admin.py looks like this from django.contrib import admin from .models import Game admin.site.register(Game) When I try to run 'python3 manage.py makemigrations' it shows that no changes are detected (even if I arbitrarily change the Game model to test the effect) and when I go into the admin site to add a new game there are no fields available to edit like there are for the User and Group models. The model itself shows up in the admin site but without any fields. Right now I'm following along the MDN Django tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Models) and it seems like I'm following all of the necessary steps so can someone let me know what I might … -
Selenium on Chrome drive running on server as a part of website is in-excessable to clients on there windows PC
I am unable to understand this technicality. Or how to go about it. During development of a Django website on my local machine, I included selenium(with chromedriver) for a functionality. Where the user enters a data on the website and clicks a button which triggers selenium method to open a page, then the user makes his choice which causes the selenium to scrap off the data and quit the driver. And take the scrapped up data as one of the semi-auto-filled form entries on the website. All this worked fine with Chrome drivers path present on my local machine. But when I shifted the website to production on the server and uploaded the chrome drive along with the website as well, giving drivers proper path name on the server machine. I am unable to get the driver working on remote client window machines when I access the website. How can I get the same functionality as in during development in local machine for remote clients as well? -
How am I supposed to render timezone-aware model field with local time setting in django
Let's say I had the following code # settings.py in a proper location ... TIME_ZONE = 'Asia/Seoul' USE_TZ = True # models.py in a proper location class Post(models.Model): created = models.DateTimeField(auto_now_add=True) def created_formatted(self): return self.created.strftime("%Y/%m/%d %H:%M") Then, I rendered the following django template to html before formatting: {{ a_post.created }} # localtime after formatting: {{ a_post.created_formatted }} # not localtime I expected both {{ a_post.created }} and {{ a_post.created_formatted }} have the same timezone, but they don't. I tried to find out how {{ a_post.created }} is rendered to localtime but I'm not sure which part of the django code is the right place to look for yet. (It will be really helpful if you let me know the right part of the django source code to look for). I want to apply the same idea to my created_formatted after I find how the rendering of datetime works.