Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can you host a Django app and Strapi API on the same server using NGINX?
Is it possible to have... A static file is served from => 0.0.0.0 A Django application served at => 0.0.0.0/django A Strapi API at => 0.0.0.0/strapi ... with NGINX? I've tried server { listen 80; server_name 0.0.0.0; root /var/www/html; index index.html; location /static/ { root /home/user/app/static/; } location /django { proxy_pass http://0.0.0.1:8000; } location /strapi { proxy_pass http://0.0.0.1:1337; } } # I have my real IP not 0.0.0.0 in the file But / returns my static /django returns a django 404 page /strapi returns an html with 'not found' Is the question I'm asking "Can an NGINX location alias a port?" -
Django ModelChoiceField how to save not just the string representation but also the other database(model) row values
I have 2 models. The customer model and the customerpricing model. class Customer(models.Model): priceline= models.IntegerField() billto=models.IntegerField(null=False,default=False,db_column="billto") customername=models.CharField(max_length=500) def __str__(self): return self.customername class Meta: db_table='customer' class Customerpricing(models.Model): rep=models.CharField(max_length=10) billto=models.ForeignKey(Customer, on_delete=models.CASCADE, null=False,db_column="billto") customernm=models.CharField(max_length=60) specialterms=models.CharField(max_length=100) start=models.DateField(default=timezone.now) Here is my form. class CustomerpricingForm(forms.ModelForm): customernm=forms.ModelChoiceField(queryset=Customer.objects.all()) priceline=forms.ModelChoiceField(queryset=priceline.objects.all()) billto=Customer.objects.all() class Meta: model = Customerpricing fields = ['customernm','billto', 'priceline','rep','specialterms'] widgets= { 'rep': forms.TextInput(attrs={ 'class': 'form-control' }), 'start': forms.SelectDateWidget(empty_label=("Choose year", "choose Month", "choose day" ),attrs={ 'class': 'form-control' }), 'specialterms': forms.TextInput(attrs={ 'class': 'form-control' }), } Here's my view. def addnew(request): if request.method == "POST": form = CustomerpricingForm(request.POST) if form.is_valid(): try: form.save() return redirect('/customerpricingfile') except Exception as e: #print (e.message, e.args) print (form.errors) print(e) else: messages.error(request,"Error") else: form = CustomerpricingForm() What I want to do seems so easy. When the user selects their value from the ModelChoiceField named customernm I want to also save that model's (Customer model) other database rows aka model fields which are billto and shipto with the Customerpricingform. How can I do this? I've spent far too much time on this and your help would be greatly appreciated. -
How to properly use code coverage with django redis queue?
I'm creating a Django rest API that runs async tasks with django-rq. I run my unit tests in sync mode, just like the django-rq docs indicates. The problem is that my code coverage is low because the code that the async tasks run is not being covered. How can I fix this? -
How to force a value on created_at and updated_at in Django
I have a model in Django that have the created_at and updated_at fields. I implement certain functionality that depends on those dates, so I want to write some unit tests, but when I create the objects, they always save both fields with the current date. I assume (I looked up but I did not find any information) that Django in some way does not allow the client to updated those fields, and it does it by itself. There is any way to overwrite this behavior in a test? -
Django model save method don't work with celery
I'm working in a project using drf, django channels and celery i want to push notification on created to subscribed channel and it works well but when using celery the model create method doesn't excute save method or any signal that's my taks @shared_task() def send_notification_to_all(data, users=None): if not users: users = User.objects.values_list('id', flat=True) for user in users: Notification.objects.using('notifications').create(user_id=user, title=data['title'], message=data['message'], url=data['url']) and excute it using send_notification_to_all.delay(data) and that's my consumer class LiveNotificationConsumer(ListModelMixin, GenericAsyncAPIConsumer): serializer_class = NotificationSerializer permission_classes = (permissions.IsAuthenticated,) async def accept(self, **kwargs): await super().accept(** kwargs) await self.model_change.subscribe() @model_observer(Notification) async def model_change(self, message, observer=None, action=None, **kwargs): if message['user'] == self.scope['user'].id: await self.send_json(message) @model_change.serializer def model_serialize(self, instance, action, **kwargs): return NotificationSerializer(instance).data def get_queryset(self, *args, **kwargs): user = self.scope['user'] return Notification.objects.filter(user=user).using('notifications') -
call_command migrate problem python django
I'm trying to add dynamically app and do makemigrations and migration, but it doesn't show print ('2'). Reboots and asks to apply the migration manually some.py settings.INSTALLED_APPS += ('tests.apps.OrderConfig',) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False apps.clear_cache() apps.populate(settings.INSTALLED_APPS) management.call_command('makemigrations','tests', interactive=False) print('>>WORK1') management.call_command('migrate', app_module.MODULE_NAME, interactive=False, skip_checks=True) print('>>WORK2') #this don't show Terminal: No changes detected in app 'orders' >>WORK1 Operations to perform: Apply all migrations: orders Running migrations: [11/Feb/2021 02:07:22] "GET /plugins/repository/12/ HTTP/1.1" 200 14459 C:\PythonProject\ServiceCRM3\plugins\settings_plugin.py changed, reloading. Applying orders.0001_initial...Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): orders. Run 'python manage.py migrate' to apply them. February 11, 2021 - 02:07:24 Django version 3.1.4, using settings 'ServiceCRM3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. -
My django app breaks when installing geo django: libpoppler not found
I developing an app but it doesn't compile after installing django-leaflet and django.contrib.gis. Everythin works perfectly if I don't use django.gis nor django-leaflet, and it appeared after I struggled a lot installing the gdal library. I thought it could be compatibility with Python, because I'm using latest version, but downgrading didn't work form me (should I downgrade more?) Any suggestion? The error I see: > File "/home/horacio/anaconda3/envs/epec/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/horacio/anaconda3/envs/epec/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/horacio/anaconda3/envs/epec/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from … -
Django How to Fix Multiple Server Issues
I have this model, and it has been causing me a lot of trouble here are the models: class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=20) text = models.TextField(default='') created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) class Videos(models.Model): title = models.CharField(max_length=100) video = models.FileField(upload_to='videos/') def __str__(self): return self.title First, when I try to migrate anything I get: django.db.utils.OperationalError: table "blog_videos" already exists This is for model Videos. This error happened after I deleted a few migration files. Then when I try to add to the model "Comment", I get this: django.db.utils.IntegrityError: NOT NULL constraint failed: blog_comment.author_id_id This happened after I added this to comment model: author_id = models.ForeignKey(User, on_delete=models.CASCADE, default='') I then deleted this model and have this problem now. I am unable to fix this because I can't migrate anything becuase of the issue above. Please help me. I am using python 3.8 and django 3.1.5. I am fine deleting all data (It's all worthless at the moment, its just dummy data. Cheers. -
Override vs extend Django's models.Manager to handle deleted objects (best practice)
There is a requirement, that nothing should be deleted from database So, obviously, all models should be inherited from something like this: class BaseModel(models.Model): is_deleted = models.BooleanField(default=False) But, it is not obvious how to make QuerySets handle is_deleted the best way I can imagine two options: 1) Override BaseModel's Manage's ._get_query_set() method So, both will return only active objects (marked as is_deleted=False): Article.objects.all() Article.objects.filter(id__in=[1, 2]) Even .get(...) will raise 404 if is_deleted=True: Article.objects.get(id=1) Also, extend with additional method, to actually access is_deleted=True: Article.objects.deleted(id=1) 2) Second option is to extend BaseModel with additional second Manager, let's say - actual So, all three will exclude objects with is_deleted=True: Article.actual.all() Article.actual.filter(id__in=[1, 2]) Article.actual.get(id=1) Regular .objects stands with native behaviour: Article.objects.all() Article.objects.filter(id__in=[1, 2]) Article.objects.get(id=1) --- Maybe there are another good options? Is there a best practice? Big thx for advices! -
Working with one-to=many relationships (Django)
Okay....previously I wrote up a simple HTML-CSS-Javascript site. I then created an empty Django project and tried to put everything in that project. I created a real mess! So I am now writing everything up from scratch, working on the Django project first. I still am having problems with the database I set up. Here is my models.py: from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) description = models.TextField() source = models.CharField(max_length=200) source_site = models.CharField(max_length=200) def __str__(self): return self.title class Chapter(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='chapters') chtitle = models.CharField(max_length=100) chtitletext = models.CharField(max_length=200) chtext = models.TextField() def __str__(self): return self.chtitle And here is my views.py: from django.shortcuts import render, get_object_or_404 # Create your views here. from django.http import HttpResponse from .models import Book, Chapter def index(request): book_list = Book.objects.order_by('-id') output = ', '.join([b.title for b in book_list]) context = { 'book_list': book_list, } return render(request, 'sophia/index.html', context) def readBook(request, book_id): book = get_object_or_404(Book, pk=book_id) chapter_list = Chapter.objects.order_by('-id') context = {'book':book, 'chapter_list':chapter_list} return render(request, 'sophia/readbook.html', context) and here is my urls.py: from django.urls import path from . import views app_name = 'sophia' urlpatterns = [ path('', views.index, name='index'), path('<int:book_id>/', views.readBook, name='readbook'), ] and finally, my … -
How to call distinct() on django-pivot results
I've been using the django-pivot package to pivot complaint data, and it's an amazing package that generally works like a dream, but I noticed yesterday that when rows or columns are referring to ManyToMany fields, the results include some duplicates. When I'm constructing my own queries I just throw a distinct() on the end of it, is there a way to do something similar in django-pivot? -
Fetch failed loading: GET (with same path)
Got an issue with fetch in js + Django document.addEventListener("DOMContentLoaded", function () { // loading inbox as default load_mailbox("inbox"); console.log("again loaded INBOX____________") // when form is submitted, send email to other user document.querySelector("#compose-form").onsubmit = function () { fetch("/emails", { method: "POST", body: JSON.stringify({ recipients: document.querySelector("#compose-recipients").value, subject: document.querySelector("#compose-subject").value, body: document.querySelector("#compose-body").value, }), }) .then((response) => response.json()) .then((result) => { // Print result console.log(result); // after sending email, loading page with sent emails load_mailbox("sent"); }); }; }); Load mailbox will call other function, which will fetch the data for the page if (mailbox === "sent") { fetch_mail_by_folder("sent") } function fetch_mail_by_folder(folder) { fetch(`/emails/${folder}`) .then((response) => response.json()) .then((emails) => { emails.forEach(email => { // we fetching data for this page, and paste it into new div const element = document.createElement("div"); element.innerHTML = `some data`; element.addEventListener("click", function () { get_email(email.id, folder); }); const div = document.querySelector('#emails-view') // after that we add elements into existing html div div.append(element); }) }); } There is an error when mail was sent, (after concole.log with "email sent successfully") Fetch (fetch_mail_by_folder("sent")) was failed, (see screenshot). After, I tried to fetch the "sent" page with other function (just a simple button): document .querySelector("#sent") .addEventListener("click", () => load_mailbox("sent")); And it works well (see … -
How can I resolve an" ImportError: attempted relative import with no known parent package" issue in a Django project?
I'm working on Chapter 18 of Python Crash Course, and have started over from scratch twice already, all 53 steps. (A very educational process) The program was working fine until I tried to add the code for individual pages. Now, it won't run at all. It keeps saying that views aren't defined. I've tried every suggestion I've found for similar issues without success and double checked all the elements. Here is the code for my urls.py and views.py. Any information/suggestions on how to resolve this would be greatly appreciated. """Defines URL patterns for learning_logs""" from django.urls import path from . import views app_name = 'learning_logs' urlpatterns = [ path('topics/<int:topic_id>>/',views.topic,name = 'topic'), path('', views.index,name='index'), path('topics/',views.topics, name='topics'), ] from .models import Topic from django.shortcuts import render def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics':topics} return render(request,'learning_logs/topics.html',context) def index(request): return render(request,'learning_logs/index.html') def topic(request, topic_id): topic = Topic.objects.get(id= topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic,'entries':entries} return render(request, 'learning_logs/topic.html',context) -
Custom User Model in Django (email as username) - removing username safely if overriding AbstractUser
In my Django project, I would like users to register/login with their email address rather than a username, so I am planning to use a custom User model. Alongside this, I would like to define a couple of extra fields, and avoid extra database queries that would come with having a separate Profile model (with One-to-one relationship) for those. Other than these things, the default User functionality is exactly what I need, so rather than overriding AbstractBaseUser and having to rewrite code without confidence, I think overriding AbstractUser is the way to go. But I'm not sure, so that's where you come in! I have read many blog posts and threads on StackOverflow about the subject and there seems to be a common approach when using AbstractUser for this purpose (setting username = None) as follows: class CustomUserA(AbstractUser): username = None email = models.EmailField(unique=True) #necessary as it must now be unique extra_field = models.CharField(max_length=20) #for example USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] #necessary to empty this as 'email' is now USERNAME_FIELD objects = CustomUserManager() If this approach is used, a custom user manager (a subclass of BaseUserManager) needs to be set up, as it states here in the docs: You … -
Restrict access to a url unless user is coming from a certain page
For example the user won't be able to access page 'b' unless they are coming from page 'a' (they can't just paste the link and go to the page) -
Django Custom Use with Array of Another Model (Acting like a shopping cart)
Newbie to Django, Django rest_framework, and Djoser here. I am building the backend to what you can think of as a simple shopping app (think coffeeshop on this one). At the moment, I have a custom User model in one app called authapp and a Coffee model that lives in another app called apiapp. My goal is to allow User objects to have 0-infinity number of Coffee objects to act as their shopping cart and to have that data displayed in the users endpoint. Currently, I the User model looks like the following in models.py: from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): email = models.EmailField(verbose_name='email', max_length=255, unique=True) phone = models.CharField(null=True, max_length=255) coffees = models.ManyToManyField("apiapp.Coffee", verbose_name="coffee") REQUIRED_FIELDS = ['username', 'phone', 'first_name', 'last_name'] USERNAME_FIELD = 'email' def get_username(self): return self.email In serializers.py, I have: from djoser.serializers import UserCreateSerializer, UserSerializer from rest_framework import serializers from .models import * # Create your serializers here class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User field = ['id', 'email', 'username', 'password', 'first_name', 'last_name', 'phone', 'coffee'] In the admin dashboard, I currently see this when editing a User object (looks like you can select and deselect any / all of the … -
How to caught exception when django query is not performed due to no internet connection
I need to handle the scenario when django query can't reach the database due to no internet connection I tried with try-except block like this, but there's no exception caugth: try: return self.filter(my_model_id=<some int number>) except Exception as e: logger.error(e) How can i handle this? -
Django's set_exprity() in JsonResponse
I want to implement the "Remember me" functionality in my app. According to the docs and other questions the snippet request.session.set_expiry(0) is supposed to destroy the user session when the user closes the browser. My problem is that I can't find a way to add this to the JsonResponse in my login view. (the logic is not implemented yet) @require_POST def login_view(request): data = json.loads(request.body) email = data.get('email') password = data.get('password') if email is None or password is None: return JsonResponse({'detail': 'Please provide email and password.'}, status=400) user = authenticate(email=email, password=password) if user is None: return JsonResponse({'detail': 'Invalid credentials.'}, status=400) login(request, user) request.session.set_expiry(0) # does not work return JsonResponse({'detail': 'Successfully logged in.'}) -
Fastest way of performing multiple different calculations to every object in a queryset
I have these two models in my db: class Product(models.Model): name = models.CharField(max_length = 64) retailer = models.ForeignKey(Retailer, related_name = 'products', on_delete = models.CASCADE) brand = models.ForeignKey(Brand, related_name = 'products', on_delete = models.CASCADE, null = True, blank = True) enabled = models.BooleanField(default = True) def __str__(self): return self.name class Item(models.Model): product = models.ForeignKey(Product, related_name = 'p_items', on_delete = models.CASCADE) date = models.DateField(null = True, blank = True) user = models.ForeignKey(User, related_name = 'p_items', on_delete = models.CASCADE) net_price = models.PositiveIntegerField(blank = True) class Meta(): ordering = ['-date'] These models are in fact an alias to protect my employer. Keep this in mind if something doesn't really make sense - The db structure can't change. An Item represents one sale made by one of our users. The user needs to fill which type of product and when they did sell it, also by how much. However, the net_price chosen by the user isn't whats being charged at the client. There are two types of "added costs" later added to the net_price. One of them is deliberately chosen by the management, and it can be done days after the item has been added to the db. With this new model: (...) class GradeInflation(models.Model): … -
How to show linked objects in Django Admin View?
I have two models that are linked by a foreign key relationship: class A(models.Model): q1 = models.CharField(max_length=60) q2 = models.CharField(max_length=60) ... class B(models.Model): b = models.CharField(max_length=60) a = models.ForeignKey("A", on_delete=models.CASCADE) In my admin site I have the A model showing, and ideally would like to keep it that way. Is there a way for me to within the individual A instances show the B instances? I have only been able to find solutions for the reverse (showing a dropdown of A instances in the individual B instances). -
Ajax function not showing values in django
Bit of a problem. What i am trying to do is determine what date the user has selected from an option picker and print the value from a main.py function. So let me show my set up. first thing i have done is calculate the date and in my views.py: def index(request): #GOING TO PUT THE DATE DIFFERENCE CALCULATION HERE the_uploaded_excel_file = excel_upload.objects.order_by('-id').first() excel_file_path_from_db = the_uploaded_excel_file.my_excel_file.path print(excel_file_path_from_db) wb = load_workbook(excel_file_path_from_db) ws = wb["Sheet1"] df = pd.read_excel(excel_file_path_from_db, engine='openpyxl', sheet_name='Sheet1', skiprows=1) max_date_column = ws.max_column last_date_entered = ws.cell(row=1, column=max_date_column).value todays_date = datetime.datetime.now().date() Date_difference = pd.date_range(start= last_date_entered, end=todays_date, freq='D') print("last date entered was ") print(last_date_entered) print("todays date is ") print(todays_date) print("the days not done are") print(Date_difference) for date in Date_difference: print(date) return render(request, "index.html", { 'Date_difference': Date_difference }) Then I show the dates in my html: <h2> {% for daterange in Date_difference %} <h5>{{ daterange|date:"d M Y" }}</h5> {% endfor %} </h2> <select style="background-color: #ceedd0;" id="date_selector" onchange="what_date_has_been_picked()" name="filter_for"> {% for daterange in Date_difference %} <option value={{ daterange }}>{{ daterange|date:"d M Y" }}</option> {% endfor %} </select> this produces the following: now what I want to do is to be able to print this result in my main.py. so i set up an ajax function. … -
Django rest framework bulk post object
I want insert bulk json via django rest_framework however, I get a error message ; typed following line ; "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 2 column 6 (char 7)" my serializer.py file include following code block; class DrfSerializerV2(serializers.ModelSerializer): def __init__(self,*args,**kwargs): many=kwargs.pop('many',True) super(DrfSerializerV2,self).__init__(many=True,*args,**kwargs) class Meta: model = DrfData fields=['id','name','duration','rating','typ'] and my views.py file ; class ActionViewSet(viewsets.ModelViewSet): queryset = DrfData.objects.filter(typ="action") serializer_class = serializers.DrfSerializerV2 finally send json file via post; [ {'name':'m1','duration':120,'rating':4.7}, {'name':'m2','duration':120,'rating':4.5} ] however, I can't handle this error message. if I send sperataly, there is no problem. but, I can't resolve this error for bulk insert -
Can't run the server on Django TCP/IP conection?
I've already download all packages from django, whitenoise, etc, and the error continues. The cmd is running with the env and triyng to push i'm still on the same error I'm trying to run with a local host my server and that happend : Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Domestico\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check_migrations() File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\migrations\recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Domestico\Documents\GitHub\venv\lib\site-packages\psycopg2\__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, … -
How to pass variable from JavaScript to Django as part of url?
I'm building video player in Django. I use JavaScript to change prev/next video without refreshing the page by passing queryset from Django to JS. I need to add Like button to like currently played video. I can bring variable (ID) of current video but don't know how to include it in URL. This is how I'm bringing variable from JS to HTML. JavaScript: document.getElementById("video_controler").innerHTML=video_controler; Displaying it in HTML: Video controler: <a id="video_controler"></a> And in this form I want to replace hardcoded 'videos.0.pk' with 'video_controler' varibable: <form action="{% url 'like_post' videos.0.pk %}" method="POST"> {% csrf_token %} <button type="submit" name="post_id" value = '{{ videos.0.pk }}'>LIKE</button> </form> -
Passing values from Jquery with Ajax to Django views
I'm building an django app where user can organize notes in three columns "To Do", "Progress" and "Done" with drag and drop made with Jquery sortable. On screen load, notes are imported from database and put inside column matching their status values. After user changes, "save" button can be clicked. That's where i want to make an update to note's status in database. Here's HTML with Javascript {% load staticfiles %} {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="{% static '/css/bootstrap-5.0.0-beta1-dist/css/bootstrap.css' %}"> <script src="{% static 'css/bootstrap-5.0.0-beta1-dist/js/bootstrap.js' %}"></script> <script src="{% static 'js/jquery.js' %}"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="{% static 'js/jquery.bootstrap.modal.forms.js' %}"></script> </head> <body> <div id="con_p" class="col-sm-10 "> <div id="2"> <div class="row "> <div class="col text-center"><h3 class="display-5">TICKETS</h3></div> </div> </br></br> <div class="d-flex flex-row-reverse"> <button id="add-ticket" class="btn btn-primary btn-sm mx-2 " type="button" name="button">Add Ticket</button> <button id="save_tickets" class="btn btn-primary btn-sm " type="button" name="button">Save</button> </div> <div class="row border"> <div class ="col text-center"> <h4>To Do</h4> </div> <div class ="col text-center"> <h4>In Progress</h4> </div> <div class ="col text-center"> <h4>Done</h4> </div> </div> <div class="row"> <div class ="col border text-center" > <fieldset class="sortable"> <ol id="to_do" class="min-vh-100"> {% for i in ticket %} {% if i.status == "To Do" %} <li class="ticket" > …