Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form field in if statement fail
I'm rendering a Django form using an if statement to construct the html template: {% for field in form %} {% if field.name == 'user_name' or 'phone' or 'email' or 'password1' %} <div class="col-12 col-md-6 col-lg-3"> <p class="text-left m-0 fs-13">{{ field.label_tag }}</p> {% render_field field class="form-control is-invalid" %} </div> {% else %} bla bla {% endif %} {% endfor %} But when I call the template, all fields are constructed using the if statement code, but I have fields like: location, birth_date... that are True in the else statement. What am I doing wrong? -
Overriding Django admin vs creating new templates/views
I am a total noob with Django, I come from the PHP world and I am used to doing things differently. I'm building an app and I want to change the way the backend looks, I want to use Bootstrap 4 and add a lot of custom stuff e.g. permission based admin views, and I was wondering what is the best practice, or how do more experienced django devs go about it? Do they override all the django.contrib.admin templates, or do they build custom templates and login/register next to it, and use the django.contrib.admin only for the superuser? What is the django way? -
Django MimeType error
guys, I have no idea what is wrong with this error. The code is not something that I wrote so I don't know much about it. Any help is greatly appreciated. I will update the question with any other information that you ask for when it is needed. The code is very hard to read an upload to stack overflow so code posts may take a long time to reply. Environment: Request Method: GET Request URL: http://192.168.2.214/accounts/login/?next=/ Django Version: 1.11.6 Python Version: 2.7.12 Installed Applications: ('django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'tsa.events') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'tsa.settings.ChapterMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/usr/local/lib/python2.7/dist- packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File " /home/serverad/django14_project/my_django15_project/tsa/events/views.py" in login_view 185. next=request.GET.get('next', '/'), chapters=Chapter.objects.all(), error_msg=error_msg) File "/home/serverad/django14_project/my_django15_project/tsa/events/views.py" in render_template 71. return HttpResponse(txt, mimetype=kwds.get('mimetype','text/html')) File "/usr/local/lib/python2.7/dist-packages/django/http/response.py" in __init__ 301. super(HttpResponse, self).__init__(*args, **kwargs) Exception Type: TypeError at /accounts/login/ Exception Value: __init__() got an unexpected keyword argument 'mimetype' -
django image file not found . image name same as directory
In windows system if there is an image file named same as the parent directory name then django server does not show the image file. e.g: http://127.0.0.1:8000/a/a.jpg This url does not give any image. But when the same image is renamed as "b.jpg" http://127.0.0.1:8000/a/b.jpg This url gives the image. Note: This problem exists only when the django server is on windows operating system and browser - chrome. There is no problem with linux. -
Attribute Error when extending user model
I'm using Django 1.11 and Python 3. Currently I have my LDAP authentication working. However, I want to extend my user model and I'm getting the following error when attempting to extend my user model. AttributeError: 'User' object has no attribute 'profile' [25/Oct/2017 14:47:28] "POST /account/login/ HTTP/1.1" 500 224535 I've tried to change my code to user.profile or user.AllEeActive but then it gives me the following error: File "C:\python\security\accounts\models.py", line 52, in save_user_profile instance.username.save() AttributeError: 'str' object has no attribute 'save' [25/Oct/2017 14:43:31] "POST /account/login/ HTTP/1.1" 500 224521 Below is my models.py, what am I doing incorrect? from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from django.db.models.signals import post_save from django.dispatch import receiver import django_filters class AllEeActive(models.Model): employee_ntname = models.OneToOneField(User, db_column='Employee_NTName',max_length=12) # Field name made lowercase. employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, blank=True, null=True) # Field name made lowercase. r_level = models.CharField(db_column='R_Level', max_length=10, blank=True, null=True) # Field name made lowercase. division_name = models.CharField(db_column='Division_Name', max_length=100, blank=True, null=True) # Field name made lowercase. … -
how to do i automatically set the user field to current user in django modelform
How can i set the current login user to the user field of django model .In my view ,i am using function base view .My model is something like this . class create(models.Model): user=models.ForeignKey(User,related_name='create',unique=True) view.py def createform(reques): #help me -
AWS DMS migration causes null primary key error
i am using AWS RDS postgres database with django. I migrated the database to a new RDS postgres instance. I am able to connect to it through django and view all the records. But whenever I try to add records lets say new user it gives me # django.db.utils.IntegrityError: null value in column "id" violates not-null constraint # and some times i also get # Primary key (id) duplication error. # i dont understand, django is supposed to handle primary keys (id) and auto increments by default. It is strange why it is passing null while creating new records or why passing those keys which are already in use. I am unable to figure out what is wrong in whole process. It is simple homogenous DMS migration from postgres to postgres. Migration task completes successfully. It shows no errors. All the data and tables with public schema are replicated successfully. But i am unable to add new records to it. Note: I tried migrating db using "pg_dump" command and it worked fine. I was able to add records to it after migration. Also I tried using same postgres engine versions (9.5) on both instances. Any type of help would be … -
Django Channels. Adding users to a Group
I am coding kind of a social network app. I want to have users create conversations and add their friends to the conversation at creation of the conversation. They are going to receive messages via websocket. The problem that I have is that I can add users to listen to their conversations upon establishing websocket connection but how do I add a user's reply_channel to the Group of the newly created by some other user conversation (while the former user already has websocket connection established) so that they could start listening to incoming messages from the conversation? -
Create PostgreSQL Database on another Server using Django
I have a working local environment using Django 1.11 with a PostgreSQL 10 database running on Linux Mint. I am trying to take a copy of this environment and install it on two Ubuntu 16.04 development servers: one for the web server and the other for the SQL server. The problem is running Django with the Ubuntu PostgreSQL server. When I take the Django settings.py file, and change the server from 'localhost' to the IP address of the new PostgreSQL server, every command issued with manage.py fails. This includes createsuperuser, makemigrations and migrate. This fails on both my working, development machine and the new Ubuntu web server. Is there a step I am missing that should be done after changing the database server and before running a manage.py command? Everything I have read says to simply run the makemigrations, and migrate commands. I have even tried to delete the makemigrations folders, but still no luck. Verified: Can connect to the new PostgreSQL server remotely using the same user ID and password, and was able to create a table (so problem should not be related to security or remote access). Here is the (shortened) error that comes up each time: Traceback … -
socket.gaierror [errno 11004] django cassandra engine, Sync_cassandra error
File "C:\Python\Python35-32\lib\site-packages\cassandra\cluster.py", line 784, in <listcomp> for endpoint in socket.getaddrinfo(a, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)] File "C:\Python\Python35-32\lib\socket.py", line 732, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11004] getaddrinfo failed what should I do to solve this error -
Styling UserForm in Django
I made a custom user form with fields username, password1 and pasword2, based on UserCreationForm. I want to style it using bootstrap form-control in Meta widgets, but it doesn't work. Is this possible? EDIT Although password1 and password2 are not in Meta fields, they are rendered. The code: class UserForm(UserCreationForm): class Meta: model = User fields = ['username'] widgets = { 'username': TextInput(attrs = { 'class': 'form-control', }), 'password1': PasswordInput(attrs = { 'class': 'form-control', }), 'password2': PasswordInput(attrs = { 'class': 'form-control', }), } -
How to access Postgres database within docker-compose
I'm pretty new to Postgres and Docker, but I am building a webapp with Django that runs inside a docker with a postgresql database. I am trying to view my Postgres database via the command prompt or pgweb. Unfortunately, I can't seem to find the database at all, I tried using the postgres psql terminal commands, but my database wasn't listed inside. My question is, how is the postgresql database stored within a docker-compose container. Do I need to go into the container manually and then view the database? My ultimate goal is to be able to see a list of all my tables and data within the postgresql database. Any documents explaining how the postgresql database interacts with a docker-compose would be appreciated. Thanks! -
Showing multiple views in a single template
I have a current use-case where I need to have a number of UpdateViews in a single Django template. The views I currently have are: class ProductiveMinutesDetail(UpdateView): model = models.ProductiveMinutes pk_url_kwarg = 'productiveminutes_pk' form_class = forms.ProductiveMinutesDetailEditForm template_name = 'main/productiveminutes_detail.html' success_url = reverse_lazy('productiveminutes_list') class ProductiveMinutesUpdate(UpdateView): model = models.ProductiveMinutes pk_url_kwarg = 'productiveminutes_pk' form_class = forms.ProductiveMinutesEditForm def form_valid(self, form): self.object = form.save() return render(self.request, 'main/productiveminutes_edit_success.html', {'amount': self.object}) And the my template is currently: {% extends 'pages/dashboard.html' %} {% load django_bootstrap_breadcrumbs i18n humanize crispy_forms_tags %} {% block breadcrumbs %} {{ block.super }} {% breadcrumb "Productive Minutes" "productiveminutes_list" %} {% breadcrumb "View/Edit Productive Minutes" "productiveminutes_detail" %} {% endblock breadcrumbs %} {% block content %} <div> <h1 class="text-center">Productive Minutes: {{ productiveminutes.name }}</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Edit productive minutes: {{ productiveminutes.name }}</h3> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} <button class="primaryAction btn btn-primary pull-right ml-1" type="submit">{% trans "Update" %}</button> <a class="btn btn-secondary pull-right" href="{{ request.META.HTTP_REFERER }}" role="button">{% trans "Cancel" %}</a> </form> </div> <div class="col"></div> </div> <hr> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Data Records</h3> <div class="table-responsive"> <table class="table table-bordered"> <thead class="thead-default"> <tr> <th>ID</th> <th>Productive Minutes</th> <th>Action</th> </tr> </thead> <tbody> <tr> <td>{{ productiveminutes.id }}</td> <td>{{ productiveminutes.amount|intcomma }}</td> <td> <a href="{% url … -
Pass a parameter across views - Django
I have the following scenario: I have created globalModels (Season, Team, Player, Referee). Also, I have created seasonalModel (SeasonTeam, SeasonPlayer, SeasonReferee) as I want to record statistics from a Team every particular season, same with Player and Referee) and also I will aggregate statistics from every SeasonTeam into the globalModel Team. I am building platform for administration. So I have next urls: adminSite.urls url(r'^$', views.homeAdmin, name='homeAdmin'), url(r'^addGlobal/', include('globalModels.urls', namespace='addGlobal')), url(r'^addSeasonal/', include('seasonalModels.urls', namespace='addSeasonal')) globalModels.url url(r'^$', admin_views.addGlobal, name='addGlobal'), url(r'^addSeason/', views.addSeason, name='addSeason'), url(r'^addPlayer/', views.addPlayer, name='addPlayer'), url(r'^addTeam/', views.addTeam, name='addTeam'), url(r'^addReferee/', views.addReferee, name='addReferee') Now, in order not to have to choose the season (foreignKey in every seasonalModel) everytime I want to add a new seasonalModel, I want to make a first step of choosing the season, and then let the administratos choose between adding a seasonalTeam, seasonalPlayer... How would you accomplish this? I have thought about 2 possibilities: FRONT END Display with a list of the seasons registered as divs and with JS get the id that the administrator has click on: {% for season in seasons %} <div id="{{ season.season }}" class="adminButton chooseSeason "> {{ season.season }} </div> {% endfor %} And then pass it inside the url: $(".chooseSeason").click(function (){ var season = $(this).attr('id'); … -
Upgrade django in a dokku environment
I need to upgrade the version of django that is running in a dokku container. I tried dokku run staging pip install Django==1.8.18 --upgrade But when I checked the django version it was still 1.8.13 How am I meant to do the upgrade? -
Django use of uuid with postmark templates
I'm new on SO and on Django. I'm currently using Django and Postmark but I have a few problem with confirmation url within the confirmation mail for authentification. I have this fonction in my views.py : def form_valid(self, form): self.created_user = self.create_user(form, commit=False) self.created_user._disable_account_creation = True self.created_user.save() self.use_signup_code(self.created_user) email_address = self.create_email_address(form) if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED and not email_address.verified: self.created_user.is_active = False self.created_user.save() self.create_account(form) self.create_password_history(form, self.created_user) self.after_signup(form) if settings.ACCOUNT_EMAIL_CONFIRMATION_EMAIL and not email_address.verified: try: postmark = PostmarkClient(server_token=settings.POSTMARK['TOKEN'], verbosity=3) id_test = uuid.uuid4().hex active_url = "http://127.0.0.1:8000/account/email_confirmation/" + str(id_test) +'/' postmark.emails.send_with_template( TemplateId=3676362, TemplateModel={ "product_name": "Pagela", "product_url": "product_url_Value", "action_url": active_url }, From=settings.FROM_EMAIL, To=self.created_user.email) except: a = "donothing" if settings.ACCOUNT_EMAIL_CONFIRMATION_REQUIRED and not email_address.verified: try: return self.email_confirmation_required_response() except: a = "donothing" else: show_message = [ settings.ACCOUNT_EMAIL_CONFIRMATION_EMAIL, self.messages.get("email_confirmation_sent"), not email_address.verified ] if all(show_message): messages.add_message( self.request, self.messages["email_confirmation_sent"]["level"], self.messages["email_confirmation_sent"]["text"].format(**{ "email": form.cleaned_data["email"] }) ) self.form = form self.login_user() return redirect(self.get_success_url()) And this one in my urls.py: urlpatterns = [ ... url(r"^account/", include("account.urls")), url(r"^account/email_confirmation/(?P<id_test>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$", ConfirmEmailView.as_view(), name="confirm_email"), ...] I do not understand why there is a 404 error : [25/Oct/2017 16:13:04] "GET /email_confirmation/148a1e55817744dd9ab031ea4f6302f4/ HTTP/1.1" 404 3622 I don't really understand why it cannot get the uuid in my url. Anyone has had the same problem ? Thanks, Arnault -
How to keep a remote server connected with my machine off?
I created a project in Django and it is running remotely on a server from my university with SSH. I would like to know how to keep it running with my machine off. I use Ubuntu -
Form is not returning contents of search, instead it returns "csrfmiddlewaretoken"?
I have the following search bar (which is included in a Bootstrap Navbar): {% csrf_token %} Search The view that handles the 'search' url: def search(request): if request.method == "GET": contents_of_search = request.GET return HttpResponse(contens_of_search) The problem is is that whenever something is searched in this search bar it returns "csrfmiddlewaretoken" and the contents of the search. Does anyone know how to fix this? -
virtualenv and virtualenvwrapper "There was a p roblem running the initialization hooks" all of a sudden
So my development environment really hasn't changed for a long time. I am using Bash on Ubuntu on Windows for about a year now. I just apply the regular updates with: sudo apt-get update sudo apt-get upgrade sudo apt-get dist-upgrade Haven't had any issues until last week. When I would workon env and then start up Django, all of these Python errors related to encryption and hashing would come up. Don't really remember what they said, but apparently couldn't find something. I just ignored them because I am in the middle of a project and figured I'd address them later since it is just the dev server. Anyway, I come in yesterday to work and all of a sudden I am getting: -bash: /usr/local/bin/python3.6: No such file or directory virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3.6 and that PATH is set properly. I read a number of SO questions related to this. Basically they all suggested to uninstall virtualenv, virtualenvwrapper, and pip. That is if doing pip3 install --upgrade virtualenvwrapper didn't work, which it didn't. Uninstalled, reinstalled, and left work yesterday with … -
django's get_user_model() only in 1.11 during import time
I've created this draft of a reusable app: django-separate-users. It basically works :) But, this code only runs on django 1.11+. The problem is right here, the call to get_user_model(): models.py. The docs state, that in 1.11 "The ability to call get_user_model() at import time was added.": https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#referencing-the-user-model How can I make this code work down to django 1.8? AUTH_USER_MODEL is a string, so it doesnt work? -
how to add attribute in an inline field Django?
When i try to add an attribute in an inline field, nothing added. I want a same class for each each select to add a javascript event on select change. This is my models.py: class Conversation(models.Model): conversation_name = models.CharField(verbose_name="Nom du conversation", max_length=255) group = models.ForeignKey(Group, verbose_name="Groupe") class ConversationMessage(models.Model): conversation_title = models.ForeignKey(Conversation, verbose_name="Conversation") from_message = models.ForeignKey(MessageList, verbose_name="De", related_name="from_message") to_message = models.ForeignKey(MessageList, verbose_name="A", related_name="to_message") my admin.py: class ConversationMessageInline(admin.TabularInline): model = ConversationMessage` class ConversationMessageAdmin(admin.ModelAdmin): form = ConversationMessageForm list_display = ['conversation_title', 'from_message', 'to_message'] class ConversationAdmin(admin.ModelAdmin): form = ConversationForm list_display = ['conversation_name'] inlines = [ ConversationMessageInline, ] my forms.py: class ConversationMessageForm(forms.ModelForm): model = ConversationMessage from_message = forms.ModelChoiceField(MessageList.objects.all(), widget=forms.Select(attrs= {"onChange":'refresh()'})) class Media: js = ('js/forms_event.js',) class ConversationForm(forms.ModelForm): model = Conversation class Media: js = ('js/forms_event.js',) my forms_event.js: function refresh() { alert("salut la planete"); } The event onchange didn't added when I'm at "Add Conversation": -
Django authentication how to log in the user to their project
If a user has multiple projects under their account, how do I authenticate the user so that the content is not only specific to their account, but to their default project. Ideally, the project is right at the top portion of the page, inside the base template of the site, right beside the sign-out link. The user should be able to just change the project without signing out and signing back in. The request object should be loaded with the project, so I could query the contacts model like this: Contact.objects.filter(project = request.project) Currently, I have to do the same query like this: user_project = Project.objects.get(user = request.user, project_name = 'summer') Contact.objects.filter(project = user_project) A little nudge in the right direction is much appreciated -
How to include Jupyter notebook on Django view?
Jupyter notebook is a great tool and I would like to incorporate fully working note with django shell on Django view. It it possible without iframe? Project owner wants to have a seperate views with jupyter notebook in user panel -
Django - get element index in a list in template
I have a list in template for iteration, and when iterating, I want to print its index in this list. Now I am using list.index(element), but this does not work. I do: <tbody> {% for core in cores %} <tr> <td>{{cores.index(core)}}</td> <!-- this line doesn't work --> <td>{{core.user}}</td> <!-- this line works. --> This is not the way? I have to do for i in length(cores)? -
Use table.ajax.reload and send parameters to the view
Hi i'm trying to do a reload on datatable with parameters. View: def listProduct(request): Req = TbProduit.objects.filter(espece = "00") data = getDataQuery(Req) return HttpResponse(json.dumps(data), content_type = "application/json") In document.ready : mytable = $('#prodTab').dataTable( { "ajax": { "url": "{% url 'listProduct' %}", columns: [ { "data": 0 }, { "data": 1 }, { "data": 2 }, { "data": 3 }, { "data": 4 }, { "data": 5 }, { "data": 6 }, { "data": 7 }, { "data": 8 }, { "data": 9 }, { "data": 10 } ] } }); get_product = function(){ mytable.api().ajax.reload(); alert("RELOAD"); } On my page i have two editbox, one to choose a specie and the other to choose a product. My goal is to be able to send the ID of the specie to the ajax.reload function so i can access it in my view and use it as parameter in the filter so the datatable to choose the product is correctly filtered.