Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Дублирование полей в админке django [closed]
Извиняюсь, если такой вопрос уже был, но сам я не смог найти точного ответа либо понять его, так как недавно изучаю django. Можно ли реализовать в стандартной админке django такой же функционал как в премиум версии плагина ACF на wordpress? То есть, плагин ACF позволяет создавать клоны полей при добавлении записи в админке. Например, мы создаем одно поле изображения или размера товара, а при добавлении записи можем нажать на плюсик рядом с полем и появится его клон и так далее. А потом на странице перебором перебрать все значения этого поля, сколько бы их не получилось. -
Django can I use one Model for multiple Database tables?
I have a problem, I have a database with the following tables: Images(recipeID,image_url) Recipe(recipeID,recipe_title) Preperation(recipeID,preparation) Ingredients(ingredientID,recipeID,amount,unit,unit2,ingredient) I auto-created a models.py file with Django from the database with the following command: python manage.py inspectdb > models.py. In this file, he created all the models and three "strange" models: AllRecipesIngredient, AllRecipesRecipe, and AllRecipesRecipeIngredients. Now I want to know what they are and how I can use the recipes from one model or class like recipes.objects.all(), at the moment it would just give me the title or the preparation. I think the "strange" models he created are a part of what I need but I found no working solution so I hope you can help me. Here is the code: from django.db import models class Images(models.Model): rezept = models.ForeignKey('Rezepte', models.DO_NOTHING, db_column='Rezept_ID', blank=True, null=True) # Field name made lowercase. image_url = models.CharField(db_column='Image_URL', blank=True, null=True,max_length=1000) # Field name made lowercase. class Meta: managed = False db_table = 'Images' class Rezepte(models.Model): rezept_id = models.AutoField(db_column='Rezept_ID', primary_key=True, blank=True) # Field name made lowercase. rezept_title = models.CharField(db_column='Rezept_Title', blank=True, null=True,max_length=1000) # Field name made lowercase. class Meta: managed = False db_table = 'Rezepte' class Zubereitungen(models.Model): zubereitungs = models.OneToOneField(Rezepte, models.DO_NOTHING, db_column='Zubereitungs_ID', primary_key=True, blank=True) # Field name made lowercase. zubereitung = models.TextField(db_column='Zubereitung', … -
Django: Many to Many Relationship puts all object in model in another object
I am trying to have it so I can select which clusters I select for each Issue. However, it auto adds all of them, why is that? -
how can django only render a modal when called
Is it possible to reload a modal without leaving the main page. on the main page i have a table, after clicking on an element i would like to display additional information via modal. The problem is that I have to reload this additional information first, as different information is available for each table element. For example, I could now open a completely new window and cause django to render this window with the tags, but this is ugly. therefore the question would be whether I can deliver the django tags for part of the page (the modal), or can only render the modal later? Since I would like to use the django tags, I don't want to generate an ajax request. is there any trick, how would you do it? Unfortunately, I can't find anything about it, or I'm missing the search terms ... -
Serving private media files from S3 to single page React App (Django DRF backend)
I have set up an S3 bucket on AWS where I upload my sensitive ‘media’ files from my Django DRF + React app. The files are not public. I use boto3 and Django-storages for that and the upload process works fine. I can also download the files for report generation from backend to return PDF response. I would now like to display those files one by one from frontend. It seems like I now have two options: Create a route in Django API/urls to handle media requests and point the app to the media directory. This way, the AWS login is handled by the backend server. This seems to beat the point of using a CDN as all media requests would go via the backend server? Incorporate login credentials to React front end. This seems insecure. What would be the recommended way to achieve this? I can’t seem to find the required information. Thank you. -
Django API REST error using Postman: "detail": "Authentication credentials were not provided."
I learn about Django API REST and have implemented the quickstart project (https://www.django-rest-framework.org/tutorial/quickstart/). It works fine locally but I would like to use API with Postman but it dose'nt works I got 401 Unauthorized error I try adding 'DEFAULT_AUTHENTICATION_CLASSES' key in settings.py but dose'nt works neither settings.py INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10 } moreover, I have a huge traceback in terminal when saving projects (below), even if py manage.py runserver works Traceback (most recent call last): File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 196, in finish_response self.close() File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\core\servers\basehttp.py", line 111, in close super().close() File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\simple_server.py", line 38, in close SimpleHandler.close(self) File "C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 334, in close self.result.close() File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\http\response.py", line 252, in close signals.request_finished.send(sender=self._handler_class) File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\dispatch\dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\dispatch\dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\__init__.py", line 57, in close_old_connections conn.close_if_unusable_or_obsolete() File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\backends\base\base.py", line 514, in close_if_unusable_or_obsolete self.close() File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 248, in close if not self.is_in_memory_db(): File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\jl3.PRT-063\Desktop\Python\Django\env\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type … -
How to properly make a query in Django?
I've ran into a little problem. I want to construct a proper queryset to get values which represent the number of the expenses per category to display this like that. This is what I got now: class CategoryListView(ListView): model = Category paginate_by = 5 def get_context_data(self, *, category_object_list=None, **kwargs): **categories = Category.objects.annotate(Count('expense')) queryset = categories.values('expense__count')** return super().get_context_data( category_object_list=queryset, **kwargs) Of course it doesnt work and I have terrible table like this. I suppose the problem isn't in HTML but in my absolutely wrong query... What should I do? This is my HTML in case it would be needed: {% for category in object_list %} <tr> <td> {{ category.name|default:"-" }} </td> <td> {% for number in category_object_list %} {{ number.expense__count }} {% endfor %} </td> <td> <a href="{% url 'expenses:category-update' category.id %}">edit</a> <a href="{% url 'expenses:category-delete' category.id %}">delete</a> </td> {% endfor %} </tr> Also my models.py: class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('-date', '-pk') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' -
double inheritence of ModelForm class, can't change required fields
I have a ModelForm class that I use as a parent for all my other form classes. It looks like this: class BootstrapForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BootstrapForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs['class'] = 'form-control text-center' if field != 'email': self.fields[field].widget.attrs['class'] += ' text-capitalize' for error in self.errors: if error in self.fields: self.fields[error].widget.attrs['class'] += ' is-invalid' Also I have a model that has a field 'tax_no' with blank set to True: class Institution(CustomModel): name = models.CharField(max_length=256, null=False, blank=False, verbose_name=_('nazwa')) address = models.ForeignKey('Address', on_delete=models.PROTECT, null=False, blank=False, verbose_name=_('adres')) phone = PhoneNumberField(null=True, blank=True, verbose_name=_('telefon')) tax_no = models.CharField(max_length=15, null=True, blank=True, validators=[validate_tax_number, ], verbose_name=_('NIP')) What I want is a model that allows empty tax_no field by default but I want a possibility to set it as a required on demand. My problem is that when I try set the field to required like this: class InvoiceInstitutionForm(BootstrapForm): class Meta: model = Institution exclude = ('address',) def __init__(self,*args, **kwargs): super(InvoiceInstitutionForm, self).__init__(*args,**kwargs) print(self.fields['tax_no'].required) self.fields['tax_no'].required = True it only works correctly if the InvoiceInstitutionForm inherits directly from forms.ModelForm. It doesn't work when inherited from BootsrapForm class. Any ideas why it doesn't work and how to fix it? -
ModuleNotFoundError: No module named 'crispy_forms'
django-crispy-forms is present in requirements.txt (added using pip freeze > requirements.txt) requirements.txt asgiref==3.2.10 autopep8==1.5.4 beautifulsoup4==4.9.1 certifi==2020.6.20 chardet==3.0.4 Django==3.1 django-crispy-forms==1.9.2 feedparser==5.2.1 idna==2.10 Pillow==7.2.0 pycodestyle==2.6.0 python-dateutil==2.8.1 pytz==2020.1 requests==2.24.0 six==1.15.0 soupsieve==2.0.1 sqlparse==0.3.1 toml==0.10.1 urllib3==1.25.10 heroku run pip freeze appdirs==1.4.4 asgiref==3.2.10 certifi==2020.6.20 distlib==0.3.1 Django==3.1.1 filelock==3.0.12 gunicorn==20.0.4 pipenv==2018.5.18 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 virtualenv==20.0.31 virtualenv-clone==0.5.4 whitenoise==5.2.0 So, this leads to Application Error on heroku deploy and the heroku logs --tail gives ModuleNotFoundError: No module named 'crispy_forms' -
Send changes in my django application to the client via socket.io using django signal
Recently I received a demand on the company I work for. They wanted me to build a API using django that will give support a chatbot client. Basically It is supposed to work like that: The API receives a JSON object, containing a message_receiver and a message_body, and it is send to the chatbot client that will handle all the "message-sending" stuff. Great! After doing some research I decided to, instead of going for a logic in which the client periodically pings the server in search for new messages to be sent, go for the inverse logic, in which whenever the server receives a message It would automatically emit an event for the client telling him to send the message. For doing that, I stumbled in some interesting tools, like socket.io, and django channels. I particularly liked socket.io more. So before getting my hands dirty, I drew all the process and ran into a problem that I couldn't find a straight answer to on the internet, most of the tutorials I looked into focused on showing how the communication client-server works, but I couldn't find one that would clearly tell me how to make the communication between django app - … -
Can I figure out why my apache server is only accessible via a proxy?
I just deployed a django app on a linux based server with wsgi_module. The app works perfectly when I use a VPN, but without that, I get "This site can't be reached." Here is the few lines I added in httpd.conf <Directory /path/to/myapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess ip_adress python-home=/usr/local/apache/htdocs/env python- path=/path/to/myapp/ WSGIProcessGroup ip_adress WSGIScriptAlias ip_adress /path/to/myapp/wsgi.py process- group=ip_adress Don't know where is the problem. -
Django oscar custom benefits
I am building a commercial app using Django and Django-oscar and I am trying to create a custom benefit. I have read Oscar's documentation here and I have also found this relative question in Stack Overflow. I have forked Oscar's offer app and created a benefits.py file where I want to put my custom benefit. I also have change the INSTALLED_APPS setting to include my offer app and not Oscar's default. The problem is that Oscar's doesn't see the benefits.py file no matter what I try. At first I thought that something is wrong with my custom Benefit Class but I tried using Oscar's example and that didn't work either. Then I wrote a piece of code designed to fail (for example a variable which had never been assigned a value to) but it didn't so I am thinking that the file is never accessed. Does anybody knows what might be wrong? I am using Django 2.2 and Oscar 2.0.4 Thanks in advance for your time! -
Django Test message passed in with Http404
I'm trying to check if my app passes a message alongside my Http404 call. However I've not been able to access that message inside the tests, only via hacking manually in shell. my_app.views.py: from django.http import Http404 def index(request): raise Http404("My message") Then in this app's test file I call: from django.test import TestCase from django.urls import reverse class AppIndexView(TestCase): def test_index_view(self): response = self.client.get(reverse("my_app:index")) self.assertEqual(response.status_code, 404) # This checks self.assertEqual(response.context["reason"], "My message" # This gives: KeyError: 'reason' # However if I manually trace these steps I can access this key. self.assertContains(response, "My Message") # This gives: AssertionError: 404 != 200 : Couldn't # retrieve content: Response code was 404 (expected 200) # Even though the status code test checks. I also have tried various version to get that message with response.exception, response.context.exception etc. as detailed in this question If I execute in django's shell I can access that message: >>> from django.test import Client >>> from django.urls import reverse >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> client=Client() >>> response = client.get(reverse("my_app:index")) >>> response.context["reason"] 'My Message' How can I get access to this message in my tests.py? -
Django / Anaconda - Can not start server
I made a new django project on a different machine (PC) in a conda enviroment. Now I copied the django project folder and created a new enviroment on the new PC with conda. I installed everything like on the "old" machine but however if I type python manage.py runserver it throws a message: Image Does someone know if something is missing or what can I do to run the django project on the new pc? I have latest conda version 4.8.4, django version 3.0.3 -
How to Check m2m field if exist? if yes add if no remove
How to check m2m field if user is exist -remove. if not add? here is my coed , where im wrong? because it's always just remove if user.following.exists(): user.following.remove(following_profile) return Response({'message': 'now you are unfollow user'}, status=status.HTTP_200_OK) else: user.following.add(following_profile) return Response({'message': 'You are following user'}, status=status.HTTP_200_OK) -
How can i make a main URL with sub URL for different Django app
i want to make main Url and that URl will be main route for all django app. Suppose i have 3 apps blog, linux, business. i want to make url like this: 127.0.0.1:8000/blog/ (when i will click blog menu) 127.0.0.1:8000/blog/linux ( when i will click linux menu) 127.0.0.1:8000/blog/business (when i will click business menu) the blog app will be my index home page and all app link will be like this. I don't want to import all views and models in blog app. the project structure will be same and i don't want to change it. All i want to make blog common for all the app link. If i click a post on linux page the url will be like this:- 127.0.0.1:8000/blog/linux/post name How can i do this.? this is my project structure.. project structure image -
Django ImageField.url returning URL with expiration querystring instead of plain url
I have a simple Model for storing a Client's Logo in my system. I am running into an issue where the returned file.url value is also providing expiration querystring parameters and occasionally it expires before the client logs out of the system so they get a 404 error. With that, I cannot figure out how to disable the querystring from being added other than by either building the URL manually (which probably isn't the best option as Django provides the URL), or by doing (what I have done) and parsed the querystring off from the URL before storing it. Can someone explain what is going on here? - I use Digital Ocean Spaces if that matters but it shouldn't as my static files are stored there as well and there is no expiration set on those files once they are loaded. Here is the model with the upload path: # for client logo uploads def logo_upload_path(instance, filename): # client_name/ClientLogo/logo.[png, jpg, ...] return f'{instance.client_url}/ClientLogo/logo.{filename.split(".")[-1]}' class ClientLogo(models.Model): """ Basically a singleton class, I only want 1 logo per client """ file = models.ImageField(upload_to=logo_upload_path,) client_url = models.CharField(max_length=100) changed = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): # already saved if self.pk is not None: super().save(*args, … -
Django PostgreSQL Connection refused
I am running two applications that use Django 3.07, psycopg2==2.8.5. Both of them live on an Ubuntu 20.04 server with PostgreSQL 10. The first app has no problem connecting to the db When I run the second app it returns this error: RuntimeWarning Traceback (most recent call last): File "/home/noodles/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/noodles/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/noodles/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/home/noodles/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/noodles/venv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/home/noodles/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5342? The db settings are using the same structure and the only difference is in the dbuser, pass and dbname: postgres://dbuser:pass@localhost:5432/dbname The user and the database for the second app are created and can connect to the db using psql -h localhost -U {user} I'm baffled by this. Any ideas? -
How do I upload a file in a FileField using django rest framework
I'm trying to make an API endpoint to upload a file on the server under a unique name and have a FileField relate to it. My models.py: def user_directory_path(instance, filename): ext = filename.split('.')[-1] return f'construct/user_{instance.user.id}/{uuid.uuid4()}.{ext}' class File(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) scenariofile = models.ForeignKey(ScenarioFile, on_delete=models.CASCADE, null=True, blank=True) file = models.FileField(upload_to=user_directory_path, blank=True, null=True) My views.py class FileUploadView(APIView): parser_class = [FileUploadParser,] def put(self, request): if not request.user.is_authenticated: raise ParseError('User is not Authenticated') if 'file' not in request.data: raise ParseError('No file') f = models.File(user=request.user, file=request.data['file']) f.save() return Response(status=status.HTTP_201_CREATED, data={'id': f.id}) I would like to be able to upload a file using a single API endpoint (e.g /upload/file), I do not need to save the filename. My code seems to save the model instance saved in the database, but when I try to the file it seems to be corrupt and opening the file as plain text shows that the first two lines are HTTP headers that were passed in the file upload request. My request: curl --location --request PUT 'https://example.com/upload' \ --header 'Authorization: Token <TOKEN>' \ --header 'Content-Disposition: attachment; filename=img.jpg' \ --form 'file=@/home/myself/img.jpg' -
can i render the template with rest framework django?
how can i render the template with rest framework because when i try to run this code i am getting error 405 Method Not Allowed and in terminal "GET /report/create/ HTTP/1.1" 405 22. how can i solve this error! i want to make a post request with json form. views.py from rest_framework.renderers import TemplateHTMLRenderer, JSONRenderer from rest_framework.generics import (CreateAPIView) from .serializer import ArticleSerializer from .models import Article class ArticleCreateView(CreateAPIView): renderer_classes = [JSONRenderer, TemplateHTMLRenderer] template_name = 'create.html' queryset = Article.objects.all() serializer_class = ArticleSerializer -
For loop inside of Javascript dynamic Html content in Django
I will have a strange question. Version: Django version 3.0.8 This is my Javascript code: fetch(`/loadbox/${message.id}`) .then(response => response.json()) .then(dialog => { let detailcontent= `<div class="hepsi"> <div class="sender"> <h3>${dialog.sendername}</h3><br> @${dialog.sender}</div> <p class="posting msj"> ${dialog.content}</p> <p class="posting rep"> ${dialog.reply}</p> // Here I have a list named replies and I want to loop through all elements and display every reply for that particular message. <br> <div class="m-form"> <form class="form-control"> <input class="msj-i" type="text" placeholder="Start a new message"></input> <input type="submit" value="Send" class="msj-s"></input> </form> </div></div>` ; document.querySelector('#message-view').innerHTML=detailcontent; document.querySelector('.msj-s').onclick = function() { sender=`${dialog.sender}` reply_message(sender); } }) } so where I fetch the data /loadbox/message.id, I have this data for example: {"replies": ["hi there", "haha", "last"],"sendername": "Bilge", "sender": "bilge", "content": "hi"} As you see replies is a list and I want it to loop through in the HTML template. However, I use dynamic content in my javascript code. Normally in Django template, I would easily do {% for reply in replies %} {{reply }} { % endfor %} However, I am writing a dynamic html with this method: content = `"some content"` document.querySelector(".message-view").innerHtml = content So I need to loop this through inside of the content I think. I tried: {for (${reply} of ${replies})} <p class="posting rep"> … -
django form redirect to new url
I have a django form with a DateField and then I use it to construct a local url, the idea is to redirect the user to that url but all i get is a new tab with the current page. I use here a public url since the one I'm using is local. in my form.py I have this: class DateInput(forms.DateInput): input_type = 'date' class DateForm(forms.Form): date = forms.DateField(label='',widget=DateInput) def clean_date(self,*args,**kwargs): date = self.cleaned_data.get('date') if date < datetime.date.today(): raise forms.ValidationError("No past data available ") if date > datetime.datetime.now().date() + datetime.timedelta(days=2): raise forms.ValidationError("You cannot consult beyond three days") year_i=date.strftime("%Y") month_i=date.strftime("%m") day_i =date.strftime("%d") url=f'http://weather.uwyo.edu/cgi-bin/sounding?region=samer&TYPE=TEXT%3ALIST&YEAR={year_i}&MONTH={month_i}&FROM={day_i}12&TO=0212&STNM=72672' return redirect(url) in my views.py I have this: from .form import DateForm def met(request): form = DateForm() if request.method =='POST': form = DateForm(request.POST) context = { 'form':form } return render(request,'apps/met.html',context) and in my html file I have this: <form class="form-group pt-2 " method="post" target="_blank"> {% csrf_token %} <div class="pt-3"> {{ form.as_p }} <button class="btn btn-primary "type="submit" name="button">Seach</button> </div> </form> -
Django media url mismatch with digitalocean spaces
I have a droplet running a django app on digital ocean using digital ocean spaces.I have managed to set up the spaces wich runs well with static files using a cdn.However, my problem lies with the uploaded media files.I am facing an issue of mismatch in the urls of the uploaded file served by django and what the actual path of the uploaded files in the spaces. For example if i upload a file using models: attachment = models.FileField(upload_to='Mailserver/',blank=True,null=True) and the path of the file returned when i click on it, returns an error with the path as 'https://freelance.ams3.cdn.digitaloceanspaces.com/media/Mailserver/download.png' which is wrong because the correct path of the file uploaded to spaces is: 'https://freelance.ams3.cdn.digitaloceanspaces.com/freelance/media/Mailserver/download.png' This is my settings config: AWS_ACCESS_KEY_ID = '****************************' AWS_SECRET_ACCESS_KEY = '*****************************' AWS_STORAGE_BUCKET_NAME = 'freelance' AWS_S3_ENDPOINT_URL = 'https://freelance.ams3.digitaloceanspaces.com/' AWS_S3_CUSTOM_DOMAIN = 'freelance.ams3.cdn.digitaloceanspaces.com' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = 'public-read' STATIC_URL = '{}/{}/'.format(AWS_S3_CUSTOM_DOMAIN, 'static') STATIC_ROOT = 'static/' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIA_ROOT = 'media/' MEDIA_URL = '{}/{}/'.format(AWS_S3_CUSTOM_DOMAIN, MEDIA_ROOT) DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' And custom_storages looks like: from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticStorage(S3Boto3Storage): bucket_name = settings.AWS_STORAGE_BUCKET_NAME location = settings.STATIC_ROOT class MediaStorage(S3Boto3Storage): bucket_name = settings.AWS_STORAGE_BUCKET_NAME location = settings.MEDIA_ROOT I have tried creating folders and … -
Cannot filter data inside Django template html
I want to filter data using return redirect if the value is equals to somevalue then it will trigger the toast template but currently it doesn't work. Below is my current code. can you help me with this problem?, thanks in advance. views.py def register(request): somevalue='Successfully created' return render(request, 'register.html',{"somevalue":somevalue}) register.html -script {% if somevalue =="Successfully created" %} <script> $(document).ready(function() { setTimeout(function() { toastr.options = { closeButton: true, progressBar: true, showMethod: 'slideDown', timeOut: 4000 }; toastr.success('Success', 'Successfully created'); }, 1300); }); </script> {% endif %} -
How to display the date of my selected item.? - Django
Right now the problem I want to show the date of the item1 I have selected, what days this item1 is available for sale. For example, item1 is available for sale on Monday, Tuesday. If I choose to buy this item1, In the Checkout page Must show the date All of this item1 In order that people can order and configure another date that they want to be delivered on. I don't know what to do. I'm not sure how to create a function in the Orderform class in form.py to display the date. Code snippets on this question 1. Models.py class Meal(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() def dates_available(self, mindate=None, maxdate=None): mindate = mindate or now().date() maxdate = maxdate or mindate + datetime.timedelta(days=365) ret = [] for availability in self.availability.all(): ret.extend( [available.available_on for available in availability.dates.all()] ) return list(filter(lambda a: mindate <= a <= maxdate, ret)) class MealAvailabilityManager(models.Manager): def available_meals(self, date=None): return self.get_queryset().filter(dates__available_on=date or now().date()) class MealAvailability(models.Model): meal = models.ForeignKey( Meal, on_delete=models.CASCADE, related_name="availability" ) supplier_price = models.DecimalField(max_digits=14, decimal_places=2) sell_price = models.DecimalField(max_digits=14, decimal_places=2) objects = MealAvailabilityManager() def __str__(self): return f"{self.meal}: {self.dates.first()} - {self.dates.last()}" class Order(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.SET_NULL, null=True) phone = …