Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Which model field type would be appropriate for a date-time object that is repeatedly saved in the database, and needs to be displayed as a string?
The question is a bit ambiguous, allow me to explain: I'm creating something like a changelog, which will note the date-time an object is created along with the objects created. When the objects are updated in the database, I'll get a snapshot of the date-time and record the newly changed objects along with the current & new date-time--the previous snapshots of object+date-time are already also stored. Here is an example of the kind of "changelog" I am trying to display as text on the site: Oct. 24, 2017, 11:22 a.m "Cats and dogs", "Apples and oranges" Oct. 19, 2017, 12:04 p.m "This is a string object", "This is the second object/preference" Sep. 03, 2017, 01:22 a.m "This object was saved long ago", "As was this one" So, the question is two-fold--which model fieldtypes would be appropriate for an object that needs to record the current date-time, but also how do I have the previous changelogs persist in the DB as text to be displayed, instead of just querying the most recent one? In the following failed attempt, the Profile model contains the objects/"preferences" to be changed and recorded, and an updated field to save the current date-time when the object … -
Django-rest-framework: Validate a ListSerializer
I receive a number of similar objects as an input for my API, and I deserialize them using my own serializer with the parameter many=True like this: serializer = MySerializer(data=request.data, many=True) The serializer is an instance of ListSerializer. Then I need to make sure that there are certain combinations of objects in that list. However, I don't seem to find a way to write a .validate() method on the ListSerializer of replace it by my own ListSerializer implementation. Is there a way to do this validation in the serializer, or do I have to iterate over the deserialized objects and check them? -
Javascript (string) Equality with Django Template
I'm new in Javascript and this is my html code that contain django template : <img src="{% static 'basic/main.js' %}" alt="img"/> and my js is : var myImg = document.querySelector('img'); var myImgSrc = myImg.getAttribute('src'); my problem is when i try equality test in web console : myImgSrc === "{% static 'basic/main.js' %}" is return false may be there is escape character or special character to represent my django template, can someone explain how to represent django template in literal js string. Thank you sorry for my bad english. -
Trying to add custom fields to users in Django
I am fairly new to django and was it was going well until this. i'm trying to add fields 'address' and 'phone_number' to users (create custom user basically) but i keep getting this error like this... File "C:\Users\will5\Desktop\City\city_info\forms.py", line 5, in <module> class UserForm(forms.ModelForm): File "C:\Users\will5\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\forms\models.py", line 257, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (phone_number, address) specified for User this is models ... from django.contrib.auth.models import AbstractUser class User(AbstractUser): phone_number = models.IntegerField(default=0) address = models.CharField(max_length=150) ... this is in my forms from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password', 'address', 'phone_number'] I also read that in order to fix this problem i will have to restart my project by creating the custom user and migrating and i don't wanna do that. -
Page not found (404) error happens
I got an error,Page not found (404) when I put logout button in detail.html. I wrote in header.html <header class="clearfix"> <h1 class="title">WEB SITE</h1> <div class="collapse navbar-collapse head_content" id="navbarNavDropdown"> <ul class="navbar-nav top-menu"> <li class="nav-item top-menu-item"><i class="fa fa-plus" aria-hidden="true"> <a class="nav-link icon_head" href="/accounts/see">SEE</a></i> </li> <li class="nav-item dropdown top-menu-item"><i class="fa fa-eye" aria-hidden="true"> <a class="nav-link dropdown-toggle icon_head" href="" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> KNOW </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <div class="dropdown-content"> <a class="dropdown-item" href="/accounts/nowknow">KNOW1</a> </div> <div class="dropdown-content"> <a class="dropdown-item" href="/accounts/pastknow">KNOW2</a> </div> </div> </i> </li> </ul> </div> <a class="logout_button" href="/accounts/logout_view">LOGOUT</a> </header> I wrote in views.py @login_required def logout_view(request): logout(request) return redirect('regist') @login_required def regist(request): return render(request, 'registration/regist.html') @login_required def see(request): return render(request, 'registration/see.html') @login_required def nowknow(request): return render(request, 'registration/nowknow.html') @login_required def pastknow(request): return render(request, 'registration/pastknow.html') @login_required def detail(request): return render(request, 'registration/detail.html') in urls.py urlpatterns = [ url(r'^product$', views.logout_view,name='logout_view'), url(r'^past_result$', views.see,name='see'), url(r'^privacy_policy$', views.nowknow,name='nowknow'), url(r'^privacy_policy$', views.pastknow,name='pastknow'), url(r'^detail$', views.detail,name='detail'), ] I wrote in index.html <html lang="ja"> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <title>WEB SITE</title> </head> <body class="relative"> {% include '../header.html' %} <main> <p>HELLO WORLD</p> </main> </body> </html> When I acsess index.html and put LOGOUT link,logout is done accurately.But I wrote in detail.html <html lang="ja"> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <title>DETAIL</title> </head> <body class="relative"> {% include '../header.html' %} <main> <p>HOGE</p> </main> </body> … -
django markdownx isn't allowing normal html tags
yesterday i added django-markdownx to my project every thing is working fine with this custom filter: import markdown @register.filter def markdownify(text): return markdown.markdown(text, safe_mode='escape') this is converting markdown to html but if the filed contain normal html it will convert the markdown successfully but not the normal html this is how i use the filter {{ Post.body|markdownify|safe|linebreaks }} thanks in advanced -
Django: get duplicates based on annotation
I want to get all duplicates based on a case insensitive field value. Basically to rewrite this SQL query SELECT count(*), lower(name) FROM manufacturer GROUP BY lower(name) HAVING count(*) > 1; with Django ORM. I was hoping something like this would do the trick from django.db.models import Count from django.db.models.functions import Lower from myapp.models import Manufacturer Manufacturer.objects.annotate( name_lower=Lower('name'), cnt=Count('name_lower') ).filter('cnt__gt'=1) but of course it didn't work. Any idea how to do this? -
Select a valid choice. x is not one of the available choices
I know this question has been asked a dozen times already on Stackoverflow, but I have been through all of them and they don't fix my problem. Usually most of them are related to choices being characters when the model field is integer and vice versa. But this is my situation I'm working on Django helpdesk, an open source django based ticketing platform that can be found here: https://github.com/django-helpdesk/django-helpdesk And I have made a few changes to their forms.py for Public ticket submission and it was working all this while until I recently added a new queue. Forms.py class PublicTicketForm(CustomFieldMixin, forms.Form): queue = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), label=_('Queue'), required=True, choices=() ) So, this form will get choices populated in the views when its called form = PublicTicketForm(initial=initial_data) form.fields['queue'].choices = [(q.id, q.title) for q in Queue.objects.filter(allow_public_submission=True)] + \ [('', 'Other')] #I'm thinking this line may be the problem here return render(request, 'helpdesk/public_homepage.html', { 'form': form, 'helpdesk_settings': helpdesk_settings, }) Here's what the form.fields['queue'].choices prints: [(6L, u'Account'), (7L, u'Support'), (4L, u'Orders'), (5L, u'Products'), (8L, u'Request '), (u'', u'Other')] So, whenever I select a queue and submit, the form won't submit and will throw me "Not one of the available choices" error. As far I … -
Getting latest value in a queryset?
I have a table that looks a bit like this: date | timestamp | predicted_value 2017-10-25| 21758492893 | 0.4 2017-10-25| 21758492917 | 0.3 2017-10-25| 21758493210 | 0.4 2017-10-25| 21758493782 | 0.2 2017-10-25| 21758494903 | 0.1 2017-10-26| 21758492893 | 7.2 .... I'd like to be able to use a single query to get the latest predicted_value for a given date, by timestamp. I.E in my output I want: date | timestamp | predicted_value 2017-10-25| 21758494903 | 0.1 2017-10-26| 21758494903 | 7.7 .... I think it should go something like this: Predictions.objects.all().order_by( '-timestamp' ).values( 'date' ).annotate( prediction=F('predicted_value') ) Is this going to work? Will F select the first value found in the aggregation or can I not use it that way? -
How to three-level query in Django?
I have three tables, names A, B, C: class A(models.Model): name = models.CharField(max_length=12) class B(models.Model): name = models.CharField(max_length=12) a = models.ForeignKey(to=A) class C(models.Model): name = models.CharField(max_length=12) email = models.EmailField() b = models.ForeignKey(to=B) I want get the bellow data: [ {"name":"a1", "data":[{ "name":"b1", "data":[ {"name":"c1", "data":{"c1_name":"c1_name", "c1_id":"c1_id"} }, {"name":"c2", "data":{"c2_name":"c2_name", "c2_id":"c2_id"} } ] }, { "name":"b1", "data":[ {"name":"c1", "data":{"c1_name":"c1_name", "c1_id":"c1_id"} }, {"name":"c2", "data":{"c2_name":"c2_name", "c2_id":"c2_id"} } ] } ] } ] You see, there is three-level data, if there is only table A and B, I can multi-table connection query: B.objects.filter(a='search_id') But now there is three tables, and you see the table C's email is not contain in the query data. How to realize this requirement in my scenario? -
Django migration between branches releases
We are to start branching our master code in the first stable version, and the company has to maintain 2 feature releases. To manage the migrations we use the django migration, but what we don't know is how to load with the hotfix scripts that we could have in the feature releases and master too. I used to use flyway witch let you run the migration with out of order, so if you had in you branch the versions [001, 002, 003, 006], and master [001, 002, 003, 004, 005, 006, 007], where 006 was a hotfix replicated in both, when you migrate to the next version from master the 006 will be skipped. I need a solution like this or a workflow that solve it in django. I couldn't find it. Thank you