Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Vue - how to generate view for tag, or?
Im use vue and django with rest framework. In django models.py i have model field "tahs" this is charfield with tags separated by comma. exaple : django,forest,native I want to generate view for each tag example "django". OR try to search in filed tahs and return objects contains this tag[ex.django] this is my views.py class TagsResultsViewSet(viewsets.ModelViewSet): serializer_class = TagResultsViewSetSerializer queryset = CustomUserPass.objects.all() lookup_field = 'tahs' def get_queryset(self, *args, **kwargs): context = super().get_queryset(*args, **kwargs) tag = self.kwargs['tahs'] print('this is tags:', tag) context = self.queryset.filter(tahs__icontains=tag) print(context) return context serializer.py class TagResultsViewSetSerializer(serializers.ModelSerializer): tahs = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = CustomUserPass fields = '__all__' urls.py router = DefaultRouter() ... router.register('tags', TagsPassViewSet, basename='tags') router.register('tag', TagsResultsViewSet, basename='tag') urlpatterns = [ path('', include(router.urls)), ] vue file: TagView.vue <template> <div class="about"> <h1>You looking: {{tag}}</h1> <div v-for="result in results" :key="result.id"> <div>{{result.username}}</div> </div> </div> </template> <script> import axios from 'axios' export default { name: 'TagView', data() { return { results: [], errors: [], } }, props: { tag: { type: String, required: true, }, }, mounted() { this.getTagsResults() }, methods: { async getTagsResults() { this.$store.commit('setIsLoading', true) axios .get(`/api/v1/tag/${this.tag}`) .then(response => { this.results = response.data console.log(this.results) }) .catch(error => { console.log(error) }) this.$store.commit('setIsLoading', false) }, } } </script> actually when … -
How to fill in programmatically Django admin built-in autocomplete?
I would like to use JS in the Django admin to fill in programmatically a field that uses the built-in autocomplete option (NOT autocomplete-light). Let's say the field is called myfavfield. I can retrieve it with JS as follows $("#id_myfavfield"). If it is already filled in with some values, I can retrieve them with $("#id_myfavfield").val();, which, for example, returns ['1', '4'], I can also clear myfavfield with $("#id_myfavfield").empty();. However, I can't fill it in, for example, by running $("#id_myfavfield").val(['2', '4', '5']); or any other way that I have tried. Does anybody know how one can achieve that? -
Django - display image from database in edit form
I recorded a form that also contained an image. I would like that later in edit form to be able to visually see the previously uploaded image before changing it. I tried to display it in edit form via <img src = "{{curs.poster_curs.url}}" alt = "alternate text"> but in inspect it shows src = "unknown". How can I display the image already uploaded in edit form? I ask for a solution in this regard. Thank you -
Post a dcitionaries and lists along with a file using python resquests
I built an endpoint using Django-rest-framework which expects a file and some other information, including some dictionaries and lists. If I make the request using the browsable API from drf, none of the data is truncated and I also receive the file. However if I make a POST request through Python-requests library it doesn't work and the data received on the server side is received truncated as HTTP form-encoding is not capable of representing nested data structures. Does anyone know how can I reproduce the same behavior as the browsable API in the request through python requests library and avoid the truncation? Any help is greatly appreciated. -
django-tenants: redirecting to tenant url after login raises "NoReverseMatch: 'demo.localhost' is not a registered namespace"
I don't seem to find a way to solve an error happening at the user authentication. User needs to login at the public website level let's say localhost/login and when he/she is authenticated, I need the user to be redirected in the corresponding sub domain, for example demo.localhost. This is not working for me so far, even after checking some posts about the subject. Here is the views.py in customers.views where user log in: def login_view(request): if request.method == 'POST': form = AuthenticationForm(request,data=request.POST) print("form login view") if form.is_valid(): print("checkpoint") username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) user = form.get_user() schema_name = user.schema_name print(user) if user is not None: login(request, user) url = reverse(schema_name + '.localhost:8000/mydashboard/') print("url") return HttpResponseRedirect(url) else: print("not working") form = AuthenticationForm() context = { 'form': form, } return render(request, 'login.html', context) here is what urls in the core folder: urlpatterns = [ path('admin/', admin.site.urls), path('django_plotly_dash/', include('django_plotly_dash.urls')), path('mydashboard/', include('mydashboard.urls',namespace="mydashboard")), ] and I have added app_name = 'mydashboard' in mydashboard.urls Here is the traceback of the error I keep getting: Internal Server Error: /registration/loginUser Traceback (most recent call last): File "/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/urls/base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'demo.localhost' During handling of the above … -
Django ORM count or get precentage report
I have three models named Category, Account, and AccountCategory. I need to be able to generate a report wherein I can show the number of which each account was categorized. (e.g let's say I have 10 accounts, then I have three categories (A, B, C) I need to be able to show a piechart) Account has a many-to-many relationship with Category and AccountCategory is the junction table. Ideally, I need to have a result of Name Slug Percentage Num of Accounts A a 40% 4 B b 10% 1 C c 50% 5 I was able to get the raw Query but I still need to get the total number of accounts so I can get the percentage I'm struggling with how to do this on ORM. Basically, I did query the categories, joined account categories, and did a distinct on the account so it won't return the duplicates and then just total the result. For the ORM I think I need to filter the account categories to only return the latest account category per account and then total it but I can't seem to write the exact query using ORM I tried using the Subquery and Prefetch but no … -
Save a CSV in a Django FileField through a Django view
I am trying to save a whole CSV file uploaded from a form through a Django view. However, when I click the button to upload the CSV to the FileField I get 'str' object has no attribute 'file' I have seen some questions like this but I haven't managed to save the CSV in the model. What am I missing? The model: class wordsFile(models.Model): table = models.ForeignKey(WordsTable, on_delete=models.CASCADE) file = models.FileField(upload_to='media/%Y/%m/%d/', blank=True, null=True) def save(self, *args, **kwargs): self.file.save(self.file.name, self.file, save=False) views.py: def home(request): if request.method == 'POST': tp = request.POST.get('tp') if tp == "Upload CSV": if request.user.is_authenticated: upCSV = request.FILES.get('upload') wordsFile.save(upCSV.name, upCSV) #HERE is where I save the CSV to the FileField decoded_file = upCSV.read().decode('utf-8') io_string = io.StringIO(decoded_file) usr = User.objects.get(username=request.user) for idx,row in enumerate(csv.reader(io_string, delimiter=',')): if idx!=0: wt = WordsTable() wt.user = usr wt.word1 = row[0] wt.word2 = row[1] wt.word3 = row[2] wt.word4 = row[3] wt.word5 = row[4] wt.save() return redirect("home") The form: <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="upload" accept=".csv, .xlsx" value="Upload"> <br> <input type="submit" id="btnupload" class="button btn btn-primary" name="tp" value="Upload CSV"> </form> -
How to get query list that does not exist in another model in Django ORM?
I have three table: Table1 class Table1(models.Model): field1 = model.CharField(...) field2 = model.CharField(...) Table2 class Table2(models.Model): field1 = model.CharField(...) field2 = model.CharField(...) Table3 class Table3(models.Model): table1 = model.ForeignKey(Table1) table2 = model.ForeignKey(Table2) I want to get all Table1 data that does not exists in Table3 with a which also includes Table2. For Example: In Table1 I have three rows: rows1, rows2, rows3 In Table2 I have One rows: r1 In Table3 I have One rows: table1 = rows1 table2 = r1 I want to get rows2 and rows3 from Table1 when I am searching against Table2s r1 in Table3 I can get my expected result using this code: table3 = Table3.objects.filter(table2=Table2.objects.get(field=r1)).values_list('table1') queryset = Table1.objects.filter(~Q(id__in=table3 )) My Question now is there any better way to do this? Thanks -
how to send POST request with Postman using Django 4 ?? faced with : "detail": "CSRF Failed: CSRF token missing."
I faced with the problem. I write a simple test app. Now I want to use Postman to send a request. Everything is going ok if I send GET request I got all staff correctly. But if I try to send POST or PUT the error is "detail": "CSRF Failed: CSRF token missing." I logged in by admin. I took cookies from the session: sessionid and csrftoken but it did not work. In postman I tried copy CSRF token from headers. I used all this 3 tokens in fact. I tried usr each separately but all my attempts fold. What shall I do to send POST in Django 4 through Postman?????? I use here oauth with github but the error appears in both cases: login with admin or oauth. My code is below settings.py '''' """ Django settings for books project.`enter code here` Generated by 'django-admin startproject' using Django 4.0.3. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # … -
Error with Django import-export. | unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'
I'm trying to import data with import-export to my model on the admin page. When I do this I get the following error: unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta' I can trace the error back to my model. See below. It's in the 'def save' part. class MeetingDataLED(models.Model): led_date = models.DateField() led_meeting_date = models.DateField(blank=True) led_start_time = models.TimeField(blank=True) led_type_of_meeting = { ('GBS', 'Special one'), ('KO', 'Special two'), ('NM', 'Special three'), } led_meeting_type = models.CharField(max_length=3, choices=led_type_of_meeting) def save(self, *args, **kwargs): d = timedelta(days=MeetingSetting.objects.get(id=1).meeting_day_led) self.led_meeting_date = self.led_date + d self.led_start_time = MeetingSetting.objects.get(id=1).meeting_time_led super().save(*args, **kwargs) I've read in this post on stackoverlfow that it might have to do with the datetime instance (if I understand it correctly). I tried to adjust it, but got errors. But when I manually import 1 record on the admin page I do not get this error. So I don't now if I have to look for a solution in this direction. Also, in my resources.py file I do not ask to import the fields of led_meeting_date and led_start_time. See below for the admin and resource file. admin.py from import_export.admin import ImportExportModelAdmin from .resources import MeetingDataLedResource from django.contrib import admin from .models import MeetingDataLED, MeetingSetting admin.site.register(MeetingSetting) class … -
Get relative path in Django
I've created a map where I want to implement some kml files into it . If i harcode the url it works but im trying to pass it through a variable because Im dealing with many kml files in a for loop. Even though the url path im getting in console is right i dont get the result i need.Any idea how to fix that? view: def map(request): field_list = models.Field.objects.all() context = { "title": "Map", "field_list": field_list, } template = 'agriculture/map.html' return render(request, template, context) If i hardcode the url it goes like this : var polygon = omnivore.kml("{% static '../media/kml/user_admin/2022-04-07-2-Arnissa_cherry.kml' %}", ... ); I've tried doing it like this but even though the path Im getting is correct it seems django does not read the path(kml is the FileField in my model): map.html {% for field in field_list %} $(".search_area").append(new Option("{{field.friendly_name}}")); //friendly name var kmldir = "../media/" + "{{field.kml.name}}" console.log(kmldir) // ../media/kml/user_admin/2022-04-07-2-Arnissa_cherry.kml var polygon = omnivore.kml("{% static 'kmldir' %}", null, new L.GeoJSON(null, { //file url style: function() { return { color: 'red', transparent: true, opacity: 1, fillOpacity: 0.05 }} })); kml_arr.push([polygon, "{% static 'kmldir' %}"]); //file url {% endfor %} -
Django UserPassesTestMixin raises an unhandled exception
I'm using the UserPassesTestMixin on one of my views. It works fine, but every time a user fails the test (test_func returns False), an exception is raised in the server: Forbidden (Permission denied): /m/chats/8/ Traceback (most recent call last): ... .../django/contrib/auth/mixins.py", line 48, in handle_no_permission raise PermissionDenied(self.get_permission_denied_message()) django.core.exceptions.PermissionDenied: Sorry, you can't access this chat. [11/Apr/2022 11:53:04] "GET /m/chats/8/ HTTP/1.1" 403 135 Why doesn't it just show the last line? Like a 404 error when using a get_object_or_404 function. And also, it only uses the permission_denied_message attribute that I set for the exception message and it is not shown to the user. I know that I can override the handle_no_permission method, but is there a better way? Why does this even happen? get_object_or_404 raises an exception too; so how come that one is handled and this one is not?? -
TypeError: __str__ returned non-string (type tuple) , No sure where I got wrong
Customer ID is the foreign key in phones model, the idea is to populate PhonesForm with customers ID during Form creation on my views. Here my model.py class class Phones(models.Model): primaryimei = models.BigIntegerField(primary_key=True) customerid = models.ForeignKey(Customers,on_delete=models.CASCADE,max_length=200) def __str__(self): template = '{0.primaryimei}' return template.format(self) class Meta: ordering = ['status'] Here is my forms.py class class PhonesForm(forms.Form): customerid = forms.ModelChoiceField( queryset=Customer.objects.all().only('idno'),to_field_name="customerid") def label_from_instance(self): return str(self.customerid) class meta: model = Phones fields = '__all__' views.py file look like this class PhoneCreate(LoginRequiredMixin, CreateView): model = Phones form_class = PhonesForm() success_url = reverse_lazy('phones') def form_valid(self, form): form.instance.user = self.request.user return super(PhoneCreate, self).form_valid(form) ``` -
why do we get the below error in python django when the function is working postgresql [closed]
from rest_framework.response import Response from rest_framework.request import Request import json from django.db import connection from django.http import HttpResponse import psycopg2 from rest_framework.views import APIView from DBConnections.connections import executeGet, executePost, executeGetCustomer class getCoustomerDetails(APIView): def get(self, request): try: customerdata = 'public.fn_getcustomerudetails' customerno = request.data['Customer_No'] data = { "cust_id": customerno } result = executeGetCustomer(customerdata, data) return Response(result) except Exception as error: print("connection failed", error) finally: connection.close() print("connection closed") -
Element not hide when page is reloaded?
I use JQuery formset librairy to manage django inline formsets in my forms. I can add new formset using 'add' button and suppress formset using 'delete' buttons (django-inline-formet). But I have added "lock/unlock" functionality to my forms that disabled all fields when lock button (id = lock) is clicked. So, when form is "locked", fields are disabled and 'add' and 'delete' buttons must also be hidden. I manage to show/hide buttons on lock button click by user. But, when form is locked and page is reloaded by user (F5), 'add' and 'delete' buttons are displayed. It seems that code in function executed with document.ready is not fire. But if I 'manually execute' the code it works. What I have missed? function disabled_field(action) { $('#form').find(':input').not(':button,:hidden').each(function () { if (action == 'locked') { $(this).prop('disabled', true); } else { // only if user has write privilege on form if ($('#is_locked').data('add-privileges') === 'True') { $(this).prop('disabled', false); } } }); } //index of the last empty formset added with 'extra' inlineforsmet parameters var index = formsetnumber() - 1; /* lock a form */ $("body").on("click", '#lock', function (event) { // form is locked => hide inlineformset buttons if ($('#lock').attr('aria-pressed') == 'false') { // hide all formset … -
Reset Postgres' table sequence
I have a table in my application dockets for which I want to reset the sequence/pk I read that sqlsequencereset is used to do so but how do I do that for a single table and not the whole application I tried: python manage.py sqlsequencereset dockets and it produced the following: BEGIN; SELECT setval(pg_get_serial_sequence('"dockets_materialrequestflow"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "dockets_materialrequestflow"; SELECT setval(pg_get_serial_sequence('"dockets_materialrequest_flows"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "dockets_materialrequest_flows"; SELECT setval(pg_get_serial_sequence('"dockets_materialrequest"','id'), coalesce(max("id"), 1), max("id") IS NOT null) FROM "dockets_materialrequest"; COMMIT; How to proceed with only making changes in this particular table ? -
How to show files in django templates from database?
I am trying to display files in django templates. It's showing successfully from the database. I don't why it's not showing from templates. Here I am sharing my codes so far. #models.py class Answer(models.Model): description = models.TextField(blank=True, null=True) question_id = models.ForeignKey( Question, blank=False, on_delete=models.CASCADE) created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE) def __str__(self): return self.question_id.description class AnswerFile(models.Model): answer = models.ForeignKey( Answer, on_delete=models.CASCADE, related_name='files', null=True, blank=True) file = models.FileField( 'files', upload_to=path_and_rename, max_length=500, null=True, blank=True) def __str__(self): return str(self.answer) As I need multiple files so I have created another file model with foreign key #forms.py class AnswerForm(ModelForm): # question_id = forms.IntegerField(required=True) class Meta: model = Answer fields = ['description'] widgets = { 'description': forms.Textarea(attrs={"class": "form-control", "id": "exampleFormControlTextarea1", "rows": 5, "placeholder": "Add a reply"}), } class AnswerFileForm(AnswerForm): # extending Answerform file = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False) class Meta(AnswerForm.Meta): fields = AnswerForm.Meta.fields + ['file', ] def clean(self): cleaned_data = super(AnswerFileForm, self).clean() file = cleaned_data.get("file") description = cleaned_data.get("description") if not file and not description: raise forms.ValidationError("This is a required field.") return cleaned_data in forms I also try to stay clear and everything is working perfectly in views.py #views.py def question_details(request, pk): question = Question.objects.filter(id=pk).first() # answers list answers = Answer.objects.filter(question_id=pk).order_by('-id') # end answers list answerForm = AnswerFileForm() … -
ABSTRACT USER IN DJANGO ALL AUTH
I use the Abstract User in my registration using the all auth plugin instead of the contrib auth. Here is my code in forms.py: class CustomSignupForm(UserCreationForm): first_name = forms.CharField(max_length=30, label='First Name', widget=forms.TextInput(attrs={'placeholder': 'First Name','required':'required'})) last_name = forms.CharField(max_length=30, label='Last Name', widget=forms.TextInput(attrs={'placeholder': 'Last Name','required':'required'})) email = forms.EmailField(max_length=40, label='Email Address', widget=forms.TextInput(attrs={'placeholder':'Email Address','required':'required'})) class Meta: model = Registrations fields = ['first_name', 'last_name','email', 'user_type'] In my models.py: class Registrations(AbstractUser): usertype =[ ('Student', 'Student'), ('Staff', 'Staff') ] user_type = models.CharField(max_length=10,choices=usertype, blank=True, null=True) And here is the settings.py for my registration: ACCOUNT_FORMS = {'signup': 'libraryApp.forms.CustomSignupForm',} AUTH_USER_MODEL = 'libraryApp.Registrations' My very concern is that if I did it right using the abstract user with the Django All Auth because I have not seen tutorials regarding the use of abstract user in All Auth. -
Django CheckboxSelectMultiple widget rendering as radio with Crispy Forms
The field was already set as a ModelMultipleChoiceField with the CheckboxSelectMultiple widget. It displays normally when rendering the form with { form.as_p } on the template, but using CrispyForms changes the field to radio buttons. forms.py: class RequisitionModelForm(forms.ModelForm): class Meta: ... def __init__(self, *args, **kwargs): super(RequisitionModelForm, self).__init__(*args, **kwargs) self.fields['reqItems'] = forms.ModelMultipleChoiceField( queryset=Inventory.objects.all(), widget=forms.CheckboxSelectMultiple, ) Images: Using { forms.as_p } Using { forms|crispy } -
Django - prevent function to execute multiple times
DJANGO: The form data is downloading multiple times when I call the function multiple times by clicking the form "submit" button. How do I avoid multiple function calls? -
How to implement SQLAlchemy Postgres async driver in a Django project?
I have come across really weird behavior implementing SQLAlchemy in my Django project using the asynchronous Postgres driver. When I create a SQLAlchemy Session using a sessionmaker and then execute a simple SELECT statement within a session context manager, it generates the correct result the first time, but the proceeding attempts result in a RuntimeError exception stating "Task ... attached to a different loop". I looked up the error and it usually indicates that the session is persisted across multiple Django requests; however, in my code, I don't see how that is possible since I am creating the database session within the request using the sessionmaker and using the session context manager to close it. It gets weirder when reloading the page for a 3rd time using the session context manager approach because the RuntimeError changes to an InterfaceError stating "cannot perform operation: another operation is in progress". But when not using the context manager approach and creating the session manually and immediately after using it closing the session it only produces the RuntimeError exception even after the 2nd attempt. And it continues to get weird, when I do the second approach and do not await the session close, then … -
Gunicorn error: unrecognized arguments wsgi:application
I was trying to run Django in Nginx with the centos7 platform and also I am a newbie to it. After some time, I configured Django in Nginx with the help of the gunicorn service, But suddenly gunicorn service stopped with an unrecognized argument error (WSGI). enter image description here and my gunicorn service file: [Unit] Description=gunicorn daemon After=network.target [Service] User=user Group=nginx WorkingDirectory=/home/websitehg/websites/qatarfactory/qf_project ExecStart=/home/websitehg/websites/qatarfactory/qf_env/bin/gunicorn --workers 3 --reload true --bind unix:/home/websitehg/websites/qatarfactory/qf_project/qf_project.sock qf_project.wsgi:app [Install] WantedBy=multi-user.target I don't know what's wrong with it -
Error while install mysqlclient in Ubuntu 20.04 (WSL)
I'm using Ubuntu 20.04 in WSL, using conda virtual environment with python 3.8. I need to create a django project using MySql but I have a problem installing mysqlclient. Specifically, when I run: pip install mysqlclient I get the following error: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c1955ea90>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c19559670>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c195597c0>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c19559fa0>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c19559d90>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ ERROR: Could not find a version that satisfies the requirement mysqlclient==2.0.3 (from versions: none) … -
Migrate with database postgres fails
I aim to use postgres as default database for my django models. I am using docker-compose for the postgres and it seems to be up and running. version: '3.2' services: postgres: image: postgres:13.4 environment: POSTGRES_DB: backend_db POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - database-data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - postgres volumes: database-data: driver: local networks: postgres: driver: bridge However, when I am doing python3 manage.py migrate --database postgres I am getting the following: Operations to perform: Apply all migrations: admin, auth, authentication, authtoken, contenttypes, sessions, token_blacklist, vpp_optimization Running migrations: No migrations to apply. The problem is evident also when I am doing python3 manage.py runserver, where I am getting: Performing system checks... System check identified no issues (0 silenced). You have 31 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, authentication, authtoken, contenttypes, sessions, token_blacklist, vpp_optimization. Run 'python manage.py migrate' to apply them. April 11, 2022 - 05:32:10 Django version 3.1.7, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. It appears like the command python3 manage.py migrate --database postgres was not executed. Here is the settings.py part of the databases: DATABASES = { 'default': get_config( 'DATABASE_URL', 'sqlite:///' … -
How to pass response from one function to another function using ajax in django HTML?
I am trying to pass flight data which is in dictionary form and this is generated when user searches for flight and selects offer. What I want is the flight data should be passed in the url but user should not be able to read or modify it. Currently, I have passed flight data with {% for flight in response %} href="{% url 'get_detail' flight %}" {% endfor %} but it shows flight information in URL like 127.0.0.1/get_detail/{flightinfohere} . Is there any idea so that I can save this flight data for another function without passing in URL or I can hide this data or encode it? Any help would be appreciated. I tried to use AJAX, but I don't know how to pass the flight data in ajax as it is response of another views.py function.