Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django dynamic multiple form
I have form for adding Company: class Company(models.Model): name = models.CharField(max_length=50, ) profile = models.ForeignKey("Profile", blank=True, null=True) sector = models.ForeignKey("Sector", blank=True, null=True) I want to dynamically add another form on same site when proper button is clicked. For example after clicking "Add Address" button, form should be extended with: city = models.ForeignKey("City", blank=True, null=True) street_name = models.CharField(max_length=50, blank=True) and submiting this form will create new Customer, Address and CustomerAddress records. I already have worked out solution which isn't perfect, cause I added "blank=True", to fields in additional forms and show/hide form in JS. This soultion is causing another problem, because now I don't have any validation for form. I don't want to create custom validation for every template, in which I add multiple forms. -
Compare an object type with string in jinja
I am making a project in djnago. I am having a condition in jinja html template where a comparision is not running correctly.Even through there values are same . part of code which is not working:- {%if user_obj.status =='Online'%} <p>Working</p> {%endif%} i think they are of different type that's why they are not working.But how can i make them working. -
html template using django,
` Total No. of User {{total_user}} <td width="30%">Total No. of New User(Today)</td> <td>{{new_user}}</td> </tr> <tr> <td>Total No. of Transaction</td> <td>{{total_trans}}</td> <td>Total No. of Transaction (Today)</td> <td>{{total_trans_today}}</td> </tr> <tr> <td>Total No. of Refer a Friend</td> <td>{{total_refer}}</td> <td>Total No. of Vehicle</td> <td>{{total_vehicle}}</td> </tr> <tr> <td>Total No. of Suggest </td> <td>{{suggest_pump}}</td> <td>Total No. of Suggest (Today)</td> <td>{{suggest_today}}</td> </tr> <tr> <td>Total No. of Reported </td> <td>{{reported_price}}</td> <td >Total No. of Reported (Today)</td> <td>{{reported_today}}</td> </tr> <tr> <td>Total No. of review</td> <td>{{total_review}}</td> <td>Total No. of station reviewed</td> <td>{{total_station_review}}</td> </tr> </tbody> </table> </div>`<td width="20%">Total No. of User</td> <td>{{total_user}}</td> How do i add link to the outcome in Django? like the outcome is in integer but it should redirect to the list, which i have made in views. Just a hint for including a link to numbers -
FATAL: password authentication failed for user "ubuntu"
I'm using djanog version 1.11 and postgressql 9.5###, I'm facing below error. but my django databases settings different. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME':'test_db', 'USERNAME':'rails', 'PASSWORD':'rails', 'HOST':'localhost', 'PORT':'5432', } } I think django pass user as ubuntu user, it's system logged in user. System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7f39fbfe5488> Traceback (most recent call last): File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 128, in inner_run self.check_migrations() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__ self.build_graph() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 254, in cursor return self._cursor() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 229, in _cursor self.ensure_connection() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/home/ubuntu/sooky_env/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) … -
Djaongo: ModelChoiceField and Widget - Could not display non-foreign key field
I want to create a select field that displays a list of record from a column that is not a foreign key. I am able to do it using widget=ForeignKeyRawIdWidget(rel=Slum._meta.get_field('electoral_ward').rel where 'electoral_ward' is a foreign key in 'Slum' model. I wish to have the same behavior for a field ('name') which is just a char field in 'Slum' model. Thank you! -
How to make a queryset also contain a PK in django
I've got this model: class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, to_field='username') video = models.ForeignKey(Video, on_delete=models.CASCADE) description = models.TextField(default="none") replyto = models.ForeignKey('self', blank=True, null=True, on_delete=models.CASCADE) uploaded = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # maybe add ability to update comments... indent = models.IntegerField(default=0) On which i've got to return a queryset like this: Comment.objects.filter(video_id=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end] I get this as a response (after having serialized it to json and send it as response to a Ajax request. ): Object { user: "TestUser", video: 7, description: "test new video comment lol", replyto: 5, uploaded: "2018-01-12T09:14:24.281Z", updated: "2018-01-12T09:14:24.281Z", indent: 0 } Object { user: "admin", video: 7, description: "testing the new comment system per …", replyto: null, uploaded: "2018-01-12T09:14:05.740Z", updated: "2018-01-12T09:14:05.740Z", indent: 0 } However i'd like to include the PK of each object in the list of values. So I tried: Comment.objects.value_list('pk','user','video','description','replyto','uploaded','updated','indent').filter(video_id=Video.objects.get(identifier=request.GET['identifier'])).order_by('-uploaded')[:end] which caused the error: AttributeError: 'Manager' object has no attribute 'value_list' why is this? how can I get a queryset which also includes the PK? EDIT as requested: here is the code for serializing the object: def obtain_comments(request, *args, **kwargs): begin = int(request.GET['begin']) end = int(request.GET['end']) # check if end is less than number of comments and begin is more or equal than 0 … -
Visualising Django Models
We have some legacy code for a Django REST Framework which is connected to a Postgresql database. I would like to visualise all the tables in such a way that I know which fields are there in each column and how they are connected to each other (What my research tells me is an ER diagram). I tried using Dvisualiser and MySQL workbench, but owing to lack of familiarity was not able to extract the required data. Query: Is there a quick and dirty way to visualise this so we can understand how th data and relatonships are structured? If yes, which tool will offer the shortest learning curve, as this is an one off requirement. -
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; }