Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python module random has no attribute choices working on local server but not on live server
I have a script which selects a random number form available list at random. I have been testing it on django's local server and it worked fine but when I moved it to a live server I keep getting this error: AttributeError: 'module' object has no attribute 'choices' Here's my code: import json class singlePull(TemplateView): template_name = 'gacha/singlepull.html' def randomStar(self): choice = [5,4,3] probability = [0.1, 0.2, 0.7] star = random.choices(choice, probability) return star def post(self, request): result = self.randomStar() for key in result: character = Characters.objects.filter(stars=key).order_by('?')[:1] for obj in character: name = obj.name stars = obj.stars series = obj.series image = obj.image return JsonResponse({'name': name, 'stars': stars, 'series': series, 'image': image}, safe=False) How come I keep getting this error? What could be wrong here? -
SERVER error 500 on heroku deployment
Server 500 Error: heroku logs After running heroku open and heroku logs , i am getting the server 500 error. I have ran migrations and checked logs multiple times. Nothing really seems like an error... I have added the settings file, requirement.txt file and Procfile below. PS : i added heroku logs --app app_name, it said permission denied. settings import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY','2z9y6') DEBUG = bool( os.environ.get('DJANGO_DEBUG', False) ) ALLOWED_HOSTS = ['127.0.0.1', 'hackingonlineeducation.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'star_ratings', 'crispy_forms', #my_apps 'newsletter', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'Books.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'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 = 'Books.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ … -
$.get() gives error, on callback (?)
I know there are many questions like this, but I can't find the solution for my problem. MyScript.js: $('#id_tags').keyup(function(){ var query; query = $(this).val(); $.get('/blog/suggest-category/', {suggestion: query}, function(data){ console.log('data') $('#id_tags').html(data); }); }); My view.py: def get_category_list(max_results=0, starts_with=''): print('get_category_list') cat_list = [] if starts_with: cat_list = Tag.objects.filter(slug__istartswith=starts_with) if max_results > 0: if len(cat_list) > max_results: cat_list = cat_list[:max_results] return cat_list def suggest_category(request): print('suggest_category') cat_list = [] starts_with = '' if request.method == 'GET': starts_with = request.GET['suggestion'] cat_list = get_category_list(5, starts_with) print('cat_list', cat_list) #return render(request, 'blog/suggest_tag.html', {'suggestions': cat_list }) return cat_list query, in MyScript.js is a string. The view is called (I can read the print('cat_list', cat_list)) but then it throw an error: when the list is empty =>AttributeError: 'list' object has no attribute 'get' when isn't (for example: cat_list [<Tag: General>]) => ValueError: too many values to unpack (expected 2) -
Django annotation in a loop
I'm trying to create an unknown amount of columns with annotate: def add_daily_usage_record(query, days): for i in days: query.annotate('day_' + i + '_usage'= "doesn't matter" But it doesn't seem to work. Is there any way to give an annotation a name without writing it? or maybe if I have the name of the new column in a variable, is it possible to pass it to annotate? Thank you. -
Django abstract user model not migrating
So I am working on implementing a custom user model, and to do so i followed tutorial 'this tutorial. I am now trying to run python3 manage.py migrate and I get this error: [wtreston] ~/gdrive/mysite2/ $ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, reviews, sessions, users Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 164, in handle pre_migrate_apps = pre_migrate_state.apps File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/state.py", line 218, in apps return StateApps(self.real_apps, self.models) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/state.py", line 295, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'. The field reviews.Answer.student was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'. The field reviews.ReviewBlock.teacher was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'. The field users.Student.user was declared with a lazy reference … -
Django - User registration and login via REST API in the same project
I mainly have two questions. I haven't read this anywhere but, I am wondering whether or not it is a good idea to make it so that all the data that is going in and out of all apps in your project solely depended on REST API calls. So that if you, for instance, want to register a new user. Gather the data from a front-end, with no back-end work, and just send this data as a REST call to you "registration-app" where all validation and back-end work is done. I find this method effective when working in big teams as it makes dependencies even more decoupled, as well as making each part of the project more separated and "clear". My question is, therefore, is this a viable way of developing? Are there any security or performance issues with this? And where can I read more? Thanks Max -
Dynamically accessing a "Friend" model with two foreign-keys to "Profile"
I've created a Friend model that consists of two Profile model instances. The reason for a separate model in the first place is due to the Friend model having special attributes related to the "friend" relationship. In this Friend model, I am also tracking the requester & accepter of the relationship as it is significant to my site--this requires that I have a separate field for each of these, and they are FKs to the Profile model. Here are the two models: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) profile_picture = models.ImageField( upload_to=profile_photo_upload_loc, blank=True, null=True, created = models.DateTimeField(auto_now_add=True) class Friend(models.Model): requester = models.ForeignKey(Profile, related_name='is_requester') accepter = models.ForeignKey(Profile, related_name='is_accepter') requester_asks = models.CharField(max_length=60, null=True) accepter_asks = models.CharField(max_length=60, null=True) With this structure, in instances that I want to retrieve all of the Friend instances that a single Profile is a participant in, I need to make two queries: one for those in which he's the requester and another for those in which the profile is an accepter. The combination of these two querysets gives me the total list of all Friend relationships a Profile belongs to--I need this total list when making things like a message inbox. Attempting to create a message … -
How to achieve asynchronous execution of tasks united in celery group?
The first part The task was to inform the user about the performance of certain functions @task(base=NotifierTask) first(*args): # runs some time return json_resp @task(base=NotifierTask) second(*args): # runs some time return json_resp @task(base=NotifierTask) third(*args): # runs some time return json_resp # Get request # the number of execute functions can vary depending on the request # can run from 1 to 40 functions def main(request): # there we get some data data = request.POST.get('data') for some_func in data: if some_func == 'first': first.delay(args) elif some_func == 'second': second.delay(args) elif some_func == 'third': third.delay(args) # The whole thing gets into a celery worker # Notifier Task class NotifierTask(Task): """ Tasks that sends notification on completion. """ abstract = True def after_return(self, status, retval, task_id, args, kwargs, einfo): # The result of the execution and negotiates through a socket on the client side The second part For these purposes, try to combine all the tasks in the group to obtain the result of the completion of all tasks in the group. @task(base=NotifierTask) def celery_test(id, position): time.sleep(id) return "Time delay: %s, Position: %s" % (str(id), str(position)) def some_request(request): from django.http import JsonResponse if request.method == 'GET': job = group([ celery_test.s(10, 1), celery_test.s(2, 2), … -
Django rest framework conditionally required fields
I would like to write a drf validator that will mark a field as required based on the value of an other field. For example: class MySerializer(serializers.Serializer): has_children = fields.BooleanField() nb_childs = fields.IntegerField(min_value=1, validators=[RequiredIf(field='has_children', value=True)], required=False) At first i believed the class based validator was the way to do it, by retrieving the value of 'has_children' with a method like this: def set_context(self, serializer_field): print serializer_field.parent.initial_data but the 'initial_data' is not set. Any clue? -
Django URLs from different apps in just the base one
So I have 2 apps for my django project. In the default mysite folder, you have the urls.py file. I cant seem to find out how to write all my urls for all the apps in just the one urls.py file. I have tried this: from reviews.models import * however that isnt working. Thanks for any help! -
HTML5 video tag does not work on Safari
I'm a coding beginner and currently working on a fitness app. I'm facing the problem that my HTML5 sample video doesn't load in Safari 11, but works perfectly fine with Chrome and Firefox. Here is the html: <video id="VideoElement" width="200" height="160" muted controls src="/static/media/fitness/theraband1.mp4" type="video/mp4"></video> Yet, I don't think that the html is the problem, as I cannot even access the video on Safari with a direct link to the file. In case you want to try by yourself, here is the link: Placeholder video The app is programmed in Python 3 and Django 2. The video can neither be loaded by using the pythonanywhere page nor by my local Django development server. I already searched stackoverflow, but cannot not find a solution. However, I read in some posts that the problem could be related to http headers. -
Product will not appear for others user when current user add product in Cart
In Django, I want if a user adds a product to a cart or buy a product. The product will not show on other users product list or anywhere. Just show for current user who adds the product to a card or buys it. How I implement it? Thanks. product model class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def all(self): return self.get_queryset().active() def get_by_id(self, id): qs = self.get_queryset().filter(id=id) # Product.objects == self.get_queryset() if qs.count() == 1: return qs.first() return None def search(self, query): return self.get_queryset().active().search(query) class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) gallery_image = models.ImageField(upload_to=upload_image_path_gallery, null=True, blank=True) genre = models.ForeingKey(Genre) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) is_digital = models.BooleanField(default=True) # User Library objects = ProductManager() def get_absolute_url(self): return reverse("products:detail", kwargs={"slug": self.slug}) def __str__(self): return self.title @property def name(self): return self.title def get_downloads(self): qs = self.productfile_set.all() return qs def product_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(product_pre_save_receiver, sender=Product) cart model from decimal import Decimal from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from project.products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request, *args, **kwargs): cart_id … -
Django Project: Link in base.html resulting in an error
I have a link to "Add Album" specified in the base.html in my Django project. The code is below <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="{% url 'music:album-add' %}"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp; Add Album </a> </li> When the "Add Album" link is clicked however, it results in an error: ValueError at /music/album-add/ invalid literal for int() with base 10: 'album-add' Request Method: GET Request URL: http://127.0.0.1:8000/music/album-add/ Django Version: 2.0 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'album-add' Exception Location: C:\Python34\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 947 The music/views.py file code is below from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import Album #=============HOME PAGE=================== class IndexView(generic.ListView): #specify template being used template_name='music/index.html' #when we get a list of all albums, plug them into this template context_object_name='all_albums' #if you don't use this variable it is automatically just object_list (which is used in index.html) #make a query set def get_queryset(self): return Album.objects.all() #=============DETAILS VIEW=============== details about one object class DetailView(generic.DetailView): #what model are we looking at /for model=Album template_name='music/detail.html' #===============For the add album form class AlbumCreate(CreateView): model=Album fields=['artist','album_title','genre','album_logo'] template_name='music/album_form.html' The urls.py code: from django.contrib import admin from django.urls import include, path from . import … -
method object is not JSON serializable
I am using ajax to refresh the cart items when cart item is removed. It works well, if i don't response object with image otherwise I get an error method object is not JSON serializable. If i use model_to_dict for the image part, i get an error 'function' object has no attribute '_meta'. here is the code def cart_detail_api_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) products = [{ "id": x.id, "url": x.get_absolute_url(), "name": x.name, "price": x.price, "image": x.first_image } for x in cart_obj.furnitures.all()] cart_data = {"products": products, "subtotal": cart_obj.sub_total, "total": cart_obj.total} return JsonResponse(cart_data) class Furniture(models.Model): name = models.CharField(max_length=100, blank=True, null=True) manufacturer = models.ForeignKey(Manufacturer, blank=True, null=True) slug = models.SlugField(max_length=200, unique=True) def __str__(self): return self.name def first_image(self): """ Return first image of the furniture otherwise default image """ if self.furniture_pics: return self.furniture_pics.first() return '/static/img/4niture.jpg' class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) furnitures = models.ManyToManyField(Furniture, blank=True) I get 'function' object has no attribute '_meta' error while wrapping x.first_image to model_to_dict How do i resolve such issue? -
making gcp bucket default storage in django
I am not using Appengine. I have deployed my django server in my GCP instance and using django root location for the storage but I want to access the GCP bucket and make it as default storage location for uploading and sending the path to the function used in the views.py Here's a link Configure Django and Google Cloud Storage? From the above url I think the issue can be solved but i am unable to understand where to deploy the code whether in the settings.py or views.py file Is it possible that someone can help me with the steps in it. -
to_python() and from_db_value() methods overlapping in function?
I've been looking at this code example from the docs: import re from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import gettext_lazy as _ def parse_hand(hand_string): """Takes a string of cards and splits into a full hand.""" p1 = re.compile('.{26}') p2 = re.compile('..') args = [p2.findall(x) for x in p1.findall(hand_string)] if len(args) != 4: raise ValidationError(_("Invalid input for a Hand instance")) return Hand(*args) class HandField(models.Field): # ... def from_db_value(self, value, expression, connection): if value is None: return value return parse_hand(value) def to_python(self, value): if isinstance(value, Hand): return value if value is None: return value return parse_hand(value) As far as I understand, from_db_value() is responsible for turning a string that's coming from the database to the right python type (please correct me if I'm wrong). to_python() is also responsible for turning a string value into a python type. If we look at the example, the two functions do similar stuff. No, not the exact same stuff, but very similar. My questions: What is the reason for having two very similar methods on the field? Why does to_python() have to be able to handle value = Hand()? I thought it was made for turning strings into Hand objects. Why does … -
popup UserCreationForm in django
Basically im very new to django only 5 days old. i need to know can i popup UserCreationForm of django? i'm building a website what i need to do is when i click on signup page popup signup page needs to show. right now i have a signup page and login page and they are working but i need to popup them and i'm using usercreationform of django and second thing can i add bootstrap and css in that form too? kindly please help me from django.contrib.auth.forms import UserCreationForm -
Django swagger- How to disable DjangoFilterBackend filters from delete, put methods?
I've created below AssetsFilter: from django_filters import Filter from django_filters import rest_framework as filters from django_filters.fields import Lookup from .models import Asset class ListFilter(Filter): def filter(self, qs, value): value_list = value.split(',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class AssetsFilter(filters.FilterSet): name = filters.CharFilter(lookup_expr='icontains', help_text=u'Filter by Asset name') assets_criticality = ListFilter(name='assets_criticality', help_text=u'Filter by criticality id') class Meta: model = Asset fields = ['name', 'assets_criticality'] Now I'm using this filter in my viewset see in below: from .serializers import AssetSerializers from .filters import AssetsFilter class AssetViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Asset.objects.all() serializer_class = AssetSerializers filter_backends = (DjangoFilterBackend,) filter_class = AssetsFilter http_method_names = ['get', 'post', 'put', 'delete'] def list(self, request): """ Returns a list of Asset. """ return super(AssetViewSet, self).list(request) def create(self, request): """ Creates a new Asset.<br> """ return super(AssetViewSet, self).create(request) def destroy(self, request, pk=None): """ Deletes a Asset. """ return super(AssetViewSet, self).destroy(request, pk=pk) def retrieve(self, request, pk=None): """ Returns a Asset with id={id} """ return super(AssetViewSet, self).retrieve(request, pk=pk) def update(self, request, pk=None, *args, **kwargs): """ Updates an existing Asset.<br> """ return super(AssetViewSet, self).update(request, pk=pk, *args, **kwargs) def partial_update(self, request, pk=None, *args, **kwargs): """ Partially updates an existing Asset.<br> """ return super(AssetViewSet, self).partial_update(request, … -
Reverse for 'create_song' not found. 'create_song' is not a valid view function or pattern name
I have a Django project in which the page that should load to show the album that has just been added, does not. It should go to the primary key for that album (auto generated) with the reference: http://127.0.0.1:8000/music/1/ but instead gives the error: Reverse for 'create_song' not found. 'create_song' is not a valid view function or pattern name. A variant of the same problem, I assume, Is that when I click on the VIEW DETAILS BUTTON (shown below in the index.html) it doesn't load: <div class="caption"> <h2>{{ album.album_title }}</h2> <h4>{{ album.artist }}</h4> <!-- View Details --> <a href="{% url 'music:detail' album.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> <!-- Delete Album --> <form action="#" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="album_id" value="{{ album.id }}" /> <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form> The code for the various sections is below: music/templates/music/album_form.html <div class="row"> <div class="col-sm-12 col-md-7"> <div class="panel panel-default"> <div class="panel-body"> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'music/form_template.html' %} <!-- how form fields and inputs are laid out--> <div class="form-group> <div class="col-sum-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> {% endblock %} music/views.py from django.views … -
How to use active record as DTO to my business objects.
I struggle with this problem for a long time. I searched and searched the whole internet for solution but nothing was acceptable for me. We started a project which looked very simple in terms of business logic required, so I picked Django as a framework to make things easier. The problem got complex and maybe the implementation will be used in a much larger project so I want to decouple my business objects objects from activerecord and I want to use django only as a DB backend and something which uses my objects. The UI is already decoupled from the start, it only calls a REST API provided by the django backend. My problems with an example: I have a Request model which connected to many other models. This request contains some requirement specification related to networks. These networks are associated to a Cloud models. The networks under a cloud will be connected to the reservation which is generated from the request (currently they are connected to the request's nw descriptors to determine the configurations during queries). class Request(Model): ... # bunch_of_stuff_here class NetworkDescriptor(Model): request = ForeignKey(Request) configA = ... configB = ... class Cloud(Model): ... class Network(Model): cloud = … -
Trying to understand JSONField for django postgresql
I'm reading the docs on JSONField, a special postgresql field type. Since I intend to create a custom field that subclasses JSONField, with the added features of being able to convert my Lifts class: class Lifts(object): def __init__(self, series): for serie in series: if type(serie) != LiftSerie: raise TypeError("List passed to constructor should only contain LiftSerie objects") self.series = series class AbstractSerie(object): def __init__(self, activity, amount): self.activity_name = activity.name self.amount = amount def pre_json(self): """A dict that can easily be turned into json.""" pre_json = { self.activity_name: self.amount } return pre_json def __str__(self): return str(self.pre_json()) class LiftSerie(AbstractSerie): def __init__(self, lift, setlist): """ lift should be an instance of LiftActivity. setList is a list containing reps for each set that has been performed. """ if not (isinstance(setlist, collections.Sequence) and not isinstance(setlist, str)): raise TypeError("setlist has to behave as a list and can not be a string.") super().__init__(lift, setlist) I've read here that to_python() and from_db_value() are two methods on the Field class that are involved in loading values from the database and deserializing them. Also, in the docstring of the to_python() method on the Field class, it says that it should be overridden by subclasses. So, I looked in JSONField. Guess … -
Cant get Django debug-toolbar 1.9 to work on django 2.0
I have installed Django debug-toolbar using pip, and added 'debug_toolbar' to the installation app list , but can't manage to get it to work on django 2.0. -
Django serve file to download with CBV
I am trying to serve multiple files in a DetailView. This is the flow: user uploads some docx files in a folder named 'documents' using formsets. In this detailview the admin will be able to see the files and download them. models.py class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) created = models.DateTimeField(auto_now_add=True) number = models.CharField(max_length=100, unique=True) class OrderDoc(models.Model): order = models.ForeignKey(Order) language_source = models.ForeignKey(Language, default=None, null=True) file = models.FileField(upload_to='documents') views.py class OrderUpdateView(LoginRequiredMixin, UpdateView): template_name = 'core/admin_order_update.html' model = Order form_class = OrderForm success_url = reverse_lazy('core:admin_order_list') def get_context_data(self, **kwargs): context = super(OrderUpdateView, self).get_context_data(**kwargs) context['order_documents'] = OrderDoc.objects.filter(order__pk=self.kwargs['pk']) return context admin_order_update.html <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> {% for document in order_documents %} {{ document.file }} {% endfor %} Obviously here document.file shows just the path. I've seen some examples but i don't know how to implement them in cbv. How can i make the files downloadable in detailview? -
Django yearless ranges
I need to store start and ending dates to save holidays. I don't care about the year part of dates, as a holiday will repeat every year. Also I need to be able to query this dates to see if a random datetime is in the range. And even when I don't want years stored, the query must understand that a holiday can start in one year and end next year (i.e. Dec 25th to Jan 4th). Previously I was storing the dates as DateTimeFields, then iterating over each stored holiday and checking if a given target date was inside the dates range. This was made in Python and forced me to evaluate the QuerySets into lists and finally add the value using something like getattr(result, 'is_a_holiday', value) As performance issues have arise I want to move this into an annotation (so I can keep the queryset with select_related and prefetch_related data) and make the database (Postgresql) do the query part, but then I run into the problem that the database considers the year, and thus a date inside a holiday for this year is not considered inside a holiday the previous year or next year. I've already tried django-yearlessdate … -
Applying ckeditor to a textarea
I am trying to add the (inline) CKEditor 5 to an existing django project. I figured I would just use the normal form workflow and simply add the CKEditor to a textarea element inside a form, as via the documentation. <form enctype="multipart/form-data" action="{% url 'some_url' %}" method="post"> {% csrf_token %} {{ message_form.media }} {{ message_form.as_p }} <textarea id="something"></textarea> <input type="submit" value="Post message" class="button-bright button-static" /> </form> <script> InlineEditor .create( document.querySelector( '#something' ) ) .catch( error => { console.error( error ); } ); </script> When I add this to my template the textarea shows up with some of the ckeditor styling applied, and it also shows the inline texteditor, but with all of the buttons greyed out. The only thing I can do is type stuff in the textarea but literally nothing else. I can't use enters and I can't even delete anything I typed by pressing the backspace button either.