Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin TabularInline dynamic readonly fields
If I have an admin.TabularInline, can I have dynamic readonly fields (for instances) by my logic? For example I would to show a tabular inline like this: ------------------------------- | A | B | C | D | =============================== | *va* | vb | vc | *vd* | ------------------------------- | va | vb | *vc* | *vd* | ------------------------------- A, B, C, D are title of headers va, vb, vc, vd are the values *v_* indicates that the field is readonly -
djangocms_text_ckeditor not working on Google chrome
I have install Django Cms by hand using this tutorial http://docs.django-cms.org/en/release-3.4.x/how_to/install.html. Everything works fine but for some reason i can't add or edit text on Google chrome Browser. On Firefox and safari i can though. enter image description here -
Page not found error in Django REST framework tutorial
I am doing the Django REST Framework Tutorial, and I got to the part when they add the view for an individual snippet (view snippet_detail, tutorial 2). When I start the server and point the browser to url http://127.0.0.1:8000/snippets, it returns the 3 snippets I have created before (ids:1,2,3), fine. At url http://127.0.0.1:8000/snippets/2, it returns only the snippet 2, perfect. But when I try http://127.0.0.1:8000/snippets/1, it raises a Page not found error: Using the URLconf defined in tutorial.urls, Django tried these URL patterns, in this order: ^ ^snippets/$ ^ ^snippets/(?P<pk>[0-9]+)$ ^admin/ The current path, snippets/1/, didn't match any of these. I don't understand why snippets/1 doesn't match the second url pattern. Can someone please clarify this error and help me overcome this. -
When I am trying to execute django core management code in the function it doesn't work
I need to upload cvs data to database and I wrote the code which did it. but I need to do it triggered: every time user upload file - the python script update the database. In my code: I have call_command('uploadDb') when I place it not in function upload - it works, but when I place it inside the upload function - it didnt What is the problem? Thank you enter code here from django.shortcuts import render import os from django.core.management import call_command Create your views here. (file views.py) from django.http import HttpResponse def index(request): return HttpResponse("<h1>Upload the file</h1>") def home(request): return render(request, 'index.htm', {'what':'File Upload'}) def upload(request): if request.method == 'POST': handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) return HttpResponse("Successful") return HttpResponse("Failed") def handle_uploaded_file(file, filename): if not os.path.exists('upload/'): os.mkdir('upload/') with open('upload/' + filename, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) call_command('uploadDb') -
Getting Pytest & Mailhog to run in a Django cookiecutter project
I am building a new cookiecutter-django project, and I'm running into two issues that I suspect are related. (Here are the local setup instructions which I've followed.) When I run "pytest" I get the following error 7 times when it tries to collect: ERROR collecting node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py ERROR collecting node_modules/node-gyp/gyp/pylib/gyp/common_test.py ERROR collecting node_modules/node-gyp/gyp/pylib/gyp/easy_xml_test.py ERROR collecting node_modules/node-gyp/gyp/pylib/gyp/input_test.py ERROR collecting node_modules/node-gyp/gyp/pylib/gyp/generator/msvs_test.py ERROR collecting node_modules/node-gyp/gyp/pylib/gyp/generator/ninja_test.py ERROR collecting node_modules/node-gyp/gyp/pylib/gyp/generator/xcode_test.py ../../Envs/kishikoi/lib/python3.6/site-packages/_pytest/python.py:395: in _importtestmodule mod = self.fspath.pyimport(ensuresyspath=importmode) ../../Envs/kishikoi/lib/python3.6/site-packages/py/_path/local.py:662: in pyimport __import__(modname) E File "/Users/emilepetrone/Sites/kishikoi/node_modules/node-gyp/gyp/pylib/gyp/__init__.py", line 37 E print '%s:%s:%d:%s %s' % (mode.upper(), os.path.basename(ctx[0]), E ^ E SyntaxError: invalid syntax When I run grunt serve to launch mailhog: Running "watch" task Waiting... >> /bin/sh: ./mailhog: No such file or directory >> Error: Command failed: ./mailhog Running "sass:dev" (sass) task Any ideas? Thank you- -
Secret key permissions - "'HasAPIAccess' object has no attribute 'authenticate'" when api url is exempt
I want to create API which will be accessible by api key in requests headers. Everything is working as I want, except one thing - when I set up access permissions I do not have access to the api from login exempt url, when not logged in. Error occurs: AttributeError at /api/users/ 'HasAPIAccess' object has no attribute 'authenticate'. I am using standard Django authentication system. Please notice, that I am new to Django REST framework. settings.py: LOGIN_EXEMPT_URLS = { r'^api/users/$' } API_KEY_SECRET = '123abc' permissions.py: class Check_API_KEY_Auth(BasePermission): def has_permission(self, request, view): api_key_secret = request.META.get('API_KEY') return api_key_secret == settings.API_KEY_SECRET serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' views.py: class UserList(APIView): def get(self, request): users = User.objects.all() serializer = UserSerializer(events, many=True) return Response(serializer.data) def post(self): pass urls.py: urlpatterns = [ url(r'^api/users/$', views.UserList.as_view()) ] -
Django - load statics
I am trying to load static file into my html files. index.html extends base.html. However, files are not read(at least not shown on the screen, however, the terminal doesn't say Not Found) In the head of index.html and base.html, I have a tag {% load static %} I read .css file by using tag in index.html: {% static 'base/css/style.css' %} In setting.py, I have: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['Grace/templates/', 'HomePage/templates/', 'Forum/templates/', 'CustomUser/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.csrf', ], }, }, ] my project structure is like this: |Grace |--static |----base |------css |--------boostrap.min.css |--------style.css |------templates |--------base.html |Homepage |--templates |----index |------index.html Thanks in advance! -
ProgrammingError: relation “djkombu_queue” does not exist
I have web-app with Python 2.7 and Django 1.8. I run commands: python manage.py makemigrations python manage.py migrate And I've got an error when tried to insert into DB via Django ORM. ProgrammingError: relation “djkombu_queue” does not exist I can say for sure, djkombu_queue is installed. And I mansioned it in INSTALLED_APPS: INSTALLED_APPS = ( ... 'kombu.transport.django', ) So why I get ProgrammingError: relation “djkombu_queue” does not exist? I also run python manage.py makemigrations kombu_transport_django python manage.py migrate kombu_transport_django No effect. -
how to get absolute value of interval in django F expression?
I'm trying to sort by date difference between now and recorded date of a model instance. The following are my best bet so far, but 'abs' part doesn't work Support.objects.all().annotate( datediff=Func(ExpressionWrapper( F('end_at')-Now(), output_field=DurationField()), function='ABS') ).order_by('datediff', 'id') django.db.utils.ProgrammingError: function abs(interval) does not exist I also tried Support.objects.all().annotate( datediff=ExpressionWrapper( Func(F('end_at')-Now(), function='ABS'), output_field=DurationField()) ).order_by('datediff', 'id') with the same error. -
How do I insert hidden input field in a Django / Bootstrap crispy form, before the password field?
I have a Django / Bootstrap crispy form for registering a new user: from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput( attrs={'autocomplete':'off',})) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( Fieldset( '', 'username', 'first_name', 'last_name', 'email', 'password' ), ButtonHolder( Submit('submit', 'Submit', css_class='button white') ) ) The problem is that the browser autocomplete fills in the email and password fields. The HTML generated by Django crispy forms around the password is as follows: <div id="div_id_password" class="control-group"> <label for="id_password" class="control-label requiredField"> Password <span class="asteriskField">*</span> </label> <div class="controls"> <input name="password" autocomplete="off" required="" id="id_password" class="textinput textInput" type="password"> </div> </div> Now I understand that turning autocomplete off does not work. So I would like to do the usual trick of inserting a hidden field just before the password via Django crispy forms, so that the result is: <div id="div_id_password" class="control-group"> <label for="id_password" class="control-label requiredField"> Password <span class="asteriskField">*</span> </label> <div class="controls"> <input type="text" style="display:none;"> <input name="password" autocomplete="off" required="" id="id_password" class="textinput textInput" type="password"> </div> </div> Is there a nice way to insert this HTML via Djano crispy forms, unless there is another way to prevent the autocomplete? -
Form not submitting the user input to the corresponding url, Django
I was following this video tutorials and got lost inbetween. The app has a form where one can click radio buttons in the existing list to mark it as favorite. On submit, page should reload and display something like "your favorite" along with the list that has been marked favorite and rest same way. This feature exactly works as intended from the admin page of Django but not from the html form. I guess post request is not being sent as intended. Can't figure out why. views.py from django.http import Http404 from .models import Album from django.shortcuts import render, get_object_or_404 def index(request): all_albums = Album.objects.all() return render(request, 'music/index.html', {'all_albums' : all_albums}) def detail(request, album_id): album = get_object_or_404(Album, pk=album_id) return render(request, 'music/detail.html', {'album' : album}) def favorite(request, album_id): album = get_object_or_404(Album, pk=album_id) try: selected_song = album.song_set.get(pk=request.POST['song']) except (KeyError, Song.DoesNotExist): return render(request, 'music/detail.html', { 'album' : album, 'error_message': 'You did not select a valid song', }) else: selected_song.is_favorite = True selected_song.save() return render(request, 'music/detail.html', {'album':album}) models.py from django.db import models class Album(models.Model): artist = models.CharField(max_length=100) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) def __str__(self): return self.album_title+ ' - ' + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) … -
weird behaviour in python conditional operators for "and" and "&"
Below are the different scenarios tried using '&' and 'and' conditional operators and its result. (using Python 2.7) Using '&' operator: Using 'and' operator: Wondering why both conditional operators showing different behaviour? Explanation with real scenarios would be helpful. Thanks in advance. -
Django is .using() method safe?
im currentl working on a project where i have a django app on Server A with its own Database "default" and this app comunicates in some instances with another databse "not-default" on Server B. In the latest version of this Service the app retrieves "non-critical" Data from the "non-default" database via the .using("non-default") Queryset method. But now i face the challenge to also retrieve or update critical User data from this database. So I#m now unsure how safe a Query to this "non-default" database is when performing it with the .using() method. Now the Question: Is it safe? And how is it protected ? -
convert SQLQuery into django query
how to convert this query into django queryset ?? SELECT body, ( SELECT COUNT(status_id) FROM queue WHERE queue.primary_ref_id = messages.Id AND status_id = 2) as count FROM messages i am neww on django framework .. please help me to fix this -
view in one app is not recognized by different view - Django
I have a Django project that I am building. Within the django project I have two apps. one is users and one is accounts. I want to call a view from the acounts app called user_synapse in the users app. I have imported the accounts views python file to import all the methods. I am then calling the method but I am getting an error that says the view method that I am trying to call is not defined. It was working earlier but now it is not working at all. I added the django app name to the settings file and the main urls file. Here is the code I have: Users app: views.py file: #import all references from other apps from accounts.views import * from groups.models import * from groups.views import * ... # create synapse user user_synapse(request) accounts app: views.py file: #import all references from other apps from groups.models import * from groups.views import * from users.views import * from users.models import * # synapse import statements that are needed from synapse_pay_rest import Client, Node, Transaction from synapse_pay_rest import User as SynapseUser from synapse_pay_rest.models.nodes import AchUsNode ... # ensure someone is logged in @login_required # create a … -
Django templating define a variable
Hey i have a problem with defining a variable in Django templates. I don´t know hat im doing wrong. {% set name="World" %} <html> <div>Hello {{name}}!</div> </html> Django Invalid block tag on line 1: 'set'. Did you forget to register or load this tag? -
Unit testing Django Rest API with JWT Authorization fails
I have the following problem: whenever I run my unit tests to test my Django REST API, I get an 401 Unauthorized, even though I paste in the correct Token for the User object I created during the test. However, I expect the response to be a 200.. Here's the code: class TestWebApi(APITestCase): def setUp(self): self.factory = APIRequestFactory() self.client = Client() self.user = User.objects.create_user('testuser', None, '12345a') Employee.objects.create(name='Test', surname='Employee1', role="frontend", account=User.objects.get(username='testuser')) def test_api_employee(self): user = self.user token = json.loads(self.client.post('/api/get_jwt_token/', data={'username': 'testuser', 'password': '12345a'}).content)['token'] response = self.client.get('/api/v2/employees/', HTTP_Authorization="JWT {0}".format(token)) employees = Employee.objects.all() serializer = EmployeeSerializer(employees, many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) json_response = response.json() self.assertEqual(json_response, serializer.data) Thanks in advance! -
Upload a zip file to google cloud storage bucket using Python Api Client
I'm working on a project using Python(3.6) & Django(1.10) in which I need to upload a zip file to google cloud storage bucket which has been provided by the user through a form.Then I need to get this bucket URL (in the form of gs://) to create a google cloud function using api, how can I upload a zip file to storage bucket. Here's what I have tried: From views.py: if form.is_valid(): func_obj = form func_obj.user = request.user func_obj.project = form.cleaned_data['project'] func_obj.fname = form.cleaned_data['fname'] func_obj.fmemory = form.cleaned_data['fmemory'] func_obj.entryPoint = form.cleaned_data['entryPoint'] func_obj.sourceFile = form.cleaned_data['sourceFile'] func_obj.sc_github = form.cleaned_data['sc_github'] func_obj.sc_inline_index = form.cleaned_data['sc_inline_index'] func_obj.sc_inline_package = form.cleaned_data['sc_inline_package'] func_obj.bucket = form.cleaned_data['bucket'] func_obj.save() file_name = os.path.join(IGui.settings.BASE_DIR, 'media/archives/', func_obj.sourceFile.name) print(file_name) storage_client = storage.Client(project=func_obj.project) bucket = storage_client.get_bucket(func_obj.bucket) blob = storage.Blob(bucket=bucket, name=file_name) with open(func_obj.sourceFile.name, 'rb') as my_file: blob.upload_from_file(my_file, client=storage_client, ) print(blob) -
Show a logged in user their own information from a database model
I am relatively new to Django, and web development in general. Basically, I'm trying to build a website with two types of users: customers, and suppliers. Both the customers and suppliers have user accounts (containing a username, email, and password) created using Django's built-in 'from django.contrib.auth import login -forms.Form' and stored in the table 'auth_user' in my mySQL database. But, the suppliers can also create a more detailed profile (name, bio, images etc) which is created using a 'forms.ModelForm' called 'SupplierSignupForm' and stored in a separate table to 'auth_user', called 'home_suppliersignup'. What I want to happen is, when a supplier is logged in, they can click on their 'my profile' link in the header and be taken to their profile located in the 'home_suppliersignup' table in my database. Currently, I know how to call a logged in users ID from the table 'auth_user' using their session info, and then use that to link to their respective 'auth_user' profile: views.py user = request.user template <a href="{% url 'supplier_profile' id=user.id %}">My profile</a> urls.py url(r'^supplier-profile/(?P<id>[0-9]+)', supplier_profile, name="supplier_profile") But I don't know how to use this to pull up their information from another database table (i.e. home_suppliersignup). Any help would be much appreciated! -
From wsdl to services in python
I need to query a SOAP service wrote in Java from a webapplication developed with Django. To build a SOAP client I use the Zeep library but my problem is to understand which services expose the SOAP service, which parameter need to passe to the Zeep client. Is there a python library able to parse a wsdl file and build, as example, an sdk to query the SOAP services or any ideas? -
I am using the python django, and i wanted to know to get use thingsboard dashboard, and database as postgresql
I am using the Python3, Django and database as Postgresql, and I wanted to use the Thingsboard dashboard in my web application. can anyone pls guide me how can I use this -
Tensor Flow custom re-training model with new Images as they are uploaded
I have a Django web app hosted on Heroku and am pretty ok using pretrained model like inception and mobilenet to classify images with tensorflow. My question here is how do I use Tensrflow to retrain a model to learn about new images as they get uploaded on my Django app, so that when I search the app using image it can detect if similar image exist within the app. (Similar to Google search by images) -
Frames, maps, forms, textboxes all together with leaflet : HowTo
I al new to web development. I have not done this before. I have a requirnment to build a front end (client for a server) that looks like in the image below. I am using django to build the framework when the user clicks on the provided link [maps] below webframe work should be displayed in the browser [Forms] user should be able to able to upload data after filling the field and then load [text] response should be displayed eg : Success etc Currently : I have sucessfully tested the Forms and it is working as expected. I donot know how I can include all these three together Any suggestions are welcome -
How to set up session in vuejs django after successful login?
If login is successful i need to redirect to a login success page and I need to include a session in that.. How can it be possible. I am using html with vue js for front end and back end is django. This is my vue js script for login. <script> logBox = new Vue({ el: "#logBox", data: { email : '', password: '', response: { authentication : '', } }, methods: { handelSubmit: function(e) { var vm = this; data = {}; data['email'] = this.email; data['password'] = this.password; $.ajax({ url: '/login/', data: data, type: "POST", dataType: 'json', success: function(e) { if(e.status){ alert("Login Success"); // Redirect the user window.location.href = "/loginsuccess/"; } else { vm.response = e; alert("failed to login!"); } } }); return false; } }, }); </script> So, how can I include session in login successpage.. This is the first time I am doing a work.. Please help me .. -
Cannot update the user.last_login field
I am using Django 1.11 and User model from django.contrib.auth. Here's my code: from django.contrib.auth.models import User from django.utils import timezone u = User.objects.create_user('user1') print(u.last_login) # prints old date u.last_login = timezone.now() u.save() u.refresh_from_db() # just in case print(u.last_login) # prints old date Why does the last_login field not get updated?