Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get exact values of the foreignkeys in django admin
class Mio_terminal(models.Model): terminal = models.CharField(max_length = 50) gate = models.CharField(max_length = 50) gate_status = models.CharField(max_length = 50, default = 'open') #open, occupied, under_maintenance class Meta: unique_together = [['terminal', 'gate']] class Mio_flight_schedule(models.Model): fact_guid = models.CharField(max_length=64, primary_key=True) airline_flight_key = models.ForeignKey(Mio_airline, related_name = 'flight_key', on_delete = models.CASCADE) source = models.CharField(max_length = 100) destination = models.CharField(max_length = 100) arrival_departure = models.CharField(max_length=12) time = models.DateTimeField() gate_code = models.ForeignKey(Mio_terminal, related_name = 'terminal_gate', null = True, on_delete = models.SET_NULL) baggage_carousel = models.CharField(max_length = 100) remarks = models.CharField(max_length = 100) terminal_code = models.ForeignKey(Mio_terminal, related_name = 'airport_terminal', null = True, on_delete = models.SET_NULL) this is models for terminal and flight schedule. I want to have terminal name and gate code instead of the object ... i know we can get this by using str method in models....but we get only single value for this...not more than one please let me know how should i deal with this? -
Creating a rating system scale 1-5 and average rating
enter image description here] This is in python with Django and using SQL as database. I am new to this language. I am having issues with creating the average rating for books. I want to get a list of books that userid's have rated and get the average of it. I don't know if I can use querysets. I also want to know how I can create a comment to warn people on postman that the scale is only 1-5. I don't know if I can do it as an if-else statement or not I look into the django website on aggregation to see if the average works but I can't seem to figure it out. I tried creating an if else statement but > is not supported between instances of -
How to associate an existing user with multiple social accounts (different emails)? [DRF_SOCIAL_OAUTH2]
I'm trying to associate user with multiple social accounts in Django Rest Framework. After user login, user can associate with social accounts (it doesn't matter same email or different email). Now I am using the library drf-social-oauth2. I have done signIn/singUp part. According to Social_Auth_Pipeline, I added this code to associate user SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) The endpoint "http://localhost:8000/auth/convert-token" can handle the singin/singup using social auth.(eg. Facebook, Google) social_core.pipeline.social_auth.associate_by_email managed to associate the user if same email. My Question is How can I connect/associate Social Accounts (* different email/same email) with current login user using drf_social_oauth2? Do I need to add field in user table to associate? OR Do I need to add something to setting.py?... Please advise me. Thank you. -
Active or inactive users
I'm trying to design a django application where users' accounts can only be activated after making payments...Inactive users are denied all the web functionalities until the make payments. How can I go about this? -
Django rest framework user model permissions
I am building a web app using REST API and I have a 4 users that I want them to access only the content they have added to the backend. I have created 3 users say farmers(3 farmers) and added content using each one of them. However, I have been unable to implement permissions such that a farmer can view and delete only what they added. Here's is my code in models.py User = get_user_model() # Create your models here. class Tender(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() date_due = models.DateField(default=datetime.date.today) location = models.CharField(max_length=255, null=False) contact = models.PositiveIntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Input(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.DecimalField(max_digits=10, decimal_places=2) contact = models.PositiveIntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Investor(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) description = models.TextField() location = models.CharField(max_length=255, null=False) contact = models.PositiveIntegerField(null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name Here's what I implemented in permissions.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, … -
Problem using npm of chart.js in django Project
I tried to use Chart.js in my Django project , when I Use NPM package it's not working but when I use CDN It work Perfectly char.js version 3.9.1 here is my index.html file on my project <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {# <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>#} <script type="application/json" src="/node_modules/chart.js/dist/chart.js"></script> </head> <body> <canvas id="myChart" width="400" height="400"></canvas> <script> const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { y: { beginAtZero: true } } } }); </script> </body> </html> my console error in browser is : (index):17 Uncaught ReferenceError: Chart is not defined at (index):17:17 I tried to use chart.min.js in my script but not working. I also Try previous version of charj.js but … -
Python sleep if a function runs for 20 times
I have a function for sending an email which is used in a celery task i need to make the code sleep for a second if that email function is ran for 20 times how can i make this happpen. @app.task(bind=True) def send_email_reminder_due_date(self): send_email_from_template( subject_template_path='emails/0.txt', body_template_path='emails/1.html', template_data=template_data, to_email_list=email_list, fail_silently=False, content_subtype='html' ) so the above code is celery periodic task which runs daily i filter the todays date and send the email for all the records which are today's date if the number of records is more than 20 lets say so for evry 20 emails sent we need to make the code sleep for a second send_email_from_template is function which is used for sending an email -
Group Session in Django Channels
I'm looking for a solution where I want to create a group with n number of users and let them-users join the group. and then finally, delete this group once the work is complete. (the creator of the group can delete this or when everyone from the group disconnects). I have been thinking to design this for the last 3-4 days but I'm not able to. I'm building the transcriber app and this group is to maintain sessions on each topic. For every new topic/scenario, a new group/session is required. The question is - How and when should I delete the group? Suppose I created a group and then everyone joins, I can maintain a database and delete this group when everyone disconnects from this group, somehow I don't think this to be the best option Can anyone guide me to design the best possible option? Will provide more details if required. -
Django Web Application - Monitor local folder and import csv files to database
I have this Django web application project that needs to be hosted on a local network. In addition basic CRUD features, the scope requires to continuously monitor a local storage folder (C: or D: or E:) for csv files and import them to the database (Postgresql). I have already written the code for reading the csv files and importing them to the database and moving these csv files to another folder (after importing). What I don't know is where should I put this code and call the function (import_to_db), such that it runs continuously to scan the folder for new csv files? It cannot be a python command line interface. I am not fully conversant with Django REST Framework and not sure if it applies to this scope, since the csv files will be made available in a local folder. Any tips or references to examples/libraries would help. Code to Import: def get_files(): csv_files = [] for file in os.listdir(os.getcwd()): if file.endswith('.csv'): csv_files.append(file) return csv_files def move_files_to_folder(csv_files, destination): try: os.mkdir("BackupFiles") except: print('BackupFiles Directory Already Exists') finally: for file in csv_files: shutil.move(file, destination) os.chdir(destination) return csv_files def import_to_db(): csv_files = get_files() engine = create_engine( url="postgresql://{0}:{1}@{2}:{3}/{4}".format(user, password, host, port, database)) for file … -
Overlaping URLs in Django (two applications in one Django project)
I'm making my studying project, called GuitarStore. I have two application in this project - shop and blog. Here is fictional situation: I have that "contacts" page for my team of authors, and another "contacts" page for my sale team. Here's piece ofmy guitarstore/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shop.urls')), path('blog/', include('blog.urls')), path('', RedirectView.as_view(url='/shop/', permanent=True)), ] piece of shop/urls.py: path('', views.shop, name='shop'), re_path(r'^section/(?P<id>\d+)$', views.section, name='section'), re_path(r'^product/(?P<pk>\d+)$', views.ProductDetailView.as_view(), name='product'), re_path(r'^manufacturer/(?P<id>\d+)$', views.manufacturer, name='manufacturer'), path('delivery', views.delivery, name='delivery'), path('contacts', views.contacts, name='contacts'), path('search', views.search, name='search'), and piece of blog/urls.py: path('', views.blog, name='blog'), re_path(r'^blog/(?P<month_n_year>\w{7})$', views.blog_filtered, name='blog'), re_path(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(), name='post'), path('gallery', views.gallery, name='gallery'), path('about', views.about, name='about'), path('contacts', views.contacts, name='contacts'), path('search', views.search, name='search'), I thought Django would come up with two separate paths like "shop/contacts" and "blog/contacts" but not. I have that piece of html template: <div class="top-nav"> <ul class="cl-effect-1"> <li><a href="{% url 'gallery' %}">Main</a></li> <li><a href="{% url 'about' %}">Abour us</a></li> <li><a href="{% url 'blog' %}">Blog</a></li> <li><a href="{% url 'contacts' %}">Contacts</a></li> </ul> </div> and all I get is "shop/contacts" for the last part of menu. Should I make sure that all my urls have a bit of excess so I can't overlap them or I just have to make some settings so my applications have some priorities … -
For-looping three columns per row in Django template
I'm trying to retrieve data from the database and render it in rows of three columns. I've tried as many methods as I could find, finally it seemed to be rendering with this code: <div class='container'> <div class="row"> {% for category in categories %} {% if not forloop.counter0|divisibleby:"3" %} <div class="col-6 col-md-4"> <h3>{{category.category_name}}</h3> {% for page in category.page_set.all %} <p>{{page.page_title}}</p> {% endfor %} </div> {% else %} <div class="row"> <div class="col-6 col-md-4"> <h3>{{category.category_name}}</h3> {% for page in category.page_set.all %} <p>{{page.page_title}}</p> {% endfor %} </div> {% endif %} {% endfor %} </div> It renders the elements in three columns but the columns are not aligned, and when checking the HTML, the 'row' class is the same for all the rows (giving it an id and checking by CSS), so I guess there's something I'm doing wrong. I'd like to get an output like: Category1 - Category2 - Category3 Category4 - Category5 - Category6 With the 'page' objects of each category underneath. The data is rendering OK, the view is simple (just getting all the Category objects). I just need this kind of data rendering in different rows of 3 columns. I've tried the divisibleby method, but I guess I'm still missing … -
Uploading image with FastAPI cause exc.ResourceClosedError
I have an endpoint which saves uploaded image to it: @router.post("/v1/installation/{installation_uuid}/image") @db.create_connection async def upload_installation_image(installation_uuid: UUID, request: Request): content_type = request.headers["content-type"] async with db.transaction(): installation = await get_installation_by_uuid(installation_uuid) if not installation: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Installation {installation} not found") try: content = await request.body() image_uuid = await save_installation_image(installation.uuid, content, content_type) except Exception as e: log.debug(f"An error raised while uploading image: {e}") raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Error while uploading image to db" ) return {"image_uuid": image_uuid} save_installation_image make simple insert into DB. In my tests I send 3 request to this endpoint. and all works fine: tests.py # upload image 1 data1 = b"\x01\x02\x03\x61\x05\x61" response = session.post( f"/v1/installation/{installation_uuid}/image", data=data1, headers={"content-type": "image/png"} ) # upload image 2 data2 = b"\x01\x02\x03\x61\x05\x62" response = session.post( f"/v1/installation/{installation_uuid}/image", data=data2, headers={"content-type": "image/png"} ) # upload image 3 data3 = b"\x01\x02\x03\x61\x05\x63" response = session.post( f"/v1/installation/{installation_uuid}/image", data=data3, headers={"content-type": "image/png"} ) But when FE start calling that request, each request after first one start failing with this error: Traceback (most recent call last): File "/opt/kelvatek/camlin-relink-broker/venv/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 404, in run_asgi result = await app( # type: ignore[func-returns-value] File "/opt/kelvatek/camlin-relink-broker/venv/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__ return await self.app(scope, receive, send) File "/opt/kelvatek/camlin-relink-broker/venv/lib/python3.9/site-packages/uvicorn/middleware/message_logger.py", line 86, in __call__ raise exc from None File "/opt/kelvatek/camlin-relink-broker/venv/lib/python3.9/site-packages/uvicorn/middleware/message_logger.py", line 82, in __call__ … -
How can I hide or remove a sub-menu inside dropdown menu? I am new to python django
So, I found the below Django source code file on the internet. generic_subnavigation.html {% load common_tags %} {% load navigation_tags %} {% if link|common_get_type == "<class 'mayan.apps.navigation.classes.Menu'>" %} <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true"> {% if link.icon %}{{ link.icon.render }}{% endif %} {{ link.label }} <span class="caret"></span> </a> <ul class="dropdown-menu"> {% navigation_resolve_menu name=link.name as sub_menus_results %} {% for sub_menu_results in sub_menus_results %} {% for link_group in sub_menu_results.link_groups %} {% with '' as li_class_active %} {% with link_group.links as object_navigation_links %} {% include 'navigation/generic_navigation.html' %} {% endwith %} {% endwith %} {% endfor %} {% endfor %} </ul> </li> {% else %} {% if as_li %} <li class="{% if link.active and li_class_active %}{{ li_class_active }}{% endif %}"> {% endif %} {% include link_template|default:'navigation/generic_link_instance.html' %} {% if as_li %} </li> {% endif %} {% endif %} The code renders a webpage with sub-menus shown in the picture below; How do I remove the "setup and tools" menu in the sub-menus shown in the picture? At least comment on it out. generic_link_instances.html {% if link.separator %} <li role="separator" class="divider"></li> {% elif link.text_span %} <li class="text-center link-text-span {{ link.html_extra_classes }}" >{{ link.text }}</li> {% else %} {% if link.disabled %} <a … -
Python cleaning text emoji-library django-error
I want to use the emoji library to replace emoji's in text, nothing fancy. conn = create_connection(database) cur1 = conn.cursor() cur2 = conn.cursor() sql_select = """SELECT msg_id, MessageClean FROM Tbl_RawDataPART where MessageClean <> ''""" count = 0 for row in cur1.execute(sql_select): count += 1 (msg_id, original_message,) = row # extracting all emoji's message_without_emoji = emoji.demojize(original_message) When I run this code I get an error. I can't figure out why and how to correct this (never used django). django.core.exceptions.ImproperlyConfigured: Requested setting EMOJI_IMG_TAG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
how can I use multi functions in one page without change the URL using Django?
I'm trying to use Django to build my yt-dlp app, I want to create one page with had toggle list or multi buttons, when I use the first action on the toggle list or button the yt-dlp will download the video file or best quality the video, and when I use the second action the yt-dlp will download the audio file, I tried this #views.py from django.shortcuts import render, redirect from yt_dlp import YoutubeDL def hq(request): if request.method == 'POST': URLS = request.POST['HQ'] # to input a url by the user opt = { 'format' : 'bestvideo/best' } with YoutubeDL(opt) as ydl: # with used to put ydl_opts and apply changes ydl.download(URLS) # to start downloading # print('Successfully downloaded') return render(request, 'video.html') # Create your views here. def ad(request): if request.method == 'POST': URLS = request.POST['audio'] # to input a url by the user opt = { 'format': 'bestaudio/best', } with YoutubeDL(opt) as ydl: # with used to put ydl_opts and apply changes ydl.download(URLS) # to start downloading # print('Successfully downloaded') return render(request, 'audio.html') # Create your views here. def list(request): return render(request, 'list.html') #list.html {% extends 'base.html' %} {% block title %} list {% endblock title %} {% block … -
Django raised 'django.utils.datastructures.MultiValueDictKeyError: 'image'' at uploading image
I was trying to upload an image via a form, but django raised "django.utils.datastructures.MultiValueDictKeyError: 'image'" in line 106, views.py. I don't know what's happening, and why is throwing me an error when I submit via a custom form, but it does not happen via admin interface. Can anybody help? My code: models.py: class listings(models.Model): is_sold = models.BooleanField( default=False, verbose_name="Is Sold") title = models.CharField(max_length=100) description = models.TextField(max_length=750) price = models.FloatField() user = models.ForeignKey(to=User, on_delete=models.CASCADE) category = models.IntegerField(default=0, choices=categoryChoices) image = models.ImageField(upload_to='uploads/', blank='True', null='True') time_posted = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-time_posted',) def get_image(self): if self.image: return 'http://127.0.0.1:8000' + self.image.url return '' def __str__(self): return f"{self.id}: {self.title}" views.py: def add_auction(request): if request.method == "POST": title = request.POST["title"] description = request.POST["description"] price = request.POST["price"] image = request.POST["image"] category = request.POST["category"] user = request.user listing = listings(title=title, description=description, price=price, image=image, category=category, user=user) try: listing.save() except ValueError: return render(request, "auctions/add_auction.html", { "message": "Error adding auction." }) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/add_auction.html") template: <h1>Add Listing</h1> <form action="{% url 'add_auction' %}" method="POST"> <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" name="title" placeholder="Title"> </div> <div class="form-group"> <label for="description">Description</label> <textarea class="form-control" id="description" name="description" rows="3"></textarea> </div> <div class="form-group"> <label for="price">Price</label> <input type="float" class="form-control" id="price" name="price" placeholder="Price"> </div> <div class="form-group"> … -
Whats the process for taking a python function and transferring it to Django output?
I'm experimenting with Django, and had a few questions about how python functions are translated into Django outputs. Firstly, is it correct to use Http Responses to generate Django ouptut from python functions? For example, if I have a Hello world function that returns the string Hello world, is it as simple as creating another function within my views.py, and simply return an Http response of HelloWorld()? Is there a different way in which developers conduct this transition from python function to Django? Thanks. def HelloWorld(): return "Hello World" def test(request): return HttpResponse(HelloWorld()) -
Access denied for files uploaded to digital ocean private folder after I added the custom domain
access denied for files uploaded to private folder after I added the custom domain. If I included custom_domain=False then it works but the access goes to digitalocean and not custom domain. Is it possible to use access private file using custom domain? class PrivateMediaStorage(S3Boto3Storage): location = 'private' default_acl = 'private' file_overwrite = False custom_domain = False -
How can I prevent Django view from being called repeatedly despite of long execution time?
I have a Django view which runs a sub process and returns a JsonResponse back to the user: def process_images(request, id): log.debug("Processing images view...") start = perf_counter() result = subprocess.run(["ssh", "<REMOTE SERVER>", "bash", "process_images.sh"], capture_output = True, text = True) # Run backend processing log.debug("Result stdout:\n" + result.stdout) with open(f"{settings.MEDIA_ROOT}/{id}/image.json", "r") as f: response_data = json.load(f) time_took = perf_counter() - start log.debug(f"View time took {time_took} seconds") return JsonResponse(response_data, status=201) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<id>/process', views.process_images, name='process'), path('<id>/', views.model, name='model') ] app_name = "render" However when I try accessing render/ID/process ONCE, I'm greeted with: [Oct 25, 2022 07:30:13 PM] DEBUG [render.views:49] Processing images view... [Oct 25, 2022 07:31:24 PM] DEBUG [render.views:55] Result stdout: Backend processing... [Oct 25, 2022 07:31:24 PM] DEBUG [render.views:61] View time took 70.49786422774196 seconds [Oct 25, 2022 07:31:24 PM] DEBUG [render.views:49] Processing images view... [Oct 25, 2022 07:32:16 PM] DEBUG [render.views:55] Result stdout: Backend processing... [Oct 25, 2022 07:32:16 PM] DEBUG [render.views:61] View time took 52.54661420173943 seconds [Oct 25, 2022 07:32:16 PM] DEBUG [render.views:49] Processing images view... [Oct 25, 2022 07:33:08 PM] DEBUG [render.views:55] Result stdout: Backend processing... [Oct 25, 2022 07:33:08 PM] DEBUG [render.views:61] View time … -
Alternative to eval for use in equations [duplicate]
I am creating a Django application that stores an equation with variables that needs to be calculated in the backend. i.e. the user would store the following as a string: {rower_weight}/({rower_time})^3 where rower_weight ad rower_time are variables. Then, in the backend (upon receiving new data) would store a calculated field based on the formula. I considered using eval or f-strings, however would be unsafe with user input. What would be the best alternative that would allow for unsafe user input to be used? Thanks! -
Why did come this error when I call API ?'WSGIRequest' object has no attribute 'get'
I would like to show the data in the template from the backend by calling the API I made. But the below error shows up. Why it came? Give me a relevant solution... views.py: class CourseViewSet(ModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer def CourseInfo(request): callApi = request.get('http://127.0.0.1:8000/api/courses/').json() context = { "queryset":callApi } return render(request, 'insert.html',context) urls.py: router = DefaultRouter() router.register('courses', views.CourseViewSet, basename='course') urlpatterns = [ path('', views.CourseInfo, name='CourseInfo'), path('api/', include(router.urls)), ] models.py: class Course(models.Model): name = models.CharField(max_length=250) class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = "__all__" Error: AttributeError at / 'WSGIRequest' object has no attribute 'get' Request Method: POST Request URL: http://127.0.0.1:8000/?coursename=Bangla&courseauthor=Mossaddak&courseprice=23322&coursediscount=234&courseduration=23 Django Version: 3.2.3 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'get' Exception Location: D:\1_WebDevelopment\7_ProgrammingLanguage\1_FrameWork\4_Django-Rest-Frame-work\2_CBVproject\CBVapp\views.py, line 32, in CourseInfo Python Executable: C:\Users\DCL\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['D:\\1_WebDevelopment\\7_ProgrammingLanguage\\1_FrameWork\\4_Django-Rest-Frame-work\\2_CBVproject', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\win32\\lib', 'C:\\Users\\DCL\\AppData\\Roaming\\Python\\Python39\\site-packages\\Pythonwin', 'C:\\Users\\DCL\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Tue, 25 Oct 2022 23:10:07 +0000 -
How do you pass request data to Forms in Django?
here I am using model forms and trying to make my placeholder dynamic. my approach is to take request data, pass it into widgets with f string. what I am trying to achieve is {'placeholder': f"commenting as {request.user.username}"} HERE IS MY CODE. class CommentForm(ModelForm): class Meta: model = Comment fields = ("body",) widgets = { "body": forms.TextInput( attrs={ "placeholder": "Enter your comment", "class": "comment-form-text", } ), } labels = { "body": "", } -
Page not found (404) - Django 3
Criei uma view de search, adicionei uma url e crie um template para view Quando executo e tento acessar a url aparece um erro " Page not found (404) " Estrutura criada abaixo views def job_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Opportunity.published.annotate(search=SearchVector('title'),).filter(search=query) return render(request, 'job/search.html', {'form': form, 'query': query, 'results': results}) url path('search/', views.job_search, name='job_search'), -
Dynamically-sided table with integer inputs in Django
I'm new to Django and I was wondering how to do the following task: Make a table with m rows and n columns where both m and n are specified by the user. The user should be able to type an integer into any cell of the table, and when they're done, they can hit a submit button that POSTs their input. I think Django forms are the way to go. I don't necessarily need an explicit solution (of course that is welcome too); merely pointing me towards helpful resources or design strategies would suffice. -
Vue Routing isn't returning blog posts
I am unable to return data once I click on the blog post. I believe that it is an issue with routing. When clicking to a blog post we no content is return.