Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Forms ( Template Doesn't Exist)
I'm working on Django model forms. I have created forms.py and added the following: from django import forms from .models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = [ 'title', 'description', 'price' ] And I have rendered this out in my views.py as it follows: def product_create_view(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() context = { 'form': form } return render(request, "products/product_create.html", context) and I have added urls.py: from django.contrib import admin from django.urls import path from pages.views import home_view , contact_view, about_view, social_view from products.views import product_detail_view, product_create_view urlpatterns = [ path('', home_view, name='home'), path('contact/', contact_view), path('admin/', admin.site.urls), path('about/', about_view), path('create/', product_create_view), path('product/', product_detail_view), path('social/', social_view), ] I have migrated everything and saved all files, but when I want to go to my create URL, I get this error: TemplateDoesNotExist at /create/ products/product_create.html Request Method: GET Request URL: http://127.0.0.1:8000/create/ Django Version: 3.2.4 Exception Type: TemplateDoesNotExist Exception Value: products/product_create.html Exception Location: C:\Users\Invoker\dev\trydjango\env\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\Invoker\dev\trydjango\env\Scripts\python.exe Python Version: 3.9.5 Python Path: ['C:\\Users\\Invoker\\dev\\trydjango\\src\\sadra', 'C:\\Program Files\\Python39\\python39.zip', 'C:\\Program Files\\Python39\\DLLs', 'C:\\Program Files\\Python39\\lib', 'C:\\Program Files\\Python39', 'C:\\Users\\Invoker\\dev\\trydjango\\env', 'C:\\Users\\Invoker\\dev\\trydjango\\env\\lib\\site-packages'] Server time: Wed, 23 Jun 2021 08:20:29 +0000 I have created a template as well: {% extends 'base.html' %} {% … -
Testing ASGI Django
We have been developing our REST API with Django and Django-rest for some time, and we are using Django-behave for the integration test which seems to use django.test runner to run the tests. However, we have switched from Django 2.2 to 3.2 to support async calls as we have many I/O calls to other components. We use gunicorn/uvicorn in production as our ASGI server and in production, everything seems to run nice and smoothly. But the behave tests which we use in our pipeline (Gitlab CI) started to fail - to be specific: views don't return response from time to time (all code gets executed just fine, and it just gets stuck on return Response() and the request timeouts for the client). We suspect that it's because behaves uses WSGI and not ASGI server to run our Django instance... so the question is... can we run behave with ASGI server, can we specify django.test runner, to run as ASGI? -
Django - Unable to test with two databases (postgres with gis extension and mongoDB (Djongo)
I'm not able to test two databases using Django's unittests. My databases configuration: DATABASES = { 'default': {}, 'postgres': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': "<name>", 'USER': "<user>", 'PASSWORD': "<pass>", 'HOST': "localhost", 'PORT': 5432, }, 'mongodb': { 'ENGINE': 'djongo', 'NAME': '<name>', 'ENFORCE_SCHEMA': True, } } my simple test: from django.test import TestCase class TestFormModel(TestCase): databases = {'postgres', 'mongodb'} def test_generate_persistent_data_indexes(self): assert True Error that I'm getting: AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type' I migrated both databases When I set postgres database as a default I'm getting: self = <django.db.backends.utils.CursorWrapper object at 0x1132de580> sql = 'SELECT "user_userdata"."id", "user_userdata"."user_profile", "user_userdata"."data", "user_userdata"."is_persistent" FROM "user_userdata" ORDER BY "user_userdata"."id" ASC', params = () ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0x112d96f70>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0x1132de580>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if params is None: return self.cursor.execute(sql) else: > return self.cursor.execute(sql, params) E django.db.utils.ProgrammingError: column user_userdata.data does not exist E LINE 1: ...r_userdata"."id", "user_userdata"."user_profile", "user_user... E ^ venv/lib/python3.8/site-packages/django/db/backends/utils.py:84: ProgrammingError My MongoDB model: class UserData(djongo_models.Model): id = djongo_models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_profile = djongo_models.UUIDField() data = djongo_models.JSONField(default={}) is_persistent = djongo_models.BooleanField(default=False) objects = djongo_models.DjongoManager() -
django form filter field queryset
How do I filter form's field queryset? After a little search I found that this way it's done. But I am getting an error here. class TbPeopleEntranceRightForm(forms.ModelForm): def __init__(self, user=None, *args, **kwargs): self.user = user super().__init__(*args, **kwargs) print(self.user) self.fields['user'].queryset = self.user class Meta: model = TbPeopleEntranceRight fields = ['user', 'area', 'room'] 'TbUser' object has no attribute 'all' -
You are trying to add a non-nullable field 'post' to stream without a default; we can't do that
I have models.py class Stream(models.Model): following = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stream_following') user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) date = models.DateTimeField() and function def add_post(sender, instance, *args, **kwargs): post = instance user = post.user followers = Follow.objects.all().filter(following=user) for follower in followers: stream = Stream(post=post, user=follower.follower, date=post.posted, following=user) stream.save() when I'm trying command py manage.py makemigrations I have an issue. You are trying to add a non-nullable field 'post' to stream without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: How to solve that? I put on default smth. However in function add_post I have added date=post.posted Thanks! -
Add a date picker to an already existing html form with Django
I have this template that i use for my Django app : <head> <meta charset="utf-8"> {% load static %} <link rel="stylesheet" href="{% static 'GenerateXL/form.css' %}"> <title> app title </title> </head> <body style="margin-top: 30px; margin-left: 30px;"> <h1 style="text-align:center"><span style="font-family:Georgia,serif"><span style="color:#006600"> django app </span></span></h1> <div class="wrapper"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="left"> <h3> import file <h3> <br> <input type="file" title="Upload SPORT" name="sport" style="border: 1px solid black; padding: 5px;" required="required"> <p> <input type="submit" value="Upload" name="sportt" style="border: 1px solid green; padding: 5px; border-radius: 2px; cursor: pointer;"> </p> **<!-- I would like to add a datepicker -->** </div> <div class="right"> <h3> Authenticate <h3> <div class="wrapper"> <div class="left"> <h5> Connect to proxy : <h5> <input type="text" title="Id_proxy" name="nnn" placeholder="nnn" style="border: 1px solid black; padding: 5px;" required="required"> <input type="password" title="Password_proxy" name="MDP_proxy" placeholder="mot de passe proxy" style="border: 1px solid black; padding: 5px;" required="required"> </div> <div class="right"> <h5> Connect SP : <h5> <input type="text" title="Id_Sharepoint" name="Login_sp" placeholder="Login Sharepoint" style="border: 1px solid black; padding: 5px;" required="required"> <input type="password" title="Password_sharepoint" name="MDP_sp" placeholder="mot de passe Sharepoint" style="border: 1px solid black; padding: 5px;" required="required"> </div> </div> </div> </form> </div> I want to add a date picker (actually two of them) in the specified location in the code, the dates would then … -
Given a particular id of a model object how to extract all details of its many to many field in Django?
my models.py class ChapterNames(models.Model): chapter_names = models.CharField(max_length=100, unique=True) def __str__(self): return self.chapter_names class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_ids = models.ManyToManyField(ChapterNames) chapter_details = models.TextField(default='') mentor = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) start_time = models.DateTimeField() end_time = models.DateTimeField(default=timezone.now()) doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True) isDraft = models.BooleanField(default=True) ratings = models.IntegerField(default=0) no_of_students_registered = models.IntegerField(default=0) no_of_students_attended = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_details Here chapter_names has been added as many to many field and i want to extract all details chapter names given a particular id of liveclass_details model my views.py def ChapterNames(request, id): liveclass_id = models.LiveClass_details.objects.filter(id=id) print(liveclass_id.values_list('chapter_names')) pass Here i amdoing something like this but is again giving me a queryset of chapter__ids please help me acheiving it , thanks in advance -
What should I choose Django or Node.js
I want to do Web Development and I have covered the frontend part and I'm going to the backend part. So, which language should I choose Django or Node.js? I already know the basics of Python and its libraries like Numpy, Pandas, Matplotlib. And if I will choose JavaScript I can be a MERN Stack developer but I don't know the "J" of javascript what should I do? And I want to do some data science and machine learning later. Help Me -
dynamic URL routing in Django with React
I am building an E-Commerce site. My requirement was I want to change the domain based on user visiting location(IP/any other media). ex: if a user visits my website from the USA the domain should be: domain.com/usa. or else a user visits my website from India my domain should be: domain.com/india. How can I implement this type of logic in Django? Technologies I am using: Django with React. -
How do I pass arguments to django forms?
I want to filter form fields querysets based on the user selected. Therefore, I want to pass user as argument to the form in order to filter fields querysets in the form's __init__ method. When I pass any arguments to the form I get the following error. class UserDetailView(LoginRequiredMixin, FormMixin, DetailView): model = TbUser form_class = TbPeopleEntranceRightForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) form = TbPeopleEntranceRightForm(user=self.object) context['form'] = form return context __init__() got an unexpected keyword argument 'user' how do I pass the argument correctly, and how I get it in the __init__ form method? -
Building wheel for cffi (setup.py) ... error while installing the packages from requirements.txt in django
I am trying to install a new Django project from git, I created a new virtual envt using python3(version: 3.8.5). When I try to install the required libraries in the requirements.txt, I get the following errors for cffi==1.11.5 package. Building wheels for collected packages: cffi Building wheel for cffi (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/jessica/Documents/FreelanceProjects/crowdbuy/env/bin/python3 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-71z3f0vy/cffi_136411f3ae2d49e4b889de52edc8d550/setup.py'"'"'; __file__='"'"'/tmp/pip-install-71z3f0vy/cffi_136411f3ae2d49e4b889de52edc8d550/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-1y2in5qm cwd: /tmp/pip-install-71z3f0vy/cffi_136411f3ae2d49e4b889de52edc8d550/ Complete output (49 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/cffi copying cffi/cffi_opcode.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/model.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/vengine_cpy.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/cparser.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/backend_ctypes.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/verifier.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/__init__.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/commontypes.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/vengine_gen.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/lock.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/setuptools_ext.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/api.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/ffiplatform.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/recompiler.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/error.py -> build/lib.linux-x86_64-3.8/cffi copying cffi/_cffi_include.h -> build/lib.linux-x86_64-3.8/cffi copying cffi/parse_c_type.h -> build/lib.linux-x86_64-3.8/cffi copying cffi/_embedding.h -> build/lib.linux-x86_64-3.8/cffi copying cffi/_cffi_errors.h -> build/lib.linux-x86_64-3.8/cffi running build_ext building '_cffi_backend' extension creating build/temp.linux-x86_64-3.8 creating build/temp.linux-x86_64-3.8/c x86_64-linux-gnu-gcc -pthread -Wno-unused-result … -
i am trying to learn django from django documentation but i am getting an error message in the first part of the documentation
Using the URLconf defined in blogs.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn’t match any of these. this is the error i am getting after i wrote the following code: for urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] for polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] 3.for polls/views.py """ from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") """ how i can i remove this error in vs code -
django get specific data from database
I have TbPeopleEntranceRights that is referencing TbUser TbRoom and TbArea. TbArea has multiple TbRooms. I wnat to get TbAreas and TbRooms that are not referenced by TbPeopleEntranceRights having a specific user. So I will get the rooms to the user for rooms for which user does not have permission yet. class TbArea(models.Model): id = models.CharField(primary_key=True, max_length=40) area_name = models.CharField(max_length=60, blank=True, null=True) class TbRoom(models.Model): id = models.CharField(primary_key=True, max_length=40) room_name = models.CharField(max_length=60, blank=True, null=True) area = models.ForeignKey( TbArea, on_delete=models.CASCADE, db_column='room_area_id') class TbPeopleEntranceRight(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) area = models.ForeignKey( TbArea, on_delete=models.CASCADE, db_column='room_area_id') room = models.ForeignKey( TbRoom, on_delete=models.CASCADE, db_column='room_id') user = models.ForeignKey( TbUser, on_delete=models.CASCADE, db_column='people_id') last_update_time = models.BigIntegerField(blank=True, null=True) class TbUser(AbstractBaseUser, PermissionsMixin): id = models.CharField(primary_key=True, max_length=32, default=uuid.uuid4) username = models.CharField( max_length=40, blank=True, null=True, unique=True, db_column='usname') password = models.CharField( max_length=255, blank=True, null=True, db_column='psword') -
__init__() got an unexpected keyword argument 'max_length' django charfield
I have a custom charfield and the init function tells me max_length is unexpected class field(CharField): description = _("CharField") def __init__(self, *args, **kwargs): kwargs['max_length'] = 10 super().__init__(*args, **kwargs) def formfield(self, **kwargs): defaults = {'form_class': fields.field} defaults.update(kwargs) return super().formfield(**defaults) -
Ajax returning whole page in django
I am trying to create a filter that will dynamically change page content based on choices. I am using AJAX for that but I am getting the whole page in return when I'm using dataType: 'HTML/text' and error when I'm using dataType: 'JSON' here's the code: # input[name='test'] is radio buttons, I have triggered event on radio button change $("input[name='test']").change(function(e){ e.preventDefault(); var query = $("input[name='test']:checked").val(); console.log(query) $.ajax({ url: "{% url 'testPage' %}", type: 'GET', dataType: "html", contentType: "application/json", data: {'query': query}, success: function(data){ console.log(data) }, error: function(data){ console.log("error") console.log(data) } }); }); using the above code I'm getting the whole page in return. what am I doing wrong in the above code? -
I wanna paginate in class view, but an error happened "Cannot filter a query once a slice has been taken."
I wanna implement pagination in ListView in Django. I can rewrite the view in function view, but I wanna know how to do pagination in class view for practice. What I wanna do here is to get data filtered by logged in user and display them with pagination by 20(doesn't matter the number). For example, if Alex is currently logging in, I wanna display Alex's data from the database paginated by 20. But, when I wrote the code below, I got an error "Cannot filter a query once a slice has been taken." So, now on the HTML file, there are all users' data like Alex's data, Bob's data, Lisa's data, and all other users' data. I tried to put paginate_by = 20 under the get_context_data function, but doesn't work. I even think I may not use paginate_by with get_context_data. class FoodList(LoginRequiredMixin, ListView): model = Food template_name = 'base/all_foods.html' context_object_name = 'foods' ordering = ['-created'] paginate_by = 20 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['color'] = 'red' context['foods'] = context['foods'].filter(user=self.request.user) Let me know if I need to put more info. Any advice is helpful and thank you for your help in advance!! -
Django - data inserted not reflecting in django administration table
I'm still new with django and I need some help regarding this. I have created a model for profile to store all the data inserted by user for their profile information. I already test on this using basic class model that only consist of first name, last name and email and the data is reflecting fine in the table but when I create another model with more data model somehow it doesn't work. I'm not sure where is the problem, any help on this will be appreciated. models.py class Profile(models.Model): first_name = models.CharField(max_length=300, null=True) last_name = models.CharField(max_length=300, null=True) birthday = models.DateField(null=True) GENDER_CHOICES = ( ('gender','Gender'), ('male','Male'), ('female', 'Female'), ) gender = models.CharField(max_length=10, null=True, choices=GENDER_CHOICES, default='gender') email = models.EmailField(max_length=30, null=True) phone = models.CharField(max_length=30, null=True) address = models.CharField(max_length=300, null=True) number = models.CharField(max_length=300, null=True) city = models.CharField(max_length=30, null=True) zipcode = models.CharField(max_length=10, null=True) position = models.CharField(max_length=30, null=True) ROLE_CHOICES = ( ('role','Role'), ('admin','Admin'), ('user', 'User'), ) role = models.CharField(max_length=10, null=True, choices=ROLE_CHOICES, default='role') def __str__(self): return self.first_name forms.py from .models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name', 'last_name', 'birthday', 'gender', 'email', 'phone', 'address', 'number', 'city', 'zipcode', 'position', 'role'] views.py from .forms import ProfileForm from .models import Profile def settings(request): form = … -
How to create an event in google calendar with any email Id using python
I wanted to create or modify an event in google calendar of any email Id. To achieve this I have created a project and generated & downloaded credentials json file in Google Cloud Platform. In python I'm using a module python-google-calendar-api. from calendar_api.calendar_api import google_calendar_api from oauth2client.service_account import ServiceAccountCredentials import httplib2 from googleapiclient.discovery import build def home(request): CLIENT_SECRET_FILE = 'calender_key.json' SCOPES = 'https://www.googleapis.com/auth/calendar' def build_service(): credentials = ServiceAccountCredentials.from_json_keyfile_name( CLIENT_SECRET_FILE, SCOPES ) http = credentials.authorize(httplib2.Http()) service = build('calendar', 'v3', http=http, cache_discovery=False) return service service = build_service() service.events().insert(calendarId='primary', body={ 'summary': 'Meet with someone', 'description': 'testing event', 'start': {'dateTime': '2021-06-23T10:00:00'}, 'end': {'dateTime': '2021-06-23T11:00:00'}, }).execute() return HttpResponse('event created') This code is executing successfully, eventhough event is not created in google calendar. Please any on suggest me the process of achieving this. Thanks in advance., -
Failing to render object data from Django API to Vuejs frontend
I've worked with Django 3.x for almost two years now and have just started using Vue js for about a week using the documentation to try and learn the intended way. So far my api access points work as intended whenever I DON'T use the Vue frontend to create objects. So, down to the code. I've tried to send the report via a prop from the Home.vue to the Detail.vue but for some reason it doesn't seem to load more than the noc_ticket. Just in case, the main.js for the router was made in haste when I was learning, I doubt its the issue, but you never know. Here is my monke code: Home.vue <template> <div class="home"> <div class="container"> <div class="container-fluid"> <h1 class="mt-4">Dashboard</h1> <ol class="breadcrumb mb-4"> <li class="breadcrumb-item active">Dashboard</li> </ol> <div class="row"> <div class="col-xl-3 col-md-6"> <div class="card bg-primary text-white mb-4"> <div class="card-body">Report Archive</div> <div class=" card-footer d-flex align-items-center justify-content-between " > <a class="small text-white stretched-link" href="" >View Details</a > <div class="small text-white"> <i class="fas fa-angle-right"></i> </div> </div> </div> </div> <div class="col-xl-3 col-md-6"> <div class="card bg-danger text-white mb-4"> <div class="card-body">Initial Report</div> <div class=" card-footer d-flex align-items-center justify-content-between " > <a class="small text-white stretched-link" href="" >View Details</a > <div class="small text-white"> <i … -
How to get logged in user details in viewset - django
class loksViewSet(viewsets.ModelViewSet): k='3' print(type(k)) queryset = loks.objects.all().filter(mp=k) serializer_class = loksSerializer In the above code i need to get the k value from first name of logged in user. How can i get that. -
bundle.js.map Unexpected token ':' in Django + Vue build
static files loads without a problem, but in the end I am having a bundle.js.map error which I don't understand why. Below vue.config.js module.exports = { publicPath: process.env.NODE_ENV === "production" ? "/static/" : "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, // uncomment before executing 'npm run build' css: { extract: { filename: '[name].css', chunkFilename: '[name].css', }, } }; It runs without a problem with npm run build then I pushing the builded dist folder to server. And do collectstatic Below django index.html in templates {% load static %} {% block style %} <link rel="stylesheet" type="text/css" href="{% static 'app.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'project.css' %}"> {% endblock %} {% block content %} <noscript> <strong>We're sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> {% endblock %} {% block js %} <script type="text/javascript" src="{% static 'bundle.js.map' %}></script> <script type="text/javascript" src="{% static 'bundle.js' %}"></script> {% endblock %} static files loads perfectly but bundle.js.map displays … -
How to query multiple models in Django using a variable as the models name
I have multiple models such as class PendingResults(models.Model): nct_id = models.CharField(max_length=10, blank=True, null=True) event = models.CharField(max_length=10, blank=True, null=True) event_date_description = models.CharField(max_length=10, blank=True, null=True) event_date = models.DateField(blank=True, null=True) ... or class ParticipantFlows(models.Model): nct_id = models.CharField(unique=True, max_length=10, blank=True, null=True) recruitment_details = models.TextField(blank=True, null=True) pre_assignment_details = models.TextField(blank=True, null=True) ... I would like to query the models using a variable as the model's name such as: model_name='mymodel' content = *modle_name*.objects.all() How can I achieve that? -
Django ajax dropdown with dynamic view button to access another page
I have created an ajax dropdown list and would like to insert a view button next to the second and third drop down. The view button on the second and third dropdown will bring me to another page that will show me more information on what was selected in the dropdown. I have created the respective display page for the 2 view buttons but now I do not know how I can link them together. The urls that I wrote did not work and gave me an error. I was trying to read the urls from the changes in the dropdown and use it with {% url for %}. view.html def home(request): return render(request,'website/main.html') def stackName(request, *args, **kwargs): selected_name = kwargs.get('name') stack_val = list(Metalstack.objects.filter(techname = selected_name).distinct().values()) return JsonResponse({'data': stack_val}) def techName(request, *args, **kwargs): selected_node = kwargs.get('node') name_val = list(Technology.objects.filter(node = selected_node).distinct().values()) return JsonResponse({'data': name_val}) def techNode(request): node_val = list(Technology.objects.values('node').distinct()) return JsonResponse({'data': node_val}) def stack(request,name): # name = kwargs.get('name') stackname = Metalstack.objects.filter(techname=name).values("techname","stackname","mstk_dm_id","mstk_restrict") total_stack = stackname.values("stackname").count() context = {'stackname': stackname,'total_stack': total_stack } return render(request, 'website/metalstack.html', context) def layers(request,stack): # stack = kwargs.get('stack') stackid = Metalstack.objects.filter(stackname = stack).values('id') layers = LayernameList.objects.filter(metalstack_id=stackid).values("metalstack_id","directions_id", "layers_id","pitch","space","width") context = {'stackid': stackid,'layers': layers} return render(request, 'website/layers.html', context) main.js const … -
is django-paypal safe to use it?
i'm using django-paypal package to implement my site payments settings.py INSTALLED_APPS = [ # other apps "paypal.standard.ipn", "payment", "...." ] .... PAYPAL_RECEIVER_EMAIL = "receiverEmail@gmail.com" PAYPAL_TEST = True views.py ... def payment_process(request): host = request.get_host() paypal_dict = { "business": settings.PAYPAL_RECEIVER_EMAIL, "amount": "99", "item_name": "python_book22", "invoice": "some invice name22", "currency_code": "USD", "notify_url": "http://{}{}".format(host, reverse("paypal-ipn")), "return_url": "http://{}{}".format(host, reverse("payment:done")), "cancel_return": "http://{}{}".format(host, reverse("payment:cancel")), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, "payment/payment_process.html", {"form": form}) @csrf_exempt def Done(request): return render(request, "payment/done.html") @csrf_exempt def Cancel(request): return render(request, "payment/cancel.html") I have no idea how safe is this, because in client side it renders a form like this <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick" id="id_cmd"> <input type="hidden" name="charset" value="utf-8" id="id_charset"> <input type="hidden" name="currency_code" value="USD" id="id_currency_code"> <input type="hidden" name="no_shipping" value="1" id="id_no_shipping"> <input type="hidden" name="business" value="reciverEmail@gmail.com" id="id_business"> <input type="hidden" name="amount" value="99" id="id_amount"> <input type="hidden" name="item_name" value="python_book22" id="id_item_name"> <input type="hidden" name="invoice" value="some invice name22" id="id_invoice"> <input type="hidden" name="notify_url" value="http://127.0.0.1:8000/paypal/" id="id_notify_url"> <input type="hidden" name="cancel_return" value="http://127.0.0.1:8000/payment/cancel/" id="id_cancel_return"> <input type="hidden" name="return" value="http://127.0.0.1:8000/payment/done/" id="id_return"> <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" name="submit" alt="Buy it Now"> </form> Anyone can easily change <input type="hidden" name="business" value="reciverEmail@gmail.com" id="id_business"> this and write other email, while system (can't/don't) detect it and the after the payment done to other account it returns the success url (however the … -
content function in django.http source code
I was looking into below codes from Django Official Docs from django.http import HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) Then I deep dive into the source code of django.http class HttpResponse(HttpResponseBase): """ An HTTP response class with a string as content. This content can be read, appended to, or replaced. """ streaming = False def __init__(self, content=b'', *args, **kwargs): super().__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content def __repr__(self): return '<%(cls)s status_code=%(status_code)d%(content_type)s>' % { 'cls': self.__class__.__name__, 'status_code': self.status_code, 'content_type': self._content_type_for_repr, } def serialize(self): """Full HTTP message, including headers, as a bytestring.""" return self.serialize_headers() + b'\r\n\r\n' + self.content __bytes__ = serialize @property def content(self): return b''.join(self._container) @content.setter def content(self, value): # Consume iterators upon assignment to allow repeated iteration. if ( hasattr(value, '__iter__') and not isinstance(value, (bytes, memoryview, str)) ): content = b''.join(self.make_bytes(chunk) for chunk in value) if hasattr(value, 'close'): try: value.close() except Exception: pass else: content = self.make_bytes(value) # Create a list of properly encoded bytestrings to support write(). self._container = [content] Q1: Shouldn't we use return HttpResponse(content=html) since content is a keyword argument defined in def __init__(self, content=b'', *args, **kwargs):? …