Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'pipenv install -r' is not working
Excuted this : 'pipenv install -r requirements/local.txt' D:\doc\jaeeongram> pipenv install -r requirements/local.txt Requirements file provided! Importing into Pipfile… Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Nothing happens here. (After 5min, ...., 1hour) The following is my Pipfile. [[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [packages] Django = "==1.10.8" django-environ = "==0.4.4" django-crispy-forms = "==1.7.0" django-model-utils = "==3.0.0" Pillow = "==4.3.0" "argon2_cffi" = "==16.3.0" django-allauth = "==0.34.0" awesome-slugify = "==1.6.5" pytz = "==2017.3" django-redis = "==4.8.0" redis = ">=2.10.5" coverage = "==4.4.2" django_coverage_plugin = "==1.5.0" Sphinx = "==1.6.5" django-extensions = "==1.9.8" Werkzeug = "==0.13" django-test-plus = "==1.0.21" factory_boy = "==2.9.2" django-debug-toolbar = "==1.9.1" ipdb = "==0.10.3" pytest-django = "==3.1.2" pytest-sugar = "==0.9.0" [dev-packages] [requires] python_version = "3.6" pipenv shell -> django-admin not found... How to resolve this problem? -
Expand static tree sidebar menu in django template with jQuery when new pages loads
I have a python+django app and the sidebar menu is defined in the base.html, which is extended by other dynamic pages, so let's call the sidebar tree menu static. Now, when I click a link in the sidebar, as the new pages loads, the new page has the sidebar all items collapse, which is not desirable. I want to make the link corresponding to current page highlighted(with "class=active") and its parent item expanded. My site is based on a free webpage template called "AdminLTE": https://github.com/almasaeed2010/AdminLTE and it has some code to handle the toggle/expand/collapse event, but does not solve the "remain-link-active-and-menu-open" problem, because on every page, the sidebar part is repeated and each corresponding link and its parent have their states(active and expanded) hard-coded. I want the sidebar menu "remembers" the state, by passing some arg in between calls, etc. The sidebar tree code is below: /* Tree() * ====== * Converts a nested list into a multilevel * tree view menu. * * @Usage: $('.my-menu').tree(options) * or add [data-widget="tree"] to the ul element * Pass any option as data-option="value" */ +function ($) { 'use strict' var DataKey = 'lte.tree' var Default = { animationSpeed: 500, accordion : true, followLink … -
Where should I specify the output_field kwarg in this complex query?
I wrote a little survey app. I have a query that causes an exception upon upgrade to Django 2.0: Expression contains mixed types. You must set output_field. Here's a few relationships necessary to understand the query (where --fk--> indicats a foreign key): response --fk--> question --fk--> survey response --fk--> person Here's my query: answered_surveys = SurveyResponse.objects.all()\ .values('fk_question__fk_survey__hash', 'fk_question__fk_survey__name')\ .annotate( nb_respondants = Count('fk_person', distinct=True), survey_name = F('fk_question__fk_survey__name'), survey_hash = F('fk_question__fk_survey__hash') )\ .annotate( completion=100*Count('id')/ (F('nb_respondants')*F('fk_question__fk_survey__nb_questions_per_survey')) ) It's fine up until the last annotate, but I don't know where to add the output_field kwarg since I only have F and Count models. Count outputs an IntegerField by definition, F complains if I try to add that kwarg. How do I fix this? -
Use inline formset in modleform django
this might be a simple question but I couldn't find the answer anywhere. I have a modelform which I use to update models (User model). now I want to add an inline formset to this form for some model (UserReports). I already tried: class UserModelForm(UserChangeForm, CrispyForm): reports = inlineformset_factory(User, Reports, fields=('text',)) class Meta: model = User fields = ("email", "first_name") which does not work. any ideas what am i doing wrong/ what might fix this? -
using csrf_token in django widget
I am trying to make a custom django widget with ajax. The ajax call requires csrf_token. I need to know how to pass the csrf_token to the widget html. # forms.py from django import forms from widgets import MyWidget class PenForm(forms.ModelForm): color = forms.CharField(widget=MyWidget) class Media: js = ( 'js/jquery-3.2.1.min.js', 'js/jquery-ui.min.js', ) css = { 'all': ( 'css/jquery-ui.min.css', ) } # widgets.py from django.forms.widgets import Widget from django.template import loader from django.utils.safestring import mark_safe class MyWidget(Widget): template_name = 'my_widget.html' def get_context(self, name, value, attrs={}): return {'widget': { 'name': name, 'value': value, 'attrs': attrs, 'csrf_token': '???' }} def render(self, name, value, attrs=None): context = self.get_context(name, value, attrs) template = loader.get_template(self.template_name).render(context) return mark_safe(template) Here is my widget html: <script> $( function() { $( "#autocomplete_{{ widget.name }}" ).autocomplete({ source: function( request, response ) { $.ajax( { url: "/get_colors", type: "post", dataType: "json", contentType: "application/json; charset=utf-8", headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: { term: request.term }, success: function( data ) { response( data ); } } ); }, minLength: 1, select: function( event, ui ) { log.debug( "Selected: " + ui.item.value + " , " + ui.item.id ); } } ); } ); </script> # admin.py @admin.register(Pen) class PenAdmin(admin.ModelAdmin): form = PenForm list_display = … -
Django Query Set is giving a type error
The django query set is giving me a type error when trying to do a foreign key lookup. The Django reverse look up is giving me this error Where Im trying to get the details of the applications made by the Candidate. I have given my models and views.py and attached all of my Trace of error so kindly help me! Views.py def candidateDetail(request,id=None): instance = get_object_or_404(CandidateRegister, id=id) applic = instance.applications_set.all() for i in applic: print(i) # Throwing an error here!! context = {"instance": instance,"applic":applic} return render(request,"candidatedetail.html",context) Models.py class Applications(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) jd = models.ForeignKey(JoDesc,on_delete=models.CASCADE) candidate = models.ForeignKey(CandidateRegister,on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now= False,auto_now_add=True) application_made_by = models.ForeignKey(User,on_delete=models.CASCADE) class Meta: unique_together = ('jd', 'candidate') def __str__(self): return '%s' % (self.application_made_by,self.jd) My Trace Environment: Request Method: GET Request URL: http://127.0.0.1:8000/candidateDetail/9467e007-23e8-4cc7-b256-5082cd1facbe/ Django Version: 2.0 Python Version: 3.4.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'new', 'crispy_forms', 'djutils'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/sskadit/Office/nlpondec2017/newenv/src/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/sskadit/Office/nlpondec2017/newenv/src/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/Users/sskadit/Office/nlpondec2017/newenv/src/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/sskadit/Office/nlpondec2017/newenv/src/lib/python3.4/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/Users/sskadit/Office/nlpondec2017/newenv/src/newproject/new/views.py" in candidateDetail 112. print(i) File "/Users/sskadit/Office/nlpondec2017/newenv/src/newproject/new/models.py" in __str__ … -
Unable to get request.FILES django
I am trying to upload a text file to my django backend, but my request.FILES is always empty. I am using axios to send the file and have followed the django requirement to have 'multipart/form-data' as content type of the request. What am I missing? On my app.js I send a post request via: onSubmit() { var formData = new FormData(); formData.append('reqtype', this.reqtype) formData.append('fileToUpload', this.uploadedFile) axios.post('/sreqtool/tc/', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) On the network request payload: ------WebKitFormBoundarymAnl54hGVTifZzwM Content-Disposition: form-data; name="reqtype" filebased ------WebKitFormBoundarymAnl54hGVTifZzwM Content-Disposition: form-data; name="fileToUpload" data:text/plain;base64,OTA1NTIzMzg2NQ0KOTE3NTAwMTU0Mg0KOTc3NDczNjcyNg0KMTIzNTQ2ODQ1Ng== ------WebKitFormBoundarymAnl54hGVTifZzwM-- In my views.py I have: @csrf_exempt def index(request): if request.method == 'POST': DLOG.info(request.POST) DLOG.info(request.FILES) form = ExtractForm(request.POST, request.FILES) if form.is_valid(): res = QueryManager.processRequest(request.user, form.cleaned_data) DLOG is my logger and the output of the dlog is: [2017-12-18 16:51:06,510] INFO views index: <QueryDict: {u'fileToUpload': [u'data:text/plain;base64,OTA1NTIzMzg2NQ0KOTE3NTAwMTU0Mg0KOTc3NDczNjcyNg0KMT IzNTQ2ODQ1Ng=='], u'reqtype': [u'filebased']}> [2017-12-18 16:51:06,512] INFO views index: <MultiValueDict: {}> -
How to run correct all test of each app in django (connection already closed)?
I have two django app: core and blog, each app have tests. my_project_name: ... core tests __init__.py test_views.py test_models.py test_forms.py test_api.py blog tests __init__.py test_views.py test_models.py test_forms.py test_api.py ... each test file have: from django.test import TestCase class MyNameTest(TestCase): @classmethod def setUpTestData(cls): When i ran all test: python3 manage.py test I got this erros: ERROR: setUpClass (core.tests.test_views.PageDetailViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/my_path/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 234, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "/my_path/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 212, in create_cursor cursor = self.connection.cursor() psycopg2.InterfaceError: connection already closed The above exception was the direct cause of the following exception: ... File "/my_path/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 212, in create_cursor cursor = self.connection.cursor() django.db.utils.InterfaceError: connection already closed ---------------------------------------------------------------------- Ran 20 tests in 1.884s FAILED (errors=1) What is the problem ? and how this fix ? -
Adding keyboard shortcust functionality to Django Admin
What is the easiest way to add keyboard shortcuts to Django admin panel without overriding admin templates? Like new object, save object, delete object and etc. -
Remove add another from django admin
I have an inline model in Django admin which is having OneToOneField relation with the parent. class Child(models.Model): parent = models.OneToOneField(Parent) received_on = models.DateField(null=True,) In admin Inline I don't want to show "add another button" so I have done something like this:- class CampaignInfluencerShippingTrackingInline(admin.TabularInline): model = Child can_delete = False extra = 0 fields = ['received_on'] def has_add_permission(self, request): return False But it is still showing add another button the problem is with relation with the parent as it is having OneToOneField if I try with ForeignKey with same code add another button is not showing but with OneToOneField it is always showing. Can anyone suggest me how it is working and what I can do to remove add another button from the Inline child? -
Equality of Django's Q objects
I am trying to compare django's Q objects which are composed in the exact same way. But despite all children and relations between them being same, they aren't deemed equal. from django.db.models import Q $ q1 = Q(a=1) & Q(b=1) & Q(c=1) $ q2 = Q(a=1) & Q(b=1) & Q(c=1) $ q1 == q2 $ False This is posing problems in my unit tests where I build up filters for my querysets using Q objects. Why are the two Q objects not equal? I am using Django 1.11. -
Django Error: Reverse for 'query' with no arguments not found
What I'm trying to achieve is this: I have a list of branches and clicking on it would link me to a list of services of that specific branch. (url: http://127.0.0.1:8000/branches/[slug:branch_name]) 2.I have a search form with a button upon clicked will filter out the specific service that I want on the context of the branch I'm currently in. (url: http://127.0.0.1:8000/branches/[slug:branch_name]/search/[?q=specific_service]) It seems to me that the urls are configured properly and the problem is on the search-form.html action="{% url 'branches:search:query' %}". I've tried many things including trying to add kwargs in the url template tag slug=slug and customizing my views.py to add kwargs to reverse and replacing action = "{{ reverse_url }}" but nothing seems to work. I must be missing something. The only hack I've found to work is using action = {{request.path}}search/. I was wondering if there is a cleaner solution than this. Would appreciate any leads! Thanks! main/urls.py urlpatterns = [ url(r'^$',home_page, name='home'), url(r'^admin/', admin.site.urls), url(r'^branches/', include("branches.urls", namespace='branches')),] branches/urls.py urlpatterns = [ url(r'^$', BranchListView.as_view(), name='list'), url(r'^(?P<slug>[\w-]+)/$', BranchServiceListView.as_view(), name='services'), url(r'^(?P<slug>[\w-]+)/search/', include("search.urls", namespace='search')),] search/urls.py urlpatterns = [ url(r'^$', search_catalog, name='query'), ] search-form.html <form method="GET" action="{% url 'branches:search:query' %}" class="form-inline my-2 my-lg-0"> -
Changes to model with one to one relation not saving
I have two models that I'm relating using Django's OneToOneField, following this documentation: https://docs.djangoproject.com/en/2.0/topics/db/examples/one_to_one/ class Seats(models.Model): north = models.OneToOneField('User',on_delete=models.CASCADE,related_name='north', default=None, null=True) bridgetable = models.OneToOneField('BridgeTable',on_delete=models.CASCADE, default=None, null=True) class BridgeTableManager(models.Manager): def create_deal(self): deal = construct_deal() table = self.create(deal=deal) s = Seats(bridgetable=table) s.save() return table class BridgeTable(models.Model): deal = DealField(default=None,null=True) When I run this code I can successfully get the relationship working table = BridgeTable.objects.get(pk='1') user = User.objects.get(username=username) table.seats.north = user table.seats.north.save() print(table.seats.north) The print statement prints out the name of the player sitting north. But if I try to access the table again like this: table = BridgeTable.objects.get(pk='1') print(table.seats.north) I get "None" instead of the user's name. Is there something I'm missing, like a save that I missed or some concept I'm not understanding? Thanks. -
How to install a django package that does not have a pypi release? [duplicate]
This question already has an answer here: How to install Python package from GitHub? [duplicate] 2 answers I am trying to use ActivFlow on my project. Unfortunately there is no pypi package, so how should I go about installing and using the package on my project. Here it is on django-packages -
Django - Modelform not rendering
I created a form to update a User's profile, however when I run it, there are no errors, but when I try to open up the page, nothing shows up. Secondly, I was wondering how you would create a large textbox to store someone's biography. Models.py class UserProfile(models.Model): user = models.OneToOneField(User) biography = models.CharField(max_length = 255, default = '') city = models.CharField(max_length=100, default = '') website = models.URLField(default='') image = models.ImageField(upload_to='profile_image', blank=True) def setdefault(self, default_path='/profile_image/Default.jpg'): if self.image: return self.image return default_path def __str__(self): return self.user.username Forms.Py class UpdateBioForm(forms.ModelForm): class Meta: model = UserProfile fields = ( 'biography', 'city', 'website' ) def save(self, commit=True): savedBio = super(UpdateBioForm, self).save(commit=False) savedBio.biography = self.cleaned_data['biography'] savedBio.city = self.cleaned_data['city'] savedBio.website = self.cleaned_data['website'] if commit: savedBio.save() return savedBio Views.py def update_bio(request): if request.method == 'POST': form = UpdateBioForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('/') else: form = UpdateBioForm(instance=request.user) args = {'form':form} return render(request, 'accounts/update_bio.html') update_bio.html {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Update Biography</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </div> {% endblock %} -
how to write django web script for showing our run time input in web page url?
My questionn is how to show our input in web page when we are giving url with input in address bar. For example I am giving url in my web browser like localhost:8011/Sathish means It will show my input in web page. Like "Sathish". If I give localhost:8011/Kannan It will show like this. Like "Kannan" Can you please tell me how to write that code in django? -
Use response of a method to define a model field in Django
I need some dynamic choices fields in a django model and I want to validate if a table exists before get them. I already know how to check if the table exists with raw sql and also I know how to generate my dynamic tuple for choices, but I don't know how to use the response of my validation method. Any ideas? This is a snippet of my code: class SomeModel(models.Model): ... row = False def check_table(self): with connection.cursor() as cursor: cursor.execute( "SELECT EXISTS(" "SELECT *" " FROM pg_tables WHERE schemaname = \'schema_name\' AND " "tablename = \'table_name\')") row = cursor.fetchall() return row # Then, I need to put that reponse in a variable to do something like this. if table_exists: # do something ... Thanks -
Add two TaggableManager for a modal in django taggit
I have a model like class EmotionJournal(models.Model): situation = models.TextField() emotions_before = TaggableManager() emotions_after = TaggableManager() def __str__(self): return str(self.id) where I need to have two types of tag in a single model. I looked through various solutions like from this link But I was not satisfied with the solution. I wanted to know how can I do the same? -
Using python how to upload the image file into MSSQL Server via HTML
I wanted to upload a image file from HTML and that'll be redirected to server side script written in python. Since I wanted to upload the file name from this path: 'C:\Users\Desktop\Desktop\123456.jpg' After connection is established from the database and while inserting image into Database following things happens Raises an exception It takes only fileName not the absolute path of the file (i.e, 123456.jpg) index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style type="text/css"> body { font-family: Arial; font-size: 10pt; } #dvPreview { filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image); min-height: 50px; min-width: 50px; display: none; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script language="javascript" type="text/javascript"> $(function () { $("#fileupload").change(function () { $("#dvPreview").html(""); var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/; if (regex.test($(this).val().toLowerCase())) { if ($.browser.msie && parseFloat(jQuery.browser.version) <= 9.0) { $("#dvPreview").show(); $("#dvPreview")[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = $(this).val(); } else { if (typeof (FileReader) != "undefined") { $("#dvPreview").show(); $("#dvPreview").append("<img />"); var reader = new FileReader(); reader.onload = function (e) { $("#dvPreview img").attr("src", e.target.result).width(150).height(200);; } reader.readAsDataURL($(this)[0].files[0]); } else { alert("This browser does not support FileReader."); } } } else { alert("Please upload a valid image file."); } }); }); </script> </head> <body> <form action = "http://localhost/img_upload.py" method = "post"> <label for="fileupload"> Select a file to upload </label> <br/><br/> <input type="file" name="fileupload" … -
Use different wagtail page as root without slug
I'm attempting to set a page as the root home page of my wagtail based site. I know you can set the homepage using the sites setting. But, my use case is different. I'm using a "redirect" page which redirects to an index page as the homepage. The index is restricted to only allow ertain page types (since it's an index....). But, this causes issues with other pages not being in the tree if it was set at the root. Hence, the redirect. But, upon redirecting the serve view of the redirect page to use this page it picks up the slug. I still want it to appear at the root url. Meaning, /. How can I achieve this? High level description: class IndexPage(Page): # children restricted to IndexSubpage class IndexSubpage(Page): # parent restricted to IndexPage class RedirectPage(Page): def serve(request): return redirect(self.link, permanent=True) # Link is a link to a page.... So, this will pick up the slug of IndexPage instead of being at / -
I am not able to connect mysql server with python engine getting following error
Following error I am getting ` Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03D26618> Traceback (most recent call last): Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' ` I already install Django-Mssql -
Why I use vscode run django project and debug it, then I can not get post data
I can not get post data when I use vscode run django project, insteed of command, is my configuration wrong? addition: I can not get print content from debug console. -
How to display javascript from ajax response in HTML
I am designed one web application in which I want to show the plot which will be received by ajax response.This plot is written in javascript.I want to put this plot as the HTML div. Below is my HTML code, {%load static %} {% load staticfiles %} <head> <script src=" {% static 'jquery-1.12.4.js' %}"></script> </head> <button type="button" id="myBtn" onclick="myFunction()">Try it</button> </html> <div id="plot"></div> <script> function myFunction() { $.ajax({ url: '/visualization/', type: 'POST', contentType: 'application/json; charset=utf-8', //data: JSON.stringify(finalJson), //dataType: 'text', success: function(response){ console.log("!!!Reponse!!!") console.log(reponse) document.getElementById("plot").innerHTML = response } }); } </script> Below is javascript received for plot: <style> </style> <div id="fig_el150211404154248054569977043312"></div> <script> function mpld3_load_lib(url, callback){ var s = document.createElement('script'); s.src = url; s.async = true; s.onreadystatechange = s.onload = callback; s.onerror = function(){console.warn("failed to load library " + url);}; document.getElementsByTagName("head")[0].appendChild(s); } if(typeof(mpld3) !== "undefined" && mpld3._mpld3IsLoaded){ // already loaded: just create the figure !function(mpld3){ mpld3.draw_figure("fig_el150211404154248054569977043312", {"axes": [{"xlim": [-1.1078409018075122, 1.1078409018075119], "yscale": "linear", "axesbg": "#FFFFFF", "texts": [{"v_baseline": "auto", "h_anchor": "start", "color": "#000000", "text": "RP1", "coordinates": "data", "zorder": 3, "alpha": 1, "fontsize": 8.0, "position": [-1.0, 1.7], "rotation": -0.0, "id": "el15021140415296730768"}, {"v_baseline": "auto", "h_anchor": "start", "color": "#000000", "text": "RP2", "coordinates": "data", "zorder": 3, "alpha": 1, "fontsize": 8.0, "position": [0.0, 1.7], "rotation": -0.0, "id": "el15021140415296731792"}, {"v_baseline": … -
Missing manage.py while trying to install Graphite (with Django)
I am trying to install Graphite on Ubuntu following the instructions given here: https://gist.github.com/albertohm/5697429 When I install the components, especially Django, I do not get any errors. However when I run these two commands I get an error saying that "manage.py could not be found": cd /opt/graphite/webapp/graphite sudo python manage.py syncdb I've tried many different ways of setting up Graphite but none worked :-( Can someone please help me as to why manage.py does not exist in the graphite web folder? -
What is the difference b/w authenticate() and login() in Django?
I want to understand the difference b/w both user = authenticate( username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password1') ) login(request, user)