Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django "makemigrations" problem not working
08:41 ~/myapk $ python manage.py makemigrations Traceback (most recent call last): File "/home/chaxim/myapk/manage.py", line 22, in <module> main() File "/home/chaxim/myapk/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute _from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 228, in create if not issubclass(app_config_class, AppConfig): TypeError: issubclass() arg 1 must be a class everytime i tried to make migrations it shows same thing, i even tried export DJANGO_SETTINGS_MODULE=yoursite.settings command but no result. -
Using Telegram Bot with Django
I am trying to use my telegram bot with Django. I want the code to keep running in the background. I am Using the apps.py to do this but there's one problem when the bot starts as it's an infinite loop, the Django server is never started. Apps.py: from django.apps import AppConfig import os class BotConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'bot' def ready(self): from . import jobs if os.environ.get('RUN_MAIN', None) != 'true': jobs.StartBot() Jobs.py: def StartBot(): updater = Updater("API KEY") dp = updater.dispatcher dp.add_handler(ChatMemberHandler(GetStatus, ChatMemberHandler.CHAT_MEMBER)) updater.start_polling(allowed_updates=Update.ALL_TYPES) updater.idle() What's the best way to run my bot in the background? while making sure that the Django server runs normally. I tried Django background tasks but it's not compatible with Django 4.0. -
Setup Django Push notification for web only?
I want to setup push notification for website. I just follwed as described in documenation but Unfurtunately it is now working. Here is my settings. PUSH_NOTIFICATIONS_SETTINGS = { "WP_PRIVATE_KEY": BASE_DIR / 'private_key.perm', "WP_CLAIMS": {'sub': "mailto: development@example.com"} } and here is my client side code, I just copy this code from documentation ..... <h1>Push Notification Example</h1> <script> ............... ........... var applicationServerKey = "...."; // In your ready listener if ('serviceWorker' in navigator) { // The service worker has to store in the root of the app // http://stackoverflow.com/questions/29874068/navigator-serviceworker-is-never-ready var browser = loadVersionBrowser('chrome'); navigator.serviceWorker.register('navigatorPush.service.js?version=1.0.0').then(function (reg) { reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(applicationServerKey) }).then(function (sub) { var endpointParts = sub.endpoint.split('/'); var registration_id = endpointParts[endpointParts.length - 1]; var data = { 'browser': browser.name.toUpperCase(), 'p256dh': btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('p256dh')))), 'auth': btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('auth')))), 'name': 'XXXXX', 'registration_id': registration_id }; console.log(data); }) }).catch(function (err) { console.log(':^(', err); }); } and here is error snippets. I don't know what I'm missing??. -
django-pgroonga installation error: "UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 112: character maps to <undefined>"
I need to use Japanese characters with vector searches in Django / Postres. I am trying to install django-pgroonga and keep getting the same encoding error with cp1252.py: PS C:\JGRAM\JLPT> pip install django-pgroonga Collecting django-pgroonga Using cached django-pgroonga-0.0.1.tar.gz (3.7 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [10 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "C:\Users\61458\AppData\Local\Temp\pip-install-21w4o7u8\django-pgroonga_87013717bf0e4bcca83db91a993082b4\setup.py", line 17, in <module> long_description=read('README.rst'), File "C:\Users\61458\AppData\Local\Temp\pip-install-21w4o7u8\django-pgroonga_87013717bf0e4bcca83db91a993082b4\setup.py", line 6, in read return open(os.path.join(os.path.dirname(__file__), fname)).read() File "C:\Users\61458\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] **UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 112: character maps to <undefined>** [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. PS C:\JGRAM\JLPT> Can you help? I cannot find a solution online that outlines how to resolve this error when it occurs 'during installation'. I have tried updating the cp1252.py file, copying and … -
Django admin change view not change in linux
I have a change for the model in the templates folder, I added a button to object tools. In Windows, the change works without a problem; on Linux, the change cannot be seen. I restarted nginx, gunicorn. I tried collections static and it didn't help. I put the same version of django on linux also didn't help. -
How to create default filter on django queryset
I have below model in my django app. class Segment(BaseSegmentModel): payload_json = JSONField(null=True, default=None, blank=True) owner = models.ForeignKey(CustomUser, null=True, blank=True, on_delete=models.SET_NULL, related_name='segments') name = models.CharField(max_length=100, null=True, blank=False) status = models.CharField(max_length=100, null=True, blank=True, choices=SegmentStatuses.choices, default=SegmentStatuses.STOPPED) created_date = models.DateTimeField(null=True, auto_now_add=True)as There is a field status which has three values, Active Running Archive I need to add a default filter on this model where it should not show any results with status = Archive So whenever someone query this model it should not show any Archive results. -
Django-notifications-hq How to live update notifications to read
I've spent all day scouring a few versions of docs for this plugin, I've read through all of the tutorials I can find, and I went through every file in the repo to make note of all of it's parts. This ajax aspect is what I'm struggling with. my example is essentially this getting started tutorial, I just customized the html output by overwriting the fill_notification_list javascript function: https://pypi.org/project/django-notifications-hq/ I have the notifications outputting into my template and have written a function for overwriting the default notifications javascript function. It's just a list of the notifications as text items. I want to mark all of the notifications "unread=False" when the alerts dropdown is clicked. I know I'm supposed to ping a url on my app to set the notifications to read and then update the list using ajax. I started with: $('.sh-alert-btn').on('click touch', function(){ $.get('{% url "notifications:mark_all_as_read" %}', function(response) { }); }); but I realized I don't know what to do at this point. This is my custom fill_notification_list function: function streamshiv_notify(data) { var menus = document.getElementsByClassName('live_notify_list'); if (menus) { var messages = data.unread_list.map(function (item) { if(typeof item.verb !== 'undefined'){ message = message + '<h6>' + item.verb + "</h6>"; } … -
Why does my django allow downloading files outside of static folder?
My django project allows downloding images from static folder: http://0.0.0.0:8001/static/img/login.png This makes sense. But what concerns me is that it also allows me downloading files even outside of the static folder such as: http://0.0.0.0:8000/logs/result.log or even worse: http://0.0.0.0:8000/users/models.py All my local files can be downloaded via clients. This is a high security vulnerability. No matter what is the permission of my folders on my Linux server. I do not have such items in my path and I do not expect these paths being served. How can I fix this? BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True INSTALLED_APPS = [ 'comments', 'home', 'users', 'articles', 'notifications', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.sessions', 'django.contrib.staticfiles', 'static_precompiler', 'django_markup', 'django_minify_html', 'django_rename_app', ] MIDDLEWARE = 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', 'django_minify_html.middleware.MinifyHtmlMiddleware', ] ROOT_URLCONF = 'profplus.urls' TEMPLATES = TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'profplus.wsgi.application' STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_FINDERS = STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'static_precompiler.finders.StaticPrecompilerFinder', ] -
Celery doesn't start with Django 4.0
I have upgraded from Django 2.2 to 4.0, and even though the application works fine, celery doesn't start, it only displays the Celery logo, no text, no errors. My application has some tasks.py files in different modules. According to Celery's website, everything is set up fine. I even tried the debug_task example to test it, but I am getting the same result. My celery.py file inside proj/ is the following: import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings.production') app = Celery( 'proj', backend='amqp', broker='amqp://guest@localhost:5672//' ) app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) Then, as mentioned in the official documentation, my proj/init.py is the following: from .celery import app as celery_app __all__ = ('celery_app',) -
Best way to create a unique URL to 'check-in' [Django]
I am needing to have a simple way for employees to 'check-in' to work by scanning a QR code that would be regenerated daily that would be available at the office. The qr code would take them to a page where they click 'check-in' in order to get credit for attendance. Where I'm getting stuck is that I would like is that there wouldn't be an easily sharable URL that employees could just send to one another. I've thought of having some kind of URl redirect but it seems like there would be a better solution. -
Django Query with 3 related tables
I'm hoping I can get a little guidance. I'm trying to return data from 3 related tables in my template. In SQL, this is a simple approach, but the Django requirements have me stumbling. I'd like to display information similar to this: WaiverAdult.first_name CheckIn.checkintime WaiverMinor.first_name CheckIn.checkintime WaiverAdult.first_name CheckIn.checkintime WaiverMinor.first_name CheckIn.checkintime WaiverMinor.first_name CheckIn.checkintime Here are a simplified representation of the models with the relationships defined. class WaiverAdult(models.Model): first_name = models.CharField(max_length=50, blank=True) class WaiverMinor(models.Model): first_name = models.CharField(max_length=50, blank=True) parent = models.ForeignKey(WaiverAdult, on_delete=models.CASCADE) class CheckIns(models.Model): adult = models.ForeignKey(WaiverParent, on_delete=models.CASCADE, blank=True, null=True) minor = models.ForeignKey(WaiverChild, on_delete=models.CASCADE, blank=True, null=True) checkintime = models.DateTimeField(auto_now_add=True) Here is my simplified view: class WaiverListView(ListView): waiver_adults = WaiverAdult.objects.all().prefetch_related( 'waiverminor_set').order_by('created') queryset = waiver_adults context_object_name = "waiver_list" template_name = 'waiver/waiver_list.html' And, this is my template. {% for adult in waiver_list %} <tr> <td>{{adult.first_name}}</td> <td>insert the adult checkin time here</td> </tr> {% for child in adult.waiverminor_set.all %} <tr> <td>{{child.first_name}}</td> <td>insert the child checkin time here</td> </tr> {% endfor %} {% endfor %} I would be very appreciative of details in the explanations as I really want to understand how this all works. Thank you in advance. -
Django: view not working, when i redirect to the view it failed to load the page?
I am trying to redirect to a callback view in django but it seems not to be working, the urls.py looks okay, but it keeps failing. i have a view investmentDetail that is getting the purchased_package_id , now the purchased package id is what i use to keep track of the particular payment that is being processed and i have passed in the purchased_package_id as parameter to my function, so i can do something with it in the urls, views body e.t.c but it seems that the purchased_package_id isn't working as expected and i cannot really tell what is broken? views.py def investmentDetail(request, slug): investment = InvestmentPackage.objects.get(active=True, slug=slug) if request.method == "POST": purchased_package = PurchasedPackage.objects.create(user=request.user, investment_package=investment ) purchased_package_id = purchased_package.id name = request.POST.get("name") email = request.POST.get("email") amount = request.POST.get("amount") return redirect(str(process_payment(name,email,amount, investment, purchased_package_id))) else: pass context = { "investment":investment, } return render(request, "core/investment-detail.html", context) def process_payment(name,email,amount, investment, purchased_package_id): auth_token= settings.FLUTTER_SECRET_KEY hed = {'Authorization': 'Bearer ' + auth_token} data = { "tx_ref":''+str(math.floor(1000000 + random.random()*9000000)), "amount":amount, "currency":"NGN", "redirect_url":f"http://localhost:8000/callback/{purchased_package_id}/", "payment_options":"card", "meta":{ "consumer_id":23, "consumer_mac":"92a3-912ba-1192a" }, "customer":{ "email":email, "name":name }, "customizations":{ "title":"Investment Platform", "description":" Limitless Learning For Everyone", "logo":"https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" } } url = ' https://api.flutterwave.com/v3/payments' response = requests.post(url, json=data, headers=hed) response=response.json() link=response['data']['link'] return link @login_required … -
import 'django' couldn't be resolved from source (VSCode)
I want to configure properly VSCode for working with Django but I get an error when I try to import any module from Django. I've researched many other similar questions but it doesn't solve it. One of the most popular answers is that the Python Interpreter should be the one inside my Virtual Environment in where I have Django installed. Inside the bin folder of my virtual environment I have three Python shortcuts (Python, Python3 and Python3.6). Any of them will solve the import error. Also, inside my project I have a file called pyvenv.cfg that looks like this. If I try to select the interpreter from that same path (the one in home) the import error still appears. How should I configure my Python interpreter in order that it recognizes all the Django imports? -
django model.objects.values() return related id instead of title
I want to get Chapter model data as json , i used values() method and it works but it return book id not the book title and i want the book title models.py class Books(models.Model): title = models.CharField(max_length=200 , unique=True) slug = models.SlugField(max_length=255,unique=True) data_id = models.IntegerField(unique=True) def __str__(self): return str(self.title) class Chapter(models.Model): book_id = models.ForeignKey(Books,on_delete=models.CASCADE) source = models.CharField(max_length=100,blank=True) chapter = models.CharField(max_length=10) date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.chapter)+" "+str(self.book_id) views.py class BookChapters(LoginRequiredMixin,View): def get(self,request): chapters = Chapter.objects.values() return JsonResponse(list(chapters),safe=False) json ouput [ { id: 1, book_id: 237, source: "nobel", chapter: "18", date: "2022-06-26T17:50:26Z" }, { id: 2, book_id: 237, source: "noble", chapter: "19", date: "2022-06-26T17:50:28Z" }] -
Django with Javascript fetch API: POST works but all other unsafe methods are forbidden
I am working on this CS50W project. When using the fetch API to send POST requests to the server, everything worked fine. After I changed the method to PUT, or any other unsafe methods, things stopped working. Javascript let like_form = document.querySelector('#like-form'); let data = new FormData(like_form); fetch(`post/${post_id}/like`, { method: 'POST', body: data, credentials: "same-origin" }) views.py @login_required def like_post(request, post_id): if request.method == 'POST': post = get_post(post_id) if post: if request.user in post.liked_by.all(): post.liked_by.remove(request.user) status = False else: post.liked_by.add(request.user) status = True return JsonResponse({ 'message': 'Success.', 'status': status }, status=200) index.html <form id='like-form'> {% csrf_token %} </form> Output using POST {message: 'Success.', status: false} Output using PUT PUT http://127.0.0.1:8000/post/17/like 403 (Forbidden) Forbidden (CSRF token missing.): /post/17/like The only thing I changed was the method in fetch and views.py Any help will be appreciated. -
How can I send emails with Django to my gmail account
I've tried sending emails with my Gmail account in Django, but I always get errors. I tried using a sandbox (Mailtrap) and it worked but using the actual Gmail account doesn't. I've also tried using App Password in my google account but it still doesn't work. EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "example@gmail.com" EMAIL_HOST_PASSWORD = "password" Error I always get; SMTPConnectError at /send/ (421, b'Service not available') This is what shows up Please how can this be fixed. -
Is there a way to implement the following requirements in django
Please, I need your suggestions, contributions, advise on how to implement the following in django: on user signup, validate email formatting and only allow signups with valid emails once signed up, enrich the User with geolocation data of the IP that the signup originated from based on geolocation of the IP, check if the signup date coincides with a holiday in the User’s country, and save that info data enrichment must be performed asynchronously, i.e. independently of the signup route API request implement retries for requests towards 3rd party API -
Populating Table Based on Drop Down Selection
Hi I'm trying to create a table that will show values based on the selected name. For instance if a drop down existed and a value was chosen, the rest of the fields would show the data associated with that chosen value. <div class="main-items"> <h2>Database</h2> <div class="card-items"> <table class="main-items-table"> <tr> <td class="menu-box-tab-items-identifiers">Name:</td> {% for d in database %} <td class="menu-box-tab-items" href="/cusip/{{d.company_name}}"><span>{{d.name}}</span></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Item:</td> {% for d in database %} <td class="menu-box-tab-items"><span>{{d.item}}</span></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Method of Shipment:</td> {% for d in database %} <td class="menu-box-tab-items" href="#6"><span>{{d.method_of_shipment}}</span></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Days:</td> {% for d in database %} <td class="menu-box-tab-items" href="#6"><span>{{d.days}}</span></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Location:</td> {% for d in database %} <td class="menu-box-tab-items"><a href="https://www.google.com/search?q={{d.location}}"></span>{{d.location}}</a></td> {% endfor %} </tr> <tr> <td class="menu-box-tab-items-identifiers">Country:</td> {% for d in database %} <td class="menu-box-tab-items" href="#6"><span>{{d.country}}</span></td> {% endfor %} </tr> </tbody> </table> </div> </div> Basically, if a drop down menu existed for all the "names", I would want all the other td's to show the data associated with that name. If anyone can help it would be greatly appreciated. -
Django email validation
In my django app, I want to include an email validation. I mean, is there any library or function that checks if the email domain a user enters actually exists and is valid before letting the user sign up in django? -
CSS3 Style problem - grid-template-columns using Django
(included website image) Essentially, on my website it displays the "Browse Topics" as well as the list of Topics indented as though it is 3fr(It is navigation so it should be on the left) while the "2 Rooms Available" and their contents are displayed beneath but as 1fr. I seem to have also made a mistake where it no longer shows one of 2 of the rooms with content while trying to fix it, the only thing that was changed was the <div> markers, before it displayed both.. X.X {% extends 'main.html' %} {% block content %} <style> .home-container{ display: grid; grid-template-columns: 1fr 3fr; } </style> <div class="home-container"> <div> <h3>Browse Topics</h3> <hr> <div> <a href="{% url 'home' %}">All</a> </div> {% for topic in topics %} <div> <a href="{% url 'home' %}?q={{topic.name}}">{{topic.name}}</a> </div> {% endfor %} </div> </div> <div> <h5>{{room_count}} rooms available</h5> <a href="{% url 'create-room' %}">Create Room</a> <div> {% for room in rooms %} <div> <a href="{% url 'update-room' room.id %}">Edit</a> <a href="{% url 'delete-room' room.id %}">Delete</a> <span>@{{room.host.username}}</span> <h5>{{room.id}} -- <a href="{% url 'room' room.id %}">{{room.name}}</a></h5> <small>{{room.topic.name}}</small> <hr> </div> {% endfor %} </div> </div> </div> {% endblock content %} Website Image -
Django form not working correctly after psw changing it gives error
$ the urls.py page, password change done is not working , i trued auth_views to change psw and done view but it gives the following: error Page NoReverseMatch at /accounts/settings/change_password Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Request Method: POST Request URL: http://localhost:8000/accounts/settings/change_password Django Version: 4.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name urlpatterns = [ path('settings/change_password', auth_views.PasswordChangeView.as_view (template_name="accounts/change_psw-dj.html"), name="change_psw"), path('settings/change_password_done', auth_views.PasswordChangeDoneView.as_view (template_name="accounts/change_psw_done-dj.html"), name="change_psw_done"), ] -
Django: Method to get url of images
Im working on an website currently i would like to switch from a class Product containing the images to following: models.py: class Product(models.Model): name = models.CharField(max_length=60) price = models.DecimalField(max_digits=10, decimal_places=2) # Digital Products do not need shipping digital = models.BooleanField(default=False, null=True, blank=False) # now being handled in ProductImage: # image = models.ImageField(null=True, blank=True) @property def imageURL(self): try: url = self.image.url # get placeholder if something does not work except: url = '/images/placeholder.png' return url class ProductImage(models.Model): product = models.ForeignKey(Product, related_name="images", on_delete=models.SET_DEFAULT, default=None, null=True) image1 = models.ImageField(null=True, blank=True) image2 = models.ImageField(null=True, blank=True) image3 = models.ImageField(null=True, blank=True) image4 = models.ImageField(null=True, blank=True) image5 = models.ImageField(null=True, blank=True) image6 = models.ImageField(null=True, blank=True) i used to get the url of the single image (which works fine if image is an attribute of Product) as follows: view.html: {% for product in products %} <img class="thumbnail" src="{{ product.imageURL }}"> {% endfor %} view.py: def store_view(request): # some code "product":Product.objects.all() context.update({"products":products}) return render(request, "view.html", context) Is there a way of getting the images through the ForeignKey relation? (For example by modification of the above method imageURL)? I have tried: models.py: class Product(models.Model) # same as above @property def imageURL(self): try: url = self.images.image1.url # get placeholder if something does … -
Django & AJAX combined
I'm trying to submit a simple form in Django that will contain an image to process it on server and get a response without refreshing the page. I look up for some tutorials how to use AJAX and jQuery to do this but I don't have much knowledge at this matter. I'm completly stuck and have no idea what shall I do next. So far my code looks like this: models.py class Snip(models.Model): #some fields snip = models.FileField(upload_to="snips/") latex = models.TextField(default = '') forms.py from .models import Snip from django import forms class SnipForm(forms.ModelForm): class Meta: model = Snip fields = ['snip'] HTML: <form id="snipForm" method="POST" enctype="multipart/form-data"> <input type="hidden" name="csrfmiddlewaretoken" value="..."> <div class="row align-items-center"> <div class="col-12"> <label for="id_snip">Snip:</label> <input type="file" name="snip" required="" id="id_snip" class="btn-success p-2 rounded"> <input type="submit" name="upload" id="upload" class="btn btn-secondary"> </div> </div> </form> JavaScript/AJAX var snip = document.getElementById("id_snip"); var upload_btn = document.getElementById("upload") upload_btn.addEventListener('click', function () { var form_data = new FormData(); var ins = document.getElementById('snip_file').files.length; if(ins == 0) { return console.log("No snip!!!") } form_data.append("file[]", snip.files[0]); csrf_token = $('input[name="csrfmiddlewaretoken"]').val(); form_data.append("csrfmiddlewaretoken", csrf_token); $.ajax({ url: "{% url 'generate' %}", dataType: 'json', cache: false, contentType: false, processData: false, //data: {'data': form_data, 'csrfmiddlewaretoken': csrf_token}, data: form_data, type: 'post', success: function (response) { // … -
How to use filterset before anothers filtering in get_queryset()?
What i mean: get_queryset(): q = Model.objects.some_filtering() #use filterset for this q q = q.another_some_filtering() return q Thanks for your help! -
Could not parse the remainder: '% if survey.questiontype1 == multiplechoice %' from '% if survey.questiontype1 == multiplechoice %'
I am trying to fetch a specific instance from the 'questiontype1' field in the Survey model, part of which looks like this from django.db import models from datetime import datetime # Create your models here. class Survey(models.Model): category = models.CharField(max_length=100, blank = True) description = models.CharField(max_length=5000, blank = True) location = models.CharField(max_length=10000, blank = True) image = models.ImageField (upload_to='images/') created_at = models.DateTimeField(default=datetime.now, blank = True) question1 = models.CharField(max_length=10000, blank = True) questiontype1 = models.CharField(max_length=100, blank = True) bol1 = models.BooleanField() choice1a = models.CharField(max_length=5000, blank = True) choice2a = models.CharField(max_length=5000, blank = True) choice3a = models.CharField(max_length=5000, blank = True) choice4a = models.CharField(max_length=5000, blank = True) question2 = models.CharField(max_length=10000, blank = True) questiontype2 = models.CharField(max_length=100, blank = True) Here is part of the view template that is linked to the model in question <div class="mb-3 mx-5"> <label for="question1" class="form-label ">Question 1</label> <input type="text" name="question1" class="form-control form-control-lg" id="question1" placeholder="question1"> <div class="mb-4 mx-5"> <label for="questiontype1" class="form-label">Question type</label> <div class="col-md-6"> <select name="questiontype1" id="questiontype" class="form-select col-md-6"> <option value="null">Select question type</option> <option value="multiplechoice">Multiple choice</option> <option value="freetext">Free text</option> <option value="trueorfalse">True or False</option> </select> </div> </div> So on the survey.html, I want to check the condition of 'questiontype1' and render the following section {% extends 'base.html' %} {% block …