Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django to Elastic Beanstalk, /opt/python does not exist
I'm completely lost & have been trying to fix the same issue for the past 4-5 days while deploying my django app. The issue is as follows. My migration command is failing, the migrate config file is as follows container_commands: 01_migrate: command: "python3 manage.py migrate" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: djangomicroblog.settings I've also tried changing the command to a number of different things, including: command: "python manage.py migrate" command: "django-admin.py migrate" command: "/opt/python/run/venv/bin/python3 manage.py migrate" Different commands give me different errors, python manage.py migrate reports: 2020-06-21 13:15:48,639 P8373 [INFO] File "manage.py", line 16 2020-06-21 13:15:48,639 P8373 [INFO] ) from exc 2020-06-21 13:15:48,639 P8373 [INFO] ^ 2020-06-21 13:15:48,640 P8373 [INFO] SyntaxError: invalid syntax I assume this is because it's trying to execute with python2 Python3 manage.py migrate reports: 2020-06-21 13:12:37,445 P8066 [INFO] Traceback (most recent call last): 2020-06-21 13:12:37,445 P8066 [INFO] File "manage.py", line 10, in main 2020-06-21 13:12:37,445 P8066 [INFO] from django.core.management import execute_from_command_line 2020-06-21 13:12:37,445 P8066 [INFO] ModuleNotFoundError: No module named 'django' 2020-06-21 13:12:37,445 P8066 [INFO] 2020-06-21 13:12:37,445 P8066 [INFO] The above exception was the direct cause of the following exception: 2020-06-21 13:12:37,445 P8066 [INFO] 2020-06-21 13:12:37,445 P8066 [INFO] Traceback (most recent call last): 2020-06-21 13:12:37,445 P8066 [INFO] File … -
Messages module urls.py redirect
I get the following warning after creating content. File "C:\bt\products\urls.py", line 2, in <module> from . import views File "C:\bt\products\views.py", line 29 messages.success(request, 'Your profile was updated.') ^ TabError: inconsistent use of tabs and spaces in indentation views.py def create(request): form = ProductForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Your content was create.') context = { 'form': form } return render(request, "products/create.html", context) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='product-index'), path('create/', views.create, name='product-create'), path('<int:id>/', views.detail, name='detail'), #path('<int:product_id>/', views.productDelete, name='delete'), ] Could you help? Thank you. -
How to fix TypeError at /admin/pages/course/add/ in Django admin?
I'd done my models in models.py and run migrations after makemigrations. I'd also registered my model at admin.py and I can see it appearing in the admin panel. But when i clicked add course it gave me the following error: TypeError at /admin/pages/course/add/ function missing required argument 'year' (pos 1) Request Method: GET Request URL: http://127.0.0.1:8000/admin/pages/course/add/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: function missing required argument 'year' (pos 1) Exception Location: C:\Users\ahnaa\OneDrive\Documents\Web Developent\Django\school_app\venv\lib\site-packages\django\db\models\fields\__init__.py in get_default, line 829 Python Executable: C:\Users\ahnaa\OneDrive\Documents\Web Developent\Django\school_app\venv\Scripts\python.exe Python Version: 3.8.3 Python Path: ['C:\\Users\\ahnaa\\OneDrive\\Documents\\Web Developent\\Django\\school_app', 'C:\\Users\\ahnaa\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\ahnaa\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\ahnaa\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\ahnaa\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\ahnaa\\OneDrive\\Documents\\Web ' 'Developent\\Django\\school_app\\venv', 'C:\\Users\\ahnaa\\OneDrive\\Documents\\Web ' 'Developent\\Django\\school_app\\venv\\lib\\site-packages'] Server time: Sun, 21 Jun 2020 19:50:52 +0600 -
Cannot assign "'post'": "Comment.content_type" must be a "ContentType" instance
I want to create comment option in my Post detail view for blog.I inherited FormMixin to use CommentForm in PostDetailView. Besides I had to inherit HitCountDetailView for hitcount.Now when I try to add comment it is showing this error "Cannot assign "'post'": "Comment.content_type" must be a "ContentType" instance.I tried several times to solve it but failed.How can I solve this error? Any suggetions. Thanks in advance. Here is my code: Views.py: class PostDetailView(FormMixin, HitCountDetailView): model = Post form_class = CommentForm template_name = "blog/published/post_detail.html" context_object_name = 'post' slug_field = 'slug' # set to True to count the hit count_hit = True def get_initial(self): instance = self.get_object() print(instance.title) return { "content_type": instance.get_content_type, "object_id": instance.id, } def get_success_url(self): return reverse("post-detail", kwargs={"slug": self.object.slug}) def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data(*args, **kwargs) stuff = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter_by_instance(stuff) context['comments'] = comments context["form"] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): return super().form_valid(form) models.py @python_2_unicode_compatible class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextUploadingField(blank=True, null=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) published = models.DateTimeField(blank=True,null=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') class … -
Is there way to set image file in input file using jquery?
I can compress image but can't upload compress image through ajax. my preview image is compress, but how to send it through ajax post request. I make input field in form and I want to select compress image to that input field. so that compress image can upload through it. But I don't know how to do it? I searched lot from 3 days but didn't find any help. Or if its there any other ways to upload compress image please tell. HTML {{ form.image|as_crispy_field }} //form imagefield has id=file <form action="home_page/mainpost/post/" id="mainpost-form" enctype="multipart/form-data" class="shadow-lg p-3 mb-5 bg-white rounded" method="POST"> {% csrf_token %} <input id="img-hidden" name="image" accept="image/*" type="file" style="display:none"> {{ form.info_post|as_crispy_field }} Preview Image - <br> <div class="hidden-img-div"> <img id="original-Img"/> </div> <br> <input class="btn btn-danger" type="submit" value='Post'> </form> Jquery <script> document.getElementById("file").addEventListener("change", function (event) { compress(event); }); function compress(e){ const width = 300; const fileName = e.target.files[0].name; const reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader.onload = event => { const img = new Image(); img.src = event.target.result; img.onload = () => { const elem = document.createElement('canvas'); const scaleFactor = width / img.width; elem.width = width; elem.height = img.height * scaleFactor; const ctx = elem.getContext('2d'); // img.width and img.height will contain the original … -
ModuleNotFoundError: No module named 'oscar.apps.communication'
I was trying to follow django-oscar documentation. Whenever I ran the server it gives me an exception (ModuleNotFoundError: No module named 'oscar.apps.communication') I think it happens due to the misconfiguration of settings.py file. But I can't understand what's wrong is going on there. settings.py """ Django settings for frobshop project. Generated by 'django-admin startproject' using Django 2.2.13. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from oscar.defaults import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ng)eg&5czqn675xe7oi56%ivr%uw^2dy#tv(bglq*drk0oy-&(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar.config.Shop', 'oscar.apps.analytics.apps.AnalyticsConfig', 'oscar.apps.checkout.apps.CheckoutConfig', 'oscar.apps.address.apps.AddressConfig', 'oscar.apps.shipping.apps.ShippingConfig', 'oscar.apps.catalogue.apps.CatalogueConfig', 'oscar.apps.catalogue.reviews.apps.CatalogueReviewsConfig', 'oscar.apps.communication.apps.CommunicationConfig', 'oscar.apps.partner.apps.PartnerConfig', 'oscar.apps.basket.apps.BasketConfig', 'oscar.apps.payment.apps.PaymentConfig', 'oscar.apps.offer.apps.OfferConfig', 'oscar.apps.order.apps.OrderConfig', 'oscar.apps.customer.apps.CustomerConfig', 'oscar.apps.search.apps.SearchConfig', 'oscar.apps.voucher.apps.VoucherConfig', 'oscar.apps.wishlists.apps.WishlistsConfig', 'oscar.apps.dashboard.apps.DashboardConfig', 'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig', 'oscar.apps.dashboard.users.apps.UsersDashboardConfig', 'oscar.apps.dashboard.orders.apps.OrdersDashboardConfig', 'oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig', 'oscar.apps.dashboard.offers.apps.OffersDashboardConfig', 'oscar.apps.dashboard.partners.apps.PartnersDashboardConfig', 'oscar.apps.dashboard.pages.apps.PagesDashboardConfig', 'oscar.apps.dashboard.ranges.apps.RangesDashboardConfig', 'oscar.apps.dashboard.reviews.apps.ReviewsDashboardConfig', 'oscar.apps.dashboard.vouchers.apps.VouchersDashboardConfig', 'oscar.apps.dashboard.communications.apps.CommunicationsDashboardConfig', 'oscar.apps.dashboard.shipping.apps.ShippingDashboardConfig', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', ] SITE_ID = 1 MIDDLEWARE = … -
Django readonly_fields not showing data
My Orders model has 'rate' and 'total_amount' field. I had to derive rate from different model so i created 'unit_rate'. Same way i wanted my 'total_amount' fields should be multiplication of 'quantity' and 'unit_rate' which i tried by doing 'total_pay'. You can see my code for the same below. class OrderAdmin(admin.ModelAdmin): def unit_rate(self,obj): self.rate = Product.objects.get(pk=obj.order_id) return self.rate.price def total_pay(self,obj): self.rate = Product.objects.get(pk=obj.order_id) self.total_amount = self.rate.price * obj.quantity return self.total_amount list_display = ('order_id', 'order_item', 'order_status', 'delivery_address', 'customer', 'quantity','unit_rate','total_pay') readonly_fields = ('total_pay','unite_rate') admin.site.register(Orders,OrderAdmin) As 'total_pay' and 'unit_rate' are obtained from other columns, admin doesn't need to enter them. That's why i kept them on readonly_fields'. Problem is whenever is create order through admin interface, 'total_pay' and 'unit_rate' does not shows up in admin. It just shows dash like this -. Doing this since a while. I could really use your help.thanks -
Django view with simple GET method results in TypeError
Using a very simplistic subclass of django.views.View I only get a TypeError with »__init__() takes 1 positional argument but 2 were given« as message. urls.py is: from myapp import views from django.urls import path urlpatterns = [ path('webhook/', views.Webhook, name='myapp-webhook'), ] views.py: from django.http import HttpResponse, HttpResponseForbidden from django.views import View class Webhook(View): def get(self, request, *args, **kwargs): """We don't provide GET access here.""" # return 403 (Forbidden) return HttpResponseForbidden() def post(self, request, *args, **kwargs): # return 200 (OK) return HttpResponse() tests.py: from django.test import TestCase class WebhookTests(TestCase): def test_get_method_is_forbidden(self): response = self.client.get('/webhook') self.assertEqual(response.status_code, 403) Now, either accessing /webhook in a browser or running ./manage.py test results in: Internal Server Error: /webhook/ Traceback (most recent call last): [...] TypeError: __init__() takes 1 positional argument but 2 were given I'm surely missing something here. Pointers to what this is, are much appreciated. -
Django DB design - Book specific unique URLs with unique_together
I have two models with one to many relationship. A Book has many Chapters. Both the models have a slug field. For Book the slug column is UNIQUE. For Chapter the book_id and slug are UNIQUE together. The Chapter model also has a field order. And book_id and order are UNIQUE together. This way, I can generate unique URLs for books automatically and allow duplicate slugs for different books. Current models.py: class Book(models.Model): # other fields slug = models.SlugField(max_length=80) def save(self, *args, **kwargs): if not self.pk: self.slug = unique_slug(self.title) return super(Book, self).save(*args, **kwargs) class Chapter(models.Model): #other fields book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='chapters') slug = models.SlugField(max_length=80) order = models.IntegerField(null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['book_id', 'order'], name='unique_order'), models.UniqueConstraint(fields=['book_id', 'slug'], name='unique_slug')] ordering = ['order'] The downside here is, in my chapter views I have to query the book first and get the chapter slug with the matching book_id. While previously with just the chapter slug UNIQUE, I was just querying the chapter table alone. My goal is to have URLs like this book/rndmstrng-alice-in-the-wonderland/chapter/down-the-rabbit-hole book/rndmstrng-some-other-book/chapter/down-the-rabbit-hole Is there any issue in this design? Are too many UNIQUE constraints bad? Is there a better way to implement this? -
How to send data from custom.py to html - Django
Concept that I'm trying to achieve: A web application with speech enabled that displays what the user says, on UI. Example: If the user says "Hello there!", "Hello there!" should be displayed on the UI. What I have: Files that I have in my app: speech.py (has a variable(displayOnUI) that stores what the user says) speech.html (where I want to display what the user says) Note: speech.py repeatedly keeps listening to user and keeps storing what the user says in a variable(displayOnUI). What I tried: I tried passing the value of the variable displayOnUI which is in speech.py to view.py and then passing it to speech.html using context. speech.py displayOnUI= "Please say something.." def SpeechRecognition(): while 1: try: with sr.Microphone() as source: r.adjust_for_ambient_noise(source, duration=1) audioReceived = r.record(source, duration=3) displayOnUI= r.recognize_google(audioReceived) view.py from SpeechApp.speech import displayOnUI def speech(request): data = displayOnUI return render(request, "speech.html", {"data": data}) speech.html <div> <h3>This is what I heard: {{data}} <h3/> </div> Problem that I'm facing I'm able to display the initial value that is present in displayOnUI (that is "Please say something..") on UI, however I'm not able to display the updated value(user's command) of displayUI in speech.html. (I guess it is because view.py is executed … -
Save file uploaded in Django without a database
I am trying to save a file and do something to it a from in an html file, I am not using django forms but I am using django for backend and I don't need a database since I don't want to keep any of the files. I tried what the django documentation has instructed. html file <input type="file" id="face_files" name="face_files" multiple > save_file.py os.mkdir(folder) counter=1 for file in request.FILES.getlist('face_files'): destination=open(folder +"/face"+str(counter)+".jpg", 'wb+') for chunk in file.chunks(): destination.write(chunk) destination.close() counter+=1 But I get the error ValueError: seek of closed file Working, what am I doing wrong? -
Django JavaScript fpr bootstrap grid does not work
I deployed website using Django. I used external js code for grid (I want site to be user-friendly for all screens). When running just html using same js code it works fine. But when I actually deployed website grid become unclickable from small screens and you cannot see menu. I couldn't find anything in Google. I am not sure if I have to use load static because I use external script, but tell me if I am wrong <!DOCTYPE html> {% load static %} <html> <head> <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1"> <title></title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <!-- DOCUMENTATION NAVBAR --> <nav class="navbar navbar-default navbar-inverse navbar-fixed-top"> <!-- Inside of a Container --> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <!-- This is the actual code that create the "hamburger icon" --> <!-- The data-target grabs ids to put into the icon --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <!-- Code for the hamburger icon--> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" style="color:white;" href="{% url 'wpb:index' %}"> Mycroft Conspiracy Project</a> </div> <!-- Anything inside of collapse navbar-collapse goes … -
How to run a Django project with .pyc files without using source codes?
I have a django project and i want to create the .pyc files and remove the source code. My project folder name is mysite and I ran the command python -m compileall mysite. The .pyc files are created. After that i tried to run my project with python __pycache__/manage.cpython-37.pyc runserver command but i've got an error such as ModuleNotFoundError: No module named 'mysite' There are two things I would like to ask about this. First, how can I solve this problem and run my project with .pyc file? Secondly, is it enough to move the .pyc files created to a separate folder in accordance with the django project structure? -
Facing issue with Django version and Sqlite3 version compatibility
First of all, the issue which i am posting here was already answered earlier here. But somehow the fixed shared was not working for me. Either i havent applied properly or i am having some other issue too. I am using Django on Centos7 machine. Django version is 3.0.7 while running the server i got error with django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). I have upgraded the sqlite3 version and now it is in 3.32.2. but still when i run the manage.py i am getting the same error. By referring the solutions already mentioned here, i had tried changing the PATH definitions but still i am stuck. thanks in advance. -
Add input in html and form validation in model form
I have a form from modelForm. I have a checkbox that is not part of the model so I included it in the form field. Now, I have added it in the html manual because there will be text in between. My intention is for form validation and not the actual textfield. forms.py understand = forms.CharField(max_length=10, required=False) <form name="form" action="#" method="POST"> {{ form.as_p }} <fieldset> <p>textt</p> <div> <input type="checkbox" name="understand" value="understand" id="understand"><label for="understand" style="display: inline-block;">I Agree</label> </div> <button class="button">Submit</button> </fieldset> </form> The above code adds another Charfield. -
Django, io module for deserialization of data
In Django Rest Framework documentation, there is process of deserialization as mention below import io stream = io.BytesIO(content) data = JSONParser().parse(stream) here content is a JSON object. Why can't we directly deserialize data as data = JSONParser().parse(content), when I did that in localmachine it raised error AttributeError: 'bytes' object has no attribute 'read' -
"message": "expected string or bytes-like object",
#i want the total time taken by a session to get completed,but i am getting the above mentioned error #MODEL class User(models.Model): user=models.CharField(max_length=40) class Sport(models.Model): Sports_Name=models.CharField(max_length=30,null=True,blank=True) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') Start_time=models.TimeField(auto_now=False, auto_now_add=False,null=True) End_time=models.TimeField(auto_now=False, auto_now_add=False,null=True) class Gamification(models.Model): User_Name=models.ForeignKey(MyUser,on_delete=models.CASCADE) #viewset users=Gamification.objects.all() b=[] for user in users: b.append({ "User_Name":user.User_Name.user_name, 'Session_Created':Session.objects.filter(Host=user.User_Name).count(), "Session_Joined":Session.objects.filter(Players_Participating=user.User_Name).count(), "Completion_Time(in days)":Session.objects.filter(End_time=user.User_Name), }) return Response({'success':b}) -
Django form list field or json field?
I have a model called participants as below class participants(models.Model): username= models.CharField(max_length =50) votes = models.IntegerField(default=0) voted_by = ? Votes is the total number of votes given by users and single user can vote multiple times. If the user have voted then the user should wait 1 hour to vote again. Now i am wondering, how can i store users id in a way that it would be easier to know who voted how many times and the recent date and time the user have voted. Can someone suggest me or refer some examples that i can solve this problem. -
Django Max & Min pricse filter from models
I created an DJANGO models in my "models.py" contains "Item_Frash_pricse" field in it class Item(models.Model): item_id = models.AutoField(primary_key=True) item_category = models.ForeignKey(Product,on_delete=models.CASCADE) item_subCategory = models.CharField(max_length=30) item_name = models.CharField(max_length=30,default='') item_titile = models.CharField(max_length=30) item_FrashPricse = models.FloatField(max_length=30) the PROBLEM is that i want to fetch all the query set where Item_Frash_pricse <= max_amount andItem_Frash_pricse >= min amount are in my "views.py" def ByPricse(request,filter_by): max_amount = request.GET.get('Maxamount',None) min_amount = request.GET.get('Minamount',None) **filter_item = Item.objects.filter(Item_Frash_pricse <= max_amount and vise versa ????**) return HttpResponse('Ok') But this filter_item = Item.objects.filter(Item_Frash_pricse <= max_amount is wrong syantax cant do >= opration -
Run Apache with mod_wsgi and django
Can't start server using Apache + Django OS: MacOS Catalina Apache: 2.4.43 Python: 3.8 Django: 3.0.7 Used by Apache from Brew. mod_wsgi installed via pip. The application is created through the standard command django-admin startproject project_temp The application starts when the command is called python manage.py runserver At start for mod_wsgi - everything is OK mod_wsgi-express start-server When I start Apache, the server is not accessible. Checked at "localhost: 80". Tell me, what do I need to do to start the server? Httpd settings: ServerRoot "/usr/local/opt/httpd" LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so LoadModule authn_file_module lib/httpd/modules/mod_authn_file.so LoadModule authn_core_module lib/httpd/modules/mod_authn_core.so LoadModule authz_host_module lib/httpd/modules/mod_authz_host.so LoadModule authz_groupfile_module lib/httpd/modules/mod_authz_groupfile.so LoadModule authz_user_module lib/httpd/modules/mod_authz_user.so LoadModule authz_core_module lib/httpd/modules/mod_authz_core.so LoadModule access_compat_module lib/httpd/modules/mod_access_compat.so LoadModule auth_basic_module lib/httpd/modules/mod_auth_basic.so LoadModule reqtimeout_module lib/httpd/modules/mod_reqtimeout.so LoadModule filter_module lib/httpd/modules/mod_filter.so LoadModule mime_module lib/httpd/modules/mod_mime.so LoadModule log_config_module lib/httpd/modules/mod_log_config.so LoadModule env_module lib/httpd/modules/mod_env.so LoadModule headers_module lib/httpd/modules/mod_headers.so LoadModule setenvif_module lib/httpd/modules/mod_setenvif.so LoadModule version_module lib/httpd/modules/mod_version.so LoadModule unixd_module lib/httpd/modules/mod_unixd.so LoadModule status_module lib/httpd/modules/mod_status.so LoadModule autoindex_module lib/httpd/modules/mod_autoindex.so LoadModule alias_module lib/httpd/modules/mod_alias.so LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so LoadModule wsgi_module /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-darwin.so <Directory /> AllowOverride All </Directory> <Files ".ht*"> Require all denied </Files> <IfModule log_config_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" … -
Jquery ajax not working properly with my django
Here I am trying to add category with ajax but it is not working properly. In the admin it saves the data in format ['name'] and after saving modal doesn't hides also. script <script type="text/javascript"> $(document).on('submit','#=category-form',function(e) { e.preventDefault(); var form = $(this); $.ajax({ url: form.attr("action"), data: { name:$('#name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, type: 'POST', dataType: 'json', success:function(){ $("#myModal").modal("hide"); } }); }); </script> views class AddgoryCateView(View): def post(self, request): name = request.POST.get('name') category = Category.objects.create(name=name) data = {'category': category} return JsonResponse(data) PROBLEM2 : After modal hides creating the data in the database I want to display this data in the html page without refresh. Here the the categories comes from the database. I want to display the newly created category in the option without refresh after saving the data. <label class="text-primary">Categories</label> &nbsp;<small><i class="ic-add" data-toggle="modal" data-target="#myModal"></i></small> <select class="form-control" name="categories" multiple="multiple" id="id-categories"> {% for category in categories %} <option value="{{category.pk}}">{{category.name}}</option> {% endfor %} </select> -
Django manager queries don't work in a sequence of queries
Here's the problem: I've implemented a custom manager for a model with just one custom query named get_by_tag and it's working fine if I use it this way: UsageStatistic.objects.get_by_tag('some-tag-name').filter(user=user_id) But when I change the order of queries, in this way: UsageStatistic.objects.filter(user=user_id).get_by_tag('some-tag-name') it doesn't work! and raise this error: AttributeError: 'QuerySet' object has no attribute 'get_by_tag' Am I missing something?! P.S: FYI the custom manager is somethin like this: class MyCustomManager(models.Manager): def get_by_tag(self, tag_name): posts = Post.objects.filter(tags__pk=tag_name) return super().get_queryset().filter(post__pk__in=posts) -
Why does my preview script does not work?
here is the template i am using i tried to log the date also but it doesn't log {{ form|crispy }} <button type="submit" value="Submit"class="btn btn-primary">Submit</button> </form> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script type="text/javascript"> $(document).ready(function(){ var date = $("#id_Date"); $("#preview-date").val(date.val()) }) </script> </body> </html> -
Django forms are not being processed with POST request
I have written the most basic Django application to understand forms as below. When I enter the required data into the fields and press Submit, the code after "if request.method == 'POST'" is ignored. I am redirected to the appropriate page and an entry with the first name "John" and last name "Smith" is created in my database. As you can see in the code below, this object should only be created if the request method is not POST. I know that I have set the request method to POST because that is what is shown on my CMD so what is happening?? Here is my template 'index.html': <!DOCTYPE html> <html> <head> <title>Welcome to the site</title> </head> <body> <form action="thanks/" method='POST'> {% csrf_token %} {{ form.as_p }} <input type="submit" vlaue="Submit"> </form> </body> </html> Here is my views.py file: from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import NewObjectForm from .models import Object # Create your views here. def index(request): if request.method == 'POST': form=NewObjectForm(request.POST) if form.is_valid(): first_name=form.cleaned_data['first_name'] last_name=form.cleaned_data['last_name'] a=Object.create(first_name=first_name,last_name=last_name) a.save() return HttpResponseRedirect('/thanks/') else: new=Object.create(first_name="Not",last_name="Valid") new.save() else: #Code which is run if the request.method is not equal to 'POST' form=NewObjectForm() newer=Object.objects.create(first_name="John",last_name="Smith") newer.save() return render(request,'formapp/index.html',{'form':form}) def end(request): return render(request,'formapp/thanks.html') -
How to hide html button if queryset doesn't have next blog post in Django?
I would like to hide the Next button in my blog if there is no next blog post available. Is there some kind of built-in method to check has_next has_previous or do I need to create some logic in my view and extend the template with let's say {% if Foo %} show button {% endif %} ? views.py def render_post(request, id): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] post = get_object_or_404(Post, id=id) next_post_id = int(id) + 1 previous_post_id = int(id) - 1 PostView.objects.get(post=post) context = { 'post': post, 'id': id, 'next_post_id': next_post_id, 'previous_post_id': previous_post_id, 'most_recent': most_recent, 'category_count': category_count, } return render(request, 'post.html', context) html <div id="button-wrapper"> <button class="buttons" type="submit"><a href="/post/{{previous_post_id}}">Previous</a></button> <button class="buttons" type="submit"><a href="/post/{{next_post_id}}">Next</a></button> </div>