Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set default font family for TinyMCE HTMLFiled()
I have set default font family "Sofia Sans" in tag for all templates in custom.css but when I paste a text with different font family in the Django Admin TinyMCE HTMLFiled() it overrides the default font. Is it posible to set default font family for the HTMLFiled() to be "Sofia Sans" no matter what the copied text font is? -
Django File Field : Audio File is not forwarding and rewinding
Well I don't even know that is it a django problem or not but can you please help me I have following field in my model. url = models.FileField(upload_to='music', null=True) I have no problem uploading the file. in my API - I'm getting the url of the file which I'm uploading but when I use it with javascript I'm not able to forward it or rewind it. even if directly open it from link in the browser I face the same problem. I guess it's not loading the meta data of the file first. but what should I do. -
Error while running '$ python manage.py collectstatic --noinput'. Even though I have set STATIC_ROOT and STATIC_FILES_DIRS
This is the error message I get: [2021-05-30T10:39:25.931285815Z] -----> $ python manage.py collectstatic --noinput [2021-05-30T10:39:26.203723037Z] Traceback (most recent call last): [2021-05-30T10:39:26.216276562Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 204, in fetch_command [2021-05-30T10:39:26.218321657Z] app_name = commands[subcommand] [2021-05-30T10:39:26.220104587Z] KeyError: 'collectstatic' [2021-05-30T10:39:26.224315059Z] During handling of the above exception, another exception occurred: [2021-05-30T10:39:26.226203429Z] Traceback (most recent call last): [2021-05-30T10:39:26.228807809Z] File "/workspace/manage.py", line 22, in <module> [2021-05-30T10:39:26.229778775Z] main() [2021-05-30T10:39:26.232093136Z] File "/workspace/manage.py", line 18, in main [2021-05-30T10:39:26.234133309Z] execute_from_command_line(sys.argv) [2021-05-30T10:39:26.239913239Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line [2021-05-30T10:39:26.241335162Z] utility.execute() [2021-05-30T10:39:26.246299500Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute [2021-05-30T10:39:26.249345439Z] self.fetch_command(subcommand).run_from_argv(self.argv) [2021-05-30T10:39:26.255367504Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 211, in fetch_command [2021-05-30T10:39:26.256776257Z] settings.INSTALLED_APPS [2021-05-30T10:39:26.263303743Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 57, in __getattr__ [2021-05-30T10:39:26.263988051Z] self._setup(name) [2021-05-30T10:39:26.269528994Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 44, in _setup [2021-05-30T10:39:26.271917901Z] self._wrapped = Settings(settings_module) [2021-05-30T10:39:26.276311739Z] File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 107, in __init__ [2021-05-30T10:39:26.279100519Z] mod = importlib.import_module(self.SETTINGS_MODULE) [2021-05-30T10:39:26.283428429Z] File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module [2021-05-30T10:39:26.286322693Z] return _bootstrap._gcd_import(name[level:], package, level) [2021-05-30T10:39:26.289320899Z] File "<frozen importlib._bootstrap>", line 1030, in _gcd_import [2021-05-30T10:39:26.292269277Z] File "<frozen importlib._bootstrap>", line 1007, in _find_and_load [2021-05-30T10:39:26.295544601Z] File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked [2021-05-30T10:39:26.298809741Z] File "<frozen importlib._bootstrap>", line 680, in _load_unlocked [2021-05-30T10:39:26.302382236Z] File "<frozen importlib._bootstrap_external>", line 790, in exec_module [2021-05-30T10:39:26.306047614Z] File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed [2021-05-30T10:39:26.313158573Z] File "/workspace/onlineminer/settings.py", line 5, in <module> [2021-05-30T10:39:26.313914416Z] import dj_database_url [2021-05-30T10:39:26.316344819Z] ModuleNotFoundError: No module … -
Django REST social login with dj_rest_auth does not authenticate the user
I am building an application. The client is built with Next.js and the backend with Django and Django REST framework. In this application, I would like to have social login. So far, my situation is this. I have set up the OAuth on the Google dashboard On the client, I am using next-auth - The client is successfully calling Google and getting an access token from there. On the client, the callback that runs after getting the access token from Google makes a call my Django API. I have set up the backend with dj_rest_auth - My settings are almost identical to the ones described here. Once the client callback runs and calls my Django API with the access token from Google, I successfully get on the client an access token and a refresh token. If it is a new user loggin in the first time, a new user is created in Djangos DB const response = await fetch(`${djangoAPIurl}/api/social/login/google/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ access_token: accessToken, id_token: idToken }) }); const data = await response.json(); const { access_token, refresh_token } = data; Both access_token and refresh_token are defined and appear to be valid tokens. So … -
Chart js space above bar graph
I generate graph depending on the value from my calculations. Problem is, I don't know how to set up 'margins', how to define where to put data labels. Datalables definition: datalabels: { anchor: 'end', align: 'start', offset: 5, Problem is, when a certain month value is 0, it's written over the labels on the bottom. Easy way to fix this would be to define a space about each column, so that it can that text can never go 'off screen' and define align: 'end'. Case 2: -
Module does not define class error while replacing default admin site
I'm following a tutorial for the Django admin app and I'm trying a step in which the default admin site is replaced with a custom subclass of AdminSite from django.contrib.admin. My project structure is: MyAdminTutorial |- MyAdminTutorial |- MyActualApp |- JustAUserApp MyActualApp.admin.py: class MyAdminSite(admin.AdminSite): pass admin.site = MyAdminSite() admin.site.register(User, UserAdmin) admin.site.register(Group, GroupAdmin) MyActualApp.apps.py: from django.contrib.admin.apps import AdminConfig class MyAdminConfig(AdminConfig): default_site = 'MyActualApp.admin.MyAdminSite' MyAdminTutorial.settings.py INSTALLED_APPS = [ "MyActualApp.apps.MyAdminConfig", # 'django.contrib.admin', .... "JustAUserApp", ] If I try to run the development server I get this error: ImportError: Module "MyActualApp.admin" does not define a "MyAdminSite" attribute/class Messing around in the debugger i found the error stems from a call to getattr() inside import_string() in django.utils.module_loading.py. For the current call to import_string() the module name and path are set to MyActualApp.admin, getting the current location in the debug console yields the main MyActualApp directory (the project's), but calling getattr(module, "MyAdminSite") triggers the error above. I expect the MyAdminSite class to be found, but that's not the case, what is going on in this project, what further checks am I not considering? -
Django Add unique=True to this field or add a UniqueConstraint (without condition) in the model Meta.constraints
I was trying to set foreign key to a specific field of a model , while doing that the following error shows. ERRORS: assignment.Assignment.classes: (fields.E311) 'Teacher.Class' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or add a UniqueConstraint (without condition) in the model Meta.constraints. My Assignment model looks like this class Assignment(models.Model): user = models.ForeignKey(Teacher, on_delete=models.CASCADE, related_name='assignments') title = models.CharField(max_length=250) deadline = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) classes = models.ForeignKey(Teacher, to_field='Class', on_delete=models.DO_NOTHING) description = models.TextField(blank=True) def __str__(self): return str(self.user) + " : " + self.title And the teacher model looks like this class Teacher(models.Model): User = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) Subject = models.ManyToManyField(Subject) Name = models.CharField(max_length=50) Profile = models.ImageField(upload_to = upload_teacher_profile_to, default = 'defaults/teacher_profile.png') Class = models.ManyToManyField(Classes) Number = models.BigIntegerField(blank=True) is_banned = models.BooleanField(default=False) def __str__(self): return self.Name Please help me out . Thanks in advance -
How to connect django with remote postgresql?
How to connect django application with remote postgresql server like we connect nodejs with mongodb atlas? Is there any way to connect or we have to use pgadmin? -
Where does Django store generated tokens resp. token links?
I am currently programming a Django app & have now also included email verification. In doing so, I have shamelessly used Djangos' token generator and misused it for my own purposes. This worked because an email verification works very similar to a password reset: A user enters his data in a form An email is sent The user clicks on the hash link The link verifies the user's input But now I ask myself where Django stores these tokens or links? There is an expire value in the settings (PASSWORD_RESET_TIMEOUT) but as I look up the generator(PasswordResetTokenGenerator) it is just used for comparison. This leads me to the question: Where does Django store these links? Do they ever expire? What happens if I generate an account & never click the email link? -
Error: " Got AttributeError when attempting to get a value for field `name` on serializer `FansSerializer` ". In Multi Table Inheritance DJANGO
I'm using Django as backend, PostgresSQL as DB and HTML, CSS and Javascript as frontend. Well, I'm building a ecommerce website. I want all the data to present in Django Rest Framework. Like If a user choose one product for eg. "LG SMART REFRIGERATOR". So, I want to display the Product model + Refrigerator Model all details which present in both the model (Which is choosen by user) in Django REST FRAMEWORK but I'm getting this error. AttributeError at /showdata/ Got AttributeError when attempting to get a value for field `name` on serializer `FansSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `CartProduct` instance. Original exception text was: 'CartProduct' object has no attribute 'name'. I'm using multi table inheritance. Where the code look like this. models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) full_name = models.CharField(max_length=200) joined_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.full_name class Category(models.Model): name = models.CharField(max_length=200, db_index=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=1330) image_src = models.URLField(max_length=1330,null=True, blank=True) link_href = models.URLField(max_length=1330,null=True, blank=True) brand = models.CharField(max_length = 1330, null=True, blank=True) price = models.DecimalField(max_digits=15, decimal_places=2) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) class Refrigerator(Product): series … -
error when launching the site on django, how to solve it?
enter image description here enter image description here this is the error I get when I run the site on django Here is the code in urls.py Any help would be welcome !! -
Page not found (404) Raised by: views.product_in_category
Good morning. while implementing element_detail Page not found (404) Request method: POST Request URL: http://127.0.0.1:8000/element_detail/ By: zeronine.views.product_in_category There are no categories matching the given search term. ' An error has occurred. The category continued to show up well, but it's not an error about element_detail, but an error about a category, so I'm confused. views.py from django.shortcuts import get_object_or_404 from django.shortcuts import render from zeronine.forms import ElementForm from zeronine.models import * def product_in_category(request, category_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() if category_slug: current_category = get_object_or_404(Category, slug=category_slug) products = products.filter(category_code=current_category) return render(request, 'zeronine/list.html', {'current_category': current_category, 'categories':categories, 'products':products}) def product_detail(request, id, product_slug=None): current_category = None categories = Category.objects.all() products = Product.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) designated_object = Designated.objects.filter(rep_price='True') element_object = Element.objects.all() value_object = Value.objects.all() return render(request, 'zeronine/detail.html', {'product':product, 'products':products, 'current_category': current_category, 'categories':categories, 'designated_object': designated_object, 'element_object':element_object, 'value_object':value_object}) def element_detail(request, product_code): designated = Designated.objects.all() element_object = Element.objects.all() value_object = Value.objects.all() product = get_object_or_404(Product, id=product_code) if request.method == "POST": form = ElementForm(request.POST) if form.is_valid(): element = Element() element.value_code = form.cleaned_data['value_code'] element.designated_code = designated element.save() if request.method == "POST": join = Join() join.product_code = Product.objects.get(id=product_code) join.username = request.user join.part_date = request.POST.get('part_date') join.save() return render(request, 'zeronine/list.html', {'form': form}) else: form = ElementForm() return … -
create sub catgeory inside category with add ,edit and delete option
Guys I'm not using default admin panel as I have created my own . Now I want to add category , sub category and Sub sub category options in my self created admin panel Want to implement something like below: Models.py class Category(models.Model): name=models.CharField(max_length=265) active=models.BooleanField(default=False) #13 class Sub_Category(models.Model): category=models.ForeignKey(Category, on_delete=models.CASCADE) name=models.CharField(max_length=265) active=models.BooleanField(default=False) views.py my views.py has function for both category and sub category redirect for category is easy but where shall i redirect sub category to as each particular category accessed has different url def category(request): #context={} if request.method=='POST': post=Category() post.name= request.POST.get('category') #if request.POST.get('status')=='' post.active=request.POST.get('status') post.save() return redirect('/category') else: approval=Category.objects.all().values() queryset=Category.objects.all() check=queryset.exists() a=list(approval) # print(a[0]['name']) if(check ==True): context={ 'sr.no':a[0]['id'], 'name':a[0]['name'], 'active':a[0]['active'], 'check':check, 'query':queryset, } else: context={ 'query':queryset, 'check':check } return render(request,'category.html',context) return render(request,'category.html') @login_required def category_deactivate(request, user_id): user =Category.objects.get(pk=user_id) user.active = False user.save() messages.success(request, "Category has been successfully deactivated!") return redirect('/category') @login_required def category_activate(request, user_id): user =Category.objects.get(pk=user_id) print(user.active) user.active = True user.save() messages.success(request, "Category has been successfully activated!") return redirect('/category') @login_required def category_delete(request,user_id): t=Category.objects.get(pk=user_id).delete() #status=request.POST.get('status') #t=Service_providers.objects.get(id=oid) #t.status=status #t.save() return redirect('/category') @login_required def category_edit(request, user_id): if request.method=='POST': post=Category.objects.get(pk=user_id) post.name=request.POST.get('category') #if request.POST.get('status')=='' post.save() return redirect('/category') else: post=Category.objects.get(pk=user_id) # print(a[0]['name']) if post.active==False: active='Inactive' else: active='Active' context={ 'name':post.name, 'active':active, } return render(request,'category_edit.html',context) return render(request,'category.html') … -
Installed pyocclient got AttributeError: module 'owncloud' has no attribute 'Client'
I am trying to integrate owncloud in my django website using pyocclient package. I installed it using pip install pyocclient then I tried this example code from their documentation but got the error that owncloud has no attr Client This is my code from django.contrib.auth.decorators import login_required import owncloud @login_required def index(request): if request.method == "GET": return render(request, 'home.html') else: f = request.POST['file'] # a txt file public_link = 'https://lblostenzexxx.owncloud.online/index.php/x/3' oc.login('uid', 'password') oc.mkdir('testdir') oc.put_file(f, 'localfile.txt') link_info = oc.share_file_with_link(f) print(link_info.get_link()) return render(request, 'home.html', {'msg':"return"}) Below is console error: System check identified no issues (0 silenced). May 30, 2021 - 03:30:14 Django version 3.1.5, using settings 'owncloud.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [30/May/2021 03:30:14] "GET / HTTP/1.1" 200 1084 [30/May/2021 03:30:14] "GET /static/css/login_signup.css HTTP/1.1" 200 2813 Internal Server Error: / Traceback (most recent call last): File "C:\Users\mhashirhassan22\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\mhashirhassan22\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mhashirhassan22\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Work\Others\Upwork\owncloud\owncloud\users\views.py", line 13, in index oc = owncloud.Client.from_public_link(public_link) AttributeError: module 'owncloud' has no attribute 'Client' This is the github link for pyocclient https://github.com/owncloud/pyocclient If there is any alternative to upload, share … -
I am Unable to extend the User Model in the Django
I am unable to extend the User Model with the custom fields so anyone can help me out to solve the problem I tried to extend the user but I unable to do that it shows an error. An error part is also given below to the veiws.py files so please me out to resolve this problem. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class register(models.Model): fname = models.CharField(max_length=30) lname = models.CharField(max_length=30) dob=models.DateField() user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.fname class candidate(models.Model): full_name = models.CharField(max_length=30) position = models.CharField(max_length=30) total_vote = models.IntegerField(default=0) def __str__(self): return (self.full_name,"---------",self.position) views.py def register(request): if request.method == "POST": # Get the post parameters username = request.POST['username'] email = request.POST['email'] fname = request.POST['fname'] lname = request.POST['lname'] dob = request.POST['dob'] pass1 = request.POST['pass1'] pass2 = request.POST['pass2'] # check for errorneous input if User.objects.filter(username=username).exists(): messages.error(request, 'This Aadhaar is Already Used') return redirect('home') if User.objects.filter(email=email).exists(): messages.error(request, 'This Email is already Used') return redirect('home') if (pass1 != pass2): messages.error(request, " Passwords do not match") return redirect('home') # Create the user myuser = User.objects.create_user(username, email, pass1) regs = register(fname=first_name,lname=last_name,dob=dob,myuser=myuser) regs.save() messages.success(request, "You are successfully registered") return redirect('home') else: return HttpResponse("404 - Not found") … -
How do you apply design patterns to a framework like django
They say "whoever uses design patterns, writes better code"! I was wondering how can you apply design patterns like Facade, Adapter, Singleton etc to a framework like django. -
How to use Nginx as GRIP compatible proxy
I have an API get_alerts that returns list of alerts stored in a DB collection. I need to convert that into real time API(real time in sense that whenever alert gets added to a DB collection, that new alert should be sent to open connections, there's an API for post_alert too). For that, I have two options, websockets and server sent events. I decided to go with server sent events because I didn't need full duplex communication provided by web sockets and server sent events seemed comparatively simple. Django has a external package Django EventStream. I am following this link . It requires me to use GRIP compatible server. I am using Nginx. I searched but didn't find anything on how to make Nginx a GRIP compatible proxy. Isn't any other package that does it in Django? Do real time APIs require GRIP compatible proxies in other ecosystems too like NodeJS or etc? -
Unable to host two domain on same server with certbot (ssl certificate ) , though both my domain are working with ssl indivisually
I am hosting 2 domains on one server(droplet) in digital ocean using apache - django setup. Have created 2 virtual environment. Both website works without ssl certificate. I have used certbot to install ssl certificate individually . Both the website works with ssl individually .But when i enable both .conf file . I get "500 internal server error" domain1.com.conf file is : WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess domain1 python-home= /var/www/domain1.com/virtualdomain1 python-path= /var/www/domain1.com/domain1 WSGIProcessGroup domain1 <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName domain1.com ServerAlias www.domain1.com ServerAdmin abhayrobotics1908@gmail.com #DocumentRoot /var/www/html Alias /static /var/www/domain1.com/domain1/static <Directory /var/www/domain1.com/domain1/static> Require all granted </Directory> <Directory /var/www/domain1.com/domain1/domain1> <Files wsgi.py> Require all granted </Files> </Directory> # WSGIDaemonProcess domain1 python-home= /var/www/domain1.com/virtualdomain1 python-path= /var/www/domain1.com/domain1> # WSGIProcessGroup domain1 WSGIScriptAlias / /var/www/domain1.com/domain1/domain1/wsgi.py … -
Django user auth across sub domains is not work
I can not seem to get this to work. I would like my users to sign in to the website in the auth subdomain and the session to be recognized across the other domains. The auth subdomain to handle sign-in, sign-up, forgotten passwords... auth.mydomain.com I then have my main domain and the www. subdomain mydomain.com www.mydomain.com settings.py INSTALLED_APPS = [ ... 'django.contrib.sessions', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', #'middleware.ShareSessionMiddleware', See custom middleware below....it didn't help me ... ] SESSION_COOKIE_DOMAIN = ".mydomain.com" my cookie looks like this Name sessionid Content xxx..bux4qn44k.xxx...ofb9q9q9srgdch....xxxx Domain .mydomain.com Path / Send for Same-site connections only Accessible to script No (HttpOnly) Created Sunday, 30 May 2021 at 09:18:29 Logging in works well @ auth.mydomain.com but the session is not recgonised in www.mydomain and mydomain.com. I have tried extending session middleware and changing the COOKIE_SESSION_NAME to example_name from importlib import import_module from django.contrib.sessions import middleware from django.conf import settings class ShareSessionMiddleware(middleware.SessionMiddleware): def process_request(self, request): engine = import_module(settings.SESSION_ENGINE) session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None) if session_key is None: # Look for old cookie in request for auth purposes. session_key = request.COOKIES.get('sessionid', None) request.session = engine.SessionStore(session_key) Nothing seems to work. Can anyone help? I'm sure it's something simple. -
Run view on button click
I have a model called Car which has an attribute for view_count. On my analytics page I want to have a button which will reset the view count of all cars. What is the best way to do this? I've made forms before but I'm wondering if I need to do that or if I can call a view in a template. Note: I don't want non-authenticated users running this view. template <button>Reset View Counts</button> views.py @login_required def reset_view_counts(): cars = Car.objects.all().update(view_count=0).save() -
Extend the background div to fill the whole page
I am trying to build a forum. I want to extend the background div to the sides. Currently, the background fills the page by leaving margin-left and margin right unfilled. Here is my home.html: {% extends 'base.html' %} {% load static %} {% block content %} <style type="text/css"> @media (max-width: 768px) { .right-column{ margin-left: 0px; } } @media (min-width: 768px) { .right-column{ margin-left: 20px; } } .blog-post-container{ margin-bottom: 20px; width: 100%; } .create-post-bar{ background-color: #fff; margin-bottom:20px; } .left-column{ padding:0px; } .right-column{ padding:0px; } .lead{ font-size: 17px; color: #000220; text-align: center; } </style> <!-- main content --> <div class="container"> <div class="row"> <div id="particles-js"></div> <script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script> <script> particlesJS.load('particles-js', "{% static 'particles.json' %}", function(){ console.log('particles.json loaded...'); }); </script> <!-- blog feed --> <div class="left-column col-lg-7 offset-lg-1"> <!-- Top 'create post' bar --> <div class="d-lg-none mb-3"> <div class="card m-auto d-flex flex-column p-3"> <img class="img-fluid d-block m-auto pb-2" src="{% static 'covalent.png' %}" width="72" height="72"> <p class="m-auto"><a class="btn btn-primary" href="{% url 'blog:create' %}">Create post</a></p> </div> </div> <!-- end Top 'create post' bar --> <!-- Blog posts--> {% if blog_posts %} {% for post in blog_posts %} <div class="blog-post-container"> {% include 'blog/snippets/blog_post_snippet.html' with blog_post=post %} </div> {% endfor %} {% else %} <div class="blog-post-container"> {% include 'blog/snippets/blog_post_snippet.html' … -
Django-allauth: Store custom user model column e.g. full_name
I would like to store the combination of first_name and last_name as full_name when a user signs in using Google with django-allauth package. How can I achieve this? Do I need to customize the adapter? Or how can I do this? Thank you. -
Parameter ID from Input to Django url parameter - possible?
I want redirect id="track" from input to parameter "a" in href like you see in below code. But it doesnt return anything. How Can i put value from input to parameter a using django url? -
How to make Django-select2 styling to work
With the details below, I'm not able to get my form details displayed properly. The items display side by side instead of each below each other. I can't see where I went wrong. <form class="add_new container" method="post"> {% csrf_token %} {% for field in form %} <p>{{ field }}</p> {% endfor %}<hr><br> <input type="submit" value="Issue" class="btn btn-outline-primary" class="text-right"> </form> This is the model form class TeacherIssueForm(forms.ModelForm): def __init__(self,*args, pk,school,issuer, **kwargs): super(TeacherIssueForm, self).__init__(*args, **kwargs) self.fields['issuer'].initial = issuer self.fields['book_id'].queryset = Books.objects.filter(school=school,no_of_books=1) self.fields['borrower_teacher'].initial = pk #Sets the field with the pk and it's hidden again class Meta: model = TeacherIssue fields = ['issuer','book_id','borrower_teacher'] widgets = { 'borrower_teacher':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'book_id':Select2Widget(attrs={'data-placeholder': 'Select Book','data-width': '100%'},) } -
Displaying a python list's values in HTML dropdown using AJAX
I am using Django and AJAX to implement a chained-dropdown. The user will first be prompted to select a brand_name from a dropdown, and depending upon the brand_name selected, all the names of the products that are made by that brand will be displayed in the second dropdown. views.py def chained_dropdown(request): if request.method == "POST": brand = request.POST['brand'] print(brand) sort_by_brand = list(models.Product.objects.filter(brand=brand).order_by('product_id').values('product_id', 'product_name')) data = { 'SortByBrand': sort_by_brand } return JsonResponse(data) AJAX request: var brand = $('#brand').val() $.ajax({ type: "POST", url: "/changeddropdown", data:{ "brand": brand, }, success: function (data){ // What should I do here? console.log(data) }, }) templates snippet: This is where I want the product names to be displayed, and the option value should be their corresponding product_id. <label for="product_id"> Product ID</label> <select name="product_id" id="product_id"> <option disabled selected="true"> --Select -- </option> <option value=""> </option> </select> For your reference, this is what console.log(data) prints: {SortByBrand: [{product_id: 31, product_name: "Lotion"}, {product_id: 32, product_name: "Deo"}]} I am having trouble displaying this information in the template, any help would be greatly appreciated.