Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Permission denied error with PostgreSQL and Django. Giving rights to PostgreSQL user admin
I have Django app with PostgreSQL. The app has those environment variables: DATABASE_HOST=localhost DATABASE_USER=admin DATABASE_PASSWORD=admin Here is psql output: postgres=# CREATE USER admin WITH PASSWORD 'admin123'; ERROR: role "admin" already exists postgres=# select * from USER; current_user -------------- postgres (1 row) postgres=# GRANT ALL privileges ON DATABASE my_db to admin; GRANT When I try to take something from db I get ProgrammingError: permission denied for relation app_rangeslot. So, the questions: 1) If user admin have all rights, why I get permission denied error? 2) If user admin is created, why I cannot see it? -
Using uploaded image in frontend
I have a profile database for users in which I save their profile image. I am using DRF to create API's for this. Now when I save the profile data, it return JSON as: { "branch": "CSE", "year": 2014, "image": "static/profile_images/abhishek.jpg" } this data gets saved in database and even the image get uploaded to the desired folder. Now I want to access this image in the frontend(I am creating an android app in Ionic), so that the profile pic is viewed in the app's dashboard. How do I do it? At present simply going to the saved path is not working. -
How can I convert a selected name into a user ID in an HTML input form and populate the input field with it?
I'm creating a web application in Django. The premise: a user is attempting to create something new which is tied to a patient. Each patient in my database has an associated first name, last name, birth date, and MRN (an ID.) The user would be provided with a table/list of users to choose from. When the user clicks a name or a button next to a name, I want to populate the the "Patient" input field with the patient's MRN - not their name. How would I fill an HTML input field with the patient's MRN instead of their name? (Or, more broadly, how can I translate a selection to an input value and populate an input field with that value?) -
django - This field is required
I have two forms in my template and what I want to do is add the newly added model to an attribute of another model. The models are Customer and Order respectively. (Once I add a customer, i want to add an order with its customer, the newly added) Here is my customer views def add_customer(request): form = CustomerForm(request.POST or None) customers = Customer.objects.all() if form.is_valid(): customer = form.save(commit=False) customer.save() context = { 'form': OrderForm() } messages.success(request, "Customer added successfully!") return render(request, 'orders/add_order.html', context) context = {'form': form} return render(request, 'core/add_customer.html', context) Here is my order views def add_order(request): form = OrderForm(request.POST or None) orders = Order.objects.all() if form.is_valid(): order = form.save(commit=False) order.save() messages.success(request, "Order placed") return render(request, 'orders/index.html', {'orders': orders}) return render(request, 'orders/add_order.html', {'form': form}) Here is my template <a href="{% url 'core:add-customer' %}"> <p><em>Click this to add a new customer</em></p> </a> <form method="post"> {% csrf_token %} {% include 'core/form-template.html' %} <div align="center"> <button class="btn btn-success"> Submit </button> </div> </form> However, the order can't be added since it throws the error (This field is required) -
Iteration error in Django
I'm still a student so sorry if I make stupid mistakes and the code looks a lil ugly, I still need to clean it up. I'm busy with a project where we have to make an online webshop. The database is already set-up and so is the email-system, but whenever I try to implement the ordered data (items that got added to your ShoppingCart), I'm unable to specify the items in an email. A heads up, I have written a lot of info down below to make the error as clear as possible. This is the error I got: TypeError at /checkout/ 'OrderDetails' object is not iterable Error during template rendering 16 {% for createOrder in order %} This is the email html: <!--This order email--> {% load custom_tags %} {% load shoppingcart_tags %} {% block extrastyle %} <style type="text/css"> body.login {background-color: palegreen;} </style> {% endblock %} {% autoescape off %} <p>Beste klant,</p> <p></p> <p>U heeft zojuist een bestelling geplaatst op onze website voor de volgende producten:</p> {% block purchases %} {% for createOrder in order %} <h1>{{ orderDetails.orderNum }}</h1> <h1>{{ orderDetails.productNum }}</h1> <h1>{{ orderDetails.amount }}</h1> {% endfor %} {% endblock %} <p>Wij streven ernaar uw bestelling binnen 2 dagen … -
How to show shamsi date in django?
I'm trying to make django's default 'DateTimeField' to show Shamsi (Persian) calendar, but I have no idea of how to do it. Is there any way to make this type of field use Shamsi completely or use it as it is and just converting to Shamsi when showing on the template? -
How to distinguish between two forms in class based View
I have two form from which i got file input in single view. So my aim is to seprate files from one form from files from another. I would like to access somehow form attributes, preferably form fields attributes and based on this to make some processing in post view. Like: <form> <input type="file" id="test_file" name="file"> </form> class UploadedFileForm(forms.ModelForm): ... def post(self, request): form = UploadedFileForm(self.request.POST, self.request.FILES) and here i want to check if the file source form. In my case if, for instance, file is from the field with id test_file then do some processing, or else do another one. Currently i handle this situation having two different views one for each form, but want to combine it in one. -
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)