Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly pass django list/dictionary to javascript
I have a list of items and want to pass it to javascript array. Django version 2.2.3 In my views.py: my_list = ["one", "two"] context = { 'my_list ': json.dumps(my_list), } return render(request, 'my_template.html', context) my_template.html <script> var my_array = JSON.parse("{{ my_list|safe }}") document.write(my_array ) </script> According to the answers in most topics, my code is valid, but it doesn't display any data. Also tried: <script> var my_string = "{{my_list}}"; var my_array = my_string.split(','); document.write(my_array) </script> In this case when i want to display it i get [" one " -
How to Use CSV file in Django to Plot Graphs on web page with html
How to Generate Graphs from CSV file using Django on my HTML page. -
Django manytomanyfield with through model override through queryset
I have a project working on and it has one model that uses through for manytomany field. It worked as expected but I want to change the queryset through uses for some purpose. A.field.all() -> 1,2,3,4,5 will change to A.field.all() -> 1,2,5 when I do that. How can I change this behaviour? -
How to resolve "column {columnName} of relation {tableName} does not exist" for Django and Postgresql
I'm trying to insert data using a script into a postgresql database for Django, but unfortunately I can't get it to work. I've successfully migrated the datatables and manually generated data using the django backend. I've connected to the database using PgAdmin and confirmed that all the expected columns are there and the datatypes are correct. The django model Django model class Entries(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) quantity = models.IntegerField() typ = models.CharField(max_length=255) price = models.DecimalField(max_digits=20, decimal_places=2) def __str__(self): return self.name The psycopg2 insert line cursor.execute(f'INSERT INTO appname_entries (name, symbol, quantity, typ, price) VALUES (%s, %s, %s, %s, %s)', ('a01', 'AXB', 50, 'purchase', 50.25)) column "price" of relation "appname_entries" does not exist LINE 1: ...appname_entries (name, symbol, quantity, typ, price) ... -
create() takes 1 positional argument but 2 were given? Django
I was confused to why when I run this code it returns an error create() takes 1 positional argument but 2 were given if request.method == "POST": my_form = RawProductCreateForm(request.POST) if my_form.is_valid(): Product.objects.create(my_form.cleaned_data) but when I modify on the create method and add ** before passing the cleaned data it works! Product.objects.create(**my_form.cleaned_data) -
Django form widget does not display error
I have a model.py: class Author(models.Model): Author= models.CharField(max_length=500) ##field required and a form.py: class AuthorForm(forms.ModelForm): class Meta: model = Author widgets = { 'Author': TextInput(attrs={'class':'form-control', 'placeholder': 'Author...'}), in template I render whit: {{ form.Author }} Form works but if I try to save leave the field empty it not display any error. I try with {{ form.Author.errors }} but nothing appear! Any idea? TY -
How to make a Model and View that saves the data in DB for a guest user (not registered in User auth.model)
IS it possible to save the Form data from a Guest / Visitor in the DB? MY Idea is to display a form where a User is presented with the questions. The answers are unique for each user to I want to map the answers to the Users using a Foreign Key. Problem is that when I want to map it using ForeignKey it says that the answers come from a Null User. I ant my visiting users to access the website also. I have saved the Data in sessions and then used it I Do not want to use that approach Is there any way so that my users can access the website without saving the data in the website. Anyways, the flow of code deletes the answers data from DB once the work is done. It is not about getting the work done but exploring and getting knowledge. I can not do class AnsModel(model.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) ans=models.CharField(max_length=1024) What would be the Model and View for this? -
DRF/Multi-tenant - How to specify tenant host (domain) in unit tests?
Environment - Django, Rest Framework, Multi-tenant. In my unit tests, I'm trying to hit an endpoint in a tenant schema (not in Public). It is failing because the host is (for example) example.com instead of demo1.example.com. I've Googled (of course) but can't find how to specify the domain name part of a request. Other posts I've found say it's best to use "reverse" to get the URL instead of hard-coding it. Here's my test: def test_private_valid_authorization(self): self.demo1_tenant.activate() user = User.objects.get(username='test.admin@example.com') token, created = Token.objects.get_or_create(user=user) self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) response = self.client.get(reverse('clients:client-list')) self.assertEqual(response.status_code, 200, "Expected status code: 200; got %s." % response.status_code) Tenants (and their schemas) are created in the setUpTestData() method, so self.demo1_tenant.activate() simply connects to an already existing schema. Users are imported via fixtures, hence the "get" instead of "create_user". I get the following result: AssertionError: 403 != 200 : Expected status code: 200; got 403. Adding diagnostic displays to the code, I've narrowed it down to the process_request() method of django_tenants/middleware/main.py - specifically the hostname_from_request() method. If I put 'demo1.example.com' instead of using the return value from hostname_from_request (which is just 'example.com') my test succeeds. I hope someone can point me in the right direction here. -
How to run python scripts in one computer in LAN and send the output to other system in same LAN?
I have Django project in desktop destination and Apache24 installed in C drive. But I want to use this Django project on other system connected to Same LAN. I am using window 10. I have tried all the solution i found in SO as follows but nothing worked such as: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'localhost','192.168.1.8'] Making debug = true/false adding IP address in ALLOWED_HOSTS But nothing worked. Please help in making/give direction how i can make a connection to get access to Django project via access of LAN. Below is some structure. -
How to implement SSO (single-sign-on) with third party CAS (Central Authentication Service) for a Django-React application?
I'm setting up a Django-React application, with authentication through third party CAS. The process of CAS authentication looks like following: The web application redirects the user's browser to CAS's login URL with a "service" parameter, for instance https://cas.com/login?service=http://myapp.com. Once the user has been authenticated by CAS, CAS redirects the authenticated user back to the application, and it will append a parameter named "ticket" to the redirected URL. Its ticket value is the one-time identification of a "service ticket". For instance, http://myapp.com/?ticket=abcdefg. The application can then connect to the CAS "serviceValidate" endpoint to validate the one-time service ticket. For instance, https://cas.com/serviceValidate?service=http://myapp.com&ticket=abcdefg. In response, CAS shall return an XML containing the authenticated user id, for instance, <cas:serviceResponse> <cas:authenticationSuccess> <cas:user>johnd</cas:user> </cas:authenticationSuccess> </cas:serviceResponse> I've done some research and found it could be implemented in mainly two ways: Serve react as part of Django's static content. Standalone react single page application(SPA) through JWT. I've tried the first approach and it works, but the problem is that every time I want to test the authentication with React, I need to build the static file first and put them in Django, which is kind of slow. So I would like to try the second approach. My question … -
ImportError: Could not import 'rest_framework_simplejwt.authentication.JWTAuthentication'
I am trying to deploy a django app on GCP but when i try to make migrations it gives me this error: ImportError: Could not import 'rest_framework_simplejwt.authentication.JWTAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ModuleNotFoundError: No module named 'rest_framework_simplejwt'. Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] } SIMPLE_JWT = { 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=800), 'REFRESH_TOKEN_LIFETIME': timedelta(days=2), } OAUTH2_PROVIDER = { 'ACCESS_TOKEN_EXPIRE_SECONDS': 60 * 15, 'OAUTH_SINGLE_ACCESS_TOKEN': True, 'OAUTH_DELETE_EXPIRED': True } requirements.txt django-cors-headers pyjwt djangorestframework djangorestframework-jwt==1.11.0 What is it that I am missing ? -
Django-rest-framework validate JSONField still accept string
I'm currently trying to make a post request with only data field in models.py: class Filter(models.Model): class Meta: verbose_name_plural = "Filter" verbose_name = "Filter" db_table= "listing_filter" data = JSONField(default={}) user = models.ForeignKey('backend.user', on_delete=models.CASCADE) I have the following Serializer , i use JSONField following the drf document docs: class FilterSerializer(serializers.ModelSerializer): data = serializers.JSONField(required=True) user = serializers.CharField(required=False) class Meta: model = Filter fields = ('__all__') and use it in the APIView: class FilterView(APIView): def post(self, request): login_user = request.user received_json_data=json.loads(request.body) valid_ser = FilterSerializer(data=received_json_data) if valid_ser.is_valid(): post_data = received_json_data["data"] filter = Filter.objects.create(data=post_data, user=login_user) filter.save() return JsonResponse({'code':'200','data': filter.id}, status=200) else: return JsonResponse({'code':'400','errors':valid_ser.errors}, status=400) When i send the following data in body it worked and saved the object: { "data": { "http://example.org/about": { "http://purl.org/dc/terms/title": [ { "type": "literal", "value": "Anna's Homepage" } ] } } } But when i send data as a string(which is not a json) it still save, how do i prevent this ? { "data" : "abc" } -
Is it possible to use request object outside of views or other way to get logged user information
I want to operate some filter with user based. So I need logged user information in my admin.py or other file. But I don't understand how it possible to get current loged user id or other information. Any one help me? -
How do I nest the sub-categories right under the parent category during render
I want the sub-categories of each of my category objects rendered as a drop-down menu nested inside it's parent category. I am having a hard time implementing that. How does it work? This is my view function: def home(request): categories = Category.objects.all().order_by('-date_posted') #sub_categories = I don't know how context = { 'categories': categories, #'sub_categories': sub_categories } return render(request, 'blog/home.html', context) This is inside my template: {% for category in categories %} <div class="nav-item dropdown"> <a href="#" class="py-3 nav-link dropdown-toggle" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ category.name }} </a> <div class="dropdown-menu rounded-0"> {% for sub_category in sub_categories %} <a class="dropdown-item" href="#"> {{ sub_category.name }} </a> {% endfor %} </div> </div> {% endfor %} The categories are rendering fine, my problem is with the sub-categories. -
What are Django configurations?
I'm setting up Pycharm for the first time using Pycharm, and I'm trying to figure out what the configurations do. I have looked online at the documentation, but it seems to be more focused towards people who already know what configurations do. I'm assuming it is used to set up my localhost, however I'm unsure. Any help would be greatly appreciated! -
Could it possible to change the name of folder after creating django project?
The result that I want The problem When I try to change the default folder name which is same as the django project, here comes warning from pycharm: WSGI_APPLICATION='backend_ch1_sec1.wsgi.application' in the setting.py After changing 'backend_ch1_sec1.wsgi.application' to 'backend.wsgi.application' pycharm warns: Django settings for backend_ch1_sec1 project How the could it work in the picture one? -
TypeError TypeError: retrieve_nested_resource() missing 1 required positional argument: 'nested_id'
i am receiving the following TypeError error message: TypeError TypeError: retrieve_nested_resource() missing 1 required positional argument: 'nested_id' attempting to follow follow stripe documentation but newbie to python following outdated tutorial on Udemy but really want/ need this app to work. Any idea or solutions welcome! Thank you in advance from django.conf import settings from django.contrib.auth.decorators import login_required from django.shortcuts import render import stripe stripe.api_key = settings.STRIPE_SECRET_KEY # Create your views here. @login_required def checkout(request): publishkey = settings.STRIPE_PUBLISHABLE_KEY customer_id = request.user.userstripe.stripe_id if request.method == 'POST': token = request.POST['stripeToken'] # Create a charge: this will charge the customer's card # card = stripe.Customer.create_source( # customer_id, # source=token) customer = stripe.Customer.retrieve_source( customer_id, source=token ) stripe.Charge.create( amount=499, currency='usd', description='Example charge', customer=customer, # card=card, statement_descriptor='Custom descriptor', ) context = {'publishkey': publishkey} template = 'checkout.html' return render(request, template, context) -
Why is Primary Key not being created for new form in Django?
After I submit my form the body does not include a primary key. So when I try to save in form_valid() I receive an error: Cannot force an update in save() with no primary key. See views.py below; it breaks on that final .save(). The answer from this question was very helpful in framing the problem: my first form.save(commit=False) populates the data from the POST from the form. And when I print (self.request.body) I see the other values like gallons and customer. But I don't see index (which is the primary key). I could just create a primary key in views.py like so: self.object.index = WorkOrderTable.objects.all().order_by('index').first().index +1 Note the +1; I'm just finding the last record/work_order and adding one to that pk. But I get the feeling since 'index' is an Autofield it should already be doing this. And I may regret my work-around down the road. forms.py class WorkOrderForm(ModelForm): customer = ModelChoiceField(queryset=models.CustomersTable.objects.order_by('firstname','lastname')) class Meta: model = models.WorkOrderTable exclude = [] models.py class WorkOrderTable(BasicModelFields): index = models.AutoField(primary_key=True) customer = models.ForeignKey('CustomersTable', on_delete = models.CASCADE, related_name='wo_customers') median_gallons = computed_property.ComputedIntegerField(compute_from='_get_median_gallons') def _get_median_gallons(self): "Returns the work orders' customer's median gallons pumped." median_gallons = customer_median_gallons(self.customer) return median_gallons def get_absolute_url(self): return utils.detail_reverse(self) def __str__(self): label = … -
How to save two ModelForms in views with ManytoManyRelationship
How can i possibly save the two form below in django2.1. What i want to achieve is for the current user logged in to save the two forms and become the creator of the ChatGroupUser 'group' created automatically. Terminal error TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead. Based on the terminal error, I have tried to use create_user.user.add(request.user) the line before save() but django throw another error there. models.py class ChatGroup(models.Model): name = models.CharField(max_length=100, blank=True, null=True) group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='chat_group_admins') is_active = models.BooleanField(default=True, null=True) is_current = models.BooleanField(default=False, null=True) class ChatGroupUser(models.Model): user = models.ManyToManyField(User) chat_group = models.ForeignKey(ChatGroup, on_delete=models.CASCADE, related_name='chat_group_users') forms.py class ChatGroupForm(forms.ModelForm): class Meta: model = ChatGroup fields = ['name',] class ChatGroupUserForm(ModelForm): def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request self.fields['user'].queryset = self.fields['user'].queryset.filter(id=self.request.user.id) forms.ModelMultipleChoiceField(queryset=User.objects.all()) class Meta: model = ChatGroupUser fields = ['user'] views.py def create_group(request): if request.method == 'POST': form_group = ChatGroupForm(request.POST) form_user = ChatGroupUserForm(request, data=request.POST) if form_group.is_valid(): create_form = form_group.save(commit=False) create_form.group_admin = request.user create_form.save() create_group = form_user.save(commit=False) create_group.user= create_group create_group.save() return redirect('core:group_list') else: form_group = ChatGroupForm() form_user = ChatGroupUserForm(request) context = { 'form_group':form_group, 'form_user': form_user } return render(request, 'core/create-group.html', context) I really have tried different approaches and alternatives … -
Django 2.1 admin.py changeform_view method error with blank tables
In my admin.py i use changeform_view method for mantain some data into an add form after save Fo example one of my admin class is: class temp_mainAdmin(admin.ModelAdmin): form = TempMainForm list_filter = ('t_type',) list_display = ('descr', 't_type', 'notes', 'dt', 'active') def save_model(self, request, obj, form, change): obj.user = request.user super(temp_mainAdmin, self).save_model(request, obj, form, change) def changeform_view(self, request, obj_id, form_url, extra_context=None): try: l_mod = temp_main.objects.latest('id') extra_context = { 'lmod': l_mod, 'oId': obj_id } return super(temp_mainAdmin, self).changeform_view(request, obj_id,form_url, extra_context=extra_context) except Exception: pass admin.site.register(temp_main, temp_mainAdmin, ) The point is that if the temp_main table has at least one record all was done, but if instead the table is blank, when i try to open "add" form i receive the error DoesNotExist at /admin/backend/temp_main/add/ temp_add matching query does not exist. if i remove the entire changeform_view method from my class all was done except for the fact that after press "Save and add another" i don't have my fields already populated. Was wrong in my changeform_view method? p.s.: i use PostgreeSQL as backend db So many thanks in advance -
I need efficient Django ORM code to reduce query hitting
I am developing various statistical dashboards with Django, Python. A lot of filtered objects from each table and pass them to the template. But the result of the Debug-Toolbar is terrible. I need to change my code that is Hitting my database more efficiently. ** And this project is based on the models created by inspectDB on the server that is already developed. Django 2.2 Linux server, MariaDB Model class Consult(models.Model): consult_id = models.AutoField(primary_key=True) consult_type = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) booking_time = models.DateTimeField(blank=True, null=True) booking_time_unix = models.CharField(max_length=255, blank=True, null=True) dr_id = models.IntegerField(blank=True, null=True) uid = models.IntegerField(blank=True, null=True) session_id = models.CharField(max_length=255, blank=True, null=True) price = models.IntegerField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) consult_action = models.IntegerField(blank=True, null=True) cancel_reason = models.CharField(max_length=1024, blank=True, null=True) comment = models.CharField(max_length=255, blank=True, null=True) notify_cnt = models.IntegerField(blank=True, null=True) consult_begin_at = models.DateTimeField(blank=True, null=True) consult_end_at = models.DateTimeField(blank=True, null=True) img_url1 = models.CharField(max_length=512, blank=True, null=True) img_name1 = models.CharField(max_length=512, blank=True, null=True) img_url2 = models.CharField(max_length=512, blank=True, null=True) img_name2 = models.CharField(max_length=512, blank=True, null=True) img_url3 = models.CharField(max_length=512, blank=True, null=True) img_name3 = models.CharField(max_length=512, blank=True, null=True) class Meta: db_table = 'consult' View @login_required def index(request): today = datetime.date.today() weekday = today.weekday() last_monday = today - datetime.timedelta(days=weekday, weeks=1) last_sunday = today - datetime.timedelta(days=weekday) - datetime.timedelta(days=1) this_monday = today - … -
Erro ao rodar docker com python
https://screenshot.net/pt/ygjv6ix celeryworker_1 | File "/usr/local/bin/celery", line 10, in celeryworker_1 | sys.exit(main()) celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/main .py", line 16, in main celeryworker_1 | _main() celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/cele ry.py", line 322, in main celeryworker_1 | cmd.execute_from_commandline(argv) celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/cele ry.py", line 496, in execute_from_commandline celeryworker_1 | super(CeleryCommand, self).execute_from_commandline(argv)) ) celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/base .py", line 269, in execute_from_commandline celeryworker_1 | self.on_concurrency_setup() celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/cele ry.py", line 539, in on_concurrency_setup celeryworker_1 | self.load_extension_commands() celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/cele ry.py", line 543, in load_extension_commands celeryworker_1 | self.register_command).load() celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/bin/base .py", line 138, in load celeryworker_1 | for name, cls in imports.load_extension_classes(self.names pace): celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/celery/utils/im ports.py", line 156, in load_extension_classes celeryworker_1 | cls = symbol_by_name(class_name) celeryworker_1 | File "/usr/local/lib/python3.6/site-packages/kombu/utils/imp orts.py", line 57, in symbol_by_name celeryworker_1 | module = imp(module_name, package=package, **kwargs) celeryworker_1 | File "/usr/local/lib/python3.6/importlib/init.py", line 126, in import_module celeryworker_1 | return _bootstrap._gcd_import(name[level:], package, level ) celeryworker_1 | File "", line 994, in _gcd_impo rt celeryworker_1 | File "", line 971, in _find_and _load celeryworker_1 | File "", line 955, in _find_and _load_unlocked celeryworker_1 | File "", line 665, in _load_unl ocked celeryworker_1 | File "", line 678, in exec_module celeryworker_1 | File "", line 219, in _call_wit h_frames_removed … -
display a table within a table on a button click in angular 7
I am quite new to angular and web development and i am working with tables getting data from django PostgreSQL db to the front-end in form of tables. So, i need to have an details button in each row, clicking on which a new table is shown after that row. I am following the https://material.angular.io/components/table/examples of the expandable rows but i am not able to get desired results. I've created the buttons (expand_more mat icon)in the rows and a function(on-click event)which is getting the response from django view, what is left is to display the filtered data in details table. Is it possible to get the response in the description field as shown in the example below of angular material table, as the description is forming the expanded part of the table. Or i should follow a different approach altogether. I am very new to web development kindly ignore my mistakes. const ELEMENT_DATA: PeriodicElement[] = [ { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H', description: Hydrogen is a chemical element with symbol H and atomic number 1. With a standard atomic weight of 1.008, hydrogen is the lightest element on the periodic table. } -
How can I convert this String to an img .jpg from this Base64?
I'm working with django, and when I recived an encode image by Base64, I recive like this... enter image description here How can I decode and save on an image .jpg? I think the problem is that it start with {"imgB64":" and end with }' I been worked with Base64 before and doesn't have this begining and ending, What do you think? -
Django REST serializer queryset: access model via reverse foreign key?
I have a table that I would like to display the drawdown amounts for multiple pension funds for a proposed Investment. I have written a for loop over the 'Investment' instance in my table. However, I cannot seem to retrieve the amounts from this loop. I think that my queryset 'amountdrawdown' is incorrect as I'm trying to reverse lookup a foreign key (from the Investment model to DrawdownOnFund model). My models.py, simplified: class PensionFund(models.Model): name = models.CharField() class PensionFundDeposit(models.Model): PensionFund = models.ForeignKey(PensionFund) date = models.DateField() amount = models.DecimalField() undrawn = models.DecimalField() class Investment(models.Model): <---- Looping over this amount = models.DecimalField() date = models.DateField() class DrawdownOnFund(models.Model): Investment = models.ForeignKey(Investment) PensionFund = models.ForeignKey(PensionFund) date = models.DateField() amount = models.DecimalField() <---- I would like to retrieve this My serializer.py, simplified: class PensionFundSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'name'] class PensionFundDepositSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'fund','date','amount','undrawn', 'fundname'] class InvestmentSerializer(serializers.ModelSerializer): amountdrawdown = serializers.CharField(source='drawdown.amount') <---My attempt to write a query to retrieve the amount class Meta: fields = ['id', 'amount', 'date', 'amountdrawdown'] class DrawdownOnFundSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'call', 'commitment', 'date', 'amount', 'callid']