Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get data related from another table django rest framework
I have three model Pesticide, Disease and Instruction what i want is to get all disease with relation to pesticide which relate to instruction model class Disease(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Pesticide(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Treatment(models.Model): disease = models.ForeignKey(Disease, related_name='treatments', on_delete=models.DO_NOTHING) pesticide = models.ForeignKey(Pesticide, related_name='treatments', on_delete=models.DO_NOTHING) def __str__(self): return self.instruction and serializer class PesticideSerializer(serializers.ModelSerializer): class Meta: model = Pesticide fields = ('id', 'name') class DiseaseSerializer(serializers.ModelSerializer): pesticides = PesticideSerializer(source='treatment_set', read_only=True) class Meta: model = Disease fields = [ 'id', 'name', 'pesticides', ] My problem is that i can not get pesticides in django serializer -
Why my swipper 3d slider is not working properly when I make a for loop in Django?
{% extends 'elections/base.html'%} {% load static %} {% block content %} <div class="row"> <div class="col-lg-12"> <div class="swiper-container"> <div class="swiper-wrapper"> <div class="swiper-slide"> <div class="row candidate_details"> {% for president in presidents %} <div class="card"> {% if forloop.counter == 1 %} <div class="card-body"> <img src="{{president.imageURL}}" alt="profile image" class="profile-img1"> <h1>{{president.first_name}} {{president.last_name}}</h1> </div> </div> {% else %} {% endif %} <div class="card"> <div class="card-body"> <h1>Incoming Results</h1> <hr> <h2>Total Votes</h2> <h1>1,233,333 votes</h1> <hr> <h1>36%</h1> <hr> </div> </div> {% endfor %} </div> </div> </div> </div> </div> </div> </div> <script src="https://unpkg.com/swiper/swiper-bundle.js"></script> <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script> <script> var swiper = new Swiper('.swiper-container', { effect: 'coverflow', grabCursor: true, centeredSlides: true, slidesPerView: 'auto', coverflowEffect: { rotate: 30, stretch: 0, depth: 500, modifier: 1, slideShadows: true, }, pagination: { el: '.swiper-pagination', }, }); </script> {% endblock content %} I want to have a 3d slider of images and data in the description area. I want to display the image of a candidate and his details for each candidate one at time on each slide as shown in this image: -
Easy-thumbnails/Django Rest Framework : InvalidImageFormatError with Django File
I am using Django Rest Framework to upload profile picture and easy-thumbnails to resize my images. I test my API and I have this result : File "/home/worldorama/profile/views.py", line 84, in post profile_picture = services.upload_profile_picture( File "/home/worldorama/profile/services.py", line 225, in upload_profile_picture return ProfilePicture.objects.create( File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 422, in create obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 740, in save self.save_base(using=using, force_insert=force_insert, File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 777, in save_base updated = self._save_table( File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 870, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 907, in _do_insert return manager._insert([self], fields=fields, return_id=update_pk, File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1374, in execute_sql for sql, params in self.as_sql(): File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1316, in as_sql value_rows = [ File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1317, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1317, in <listcomp> [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields] File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1268, in pre_save_val return field.pre_save(obj, add=True) File "/usr/local/lib/python3.8/site-packages/django/db/models/fields/files.py", line 288, in pre_save file.save(file.name, file.file, save=False) File "/usr/local/lib/python3.8/site-packages/easy_thumbnails/files.py", line 759, in save content = Thumbnailer(content, name).generate_thumbnail(options) File "/usr/local/lib/python3.8/site-packages/easy_thumbnails/files.py", line 385, in generate_thumbnail raise … -
Tests not running - Postgres database not connect via circle ci
I am running a Django project and I have set up tests and wanted to run them through circle ci. However, when I push my code to GitHub. Circle CI can't seem to connect the database. This only started when I introduced a .env file and python decouple What is the best way to setup environment variables that I need for development and the same time for Circle CI? I have tried creating seperate settings config files. I have tried creating environment variables on the CircleCI dashboard but Circle CI is still not able to connect to the db and it seems like the environment variables are causing the error but I am not sure why? To see the error. Click here:https://i.stack.imgur.com/swVfK.png. You can also clone my project from github to test it out yourself and also to check out my config.yml Github Repo I would really appreciate some insight on this -
MultipleObjectsReturned at /account/ get() returned more than one Order -- it returned 2
i want to show the ordered product in the account.html as user account views but it only show one product and when item increase from more then one product then shows that error , when i change the get to filter it iterates through models but don't show the detail through that views.py class AccountView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=True) # when change get from filter it don't show the product name and details context = { 'object': order } return render(self.request, 'account.html', context) except ObjectDoesNotExist: messages.warning(self.request, "You do not have any order yet") return redirect("/") when change the object.items.all to object it don't show detail but it iterates through and print the exact number of times as the product ordered account.html {% for order_item in object.items.all %} <tr> <td data-th="Product"> <div class="row"> <div class="col-sm-2 hidden-xs"><img src="{{ order_item.item.image.url }}" alt="..." class="img-responsive"/></div> <div class="col-sm-10"> <h4 class="nomargin">{{ order_item.item.title }}</h4> <p>Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet.</p> </div> </div> </td> <td data-th="Price">{{ order_item.item.price }}</td> <td data-th="Quantity"> <input type="number" class="form-control text-center" onclick="update_item()" value="{{ order_item.quantity }}"> </td> <td data-th="Subtotal" class="text-center"> {% if order_item.item.discount_price %} &#8377;{{ order_item.get_total_discount_item_price }} <span … -
Django Image input failed, image cant save to static file
I try to allow user to upload some image using django model form, but that images cant store to my database. Went i am try to print that query that all show it but doesnt store in database Here is the code # views.py def add_thumbnails(request): if request.user.is_authenticated: if request.method == 'POST': form = PoolForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('home:index')) else: form = PoolForm() return render(request, 'home/add_thumnails.html', { 'form' : form, } ) else: return HttpResponseRedirect(reverse('home:login_status')) # models.py class Pool(models.Model): date_add = models.DateTimeField(auto_now=True) title = models.CharField(max_length=30) categories = models.ForeignKey(Categories, on_delete=models.CASCADE) status = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) img_1 = models.ImageField(upload_to='static/upload_tumb/') img_2 = models.ImageField(upload_to='static/upload_tumb/') vote_img1 = models.IntegerField(default=0) vote_img2 = models.IntegerField(default=0) def __str__(self): return self.title # forms.py class PoolForm(forms.ModelForm): img_1 = forms.ImageField(label='Image 1') img_2 = forms.ImageField(label='Image 2') class Meta: model = Pool fields = ( 'title', 'categories', 'img_1', 'img_2', ) -
Reuse queryset in multiple views
I am building a application which has several views - HomePageView, SearchPageView and DetailPageView. The aforementioned views return the same queryset. My question is, what is the proper way to define let's say a "global" queryset which would be then used in multiple Views. To illustrate my point here is an example of what I have: class HomePageView(TemplateView): def get_queryset(): return Systemevents.objects.filter(**filter) class SearchPageView(ListView): def get_queryset(): return Systemevents.objects.filter(**filter) class LogDetailView(DetailView): def get_queryset(): return Systemevents.objects.filter(**filter) What I would like to achieve: global queryset = Systemevents.objects.filter(**filter) class HomePageView(TemplateView): def get_queryset(): return queryset class SearchPageView(ListView): def get_queryset(): return queryset class LogDetailView(DetailView): def get_queryset(): return queryset Thanks in advance, Jordan -
Django - no migrations folder after refactoring projects and apps names
I have refactored my app and project names, but after that Django doesn't create migrations folder in my app and doesn't actually apply my models migrations. Even after migrations (with no warning nor error) I have no tables with my objects. Does anybody know how to force django to do those migrations? -
How to call aggregate function in html using django
How to remove unnecessary words just like this {'amount__sum': 480.0} in my html ? i just want to print the value only. this is my html <span>{{total}}</span> this is my views.py ..... total = CustomerPurchaseOrderDetail.objects.filter( id=itemID ).aggregate( total=Sum( F('unitprice') * quantity, output_field=FloatField(), ) )['total'] return render(request, "cart.html", {"total":total}) -
Django Channels - Channel Layer?
I am newbie in web development and learning mostly Django and Vanilla Javascript, CSS for now. I got confused while reading the docs about Django Channels. In tutorials it is written that Channel Layer is like kind of a router which passes HTTP request to views and Websocket traffic to Consumers and Redis is mostly used for Channel layer. As I mentioned I am kind of newbie in development and never used Redis. The thing I understood from reading couple of posts that Redis is used as cache for lowering the load on database accesses. So my question is: What is relattion of Channel Layer and Redis. If Redis is a caching technology, how it is used as router for requests? -
Selecting framework for python language with matplotlib, numpy, scipy, soundfile, sounddevice
I am trying to develop web application using python technology but searching for suitable framework. I am not sure how much django, streamlit or flask will be suitable due to its limitations. Framework should be compatible with below mentioned libraries. matplotlb, numpy, scipy, soundfile and sounddevice. Also is it possible to plot graph using matplotlib in real time on website? Please refer the following image. Please suggest supportive framework so that it won’t be a problem going forward to develop web app.Real time plotting of signal -
how django compress render , it watest time in html transport? [closed]
my django server website loads many time in content download enter image description here enter image description here my django codes is def function(request): data_list = get_data_list() #big data return render(request, 'xx.html',{'data_list':data_list}) -
Django Authentication using external Http request (http://x.x.x.x:8013/api/LDAP/LoginLDAP ) in windows 10
I have a simple Django application that is currently running on normal basic auth in Django. I need to integrate with below given external API which accepts username and password, this is provided by my organization so that all employees in the organization can access the app with their org username and password. http://x.x.x.x:port/api/LDAP/LoginLDAP { "username": "userid", "password": "password" } should be sent as JSON and use the POST method if user exists this returns me his details { "username": "userid", "email": "password", "role" : "role", } if user does not exist or auth details are wrong it returns { invalid credentials } can anyone help me with what kind of auth should I use? Thanks in advance. -
Celery failing with ValueError on Python 3.8
I upgraded my environment to python 3.8 and now my celery (tried v4.4.2 to 4.4.7) is not able to start with the following error: ValueError: invalid width -2 (must be > 0) Any ideas how I can solve this? Thanks! -
why signup form is not submitting in database ? Need advice
After fillup signup form it only shows html waning shows up(please fill this field) in the middle of the signup form and when click on the button of signup withour fill up form, same html warning shows up (please fill this field) in the middle of the signup form instead of every input field. why signup form is not submitting in the database. urls.py (connect main folder) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('account.urls')), ] urls.py (account app folder) from django.urls import path, include from account import views from django.contrib import admin urlpatterns = [ path('', views.account, name='account'), path('signup', views.signup, name='signup'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), ] views.py (account) from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import User, auth from django.contrib.auth import authenticate, login, logout # Create your views here. def account(request): return render(request, 'account/base.html') def signup(request): if request.method == "POST": # get the post parameters first_name = request.POST['fname'] last_name = request.POST['lname'] email = request.POST['email'] username = request.POST['username'] password1 = request.POST['pass1'] password2 = request.POST['pass2'] # create the user user = User.objects.create_user(username=username, password=password1, email=email, first_name=fname, last_name=lname); user.save() return redirect('account') def login(request): return HttpResponse('hello') def logout(request): return HttpResponse('hello') base.html <!doctype html> {% … -
Paginating AJAX results on a Django Template
I have a basic Django template that displays the objects in the database and I have used Django's pagination and it works just fine. However, I have a sort functionality on the template that is tied with an AJAX function that updates the template based on the choice picked. The results get displayed just fine, but I would like to paginate this new updated data but I've had no luck so far. Here is my code: The views.py def open_challenges(request): the_tags = ChallengeTag.objects.all()[:10] the_audiences=ChallengeAudience.objects.all()[:10] url_parameter = request.GET.get("q") if url_parameter: challenges = Challenges.objects.all().filter(Q(status='Open') & Q(offered_by__icontains=url_parameter)).order_by('id') else: challenges = Challenges.objects.all().filter(status='Open').order_by('date_posted') paginator = Paginator(challenges, 2) try: page = int(request.GET.get('page', '1')) except: page = 1 try: posts = paginator.page(page) except(EmptyPage, InvalidPage): posts = paginator.page(paginator.num_pages) if request.is_ajax(): html = render_to_string( template_name = "mainapp/open-challenges-partial.html", context={"challenges":posts} ) data_dict = {"html_from_view":html} return JsonResponse(data=data_dict) context = { 'challenges':posts, 'the_tags':the_tags, 'the_audiences':the_audiences } return render(request, 'mainapp/open-challenges.html', context) The open-challenges-partial.html <div class="row" id="replaceable-content"> {% for challenge in challenges.object_list %} <p>{{challenge.title}}</p> <p>{{challenge.challenge_summary}}</p> {% endfor %} </div> ..... <nav aria-label="Page navigation example"> <ul class="pagination circle-pagination justify-content-center"> {% if challenges.has_previous %} <li class="page-item"> <a class="page-link" tabindex="-1" href="?page={{challenges.previous_page_number}}"><i class="fas fa-angle-double-left"></i></a> </li> {% endif %} {% for pg in challenges.paginator.page_range %} {% if challenges.number == pg %} … -
how can I build a query where I can limit the access to lessonmodule based on the membership?
I am trying to limit the access based on URL , and database where the initial user could see all courses, and lessons which this means all syllabus, but however at the same time it contains a lesson module where not all users can have access to, and I want if the given user is free then and tries to access to a paid lesson module it will keep the object: None while if the user is paid will be able to access the content of that lesson module: example: /courses /javascript /javascript/intro /javascript/intro/hello_world # free ones /javascript/intro/if_else # paid accounts views class LessonDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, *args, **kwargs): lesson = get_object_or_404(Lesson.objects.select_related('course').prefetch_related('lessonmodule_set'), slug=lesson_slug, course__slug=course_slug) context = { 'object': lesson, 'previous_lesson': lesson.get_previous_by_created_at, 'next_lesson': lesson.get_next_by_created_at, } return render(request, "courses/lesson_detail.html", context) my old version view class LessonDetailView(LoginRequiredMixin, View): def get(self, request, course_slug, lesson_slug, *args, **kwargs): course = get_object_or_404(Course, slug=course_slug) lesson = get_object_or_404(Lesson.objects.select_related('course'), slug=lesson_slug, course__slug=course_slug) user_membership = get_object_or_404(UserMembership, user=request.user) user_membership_type = user_membership.membership.membership_type lesson_allowed_mem_types = lesson.allowed_memberships.all() context = { 'object': None } if lesson_allowed_mem_types.filter(membership_type=user_membership_type).exists(): context = { 'object': lesson, 'previous_lesson': lesson.get_previous_by_created_at, 'next_lesson': lesson.get_next_by_created_at, } return render(request, "courses/lesson_detail.html", context) template {% extends 'courses/base.html' %} {% block post_detail_link %} {% if object is not … -
Adding Data through For-Loop deletes old data
I have created a e-commerce project. I have 3 models. Item, CartItem, Placeorder(checkout). I am looping through user's cart which has multiple items so that I can get each item and make a placeorder instance. But the for loop works only for the first time and when I try to placeorder(checkout) again with multiple items, the old data(records) are deleted and replaced by new data in the for loop. I do not understand this behavior. I cannot get past this. Maybe I am making some silly mistake. models.py SUB_CATEGORY_CHOICES = ( ('Veg','Veg'), ('Non-Veg','Non-Veg'), ) QUANTITY_CHOICES = ( ('Half','Half'), ('Full','Full') ) class Item(models.Model): name =models.CharField(max_length=1000) description =models.CharField(max_length=2000) # snacks, maincourse, soups, rice, ice-cream category =models.CharField(max_length=1000) # veg, non-veg # sub_category =models.CharField(max_length=1000,blank=True,null=True) sub_category =models.CharField(choices=SUB_CATEGORY_CHOICES, max_length=1000) images1 =models.FileField(upload_to='food_image',blank=True,null=True) images2 =models.FileField(upload_to='food_image',blank=True,null=True) price =models.CharField(max_length=500) add_date =models.DateTimeField(default=timezone.now) # half, full quantity_size =models.CharField(choices=QUANTITY_CHOICES,max_length=1000, blank=True,null=True) avg_rating =models.FloatField(default='0',blank=True,null=True) def __str__(self): return '%s - %s - %s' % (self.id,self.name,self.price) class Meta: ordering = ['-add_date'] class CartItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) the_item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) price = models.IntegerField() def __str__(self): return '%s - %s' % (self.the_item.name, self.the_item.sub_category) class Placeorder(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) order_items = models.ForeignKey(CartItem, on_delete=models.CASCADE) item_quantity = models.IntegerField(default=1) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) … -
The joined path is located outside of the base path component when trying to resize images in a Django template
I am new to stack overflow and I am encountering an issue when trying to resize images within my template using django daguerre. The error is: :The joined path (C:\media\restaurants\images\Cover_Image-Big-Mac-1242x690_6_2.png) is located outside of the base path component (C:\Users\Luiza\Desktop\unifiedr\media)." Any help is welcome as I am not sure what is wrong here. Bellow are my settings: `STATIC_URL = '/static/'` `MEDIA_URL = '/media/'` `MEDIA_ROOT = os.path.join(BASE_DIR, 'media')` `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'restaurants', 'django.contrib.humanize', 'django_filters', 'daguerre', ]` Below is my urls.py: `from django.contrib import admin from django.urls import path, include from restaurants import views from django.conf.urls.static import static from django.conf import settings from django.conf.urls import url urlpatterns = [ path('', views.home, name="home"), path('admin/', admin.site.urls), path('<int:rest_id>/', views.detail, name = "detail") ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) + [ url(r'^', include('daguerre.urls')), ] ` HTML template: `{% extends "base.html" %} {% load humanize %} {% load daguerre %} {% block content %} <img class="img-thumbnail" src="{% adjust restaurant.img.url 'fill' width=128 height=256 %}" onerror="this.src = 'https://icon-library.com/images/photo-placeholder-icon/photo-placeholder-icon- 7.jpg';">` Model: `class Restaurant(models.Model):` `img = models.ImageField(upload_to = 'restaurants/images', null = True, max_length = 1000)` My project structure is attached.[enter image description here][1] [1]: https://i.stack.imgur.com/WhjKy.png -
How to change a label of another page using hyperlink?
I am new to Django and I'd like to ask if it is possible to change a page's label using a hyperlink from another page. I want to pass a value, ex. '1' and use it as a label for another template. I am able to redirect from page to page using hyperlink but I have no idea how to pass some parameters to be used by another. The Hyperlink's purpose is to tell the other page that it is for a certain value. Here's the code of my hyperlink: //It is a hyperlink with image. <a class="btn bgImg" href="{% url 'trend_view'%}"></a> Here's the code in my view: def stage_trend_view(request, value): args={ val = value} template = loader.get_template("Hole_Analyzer/trend_per_stage.html") return HttpResponse(template.render(args, request)) And here's the template I want to use the value being passed: {% extends "base.html" %} {% load static %} {% block title %}Stages{% endblock %} {% block content-nav %} {% endblock content-nav %} {% block card_title %}Trend for Stage {{val}} {% endblock card_title %} {% block content-Card %} <div class="card-body"> <div class="row"> <p>This is Graphs and shits</p> </div> </div> {% endblock content-Card %} {% block scripts %} {% endblock scripts %} Here's the url.py: path(r'^trend/(?P<value>\d+)/$', stage_trend_view, name='trend_view') -
Heroku Procfile.windows behaving oddly
I'm attempting to deploy my django app to heroku. I'm working on windows but when I name my procfile "Procfile.windows" I get a Procfile declares types -> (none) error. When I just name it "Procfile" I get a bash: py: command not found here's the file web: py manage.py runserver 0.0.0.0:8000 I tried with python instead of py and got Build succeeded 2020-09-01T06:48:12.435733+00:00 app[web.1]: Watching for file changes with StatReloader 2020-09-01T06:48:12.436952+00:00 app[web.1]: Performing system checks... 2020-09-01T06:48:12.436953+00:00 app[web.1]: 2020-09-01T06:48:12.883911+00:00 app[web.1]: System check identified no issues (0 silenced). 2020-09-01T06:48:13.163963+00:00 app[web.1]: September 01, 2020 - 06:48:13 2020-09-01T06:48:13.164126+00:00 app[web.1]: Django version 3.1, using settings 'lunaSite.settings' 2020-09-01T06:48:13.164127+00:00 app[web.1]: Starting development server at http://0.0.0.0:8000/ 2020-09-01T06:48:13.164128+00:00 app[web.1]: Quit the server with CONTROL-C. 2020-09-01T06:48:13.000000+00:00 app[api]: Build succeeded 2020-09-01T06:48:13.767832+00:00 app[web.1]: Watching for file changes with StatReloader 2020-09-01T06:48:13.768157+00:00 app[web.1]: Performing system checks... 2020-09-01T06:48:13.768163+00:00 app[web.1]: 2020-09-01T06:48:14.101794+00:00 app[web.1]: System check identified no issues (0 silenced). 2020-09-01T06:48:14.264505+00:00 app[web.1]: September 01, 2020 - 06:48:14 2020-09-01T06:48:14.264609+00:00 app[web.1]: Django version 3.1, using settings 'lunaSite.settings' 2020-09-01T06:48:14.264609+00:00 app[web.1]: Starting development server at http://0.0.0.0:8000/ 2020-09-01T06:48:14.264610+00:00 app[web.1]: Quit the server with CONTROL-C. 2020-09-01T06:49:08.160313+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch 2020-09-01T06:49:08.188765+00:00 heroku[web.1]: Stopping process with SIGKILL 2020-09-01T06:49:08.320546+00:00 heroku[web.1]: Process … -
Working with Mapbox JS in a Django project
I am working with a MapBox JS map element in a Django project, and the intention is to use the returned map result to query an SQLite3 database. My question is whether I am best placed to work with JS to query my database, or whether I can pass the JS variable/s to an existing function I have within my views.py which does the database lookup. If the latter, I would appreciate any advice/instruction on how to go about doing this. -
I'm using docker and when I installed new package to requirements.txt my python files not see new package
My docker-compose.yml looks like this: version: "3" services: web: build: . command: ./docker-entrypoint.sh volumes: - .:/code ports: - "8080:8080" environment: - DJANGO_SETTINGS_MODULE=X.settings.local worker: build: . command: python manage.py process_tasks volumes: - .:/code depends_on: - web environment: - DJANGO_SETTINGS_MODULE=X.settings.local And Dockerfile like this: FROM python:3.6.7-slim ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ requirements.txt like this: ... .. colorama==0.3.9 django-import-export==2.3.0 I tried this commends but it didn't work: docker-compose up --build Actually packages seem to have been downloaded but I'm giving ModuleNotFounError when I restarted docker from command line. -
How to create Django forms for JSON field
I want to create forms in Django for such that data what i shown above can be embedded in json field. It may contains as many number of rows according to user who creates it in webpage. Data Base: MySql This how I have modeled log = Column(JSON, name='log') I want to use the data in second column for validation How to do it? -
how can I build a query that retrieve lesson modules strictly that matches to the lesson?
how can I retrieve the lesson modules by its parent lesson strictly? e.g if I change to the next lesson where at the same contains a lessonmodule /lesson1/task1 this one shouldn't display since it doesn't belong to lesson2? how can I fix this by only retrieve slugs, content by the lesson attach to? views class LessonDetailView(LoginRequiredMixin, View): login_url = "/account/login/" def get(self, request, course_slug, lesson_slug, *args, **kwargs): lesson = get_object_or_404(Lesson.objects.select_related('course'), slug=lesson_slug, course__slug=course_slug) lessonmodule = get_object_or_404(LessonModule.objects.select_related('lesson'), slug='hello_world') context = { 'object': lessonmodule, 'previous_lesson': lesson.get_previous_by_created_at, 'next_lesson': lesson.get_next_by_created_at, } return render(request, "courses/lesson_detail.html", context) models class Lesson(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(max_length=25,unique=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('lesson-detail', kwargs={ 'course_slug': self.course.slug, 'lesson_slug': self.slug }) class LessonModule(models.Model): slug = models.SlugField(unique=True, blank=True, null=True) content = models.TextField() lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) allowed_memberships = models.ManyToManyField(Membership) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True) def __str__(self): return self.slug template {% block content %} <div class='container'> <h1>Lesson Detail View</h1> <div class='row'> <div class='col-sm-6 col-md-6'> {% if object is not None %} <h3>{{ object.title }}</h3> <p>{{ object.course.description }}</p> {{object}} {% if previous_lesson %} <a href="{{ previous_lesson.get_absolute_url }}">Back</a> {% endif %} {% if next_lesson %} <a href="{{ next_lesson.get_absolute_url }}">Next</a> {% endif %} {% else %} …