Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MaterializeCSS - working, but not sure the right way to set css and js?
I'm working on Django project with Materializecss design - Built a page with floating button for example. It's corrently working but I'm trying to understand better why it's actually working. I started using exactly the template from the website: https://materializecss.com/getting-started.html and updated from the CDN part in the page: <!--Import materialize.css--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> And added at the bottom: <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> The floating button didn't work - After reading some posts, I use a suggestion to add the below, and it worked: Why the updated version of the files is not working? What's the right way to install it for production? Thanks a lot! The full HTML with the 'ADDED PART THAT MAKE IT WORK': <!DOCTYPE html> <html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> <div class="fixed-action-btn"> <a href="#" class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a> <ul> <li><a href="#" class="btn-floating btn-large blue"> <i class="large material-icons">filter_drama</i></a></li> <li><a href="#" class="btn-floating btn-large green"> <i class="large material-icons">insert_chart</i></a></li> </li> </ul> </div> <!--JavaScript at end of body for optimized loading--> <script type="text/javascript" src="js/materialize.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> ADDED PART THAT MAKE IT WORK: <!--JavaScript at end of body for … -
Django channels live chat save sent messages
So I have a Django app in which I used channels to implement live chat. My consumer looks like this: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = self.scope["user"] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user': username.username } ) # Receive message from room group def chat_message(self, event): message = event['message'] user=event['user'] print(user) # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message, 'user':user })) So I am looking for a way to save the sent messages (because currently they are lost on refresh). I have created a Messages model that has a CharField for the message text. I think I can save new messages if I do this in my chat_message function: new_message=Messages(text=message) new_nessage.save() My question is how do I preload the last 10 messages whenever a user gets connected to the chat? -
Django 301 Redirect configuration from old websites
I'm building a website builder in Django and customers are moving their old website to my service. I'm wondering how I could set up 301 redirects the right way so they dont lose backlinks / traffic from existing external links. My url conf is: domain.com/post-name Their old conf could be: domain.com/YYYY/MM/DD/post-name or domain.com/blog/post-name (and post-name might not be the same from old and new) So ideally, I'd like to build a scalable way for them to set up 301 redirects from a variety of different URL patterns. Would I create a catchall URL conf (which allows slashes) and check that first? Or check that if nothing was found at domain.com/post-name? I could add an old_url field to the Post model and check that after a post isn't found. -
Django pagination returning %20 whitespace in URL
I cannot figure out why Django pagination sometimes adds whitespace (%20) to the URL: https://example.com/accounts/?page=2%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&q=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&ordering=-date_joined It happens if I click the Next or a specific page button so I assume it has to do with the way the pagination is written. More spoecifically I think it has to do with request.GET.items. Do context managers use request.GET.items? pagination: {% if page_obj.has_next %} <a class="btn btn-default btn-inactive mb-4 m-1" href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">Next</a> <a class="btn btn-default btn-inactive mb-4 m-1" href="?page={{ page_obj.paginator.num_pages }}{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">Last</a> {% endif %} view: class AccountStatusListView(AccountSearchMixin, ListView): model = Employee template_name = 'employees/account_list.html' paginate_by = 15 def get_ordering(self, *args, **kwargs): ordering = self.request.GET.get('ordering', '-is_active') return ordering def get_queryset(self, *args, **kwargs): queryset = super(AccountStatusListView, self).get_queryset() queryset = queryset.filter(Q( supervisor__exact=self.request.user)) | queryset.filter(Q( supervisor__isnull=False)) | queryset.filter(Q( is_active__exact=False)) ordering = self.get_ordering() if ordering and isinstance(ordering, str): ordering = (ordering,) queryset = queryset.order_by(*ordering) return queryset Anybody have any idea what is going on here? -
GET without unrequired fields in Django
Hope the title makes sense. I want to be able to search the Yelp API using a location (required) and a name (not required). Right now you are allowed to leave the name field blank but it will still use that in a search, therefore returning nothing no matter what. base.html <form action="{% url 'venue_list' %}"> <!-- NOT required --> {% render_field search_form.search_name.label %}: {% render_field search_form.search_name class="form-control" %} <!-- required --> {% render_field search_form.search_location.label %}: {% render_field search_form.search_location class="form-control" %} <input type='submit' value='SEARCH'> </form> yelp_api.py def get_name(location, term=None): url = 'https://api.yelp.com/v3/businesses/search' if term != None: params = { 'location': f'{location}', 'term': f'{term}' } else: params = { 'location': f'{location}' } headers = {'Authorization': f'Bearer {YELP_API_KEY}'} *etc etc* forms.py class SearchForm(forms.Form): search_name = forms.CharField(required=False, label='Name') search_location = forms.CharField(required=True, label='City, State, or Zip Code') views_venues.py def venue_list(request): search_location = request.GET.get('zip_code') search_name = request.GET.get('name') if not Venue.objects.filter(zip_code=search_location).exists(): venues = yelp_api.get_name(search_location) venues = Venue.objects.filter(zip_code=search_location).order_by('name') else: venues = Venue.objects.filter(zip_code=search_location).order_by('name') return render(request, 'restroom_rater/venue_list.html', { 'venues': venues, 'search_location': search_location}) views_venues.py i know is only set up to search for the location because that's how I originally had it set up. Getting stuck trying to do just location or location AND name. Let me know if there's … -
How Can make PyCharm's autocomplete work on django?
I am using pycharm community , I make test project on django and in template I make degree.html file. I have the following code in degree.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>welcome to degree site of {{student_id}}</title> </head> <body> {%for item in degree%} <h4> {{item.student_dgree}} </h4> <h4> {{item.student_id}} </h4> {%endfor%} </body> </html> I can't complete instruction like "for , endfor , .. etc" I install django from cmd and from pycharm's terminal too using pip. and from File -> Settings -> Project Interpreter I add django Package and install it help please ! -
Django upload image for current user for him cars
I am trying to make a uploading form for images with a choice of a car in the field, but in the field there should be only cars of the current dealer I have the following models: class Photo(BaseDateAuditModel): image = models.ImageField(upload_to='photos/') position = models.SmallIntegerField(default=1, validators=[MinValueValidator(limit_value=1)]) car = models.ForeignKey('cars.Car', on_delete=models.CASCADE, related_name='photos') class Dealer(User): city = models.ForeignKey('City', on_delete=models.SET_NULL, null=True, blank=False) class Car(BaseDateAuditModel): properties = models.ManyToManyField(Property) objects = CarManager.from_queryset(CarQuerySet)() views = models.PositiveIntegerField(default=0, editable=False) slug = models.SlugField(max_length=75) number = models.CharField(max_length=16, unique=True) dealer = models.ForeignKey("dealers.Dealer", on_delete=models.CASCADE, related_name='cars', null=True, blank=False) model = models.ForeignKey('CarModel', on_delete=models.SET_NULL, null=True, blank=False) color = models.ForeignKey('Color', on_delete=models.SET_NULL, null=True, blank=False) Form for upload images: class ImageForm(forms.ModelForm): class Meta: model = Photo fields = ['image', 'car'] widgets = { 'image': forms.ClearableFileInput(attrs={'multiple': True}), } View: class UpdateImageView(FormView): model = Photo form_class = ImageForm template_name = 'image-update.html' def get_success_url(self): return reverse('cars:cars-list') def form_valid(self, form): form.save() return super().form_valid(form) # 1st way, get list all car, not only for current user def get_queryset(self): ''' return a list of cars of the current user for example: my current dealer(user) have one car and this method return: Car.objects.filter(id__in=car_list) == <CarQuerySet [<Car: Audi >]> ''' user = self.request.user car_list = Dealer.objects.filter(username=user).values_list('cars', flat=True) return Car.objects.filter(id__in=car_list) # # def post(self, request, *args, **kwargs): … -
How to play an audio file through http response in Django
I want to know how to play an audio file in the browser How to play an audio file in the browser? -
Is it possible to target the single object's attributes among the objects QuerySet in Django ListView?
I want to get the attributes just for a single object in the object_list, but there is no way for me to access it as the contexts were only objects_list. I would like to access the attribute/field in the Post model(eg. Author/likes) in views.py in order to set an if statements and return the context e.g.: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context -
Serializing a block of text django rest-framework and displaying paragraphs with react
I am creating a blog and using djangorestframework as my backend and react for my frontend. When I serialize my data, I lose the formatting for my blog enteries (which are written in paragraphs). Is there a way to fix this. So: Blog Post This is my blog post, and this is my formatting. My second paragraph. becomes. [{ "title": "blog post", content: "This is my blog post, and this is my formatting My second paragraph." } ] When i pass it through my react it remains This is my blog post, and this is my formatting My second paragraph. -
Variables are not rendenring [DJANGO]
I m making a blog site.And I have been trying to render drom a model RecentPosts objects rpost1 ..etc in my template blogs-base.html which is my blogs details page. But it is not rendenring. Any solution?? views.py from django.http import HttpResponse from django.shortcuts import render from blog.models import Post from django.contrib import messages from django.views.generic import ListView , DetailView from .models import Post , RecentPosts , Comment ,Contact ,Populars from datetime import datetime from .forms import CommentForm def index(request): return render(request, 'index.html') def path(request): return render(request, 'blog.html') def cv(request): return render(request, 'cv.html') class HomeView(ListView): model = Post template_name = 'listview.html' class ArticleDetailView(DetailView): model = Post template_name = 'base2.html' def rpost(request): template_name = "blogs-base.html" rpost = RecentPosts.objects.all() context = {'rpost' : 'rpost'} return render(request ,template_name,context) This is url portion. urls.py from django.urls import path from . import views from .views import HomeView ,ArticleDetailView ,contact ,Comment_page,popular urlpatterns = [ path('', views.index, name='index'), path('index.html', views.index, name='index'), path('cv.html', views.cv, name='cv'), path('blogs/',views.HomeView.as_view(),name="blogs"), path('blogs/<slug:slug>',ArticleDetailView.as_view(),name='base2'), path('contact/', views.contact, name='contact'), path('contact.html/', views.contact, name='contact'), path('comment.html/', views.Comment_page, name='comment'), path('popular', views.popular, name='popular'), ] This is the model portion. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.timezone import now # Create your models here. class Post(models.Model): … -
Django, check if an object present in query set using exists() method
I have a below model, class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) head = models.CharField(max_length=255) authors = models.ManyToManyField(Author) I have created an object in Entry model, when I try to check if there is any objects in Entry model it shows error as attached image -
bash: /python/run/venv/bin/activate: No such file or directory
I'm trying to deploy my django app through AWS elastic beanstalk, & I've been running into an issue for the past 2 days which i've narrowed down more. A command in the deployment process is failing, this command is as follows: container_commands: 01_migrate: command: "python3 manage.py migrate" leader_only: true The section of the AWS EB console logs that tell me this refer me to cfn-init.log, checking this tells me the same thing. In cfn-init-cmd.log however, i see this 2020-06-19 18:24:24,753 P5019 [INFO] Command 01_migrate 2020-06-19 18:24:24,771 P5019 [INFO] -----------------------Command Output----------------------- 2020-06-19 18:24:24,771 P5019 [INFO] Traceback (most recent call last): 2020-06-19 18:24:24,771 P5019 [INFO] File "manage.py", line 10, in main 2020-06-19 18:24:24,771 P5019 [INFO] from django.core.management import execute_from_command_line 2020-06-19 18:24:24,771 P5019 [INFO] ModuleNotFoundError: No module named 'django' 2020-06-19 18:24:24,771 P5019 [INFO] 2020-06-19 18:24:24,771 P5019 [INFO] The above exception was the direct cause of the following exception: 2020-06-19 18:24:24,771 P5019 [INFO] 2020-06-19 18:24:24,772 P5019 [INFO] Traceback (most recent call last): 2020-06-19 18:24:24,772 P5019 [INFO] File "manage.py", line 21, in <module> 2020-06-19 18:24:24,772 P5019 [INFO] main() 2020-06-19 18:24:24,772 P5019 [INFO] File "manage.py", line 16, in main 2020-06-19 18:24:24,772 P5019 [INFO] ) from exc 2020-06-19 18:24:24,772 P5019 [INFO] ImportError: Couldn't import Django. Are you … -
Iterate json response data to loop in django
$(document).ready(function(){ $("button").click(function(){ $.ajax( { type:"GET", url: "{% url 'updatetable' %}", data:{ year_id :1}, success: function( data ) { console.log(data) ; $("#loadtable").html(data); } }); }) ; }); <div class="table-responsive" > <table class="table table-striped"> <thead class="thead-dark"> <tr> <th scope="col">S.N</th> <th scope="col">Name</th> <th scope="col">Post</th> </tr> </thead> <tbody id="loadtable" > {%for dt in data %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{dt.name}}</td> <td>{{dt.post}}</td> </tr> {%endfor%} </tbody> </table> -
Python list of dicts not converting properly in javascript GET handler
i am sending data from views.py in Javascript Ajax function, but it was not converting string to dict here is my code //////////////////////////////////// views.py def SortShop(request,shortby): items = Item.objects.order_by(shortby) item_list = [] for item in items: item_list.append({'name':item.item_name,'title':item.item_titile, 'pricse':item.item_FrashPricse,'dicsount':item.item_Discount_pricse, 'image':item.item_image}) return HttpResponse([item_list]) ///////////////////////////////////////////ajax function $('#sorting').on('change', function(e) { selected_value = this.value $.ajax({ type: 'GET', url: '/shopsorting/' + selected_value, // data: formData, encode: true, success: function(data) { y = JSON.stringify(data) x = JSON.parse(y) console.log(x) } }); }); }); ////////////////////////////Result's is [{'name': 'Shoulder Bag', 'title': 'Boys Shoulder Bag (Yellow )', 'pricse': 15.99, 'dicsount': 0.0, 'image': <ImageFieldFile: man-1.jpg>}, {'name': 'Sweeter', 'title': 'Cotton Sweeter', 'pricse': 19.9, 'dicsount': 0.0, 'image': <ImageFieldFile: product-6.jpg>}, {'name': 'Shirt', 'title': 'Full Sleeves Shirt', 'pricse': 20.99, 'dicsount': 12.99, 'image': <ImageFieldFile: man-4.jpg>}, {'name': 'Jacket', 'title': 'Jackson Jacket', 'pricse': 20.25, 'dicsount': 0.0, 'image': <ImageFieldFile: man-3.jpg>}, {'name': 'Yellow Shoes', 'title': 'Leopard Shoes', 'pricse': 29.99, 'dicsount': 25.99, 'image': <ImageFieldFile: man-2.jpg>}, {'name': 'Bag', 'title': 'Mini Cary Bag', 'pricse': 14.99, 'dicsount': 12.99, 'image': <ImageFieldFile: women-4.jpg>}, {'name': 'Coat', 'title': 'Overcoat (Gray)', 'pricse': 17.7, 'dicsount': 0.0, 'image': <ImageFieldFile: product-3.jpg>}, {'name': 'TOWEL', 'title': 'Pure Pineapple', 'pricse': 19.9, 'dicsount': 0.0, 'image': <ImageFieldFile: women-2.jpg>}, {'name': 'Coat', 'title': 'Pure Pineapple', 'pricse': 17.9, 'dicsount': 11.9, 'image': <ImageFieldFile: product-1.jpg>}, {'name': 'TOWEL', 'title': 'Pure Pineapple (White)', 'pricse': 17.9, … -
ModuleNotFoundError: Apache, Bitnami, Django app failing to import from virtual env
I'm attempting to get a very simple Django app deployed on an AWS Lightsail instance for the first time. I provisioned an AWS Apache instance set up with bitnami and django, and followed the tutorial without a virtual environment successfully but have since spent hours attempting to add my own project with a virtual environment. Most things seem set up correctly and I start Apache fine, only to navigate by browser to my url and find in the error logs a ModuleNotFoundError: No module named 'requests' error. This is the first import of any pip-installed module in my code and so suggests my virtual env has not made it into my PYTHONPATH. I just found a solution by hardcoding the path to my site-packages and appending it using sys.path.append(...) in my wsgi.py file, but I don't think this is the correct way to configure mod_wsgi with a django app and am worried it will lead to unexpected problems later. All django projects on the server are located at /opt/bitnami/apps/django/django-projects/. Following the tutorial, this directory contained projects "Project" and "tutorial". To separate my requirements.txt file and virtual environment env frome these projects, I decided to locate my project (a very simple … -
How do I add a polymorphic class in Django?
I am trying to make an application for a restaurant in django; I have to create a menu for different types of items, and all of those different types of items have to essentially be a product, so that I can add that product to a user's corresponding cart. Here are my menu items: from django.db import models from django.contrib.auth.models import User class Product(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) class Pizza(Product): pizzatype = models.CharField(max_length=15) extras = models.TextField(max_length=50) size = models.CharField(max_length=10) class Subs(Product): name = models.TextField(max_length=64) size = models.CharField(max_length=10) class DinnerPlatters(Product): name = models.TextField(max_length=64) size = models.CharField(max_length=10) class Pasta(Product): name = models.TextField(max_length=64) class Salads(Product): name = models.TextField(max_length=64) As can be seen, I tried deriving the models for different types of menu items from a single model Product, but while running makemigrations, I get the following message on the terminal: You are trying to add a non-nullable field 'product_ptr' to dinnerplatters without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py I tried googling … -
django.db.utils.IntegrityError: UNIQUE constraint failed: first_app_topic.top_name
I'm a beginner Django user... I have this code in my models.py file from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic, on_delete=models.SET_NULL) # added on_delete parameter, because DJANGO > v2.0 is name = models.CharField(max_length=264, unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage, on_delete=models.SET_NULL) # same on_delete needed to be added otherwise t>python manage.py migrate fails date = models.DateField() def __str__(self): return str(self.date) The above code is updated for Django version > 2.0 (ie with on_delete=models.SET_NULL) included as an argument. I then run the following commands in the command console python manage.py makemigrations registers the changes to your application. python manage.py migrate python manage.py shell >>> from first_app.models import Topic >>> print(Topic.objects.all()) <QuerySet [Topic: Social Network]> >>> t = Topic(top_name="Social Network") >>> t.save() This gives the following error log Traceback (most recent call last): File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: first_app_topic.top_name The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> … -
Cross checking field input in Python
I am writing a web application using oTree and Django and I am totally new to both. I am willing to ask the user to compile a form with two fields on the same page. I need to have a validation that checks whether the sum of the two values inserted in the two fields is less than a maximum value (e.g. 10). If the sum is bigger, I need to raise an error not letting the user switch to the next page. That's the code in the html file relative to the user input: {% formfield player.attribute_1 label="Your attribute 1 (from 0 to 10):" %} {% formfield player.attribute_2 label="Your attribute 2 (from 0 to 10):" %} {% next_button %} And that's the relative piece of code in the models.py file: class Player(BasePlayer): attribute_1 = models.CurrencyField( min=0, max=10, doc="""Your attribute 1""" ) attribute_2 = models.CurrencyField( min=0, max=10, doc="""Your attribute 2""" ) Currently it checks each single formfield to be in the range 0-10. How can I check the sum to be less than 10 instead? Thank you very much in advance for any help. -
How can I get the kwarg of the current url in Django
I am calling a view via an async AJAX call to lazy load blog posts. Now I am searching for a solution to get the category keyword (or named) arguments (kwarg) of the current url to use it for the database query within the view. So I either have to somehow pass that category via AJAX to the view or call it in the view directly. I do neither know which solution is the better one nor how to implement them. What I have: urls urlpatterns = [ path('<category>', render_blog_category, name='HotStocks'), path('<category>', render_blog_category, name='AsiaPacific'), path('<category>', render_blog_category, name='Europe'), path('<category>', render_blog_category, name='America'), path('<category>', render_blog_category, name='Pennystocks'), path('<category>', render_blog_category, name='Charts'), url(r'^$', render_blog_main, name='render_blog'), url(r'^lazy_load_posts/$', lazy_load_posts, name='lazy_load_posts'), url(r'^lazy_load_search/$', lazy_load_search, name='lazy_load_search'), ] blog.html which extends base.html <script type="text/javascript"> // A CSRF token is required when making post requests in Django // To be used for making AJAX requests in script.js window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <div id="blog-wrapper"> <!-- Latest Posts --> <div id="latest-posts-ctn"> <div id="posts">{% include 'blog/posts.html' %}</div> </div> <div id="lazyLoad-ctn"> <a id="lazyLoadLink" href="javascript:void(0);" data-page="2"><div id="loadmore-button">Load More Posts</div></a> </div> </div> <!-- Close Blog-Wrapper --> base.html <ul id="navbar-navigation"> <li class="navigation-item"> <a href="{% url 'AsiaPacific' category='Asia Pacific' %}">Asia Pacific</a> </li> <li class="navigation-item"> <a href="{% url 'Europe' category='Europe' … -
Auto end video call session from a page Django
I'm developing a custom video call app in Django. I want to end the video call session after 1 hour. Is there any way other than using JS or AJAX to auto exit from the page? -
Cannot open raw files from cloudinary in django admin
I do config the raw file's storage to couldinary and I can't open it in django admin(it shown 404 error). Did I miss something? I have set the storage location in setting.py as below: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' DEFAULT_FILE_STORAGE1 = 'cloudinary_storage.storage.RawMediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': 'XXXXX', 'API_KEY': 'XXXXXX', 'API_SECRET': 'XXXX-XXXXX', } CKEDITOR_UPLOAD_PATH = DEFAULT_FILE_STORAGE CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } Added to urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('team_profile.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.DEFAULT_FILE_STORAGE) Set the raw file's upload path in models.py: from django.db import models from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField from cloudinary_storage.storage import RawMediaCloudinaryStorage class apply_position(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=8) mail = models.EmailField(blank=False) file = models.FileField(upload_to='add/file_save/', null=False, storage=RawMediaCloudinaryStorage()) time = models.DateTimeField(default=timezone.now) def __str__(self): return self.name The forms.py is fine and I've put it to the views.py def recruit(request): form = addForm(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): form.save() return redirect('/') else: form = addForm() The Error I got when I try to open the files in admin site: https://res.cloudinary.com/xxxxx/raw/upload/v1/media/add/file_save/xxxx.pdf HTTP ERROR 404 -
Django website wow.js and animate.css is not working
I got animate.css to work fine , but when i imported wow.js into my static folder, it did not function on the scroll or just in general. The animation part only works without the "wow" class. As my website is built with django, im not sure if that has anything to do with it. Here is the code that includes the animate and wow files. <link rel="stylesheet" href="{% static 'css/animate.css' %}"> this is the only one that works: <div class="container"> <h1 class="animate__animated animate__bounce" style="color:black;">An animated element</h1> all of these do not work and i don't know what i am doing wrong: </div> <div class="container"> <h1 class="wow animate__bounce" style="color:black;">An animated element</h1> </div> <div class="container"> <h1 class="wow bounce" style="color:black;">An animated element</h1> </div> <div class="wow bounce"> <h1 class="wow bounce" style="color:black;">An animated element</h1> </div> I have these loaded in as well: <script language="javascript" type="text/javascript" src="{% static 'js/wow.min.js' %}"></script> <script>new WOW().init();</script> Attached image of my folder hierarchy The wow.js does not work wherever i put the containers on the page. All of this code is in my base.html folder (please refer to the image attached) On my website, they are further down with other information (i did not include as it would be too messy … -
How to use async_to_sync() & sync_to_async() in Django?
I need to use the asynchronous methods in the Django Views. How can I accomplish that. The documentation is available here, but the example is not provided. The below code is not working and I am getting the error coroutine. async def Dashboard(requests): txt = await api.com/mymessage return render(requests, 'Index.html', {'message': txt}) What is the proper way to wrap the method in the async_to_sync()? -
How can you sort the order of cards displayed in HTML
I'm using Python and Django to build a website. I'm making a rough version of the homepage with Bootstrap and HTML. I have a group of Cards that have a time written on them (i.e "12:00AM" or "2:30PM"). How can I sort these cards in order of earliest to latest? Here's a link to a rough version of my code. I put random data in there because I'm getting real data from Django : Codeply Link