Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom HTML layout for forms in Django
I am new to Django and I'm trying to get a grip on it. I worked my way through the documentation of forms. And the Django way is doing basically: <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> To render the according template. Fine. I can mayually render my fields: <div class="fieldWrapper"> {{ form.subject.errors }} <label for="{{ form.subject.id_for_label }}">Email subject:</label> {{ form.subject }} </div> And I can customize the rendered output of a field with widgets. class CommentForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'})) url = forms.URLField() comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'})) So far I am using some "standard rendering mechanism" which allows me to customize things a little bit. Question: Is there any way to design the layout of a form in a more html-like way? Say instead of {{ form.subject }} - rendering a default template enriched with widget information from somewhere else in the codebase - having something like <input type="text" minlength="10" class="wiggle" value="{{form.subject.value}}>. Which for me would be a bit more straightforward. -
Ajax form not sending data in django
I am trying to send data to django without page refresh. So i am using ajax. Created a django model and form class MyModel(models.Model): text=models.CharField(max_length=100) class MyForm(forms.ModelForm): class Meta: model=MyModel fields = "__all__" Then send the form to html page via views.py def home(request): print(request.POST.get('text',False)) form = MyForm(request.POST) if request.method=='POST': print(request.POST.get('text',False)) if form.is_valid(): data=form.save() return render(request,'home.html',{'form':form}) Create a orm in html template <form action = "" id="post-form" method = "post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit" id="submit-button"> </form> This is javascript file $(document).on('submit','#post-form', function(x){ x.preventDefault(); console.log("button clicked") $.ajax({ type:'POST', url:'/', data:{ text:$("id_text").val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ alert('Saved'); } }) } ) I am unable to find, where is the issue. -
Django modal autoimplement
Can anyone advise on how to deal with retrieving data from other models in Django? I was able to put information with the name of the company in the form, but after choosing from dropdown, I would like the tax identification number to be completed automatically. The problem is both the automatic completion and the binding and extraction of data. Model: klient_lista = Klient.objects.all().values_list("nazwa_firmy", "nazwa_firmy") class Faktura(models.Model): numer = models.CharField(max_length=260, blank=False, null=False, unique=True) klient = models.CharField(max_length=260, choices=klient_lista) NIP = models.CharField(max_length=260) kwota_netto = models.FloatField(blank=False, null=True) VAT = models.FloatField(blank=False, null=True) kwota_brutto = models.FloatField(blank=False, null=True) @login_required def Faktury(request): faktura = Faktura.objects.all() faktura_Form = Faktura_Form(request.POST or None) if faktura_Form.is_valid(): faktura_Form.save() return redirect(Faktury) return render(request, 'Faktury.html', {'form': Faktura_Form, 'faktura': faktura})` [enter image description here][1] [enter image description here][2] [1]: https://i.stack.imgur.com/hoUZw.png [2]: https://i.stack.imgur.com/DSCEj.png -
How can I manipulate Django Form fields on the run?
Might be an easy one for some but I am new to coding and have spent a day searching for the answer so reaching out. I am trying to find a way to hide a form field in the HTML when another field is selected. Specially I am asking if the stock is tracked (checkbox, default = true), if true then we want to know the stock on hand, if not then I want to remove the Stock on hand field as not relevant Thanks in advance -
Restricting choices so tree structure in preserved Django model
I have a model with a parent field that refers to itself, like so: parent = models.ForeignKey("self", null=True, blank = True ) For the root node, this field will be blank. When creating a new data instance, I want to make sure I do not add a data instance that ruins the implied tree structure. For instance, if two instances are parents of each-other. Choices for the user will be presented via a form, so I need to restrict the choices that are presented to the user, doing something like: class Meta: model = CategoryModel def __init__(self, *args, **kwargs): # Restrict choices so tree structure is not messed with self.fields['parent'].queryset = ???? What should ???? be? -
error while integrating react and django ("template doesn't exit")
i am new to django. after following a youtube video about integrating react and django following error occurs. TemplateDoesNotExist at / index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.4 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: /home/saurav/.local/lib/python3.8/site-packages/django/template/loader.py, line 47, in select_template Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/home/saurav/Desktop/Globle Project/django project/Navigator', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/saurav/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sun, 31 Jul 2022 06:54:31 +0000 any solutions? -
How can i change from FBV to CCBV DeleteView
in this case i've created the delete using the FBV, but i want to make some improvement using CCBV. i have 2 database in my projects, the sqlite3 as default database and mysql as 'backup' database so this is the delete function : def delete_class(request, link): if request.method == "POST": model = get_object_or_404(ClassName, link=link) model.delete() bc_model = model.objects.using('backup').get(link=link) bc_model.delete() return render(request, 'temp_/delete.html') i want to delete on both database with more clean code, anybody knows how to migrate to CCBV? -
{DRF | Django} How to get count of subjects taken by each students in "django"
I've two django models 'Students' and 'Enrollments'. The model schema for these is as below: class Students(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField() class Enrollments(models.Model): enroll_id = models.AutoField(primary_key=True, unique=True) student_id = models.ForeignKey(Students, on_delete=models.CASCADE) subjects = models.charField() I'm trying to achieve the result of following sql query in Django Rest Framework, for getting number of subjects enrolled by students (individually). select s.id, s.name, count(e.subjects) as count from Students as s left outer join Enrollments as e on e.student_id_id = s.id group by s.id, s.name, e.subjects order by count asc; This query returns result like: --------------------------- | id | name | count | --------------------------- | 1 | a | 1 | | 2 | b | 0 | | 3 | c | 2 | --------------------------- Can anyone please help me acheive this kind of result. Note: I need 0 count students details also. -
Django. How can I add a widget for image input
How can I add a widget for image input. Here code in file 'forms.py' in Django project class BookForm(ModelForm): class Meta: model = Book fields = ['name', 'img'] widgets = { 'name': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Name' }) } Code in HTML: <form method="post"> {% csrf_token %} {{ form.name }}<br> {{ form.img }} <button type="submit" class="btn btn-success">submit</button> <span>{{ error }}</span> </form> -
404 error when accessing Django STATIC resources inside Docker image
This is the Dockerfile for my Django project: FROM python:3.10.5-alpine ENV PYTHONDONTWRITEBYTECODEBYDEFAULT=1 ENV PYTHONUNBUFFERED=1 RUN adduser --disabled-password appuser USER appuser WORKDIR /home/appuser/app COPY requirements.txt . USER root RUN python -m pip install --no-cache-dir --disable-pip-version-check --requirement requirements.txt USER appuser COPY . . ENTRYPOINT [ "./entrypoint.sh" ] And Django settings regarding static assets: STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static/' And entrypoint.sh #!/bin/sh python manage.py makemigrations python manage.py migrate python manage.py collectstatic --no-input gunicorn project.wsgi:application --bind=0.0.0.0:8000 --workers=4 --timeout=300 --log-level=debug --log-file=- exec "$@" When I start the container I shell into it and see that static folder is created and populated with admin staff. However browsing http://127.0.0.1:8000/admin brings up the admin login page without any CSS and I get lots of 404 errors in the developer console. I also changed STATIC_ROOT to /home/appuser/app/static/ and got the same. Please assist. -
window.open() popup doesn't show anything
I have a Django website with this url that has this code in its template footer: <img referrerpolicy='origin' id = 'rgvjjxlzwlaoesgtfukzjxlz' style = 'cursor:pointer' onclick = 'window.open("https://logo.samandehi.ir/Verify.aspx?id=314061&p=xlaorfthaodsobpdgvkarfth", "Popup","toolbar=no, scrollbars=no, location=no, statusbar=no, menubar=no, resizable=0, width=450, height=630, top=30")' alt = 'logo-samandehi' src = 'https://logo.samandehi.ir/logo.aspx?id=314061&p=qftinbpdshwllymawlbqnbpd' /> which displays this image in the footer: When it is clicked, it should display a popup page like this: (this is in the footer of another website called "toplearn.com" which I just gave as an example, but it looks exactly like this page.) But it runs a blank page. Thank you for helping me find the problem -
Image is not loading on page
my image file is not loading in webpage it is showing The 'Img' attribute has no file associated with it models.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=100,unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(default=timezone.now()) status = models.IntegerField(choices=STATUS, default=0) Img = models.ImageField(null =True, blank = True, upload_to='static/images') class Meta: ordering = ['-created_on'] def __str__(self): return self.title urls.py from django.contrib import admin from django.conf.urls import include from django.urls import path from portfo import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.firstpage,name='firstpage'), path('', include('portfo.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,"static") ] MEDIA_URL ="/images/" MEDIA_ROOT=os.path.join(BASE_DIR,'static/images') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' I have a file name images inside the static. -
how can i solve this book search box in django?
im working with django making a book searcher, here is my code,im using a youtube video for making this project, i did exactly what he does but it doesnt work views.py: def books(request): if request.method == 'POST': form = DashboardForm(request.POST) text = request.POST['text'] url = 'https://www.googleapis.com/books/v1/volumes?q='+text r = requests.get(url) answer = r.json() result_list = [] for i in range(10): result_dict = { 'title':answer['items'][i]['volumeInfo']['title'], 'subtitle':answer['items'][i]['volumeInfo'].get('subtitle'), 'description':answer['items'][i]['volumeInfo'].get('description'), 'count':answer['items'][i]['volumeInfo'].get('pageCount'), 'catagories':answer['items'][i]['volumeInfo'].get('catagories'), 'rating':answer['items'][i]['volumeInfo'].get('pageRating'), 'thumbnail':answer['items'][i]['volumeInfo'].get('imageLinks').get('thumbnail'), 'preview':answer['items'][i]['volumeInfo'].get('previewLink') } result_list.append(result_dict) context={ 'form':form, 'result':result_list, } return render(request,'dashboard/books.html',context) else: form = DashboardForm() context = {'form':form} return render(request,'dashboard/books.html',context) forms.py: class DashboardForm(forms.Form): text = forms.CharField(max_length=100,label='Enter your search : ') books.html: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class='text-center container'> <h2>Search books and browse your favorite</h2> <p>just enter the search query to obtain the results</p><b></b> <form action="" method="post"> {% csrf_token %} {{form}} <input class="btn btn-danger" type="submit" value="Submit"> </form><br> <a href="#" target="_blank"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-3"> <img class="img-fluid" src="" alt=""> </div> <div class="col-md-9"> <h3 class="p-0 m-0">title</h3> <b> <u> <h5 class="p-0 m-0">subtitle</h5> </u> </b> <h6 class="p-0 m-1">description</h6> <b> <h6 class="ml-0 mt-3">Category: name</h6> <h6 class="ml-0 mt-1">Pages: 100</h6> <h6 class="ml-0 mt-1">Rating: 4</h6> </b> </div> </div> </div> </div> </a> <br> </section> {% endblock content %} actually when i … -
Docker-compose django
want to launch 3 containers. db, nginx, web. Web isn't working. Problem: ModuleNotFoundError: No module named 'api_yamdb'. I know that it's my own module, but i don't know why it's don't found. Please help. structure of project settings in settings.py docker-compose.yaml Dockerfile docker log -
Django paypal payments
I am trying to enable user to user payments in my django application with paypal integration. I can send payments to the business account. I need to know hot to let users to pay with each other. I used payee object but it did not work. can anyone help me, if it is I appreciate. Thank you! -
Django: never_cache is not working, it still shows same data on browser back button
I have a create view which is used to make an object of type Course(model). i'm using never_cache decorator to reload the page from server everytime i use it. now if i create a course it gets added in the Course database, now if i press browser back button it still shows me the data with course name that i wrote, which allows me to resubmit the same data, how can i prevent this?(ik i can prevent saving same data twice by overriding save method but i want to prevent user from going back to form in which he entered data). @method_decorator(never_cache, name='dispatch') class CourseView(CreateView): model = Course template_name = 'teacher/course.html' fields = ['name', 'year'] def get_context_data(self, **kwargs): kwargs['course_list'] = self.model.objects.all().order_by('name','year') return super().get_context_data(**kwargs) def form_valid(self, form): messages.success(self.request, 'Course added successfully.') return super().form_valid(form) def get_success_url(self): return self.request.GET.get(key='next', default=reverse('teacher:course')) -
Override (save_model) in django admin for All models/apps in projects
How could I implement override save method for all models in all Apps inside Admin panel? def save_model(self, request, obj, form, change): pass I can implement it in one or two models "inherit and adding it in register method", but I really need it to execute whenever admin clicks save in Admin panel and implement some code before save. -
Is using UUId as pk a good idea in microservices?
I am working on a microservice project which contains 4 services developed in django i use dj rest auth to handle login and register process , each service has its own database and the information of users are kept in account service and other 3 services get the users information via an api request to account service , in each service i have only access to logged in user pk (dj rest auth handles this) and when i need to save a record for example location of logged in user ,i save a user object which only has pk alongside other info so the record in db will be like this : user=request.user(which saves logged in user but i only see the pk) lat = latitue number lng = longitude number everything is fine but if i loose the database of account service and restore the backup and some how the records generate a different pk (for example before restoring backup some new records would be added) from the ones saved in other services which makes a huge problem in all services. the solution i tried is to change the pk to uuid filed but is it a good idea? … -
Keywords Must Be Strings When Passing Variable As Parameter
I'm trying to pass a variable as a keyword argument like this: true_frequency = 'weeks' next_month = today + relativedelta(**{true_frequency: true_loop}) This is for a django site and it doesn't error when I run this through the site. However, when I run a test I'm getting this error: next_month = today + relativedelta(**{true_frequency: true_loop}) TypeError: keywords must be strings I'm not entirely sure how to solve this as I've never passed a keyword as a variable before so I'm not overly familiar with the process. This is happening on a receiver object. Thanks -
productId = data['productId'] KeyError: 'productId' in django
when i added a item to cart it is successfully added by prviding the product id like Action: add Productid: 1 But when i make payment it is showing error like productId = data['productId'] KeyError: 'productId' and cart count also not updated after clicking payment here is my code def updateItem(request): data=json.loads(request.body) print(data) print("sasi") productId = data['productId'] action=data['action'] print('Action:',action) print('Productid:',productId) customer=request.user.customer product=Product.objects.get(id=productId) order,created=Order.objects.get_or_create(customer=customer,complete=False) orderItem,created=OrderItem.objects.get_or_create(order=order,product=product) if action == 'add': orderItem.quantity=orderItem.quantity+1 elif action == 'remove': orderItem.quantity=orderItem.quantity-1 orderItem.save() if orderItem.quantity<=0: orderItem.delete() return JsonResponse('Item was added',safe=False) -
DJANGO: caching a services.py method so it's always available
I'm trying to use this python ML library and turn it into an APIView for my project. There is a single line that loads the ML model which took around ~20s, so I separated that line into services.py and decorated with @lru_cache so it doesn't always take ~20s. Because lru_cache is Least Recently Used caching method, the cached model is quickly un-cached and makes user wait for another 20s sooner or later. So I am looking for a way to either cache load_model() method so it's always available, or cache it within a certain time. I tried using cache_page method for the latter but had no luck so far. Is there a better method I can use, or would just tweaking the lru_cache's maxSize be a more elegant solution? This APIView isn't called very often, which makes user wait ~20s every time. I was hoping to just make it always available so user don't have to wait. views.py from .services import load_model, extract_keyword class ExtractKeyphrase(ApiAuthMixin, APIView): def post(self, request): try: text = request.data["text"] kp_model = load_model() # the line that takes ~20s keyphrases = extract_keyword(kp_model, text) return JsonResponse(keyphrases, status=status.HTTP_200_OK, safe=False) except requests.exceptions.RequestException: Response("Request Failed", status=status.HTTP_400_BAD_REQUEST) services.py from functools import lru_cache … -
How to profiling django tests
In my django (very very ancient 1.9) project tests are very slow - Ran 758 tests in 1017.001s, ~ 1.3 s/test How to profile its using Pycharm? Or another IDE. -
Is it possible to reconnecting the Django channels socket by passing the parameter when click the button?
python class BookConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.execute_websocket_ticker() async def process_message(self, message): asyncio.create_task(self.send_json(message)) async def start_binance_depthsocket(self, symbol=None): client = await AsyncClient.create() bsm = BinanceSocketManager(client) if not symbol: symbol = 'btcusdt' async with bsm.depth_socket(symbol=symbol, depth='10') as ts: while True: data = await ts.recv() res = {'site': 'binanceSpot', 'type': 'depthsocket', 'data': data} await self.process_message(res) async def execute_websocket_ticker(self): asyncio.create_task(self.start_binance_depthsocket()) js var book_socket = new WebSocket('ws://' + window.location.host +'/ws/book?session_key=${sessionKey}') book_socket.onmessage = function (e) { let data = JSON.parse(e.data) let site = data['site'] let type = data['type'] if (type == 'depthsocket') { update_orderbook(site, data['data']['asks'], data['data']['bids']) } } What i'm trying to do button click reconnect depth_socket by passing the parameter What I've tried caching symbol value when button click fetch and set cache (But I don't think it's a good way and can't reconne) If it's impossible, I'd appreciate it if you could recommend another way. -
How to set "DJANGO_SETTINGS_MODULE" for a "config" module divided into common, local, production files
I'm setting up a wsgi.py to deploy my django app in DigitalOcean, but I'm getting the following errors during deployment phase after successful build. From the error trace, I think there is a problem with os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config") this line inside wsgi.py. My config files are organized as a python module with common, local, and production settings. I'm not sure where and how to fix this problem, and I've been stuck here for a few days now. Would appreciate any input! ERROR TRACE [2022-07-31 03:29:55] Traceback (most recent call last): [2022-07-31 03:29:55] File "<frozen importlib._bootstrap>", line 908, in _find_spec [2022-07-31 03:29:55] AttributeError: 'ConfigurationImporter' object has no attribute 'find_spec' [2022-07-31 03:29:55] [2022-07-31 03:29:55] During handling of the above exception, another exception occurred: [2022-07-31 03:29:55] [2022-07-31 03:29:55] Traceback (most recent call last): [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker [2022-07-31 03:29:55] worker.init_process() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process [2022-07-31 03:29:55] self.load_wsgi() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi [2022-07-31 03:29:55] self.wsgi = self.app.wsgi() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi [2022-07-31 03:29:55] self.callable = self.load() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load [2022-07-31 03:29:55] return self.load_wsgiapp() [2022-07-31 03:29:55] File "/usr/local/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp [2022-07-31 03:29:55] return … -
Django schema made, but "No tenant for hostname" error
I was able to create a schema (and I confirmed this via database) but for some reason, I am getting this error "No tenant for hostname" and I am not sure what is causing it. Below is my code: views.py def post(self, request): form = CreatePortalForm(request.POST) if form.is_valid(): getDomain = form.cleaned_data.get('name') instance = form.save(commit=False) user_id = request.user.id user = User.objects.get(id=user_id) tenant = Client(schema_name=getDomain, name=getDomain, created_by=user) tenant.save() domain = Domain() domain.domain = getDomain + ".example.com:8000" domain.tenant = tenant domain.is_primary = True domain.save() with schema_context(tenant.schema_name): instance.save() redirect = 'http://' + getDomain + '.example.com:8000' return HttpResponseRedirect(redirect) return render(request, "registraton/create_portal.html", {"form": form}) Like I said, the schema is creating and migrating successfully but I still cannot get to the domain.example.com as it throws the "No tenant for hostname" error. Not sure if another table is made for "tenant_domains"? Any ideas on what is causing this?