Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
using a property method in list_filter in custom admin
I have a model like this: class CustomUser(AbstractUser): @property def is_paid(self): return self.apayment4thisuser.all().filter(expirydate__gt=timezone.now().date()).count()>0 in the customadmin I am able to add this under my list display, but it is throwing error when I add it to my list filter: class CustomUserAdmin(UserAdmin): model = CustomUser list_filter = ['app_user','is_paid'] list_display = ['id', 'username', 'email', 'is_paid', ] This is the error: ERRORS: <class 'users.admin.CustomUserAdmin'>: (admin.E116) The value of 'list_filter[1]' refers to 'is_paid', which does not refer to a Field. I was wondering is there not any way to add this to list_filter? Thanks, -
Some of my tests are not running ok if I do it with Docker in Django Rest Framework
I have been developing a project without Docker, and I have integrated and to make sure everything is ok I have run my tests. It shocked me, almost half of my tests are not running ok. Most of them are testing detail api views. I will post the codes below. Please let met know if you can find something missing or hidden)) [This is the Sample Project] models.py class Book(models.Model): name = models.CharField(max_length=255) author = models.CharField(max_length=255) created_at = models.DateField(auto_now_add=True) def __str__(self): return self.name serialisers.py class BookSerializers(ModelSerializer): class Meta: model = Book fields = ('id', 'name', 'author') views.py class BookListApiView(ListAPIView): queryset = Book.objects.all() serializer_class = BookSerializers permission_classes = [AllowAny, ] class BookCreateApiView(CreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializers permission_classes = [AllowAny, ] class BookRetrieveUpdateDeleteView(RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookSerializers permission_classes = [AllowAny, ] tests.py LIST_BOOK_API_URL = reverse('book:list') CREATE_BOOK_API_URL = reverse('book:create') DETAIL_BOOK_API_URL = reverse('book:detail', kwargs={'pk': 1}) class TestBookApiView(TestCase): def setUp(self): self.client = APIClient() def test_create_book_through_api(self): payload = { 'name': 'this is book', 'author': 'test author' } res = self.client.post(CREATE_BOOK_API_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) def test_listing_book_through_api(self): Book.objects.create( name='test', author='testing', ) res = self.client.get(LIST_BOOK_API_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertContains(res, 'test') def test_retreiving_book_through_api(self): Book.objects.create( name='test', author='testing', ) res = self.client.get(DETAIL_BOOK_API_URL) print(DETAIL_BOOK_API_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) urls.py [for book app] … -
Django AJAX - HttpResponse goes to new page
I'm using AJAX for the first time and I'm having an issue with what happens after the AJAX request. AJAX/JS code $('#post_form').on('submit', function(event){ updatePost(); }); function updatePost() { $.ajax({ url : this.href, type : "POST", data : { title : $('#id_title').val() , content : $('#id_content').val()}, dataType: "text", success : function(json) { console.log(json); editPost(); } }); }; Django View Code: if request.method == 'POST': post.title = request.POST.get('title') post.content = request.POST.get('content') post.save() return HttpResponse(json.dumps({'title' : post.title, 'content' : post.content}), content_type = "application/json") So, the code works and it reaches the view and does what I need it to do up to that point. However, instead of the HtppResponse being 'sent' to the AJAX success function it instead redirects the user to a blank page containing the JSON created in the Django view. -
Django channels websocket reconnect
I am building a messaging system in Django, using web-socket to receive the message. Here is my tryouts, from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("receive", event) message = event['text'] obj = await self.create_obj(message=message) print('Created...') async def websocket_disconnect(self, event): print("disconnected", event) @database_sync_to_async def create_obj(self, **kwargs): obj = ChatMessage.objects.create(message=kwargs['message']) return obj When I start a client app the web-socket is connected, and i can receive the message and i am able to store into the DB. connected {'type': 'websocket.connect'} WebSocket CONNECT /ws/message [192.168.0.101:50148] After some idle time, the web-socket disconnects automatically, Application instance <Task pending coro=<SessionMiddlewareInstance.__call__() running at /Users/ajay/Desktop/workspace/projects/python/django/websock/venv/lib/python3.7/site-packages/channels/sessions.py:183> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x10b311510>()]>> for connection <WebSocketProtocol client=['192.168.0.101', 50148] path=b'/ws/message'> took too long to shut down and was killed. After disconnects, i am not able to receive the message, when i reload the client, web-socket is connected, is there any way to reconnect the we-socket automatically with out reloading the client. I request to guide me some suggestion to achieve this, it will be very helpful for me, Thanks in advance. -
Redirect from view function to DetailView
This example shows how to add forms dynamically to a formset. I wonder if the case #3 can be modified like so: I'd like to handle the Book creation by generic CreateView, after that proceed to the Author creation, which will be handeled by the view below and redirected to the DetailView after Author is created. Below is what I have so far. class BookCreateView(CreateView): model = Book form_class = BookModelForm success_url = reverse_lazy('store:create_book_with_authors') class BookDetailView(DetailView): model = Book context_object_name = 'book' def create_book_with_authors(request): template_name = 'store/create_with_author.html' if request.method == 'GET': bookform = BookModelForm(request.GET or None) formset = AuthorFormset(queryset=Author.objects.none()) elif request.method == 'POST': bookform = BookModelForm(request.POST) formset = AuthorFormset(request.POST) if formset.is_valid(): # here there is no point in saving the bookform since it was already saved by the CreateView, but I'm not sure how to reference to the previously saved Book instance. # book = bookform.save() for form in formset: author = form.save(commit=False) author.book = book author.save() return redirect(reverse('store:book_detail', kwargs={'pk':book.id})) return render(request, template_name, { 'formset': formset, }) -
NoReverseMatch Error in Django, can't pass id parameter
I'm trying to learn python / django but I keep running into this error when I try to add the ability for someone to be able to reply to an already existing entry on a website. It looks like I'm not passing anything for a parameter in a view but I can't figure out why as this same structure worked for another project I was doing from a book. (fyi this is my first post here, I've read a ton of other posts on this here and elsewhere and none of them have helped so far, sorry if any of this is dumb). Here's the error: Exception Type: NoReverseMatch at /instructors/instructors/1/ Exception Value: Reverse for 'new_inquiry' with arguments '('',)' not found. 1 pattern(s) tried: ['instructors/new_inquiry/(?P[0-9]+)/$'] urls.py: I'm getting the error from the last one, the 'new_inquiry' view url, but am including all just in case something could be related from django.urls import path from . import views app_name = 'instructors' urlpatterns = [ path('', views.index, name='index'), path('instructors/<int:instructor_id>/', views.inquiry, name='inquiry'), path('instructors/new_instructor/', views.new_instructor, name='new_instructor'), path('new_inquiry/<int:instructor_id>/', views.new_inquiry, name='new_inquiry'), ] views.py: Issue is with the new_inquiry function (I think). I just can't get it to pass the instructor_id parameter for some reason... from django.shortcuts … -
Celery Worker command 'method-wrapper' object has no attribute '__module__'
Currently trying to initiate a worker for my django app, unfortunately i'm receiving this error: PS C:\Users\User\Documents\Codes\highlightreel> celery -A highlightreel worker -l info Traceback (most recent call last): File "c:\program files\python38\lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\program files\python38\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Program Files\Python38\Scripts\celery.exe\__main__.py", line 7, in <module> File "c:\program files\python38\lib\site-packages\celery\__main__.py", line 16, in main _main() File "c:\program files\python38\lib\site-packages\celery\bin\celery.py", line 322, in main cmd.execute_from_commandline(argv) File "c:\program files\python38\lib\site-packages\celery\bin\celery.py", line 495, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "c:\program files\python38\lib\site-packages\celery\bin\base.py", line 305, in execute_from_commandline return self.handle_argv(self.prog_name, argv[1:]) File "c:\program files\python38\lib\site-packages\celery\bin\celery.py", line 487, in handle_argv return self.execute(command, argv) File "c:\program files\python38\lib\site-packages\celery\bin\celery.py", line 415, in execute return cls( File "c:\program files\python38\lib\site-packages\celery\bin\worker.py", line 223, in run_from_argv return self(*args, **options) File "c:\program files\python38\lib\site-packages\celery\bin\base.py", line 253, in __call__ ret = self.run(*args, **kwargs) File "c:\program files\python38\lib\site-packages\celery\bin\worker.py", line 253, in run worker = self.app.Worker( File "c:\program files\python38\lib\site-packages\celery\worker\worker.py", line 97, in __init__ self.on_before_init(**kwargs) File "c:\program files\python38\lib\site-packages\celery\apps\worker.py", line 93, in on_before_init trace.setup_worker_optimizations(self.app, self.hostname) File "c:\program files\python38\lib\site-packages\celery\app\trace.py", line 596, in setup_worker_optimizations app.finalize() File "c:\program files\python38\lib\site-packages\celery\app\base.py", line 538, in finalize _announce_app_finalized(self) File "c:\program files\python38\lib\site-packages\celery\_state.py", line 54, in _announce_app_finalized callback(app) File "c:\program files\python38\lib\site-packages\celery\app\__init__.py", line 59, in <lambda> lambda app: app._task_from_fun(fun, **options) File "c:\program files\python38\lib\site-packages\celery\app\base.py", line 452, in _task_from_fun '__header__': … -
how do I center the nav with 3 elements(lists) max in a row
I've tried multiple ways but couldn't center it without removing the padding This is what it looks like right now with my code: [1]: https://i.stack.imgur.com/sHEjj.png This is what it should look like: [1]: https://i.stack.imgur.com/yNiCz.png Thanks in advance! header nav ul { display: block; margin: 0 auto; width: fit-content; } header nav ul li { display: inline-block; float: left; list-style: none; padding: 10px 20px; } header nav ul li a { font-family: Segoe UI; color: #777777; font-size: 24px; } <nav> <ul> <li><a href="{% url 'home' %}">Home</a></li> <li><a href="{% url 'movies' %}">Movies</a></li> <li><a href="{% url 'about' %}">About</a></li> {% if user.is_authenticated %} <li><a href="{% url 'my_account' %}">My Account</a></li> {% else %} <li><a href="{% url 'login' %}">Log in</a></li> <li><a href="{% url 'signup' %}">Sign up</a></li> {% endif %} </ul> </nav> -
Uploading multiple files in Django not working
I am trying to upload multiple files using Django. The idea is that while creating a blog post the user can also add images to the post. I am using Ajax to submit the blog post, however, it seems that after adding the image form the "submit" button doesn't work and my post those not get created. I have already built two models, Images and Post. Below are my codes related to this functionality. My project name is register and images are in an app called 'home': (If I remove the image upload functionality the post is created successfully, so the ajax is working correctly) my post_creat view in home app views: @login_required def post_create(request): data = dict() if request.method == 'POST': image_form = ImageForm(request.POST, request.FILES or None) images = request.FILES.getlist('image') form = PostForm(request.POST) if form.is_valid() and image_form.is_valid(): post = form.save(False) post.author = request.user post.save() for i in images: image_instance = Images(image=i,post=post) image_instance.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: image_form = ImageForm form = PostForm context = { 'form':form, 'image_form':image_form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) my javascript code for handling the ajax request: $(document).ready(function(){ var ShowForm = function(e){ … -
Filtering Django View to a Specific Model Instance also written by the same User
This is probably a simple solution but its stumping me. Im new at Django and coding really. Thank you for you patience. I have a Profile model which is a OnetoOne relationship proxy model with an Abstract User. I use that to render a specific template choice with Profile Data. That works just fine. The problem comes in when I try to render the Inventory Model data which is also entered by the same user but is listed on a separate model and app. I am getting all of the Inventory when i list it which isn't surprising as I'm using a def get_context_data in the view with def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['profile'] = Profile.objects.all() context['inventory'] = Inventory.objects.all() return context I know the context['inventory'] is doing exactly what Im asking but i need it to filter to just the objects entered to the same items as entered by the user that made the Profile model .. and I am stumped. Both Models Below: class Profile(models.Model): """Additional User Profile info on a One to One relationship this tracks all the other info concerning the users and their websites.""" # TODO: Define fields here # add additional templates under templates/users. … -
Passenger support or documentation for Django >= 2.2
I am using a shared web host plan to deploy a Django-based website, the hosting service uses cPanel (version 86). I have successfully built the latest version of SQLite and set the LD_LIBRARY_PATH variable so that Python is actively using this version: $ python -c 'import sqlite3; print(sqlite3.sqlite_version)' 3.31.1 I have therefore no problem to run Django 2.2 and 3.0 projects on my server (eg. running python manage.py runserver in my virtual environment is running fine). I can also run python passenger_wsgi.py with no error. However, Passenger seems to fail to load the Django project as I get this error: I've searched the root of my server for this famous log file but did not find it, so I have no idea what the problem is. When uninstalling Django >= 2.2 and installing Django == 2.1.15 in the same virtual env, I get the proper Django page (eg. "The install worked successfully! Congratulations!"). So at this point it seems like the problem is coming from Passenger but I am clueless how-to configure it to be able to handle the latest Django versions. Any help appreciated! -
Specify settings file for Django deployment at GCP App Engine
Inside my Django project, my main app (where the settings.py file is located) is called "main/". But, I have deleted the settings.py file, now I have a directory called "settings/", and inside it, I have different configuration files, e.g., development.py, production.py, etc. How to specify which file Google Cloud Platform should use for my App Engine deployment? Thank you. -
Django Captcha Ask User To Enter The Next Letter / Number For Each Character Of Random / Specified Length Challenge
Code: def captcha_challenge(): challenge = u'' response = u'' for i in range(4): digit = random.randint(0,9) lower_upper_alphabet = string.ascii_letters random_letter = random.choice(lower_upper_alphabet) challenge += str(digit) response += str((digit + 1) % 10) return challenge, response This captcha code currently will display random 4 numbers and ask the user to enter the next number that comes after each number shown. Z would be A and single digit number 9 would be 0 Examples: Current Captcha shows: 1389 Current Solution: 2490 Desired Captcha Shows: 1zbg gua16k wd46ugcq32 Desired solution: 2ach hvb27l xe57vhdr43 My question is how do I get the captcha to show a random length challenge of 10 characters or less each page refresh with both letters and numbers? Where no matter what character is displayed, the user will have to enter the next letter or number that comes after that particular character to solve the captcha? -
ValueError Cannot query "customer1@gmail.com": Must be "Customer" instance
I am trying to save the customer to the Order Model, but the customer is not being saved, it shows customer1@gmail.com must be Customer instance. And also I want to save the seller to the Order model. Because, A product is related to a seller. When I order something, and after the order is saved, I should be able to see from which seller I bought that product from. But here I am not able to save the seller. cart views.py def checkout(request): cart_obj, cart_created = Cart.objects.new_or_get(request) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect('cart:cart') login_form = CustomerLoginForm() signin_form = CreateCustomerForm() address_form = AddressForm() billing_address_id = request.session.get("billing_address_id", None) shipping_address_id = request.session.get("shipping_address_id", None) billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) address_qs = None if billing_profile is not None: if request.user.is_authenticated: address_qs = Address.objects.filter(billing_profile=billing_profile) order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj, request) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del request.session["shipping_address_id"] if billing_address_id: order_obj.billing_address = Address.objects.get(id=billing_address_id) del request.session["billing_address_id"] if billing_address_id or shipping_address_id: order_obj.save() if request.method == "POST": is_done = order_obj.check_done() if is_done: order_obj.mark_paid() request.session['cart_items'] = "" del request.session['cart_id'] return redirect("cart:success") context = { 'object':order_obj, 'billing_profile':billing_profile, 'login_form':login_form, 'signin_form': signin_form, 'address_form':address_form, 'address_qs': address_qs, } return render(request, 'cart/checkout.html', context) order models.py class OrderManager(models.Manager): def new_or_get(self, billing_profile, cart_obj, request): created … -
Searching class based views in Django
I'm trying to make a search option for my ecommerce app in Django. I'm using a ListView for showing my posts and paginate them: def search(request): qs = '' title_query = request.GET.get('q') if title_query != '' and title_query is not None: qs = qs.publicaciones.objects.filter(title__icontains=title_query) context = { 'queryset': qs, } class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 4 This is the relevant HTML: {% for q in queryset %} <div class="container"> <h1>{{ q.Título }}</h1> </div> <div class="container"> {{ q.Descripción }} </div> <div class="container"> <img class="item-img" src="{{ q.Fotos.url }}" width="250"> </div> {% endfor %} However, this codes just shows all the items, my goal is to filter them by the search obviously. It's also really strange that when I set the value for queryset to anything like 'foo', it will still display all the items. I'm compleatly lost. Any help would be appreciated. I already tried these, but didn't get any results: Django: Search form in Class Based ListView How to create a filter form for a (class based) generic object list in Django? -
html css file note displaying image using jinga format for django
my index.html: {% load static %} {% static "images" as baseurl %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Travello template project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css'%}"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css'%}" rel="stylesheet" type="text/css"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.carousel.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/owl.theme.default.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'plugins/OwlCarousel2-2.2.1/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/main_styles.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'styles/responsive.css' %}"> <link rel="stylesheet" href={% static 'index.css"' %}> </head> <body> <div class="super_container"> <!-- Header --> <header class="header"> <div class="container"> <div class="row"> <div class="col"> <div class="header_content d-flex flex-row align-items-center justify-content-start"> <div class="header_content_inner d-flex flex-row align-items-end justify-content-start"> <div class="logo"><a href="{% static 'index.html' %}">Travello</a></div> <nav class="main_nav"> <ul class="d-flex flex-row align-items-start justify-content-start"> <li class="active"><a href="{% static 'index.html' %}">Home</a></li> <li><a href="{% static 'about.html' %}">About us</a></li> <li><a href="accounts/register">Register</a></li> <li><a href="{% static 'news.html' %}">News</a></li> <li><a href="{% static 'contact.html' %}">Contact</a></li> </ul> </nav> <div class="header_phone ml-auto">Call us: 00-56 445 678 33</div> <!-- Hamburger --> <div class="hamburger ml-auto"> <i class="fa fa-bars" aria-hidden="true"></i> </div> </div> </div> </div> </div> </div> <div class="header_social d-flex flex-row align-items-center justify-content-start"> <ul class="d-flex flex-row align-items-start justify-content-start"> <li><a href="#"><i class="fa fa-pinterest" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-facebook" aria-hidden="true"></i></a></li> <li><a href="#"><i class="fa fa-twitter" … -
How to change order_by dynamically using django-tables2?
My table class looks pretty typical except that maybe it includes a before_render() function. What's great about before_render is that I can access self. This gives me access to dynamic information about the model I'm using. How can I access dynamic information (like from before_render) to change the order_by variable in the Meta class? def control_columns(table_self): # Changes yesno for all Boolean fields to ('Yes','No') instead of the default check-mark or 'X'. for column in table_self.data.table.columns.columns: current_column = table_self.data.table.columns.columns[column].column if isinstance(current_column,tables.columns.booleancolumn.BooleanColumn): current_column.yesno = ('Yes','No') class DynamicTable(tables.Table): def before_render(self, request): control_columns(self) class Meta: template_name = 'django_tables2/bootstrap4.html' attrs = {'class': 'custom_table', 'tr': {'valign':"top"}} order_by = 'index' -
Chart JS Issue while rendering the data from database
From last couple of days I was trying hard to integrate chartjs-plugin-streaming on my page, data is properly coming from ajax call, even the graph is responding properly but some time the y-axis gets changed but x remains the same which makes the graph curve bad, it is basically getting overlapped, let me share you the graph and api data with codes, {% load static %} {% block header %} <link rel="stylesheet" href="{% static 'charts/cpu.css' %}"> <script src="{% static 'charts/moment.min.js' %}"></script> <script src="{% static 'charts/chart.js@2.8.0' %}"></script> <script src="{% static 'charts/chartjs-plugin-streaming@1.8.0' %}"></script> {% endblock header %} {% block scripts %} <script> var chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', grey: 'rgb(201, 203, 207)' }; function onRefresh(chart){ chart.config.data.datasets.forEach(function(dataset) { data.forEach((ele) => { dataset.data.push({ x: Date.now(), y: ele.load_1m }); }); }); }; var color = Chart.helpers.color; var config = { type: 'line', data: { datasets: [{ label: 'Dataset 2 (cubic interpolation)', backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(), borderColor: chartColors.blue, fill: false, cubicInterpolationMode: 'monotone', data: [] }] }, options: { title: { display: true, text: 'Line chart (hotizontal scroll) sample' }, scales: { xAxes: [{ type: 'realtime', realtime: … -
How can I make different photos take modal image from an array of photos, from database?
So I'm working on a Django project, a Portfolio website. And I started making some cards for showcasing: I'm pulling all data from Django Database and using bootstrap for frontend: {% for project in projects %} <div class="cardies"> <div class="card" style="width: 18rem;"> <img src="{{ project.image.url }}" class="card-img-top img-fluid" id="myImg" alt="{{ project.description }}"> <div class="card-body"> <h6 class="card-subtitle mb-2 text-muted">{{ project.date }}</h5> <h5 class="card-title">{{ project.title}}</h6> <!-- <p class="card-text">{{ project.description}}</p>--> </div> </div> </div> {% endfor %} And I have some local css styling just to display those cards inline. Now I wanted to create a image modal, where when I click on any of those images, they zoom in like shown: And as you can see, it works, but only for the first picture. I used some javascript to to it, here's the code: HTML: <div id="myModal" class="modal"> <span class="close">&times;</span> <img class="modal-content" id="img01"> <div id="caption"></div> </div> CSS: #myImg { border-radius: 5px; cursor: pointer; transition: 0.3s; } #myImg:hover {opacity: 0.7;} /* The Modal (background) */ .modal { display: none; /* Hidden by default */ position: fixed; /* Stay in place */ z-index: 1; /* Sit on top */ padding-top: 100px; /* Location of the box */ left: 0; top: 0; width: 100%; /* Full … -
Shopping cart in Python for a beginner as a learning project
I am learning Python and would like to create a simple e-commerce site, very basic - just for the sake of example to give myself a goal to create something. Is there something I should know ahead of the time, does Python have classes for this functionality or should I just look for a ready made plug-in for Django? Thank you! -
How to open a link in another tab in Django using reversed URL mapping?
I know that target="_blank" normally works, however, I'm having trouble implementing that code using reversed URL mapping. It does not work for this link as formatted. It opens the link, but in the same tab. Any ideas? Here is the code for the link: <a href="{{ meter.url }}" target="_blank"> <img src="{{ meter.image.url }}" class="img-fluid mb-2" width="100%" height="auto"> </a> -
React useState hook not consistently updating
I started integrating websockets into an existing React/Django app following along with this example (accompanying repo here). In that repo, the websocket interface is in websockets.js, and is implemented in containers/Chat.js. I can get that code working correctly as-is. I then started re-writing my implementation to use Hooks, and hit a little wall. The data flows through the socket correctly, arrives in the handler of each client correctly, and within the handler can read the correct state. Within that handler, I'm calling my useState function to update state with the incoming data. Originally I had a problem of my single useState function within addMessage() inconsistently firing (1 in 10 times?). I split my one useState hook into two (one for current message, one for all messages). Now in addMessage() upon receiving data from the server, my setAllMessages hook will only update the client where I type the message in - no other clients. All clients receive/can log the data correctly, they just don't run the setAllMessages function. If I push to an empty array outside the function, it works as expected. So it seems like a problem in the function update cycle, but I haven't been able to track it … -
"Unicode-objects must be encoded before hashing" when i try send .m3u8 file to S3 using boto3 - Django
I was able to send the video normally to my local machine, but when I changed the storage settings, I just started getting this error. The error points to the line where the code is instance.file.save(file_name_m3u8, file_m3u8) And then immediately points to # .../python3.8/site-packages/storages/backends/s3boto3.py # ... obj.upload_fileobj(content, ExtraArgs=params) # ... My file object file_m3u8 is: file_object <_io.TextIOWrapper name='/tmp/media/lectures/first_video_2/2020-04-04_16-11-20.m3u8' mode='r' encoding='UTF-8'> Simple example: from django.db.models.signals import post_save from django.dispatch import receiver from django.core.files import File from .models import Lecture @receiver(post_save, sender=Lecture) def handle_video_upload (sender, instance, created, ** kwargs): with open ( "/tmp/media/lectures/first_video_2/2020-04-04_16-11-20.m3u8", "r") as file_object: file_m3u8 = File ( name = "media/lectures/first_video_2/2020-04-04_16-11-20.m3u8", file = file_object) instance.file.save ("2020-04-04_16-11-20.m3u8", file_m3u8) The complede code: https://pastebin.com/xVc3gbCK Again: when i remove all s3 and boto storage settings and use local storage, all works fine PS: the vars in settings.py: # STATIC AWS+CLOUDFRONT STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = config("AWS_STORAGE_BUCKET_NAME") CLOUDFRONT_ID = config("CLOUDFRONT_ID") CLOUDFRONT_DOMAIN = f"{CLOUDFRONT_ID}.cloudfront.net" AWS_S3_CUSTOM_DOMAIN = f"{CLOUDFRONT_ID}.cloudfront.net" PS2: i also can upload other files to the s3, but this not works when i try send the .m3u8. -
Django BinaryTreeLike choices
I have this main choice input CATEGORY_CHOICES = ( (0, 'Default'), (1, "Development"), (2, "Business-Finance"), (3, "Entrepreneurship"), (4, "Communications"), (5, "Management"), (6, "Finance&Accounting"), (7, "IT&Software"), (8, "Office&Productivity"), (9, "Personal Development"), (10, "Personal Development"), (11, "Design"), (12, "Marketing"), (13, "Lifestyle"), (14, "Photography"), (15, "Health&Fitness"), (15, "Music"), (16, "Teaching&Academics")) Each of them has a sub-choice menu DEVELOPMENT_CATEGORY_CHOICES = ( (1, 'Web Development'), (2, 'Data Science'), (3, 'Mobile Apps'), (4, 'Programming Languages'), (5, 'Game Development'), (6, 'Databases'), (7, 'Software Testing'), (8, 'Software Engineering'), (9, 'Development Tools'), (10, 'E-commerce')) BUSINESS_FINANCE_CATEGORY_CHOICES = ( (1, 'Analytics'), (2, 'Investing'), (3, 'Stock Trading'), (4, 'Forex'), (5, 'Finance Education'), (6, 'Financial Modeling'), (7, 'Excel'), (8, 'Accounting'), (9, 'Python') ) ENTREPRENEURSHIP_CATEGORY_CHOICES = ( (1, 'Business Fundamentals'), (2, 'Dropshipping'), (3, 'Amazon FBA'), (4, 'Entrepreneurship Fundamentals'), (5, 'Business Strategy'), (6, 'Business Plan'), (7, 'Startup'), (8, 'Blogging'), (9, 'Shopify') ) COMMUNICATIONS_CATEGORY_CHOICES = ( (1, 'Writing'), (2, 'Public Speaking'), (3, 'Communication Skill'), (4, 'Presentation Skill'), (5, 'Fiction Writing'), (6, 'Story Telling'), (7, 'Novel Writing'), (8, 'Marketing Strategy') ) MANAGEMENT_CATEGORY_CHOICES = ( (1, 'Product Management'), (2, 'Leadership'), (3, 'Management Skills'), (4, 'Business Process Management'), (5, 'Agile') ) SALES_CATEGORY_CHOICES = ( (1, 'Strategy'), (2, 'Operations'), (3, 'Project Management'), (4, 'Business Law'), (5, 'Data and analytics'), (6, … -
How to fix ModuleNotFounError in Django?
I'm following a tutorial to deploy Django on Heroku and I've run into an error where after I have uploaded project to github, I can't run manage.py runserver. It sends an error message trace and one of the messages is module not found. Venv is activated, debug is set to false. Below is the stack trace errors. This is the guide I'm following for anyone curious. I am on Re-test and save changes to Github section.