Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Print Barcode in PDF with Django
I am using render_to_string in django for parse an HTML and export to PDF. html = render_to_string("etiquetaTNT.html", { 'context': context, 'barcode': b, 'barcodeimg': barcodeimg, }) font_config = FontConfiguration() HTML(string=html).write_pdf(response, font_config=font_config) return response I am trying to insert a barcode in PDF. I generate this barcode in a PNG. br = barcode.get('code128', b, writer=ImageWriter()) filename = br.save(b) barcodeimg = filename But the PDF in template, not show the image. <img class="logo" src="{{barcodeimg}}" alt="Barcode" /> I do not know the way to save the filename in the template that I want, and I do not know to show in the PDF, because any image is showed. For example, the logo, it is showed in HTML template but not in the PDF. <img class="logo" src="{{logo}}" alt="TNT Logo" /> -
self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found
I am using geodjango to implement Google Map API in my web application. I configured the database in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geodjango_project', 'USER': 'postgres', 'HOST': 'localhost', 'PASSWORD': 'postgres', 'PORT': '5432' }, } I got this error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal204", "gdal203", "gdal202", "gdal201", "gdal20"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. then according to the instruction of the error, I added `GDAL_LIBRARY_PATH = r'C:\OSGeo4W64\bin\gdal202'` and this error was thrown: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\programdata\anaconda3\Lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\programdata\anaconda3\Lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\pytuts\.virtualenvs\geodjango-project-Aa0-CBie\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load … -
filter query set on point field and distance
i am insert data of Django of model with image but image not insert model.py class Product(models.Model): name = models.CharField(max_length=100,) image = models.ImageField(upload_to='images/',null=True) form.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' views.py CreateProduct(request): context = {} form = ProductForm(request.POST or None) if form.is_valid(): form.save() context['form'] = form return render(request, "create_pro.html", context) html <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {% endblock %} settings.py MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
What does request.GET.get() mean?
What does request.GET.get() mean? I see something like this in Django, inside passing two-parameter remove = request.GET.get('remove','off') How they work ? -
Syntax error while saving postgresql server info in settings.py Django
I am trying to save Postgres server info using the book Django for professionals by WsVincent but I am getting a syntax error under Ports. This is what my code looks like: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } The error that pops up is web_1 | 'PORT': 5432 web_1 | ^ web_1 | SyntaxError: invalid syntax Could someone help me please. Kind regards -
Django - ManyToMany relationship not unique
So the case is : I have a Course model with a manytomany relationship to a student model . The course also have a one to many relationship with a Module model, so a course have many modules but each module belongs to one course . On my Module i specified a boolean field named completed to be able to calculate how much modules of that course did the student complete . The main problem is : When a module is completed by a student, it's marked as completed forever. In other words, when another user enrolls in the same course , he will find the completetion state of the modules as left by the other user . I want each modules to be initialized when a student enrolls in a course , but also want to them to be saved just for that student without saving the changes globally, it's like making an initialized copy of the course whenever a new user enrolls in it, and save his records on this copy not on the actual Course model in the database . Thanks and here's the code : class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) full_name = models.CharField(max_length=200, … -
Python Django - Are periods in a string processed correctly when retrieved from an api?
In Python to include a period in a string you need to add the escape key \ in front of the period . so "example\.com" appears as "example.com" say I'm programming in Django and a Python SDK returns a specific url such as "example.com/abcdef" I assume I don't have to worry about adding a \. to "example.com/abcdef" so that it is "example\.com/abcdef". Can you explain the reason why I don't need to add the \. in this case. -
django - invalid syntax regex
I'm trying to implement the solution to error ImproperlyConfigured TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names() Here's my urls.py as suggested from django.urls import include, path, re_path urlpatterns = [ re_path(r'^auth/registration/account-confirm-email/(?P<key>[\s\d\w().+-_',:&]+)/$', TemplateView.as_view(), name = 'account_confirm_email'), path('auth/registration/', include('dj_rest_auth.registration.urls')), ] But I'm getting this error. re_path(r'^registration/account-confirm-email/(?P<key>[\s\d\w().+-_',:&]+)/$', TemplateView.as_view(), name = 'account_confirm_email'), ^ SyntaxError: invalid syntax Any idea on what I could be missing? Thanks! -
Cannot create new Table with FK in Django
I'm trying to add a new table to my mysql database. The table consists of only two items, each of which is a foreignKey (further down). However, when migrating the changes to the DB I receive an error message (further down) I know that the problem is in the HS_Countries foreignKey as I tested it and it is possible to migrate the table when that key is not present. I have other tables where I have a HS_Countries foreignKey. Thats why I'm quite confused by the problem. The structure of HS_Countries is further down and also the structure of the other foreignKey. I am not sure what I have to change to get the migration to work. New table: class User_Accumulated_Countries(models.Model): iso_code = models.ForeignKey( 'HS_Countries', on_delete=models.CASCADE, related_name='iso_code') product = models.ForeignKey( 'User_Product', on_delete=models.CASCADE, related_name='product') console log: Operations to perform: Apply all migrations: main Running migrations: Applying main.0113_user_accumulated_countries...Traceback (most recent call last): File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (3780, "Referencing column 'iso_code_id' and referenced column … -
How do I make bootstrap card go next to each other when they are generated by django?
I made a blog in django but there is a problem. Whenever I create a new blog post it sends the bootstrap card downwards and not next to the other bootstrap card, meaning its going vertically and not horizontally. {% extends 'portfolio/base.html' %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>{% block title %}Blog{% endblock %}</title> </head> <body> {% block content %} <div class="container text-center"> <h2>Blogs</h2> <h2>PyPatriot has posted {{ blogs.count }} Blog{{ blogs.count | pluralize }}</h2> <div class="row"> <div class="col-sm-6"> {% for blog in blogs %} <div class="card" style="width: 18rem;"> <img src="{{ blog.cover_photo.url }}" class="card-img-top" width="230" height="230"> <div class="card-body"> <h4 class="card-title">{{ blog.title }}</h4> <h6>{{ blog.date | date:'M d Y'}}</h6> <p class="card-text">{{ blog.description | truncatechars:70 }}</p> <a href="{% url 'blog:detail' blog.id %}" class="btn btn-primary">View</a> </div> {% endfor %} </div> </div> {% endblock %} </body> </html> -
Sum numeric values from different tables in one query
In SQL, I can sum two counts like SELECT ( (SELECT count(*) FROM a WHERE val=42) + (SELECT count(*) FROM b WHERE val=42) ) How do I perform this query with the Django ORM? The closest I got is a.objects.filter(val=42).order_by().values_list('id', flat=True).union( b.objects.filter(val=42).order_by().values_list('id', flat=True) ).count() This works fine if the returned count is small, but seems bad if there's a lot of rows that the database must hold in memory just to count them. -
How to Retrieve info just from the token passed
I am generating a jwt access and refresh token from a separate function after taking the user credentials and authenticating them.now when the user passes a url which call a function with authentication required.he only needs to pass the token in header. how can i get that user details in that function as soon as he passes that token. -
How to save the form with posted user in the django models database
i have created the login,authenticate,logout system,no i want to add a post functionality that saves the data in the Tweet model. views.py from .models import NameForm from django.shortcuts import render, redirect, get_object_or_404 def home(request): if request.method == "POST": form = NameForm(initial={'tweetedby':request.user.id}, datarequest.POST) if form.is_valid(): form.save() return redirect('home') else: form = NameForm() return render(request,'home.html',{"form":form} ) i am using the inbuild forms framework for the post request home.html <form method="post" novalidate> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary">Submit</button> </form> forms.html from django.forms import ModelForm from django import forms from .models import Tweet class NameForm(ModelForm): tweet = forms.CharField(label="tweet",max_length="50") def clean_tweet(self): data = self.cleaned_data["tweet"] return data class Meta: model = Tweet fields = ("tweet",) when the user tweets i am getting the tweet and and the datetime form the tweet.but i want to access the tweeted_by user from the post request, model.py from django.db import models from django.contrib.auth.models import User class Tweet(models.Model): tweet = models.CharField(max_length=50) tweetedtime = models.DateTimeField(auto_now_add=True) tweetedby = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.tweet i get the error null value in column "tweetedby_id" violates not-null constraint DETAIL: Failing row contains (12, hi, 2020-06-07 09:55:20.482599+00, null) The tweeted_by coloumb gets the null value without the USER id -
How to authenticate user by custom model in Django
i want to authenticate user with my custom model but on login page user is logged in only by django admin credential, all i wanna do is to authenticate user by my custom model Please help with this code i am not able to create user authentication using custom model here is the models.py file from django.db import models from phonenumber_field.modelfields import PhoneNumberField` #Create your models here. class registerdata(models.Model): name = models.CharField(max_length=50) email = models.CharField(max_length=70, default="") phone = PhoneNumberField(null=False, blank=False, unique=True) password = models.CharField(max_length=500, default="") def __str__(self): return self.name #here is views.py of app from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib import messages` from .models import registerdata from django.contrib.auth.models import User,auth from django.contrib.auth import logout` # Create your views here. def login(request): #code for checking authentication if request.method == "POST": print(request.POST) username=request.POST.get("username") password=request.POST.get("password") user = auth.authenticate(username=username,password=password) if user is not None: print('auth pass') auth.login(request, user) return redirect('chats') else: print('auth fail') messages.info(request,"invalid credentials") return redirect('loginpage') return render(request,'login.html') def Register(request): if request.method=="POST": name = request.POST.get('name', '') email = request.POST.get('email', '') phone = request.POST.get('phone', '') password= request.POST.get('password','') Register = registerdata(name=name, email=email, phone=phone, password=password) Register.save() return redirect('loginpage') return render(request, 'register.html') def chats(request): if request.user.is_authenticated: logout(request) return render(request,'chats.html') else : return redirect('loginpage') … -
Django + openvpn authentication
I'm currently working on a django project (academic). This project consists of a ecommerce website, developed in Django. This site sells vpn subscriptions. The VPN server is ubuntu 18.04 with Openvpn server. My initial idea is to create one db (mysql) where users will be able to authenticate to the django site and also to the vpn server. So no problem to create the django authentication for the users but I'm having difficulties in finding a way to authenticate the users to the VPN server. This would be possible if I did something stupid like leaving the password in plaintext :-) but off course I will not do that. So the VPN server is up and running with mysql db, the django site not completelly yet, but I have the authentication app up and running. Django uses pbkdf2_sha256 as hashing algorithm by default and the server, for the moment, is using plaintext. I'm wondering if anyone knows a library I could use in order to make it possible for the VPN server to be able to authenticate the users, or if I should change the defaut hashing algorithm in Django to match a hashing algorithm of an existing library like … -
Upload one Image to multiple model at a time in DJango
I m very new in django web framework. I m bulding a small web application using django. There I need to upload one image in a file upload field which will upload to multiple model field at a time. I have searched a lot in internet . But I didn't get any example of it how to do. So , I am asking here. Is there anyone who can show me how I can do it with a small example ?. Help will be highly appreciated. -
Writing Unit test for 404 not found page in Django
I am writing unit test case for my class based view (DetailView) and if i pass wrong slug it should show the 404 status but i am getting error in testcase. My code is looks like: Views.py:- class TeamDetailView(LoginRequiredMixin,MultipleObjectMixin,DetailView): model = Teams paginate_by=2 def get_object(self, **kwargs): return get_object_or_404(Teams.objects.only('teams_id','slug','title','logo'),slug=self.kwargs['slug']) def get_context_data(self, **kwargs): team_players = Players.objects.filter(team_id = self.object.teams_id ).values('last_name','first_name','logo','slug').order_by('first_name') context = super(TeamDetailView, self).get_context_data(object_list=team_players,**kwargs) return context Url looks like:- path('/detail/', TeamDetailView.as_view(), name="team_detail") And My unit test looks like:- class TestTeamsDetailView(TestCase): def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username='test2', email='abc2@gmail.com', first_name='t', last_name='u', password='password' ) self.team = Teams.objects.create( title="My Team", slug="my-team", club_state="Mumbai" ) def test_team_detail_view_with_valid_user_and_invalid_slug(self): request = self.factory.get("/teams/my-team nisia/detail") request.user = self.user response = TeamDetailView.as_view()(request, slug='my-team fudsss') self.assertEqual(response.status_code,404) And i am getting this Error:- in get_object_or_404 raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) django.http.response.Http404: No Teams matches the given query. -
Problem installing mysqlclient for a website hosted on namecheap shared hosting plan
I have my small Django website hosted on namecheap. I want to migrate from sqlite3 database to MySQL but when I try to run the pip install mysqlclient command, I get the following error: Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/majeaozd/virtualenv/majestylink/3.7/bin/python3.7_bin -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-hitubcqu/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-hitubcqu/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-7na75mzf cwd: /tmp/pip-install-hitubcqu/mysqlclient/ Complete output (30 lines): /opt/alt/python37/lib64/python3.7/distutils/dist.py:274: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.7/MySQLdb creating build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.7 creating build/temp.linux-x86_64-3.7/MySQLdb gcc -pthread -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,4,6,'final',0) -D__version__=1.4.6 -I/usr/include/mysql -I/usr/include/mysql/.. -I/opt/alt/python37/include/python3.7m -c MySQLdb/_mysql.c … -
Django Changes the file name automatically on uploading a file
I am creating a form where a user comes and uploads files . In an exception seconario if two different user uploads file with same name (say index.html) , django saves the second file with a different file name (say index47pqs5m.html), it makes me a problem while retriving the file with the file name , I want the same file name which user uploaded in django admin page , i don't care how and which file name did django saved it the folder . Help me out Plz -
Handling MultiValueDictKeyError on posting dateTime object to Django database
I am trying to post two DateTime objects on my Django database. Here is my relevant part of models.py: class Timesheet(models.Model): task_id = models.AutoField(primary_key=True) project = models.ForeignKey('Project', on_delete=models.CASCADE) user = models.ForeignKey('User', on_delete=models.CASCADE) task_title = models.CharField(max_length=250) task_description = models.TextField(null=True) PRIORITY_STATUS = [ ('H','High'), ('M','Medium'), ('L','Low'), ] priority = models.CharField(max_length=1, choices=PRIORITY_STATUS) starting_time = models.DateTimeField() ending_time = models.DateTimeField() def __str__(self): return str(self.task_title) class timeSheetForm(ModelForm): class Meta: model=Timesheet fields=['project','user','task_title','task_description','priority','starting_time','ending_time'] The forms.py: class timeSheetForm(forms.Form): #other fields starting_time = forms.DateTimeField(widget=AdminSplitDateTime()) ending_time = forms.DateTimeField(widget=AdminSplitDateTime()) And the template has: <form action="/memberDashboard/" method="POST"> {% csrf_token %} <label for="starting_time" class="col-lg-1 col-form-label">Start Time</label> {{form.starting_time}} <label for="ending_time" class="col-lg-1 col-form-label">End Time</label> {{form.ending_time}} <button type="submit" class="btn btn-primary"> <strong>Create Time-Sheet</strong> </button> </form> On submission of this form, the MultiValueDictKeyError is being raised, and some second pair of eyes would be of great help here, as I am not getting what am I missing here. A newbie to Django, so sorry if posting a silly question. The error log file: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/memberDashboard/ Django Version: 2.2 Python Version: 3.7.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'timeSheetApp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\datastructures.py" in __getitem__ 78. list_ = super().__getitem__(key) During handling of the above exception … -
In django how to send json object using XMLHttpRequest in javascript
Please Help me with how to send json object and receive it it views.py in django. my script: var obj={ 'search_name':search_name,'search_email':search_email }; jsonobj=JSON.stringify(obj); //alert(jsonobj); var xhr=new XMLHttpRequest(); xhr.open('POST',"viewprofile",true); xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(jsonobj); -
Django: how to run a function that creates an object (using information from view) when user clicks a button
I have a Word model where users can create their own words (using Django's CreateView). I also have a Dictionary view that shows the WordList page (using django-filter's FilterView) for one specific (special) user, like this: from .filters import WordFilter from django_filters.views import FilterView class Dictionary(FilterView): model = Word template_name = 'vocab/dictionary.html' context_object_name = 'dict_list' paginate_by = 15 filterset_class = WordFilter strict = False def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = WordFilter(self.request.GET, queryset=self.get_queryset()) return context def get_queryset(self): qs = self.model.objects.filter(user__username__iexact='special_user') return qs def get_object(self): queryset = qs pk = self.kwargs.get('pk') if pk is None: raise AttributeError('pk expected in url') return get_object_or_404(queryset, pk=pk) What I want to do now is to give every user the option of adding any word he/she wants from this list - without having to leave the page. In other words, when a user clicks a button a certain function must be run (without the need to first go to a new page). One way I thought of doing this is to write a create view with dynamic initial values given what word the user clicked on. But the problem is that in the Dictionary view I do not have access to the object; for that … -
Get script absapth executed by Django shell
I have a script called myscript.py and I try to print the file path in it. print(os.path.abspath(__file__)) I executed the script using django shell ./manage.py shell < myscript.py However, I could not get the script file path but the shell.py file path. what I get is something like: ...lib/python3.6/site-packages/django/core/management/commands/shell.py Why abspath(file) does not show myscript.py path? is there a way to print out the path of myscript.py? Thanks -
Broken Jquery Ui style Datepicker
I am trying to use a jquery UI date picker on a datefield in django. but for some reason, it looks very bad. and the input field itself is wired. I would like to know what I am doing wrong? how can I fix the view? there is also (in green) a gap in the field how can I remove the gap?. picture: JS $("#id_start_time").datepicker({}); my head of the page: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <!-- Data Tables--> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/rowreorder/1.2.6/css/rowReorder.dataTables.min.css"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css"> <script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.3.1.js"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/rowreorder/1.2.6/js/dataTables.rowReorder.min.js"></script> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous"/> -
Adding placeholder to UserCreationForm in Django
I want to add placeholders to the UserCreationForm in Django. I'm a bit confused, bc when I search for this topic I only find stuff like this with complicated answers, where people suggest to change the /lib/site-packages/django/contrib/auth/forms.py . Isn't it an awful idea to change the code of Django itself? Couldn't you just create a custom form like this, when you add placeholders to the authenticationForm: from django import forms from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import PasswordInput, TextInput class CustomAuthForm(AuthenticationForm): username = forms.CharField(widget=TextInput(attrs={'class':'validate','placeholder': 'Email'})) password = forms.CharField(widget=PasswordInput(attrs={'placeholder':'Password'})) Thx for your help and stay healthy!