Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 %} … -
aggregate values from mongo_Db in Django
I am using mongo-DB, I have django model called expense_claim which fields like employee_name , date, price , tax etc. i am trying to aggregate total claims and total value of claims initiated by a particular employee on monthly basis. so i want my output something like this. month employee total jan john 5000 jan jack 2500 feb john 4000 feb jack 0 I think there could be two ways of doing this either write a logic in the view or maybe some inbuilt django model function Thankss -
How to make a small part of code in views.py to run for every x minutes in django server (using gunicorn and nginx)
I have to run a reset the all values of a game every four minutes. Meanwhile, if the game runs for 2 minutes last 30sec should be used to compute the result. Following the above two criteria how to design my game. And I have made some effort to do this which is successful on localserver but on the production server it is not working properly. Here is my source code link Please help me to solve this issue. -
search_view() missing 1 required positional argument: 'slug'
error TypeError at /chat/search/ search_view() missing 1 required positional argument: 'slug' Request Method: POST Request URL: http://127.0.0.1:8000/chat/search/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: search_view() missing 1 required positional argument: 'slug' my model: class UserProfile(models.Model) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') slug = models.SlugField(blank=True) image = models.ImageField(default='face.jpg', upload_to='images/avtar') friends = models.ManyToManyField("UserProfile", blank= True) def __str__(self): return self.user.username def get_absolute_url(self): return "/chat/{}".format(self.slug) def last_seen(self): return cache.get('last_seen_%s' % self.user.username) def post_save_user_model_receiver(sender, instance, created, *args, **kwargs): if created: try: Profile.objects.create(user=instance) except: pass post_save.connect(post_save_user_model_receiver, sender=settings.AUTH_USER_MODEL) My urls: url(r'^(?P[\w-]+)/$',search_view), url(r'^friend-request/send/(?P<id>[\w-]+)/$', send_friend_request), url(r'^friend-request/cancel/(?P<id>[\w-]+)/$', cancel_friend_request), my view: def search_view(request, slug): p = UserProfile.objects.filter(slug=slug).first() u = p.user;print(u) sent_friend_requests = FriendRequest.objects.filter(from_user=p.user) rec_friend_requests = FriendRequest.objects.filter(to_user=p.user) friends = p.friends.all() # is this user our friend button_status = 'none' if p not in request.user.profile.friends.all(): button_status = 'not_friend' # if we have sent him a friend request if len(FriendRequest.objects.filter( from_user=request.user).filter(to_user=p.user)) == 1: button_status = 'friend_request_sent' if request.method =='POST': query = request.POST.get('search') results = User.objects.filter(username__contains=query) context = { 'results':results, 'u': u, 'button_status': button_status, 'friends_list': friends, 'sent_friend_requests': sent_friend_requests, 'rec_friend_requests': rec_friend_requests } return render(request, 'chat/search.html', context) -
Django Mongodb output is same for each command
I have used MongoDbManager in my models to apply raw_query: class BatDataSoh(models.Model): _id = models.CharField( primary_key=True,max_length=100) bid = models.CharField(max_length=10) soh = models.IntegerField() cycles = models.IntegerField() objects = MongoDBManager() class Meta: db_table = "batDataSoh" This is my modal output: >>> b=BatDataSoh.objects.raw_query({'bid':'b10001'}) >>> print(len(b)) 9973 >>> b=BatDataSoh.objects.raw_query({'bid':'sdfj'}) >>> print(len(b)) 9973 In every query, the output is the same, Even in the 2nd query there is no bid with "sdfj" this name, If you know the solution, please post your answer. Thanks in advance -
Having problem in sending email through django using EmailMultiAltenatives
I am trying to send emails through django. This is my order.html file: <body> <img src="{% static 'assets/img/logo/original.jpg' %}" alt=""> {% for order in orders1 %} <h1>Your order number is <strong>{{order}}</strong></h1> {% endfor %} </body> This is my order.txt file: {% for order in orders1 %} Your order number is {{order}} {% endfor %} And this is my views.py: from django.core.mail import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context def email(request): orders1=Order.objects.filter(id=20) d = { 'orders': Order.objects.filter(id=20) } subject, from_email, to = 'hello', settings.EMAIL_HOST_USER, 'vatsalj2001@gmail.com' text_content = get_template('emails/order.txt').render(d) html_content = get_template('emails/order.html').render(d) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() return render(request,'emails/order.html',{'orders1':orders1}) The concern is that the email which is being sent only contains the subject('hello') and in the email body there shows an icon(with a cross) instead of image that I want and also no text shows up which I set in template. Also what is the need and requirements of having a text and html file for email? -
why my submit button's not working in updateview in Django?
When I click on submit button it goes nowhere and does nothing. Can you spot me the mistake? I want to update on department field and year field. Also I'm using MultiSelectField from django-multiselectfield third party. The form shows up correctly except submit button's not working. here is my models.py class Teacher(models.Model): type_choice = (('Full Time', _('Full Time')), ('Part Time', _('Part Time'))) departments = ( ('TC', 'Foundation Year'), ('GIC', 'Software Engineering'), ('GEE', 'Electrical Engineering'), ('GIM', 'Mechanical Engineering'), ('OAC', 'Architecture'), ('OTR', 'Telecom'), ('GCI', 'Civil Engineering'), ('GGG', 'Geotechnical Engineering'), ('GRU', 'Rural Engineering') ) years = ( ('year1', 'Year1'), ('year2', 'Year2'), ('year3', 'Year3'), ('year4', 'Year4'), ('year5', 'Year5') ) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) teacher_type = models.CharField(max_length=50, choices=type_choice) department = MultiSelectField(choices=departments) year = MultiSelectField(choices=years) def __str__(self): return '%s %s' % (self.user.email, self.teacher_type) forms.py class TeacherForm(forms.ModelForm): class Meta: model = Teacher fields = ['teacher_type', 'department', 'year'] views.py @method_decorator(teacher_required, name="dispatch") class TeacherDepartEditView(LoginRequiredMixin, UpdateView): model = Teacher login_url = "/" form_class = TeacherForm template_name = "attendance/content/teacher/teacher_dep_edit.html" def get_success_url(self): return reverse('teacher_info') template <form method="POST"> {% csrf_token %} <div class="row mt-3"> <div class="col-md-6"> <label>Choose department ( can choose more than one )</label> {{ form.department}} </div> <div class="col-md-6"> <label>Choose Year ( can choose more than one )</label> {{ form.year }} … -
Creating Tags and filtering according to them in django
I'm creating a blog application to share interview experiences and i would like to filter the blog posts based on year, company of interview and job roles etc.. how do i take the above parameters as tags and when clicked on a certain tag, have to show all posts on that? My model looks like this class experience(models.Model): name=models.CharField(max_length=200) job_role=models.CharField(max_length=200) company=models.CharField(max_length=200) year=models.CharField(max_length=20) -
images are not showing in django
hi when i am saving images from my admin they are saved in project directory like this images/images/myimg.jpg.. but when i am trying to display them in my template like this <img src="{{About.image.url}}" alt="profile photo"> the image do not displays.. when i inspect the page in chrome... it shows image source unknown.. <img src="(unknown)" alt="profile photo"> please see the files .. settings.py STATIC_URL = '/static/' STATICFILES_DIRS =[ os.path.join(BASE_DIR,'portfolio/static') ] STATIC_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'images') project urls.py from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('home/', include("home.urls")), path('blog/', include("blog.urls")), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT ) the model having image is inside a app named 'home' models.py of home app from django.db import models import datetime # Create your models here. class About(models.Model): image = models.ImageField(upload_to = 'images') desc = models.TextField() home/views.py from django.shortcuts import render from home.models import * from django.views.generic import ListView # Create your views here. def index(request): abt = About.objects.all() return render(request,'home/index.html',{'abt': abt.first()}) def Experience(request): Exp = Experience.objects.all() return render(request,'home/Experience.html',{'Exp': Exp}) class MyView(ListView): context_object_name = 'name' template_name = 'home/index.html' queryset = About.objects.all() def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) context['Experience'] = … -
How to upload ebooks on dtabaseses
I recently started creating a website with angular and Django. This is to be an online bookstore or an ELibraby something like Amazon Kindle, my problem is that I found out that it's not advisable to store ebooks on a database but I need a way for users to get these ebooks from the database and for admins to be able to upload to some sort of file system since database is not possible, please is there anyway I can accomplish this on my site. I have checked the internet but I haven't seen anything helpful, maybe I am searching wrong or something but I will really appreciate any advice. And also I will like to know if there is any API that can help me add books to my website at least to fill in some space till actual ebooks are uploaded. Any advise will really help... -
Django get nearby objects based on locations (coordinates) in two models and serializers?
I'm struggling a little bit about how to get objects around a radius in Django Rest Framework. Basically, what I need is to get restaurants & promotions based on Point (coordinates - latitude and longitude), so for example if I have 2 restaurants and 4 promotions I just pass the location in coordinates and want to get only nearby ones from those 2 restaurants and promotions, from their respectively endpoint. (/restaurant and /promotion) I get it working for Restaurant, but not for Promotion since that model don't have location field but has a Foreign key with Restaurant I though it could work fine ... but nope. So I'm out of ideas ... I put what I have done below: Models.py from django.contrib.gis.db import models class Restaurant(models.Model): """Restaurant model""" restaurant_name = models.CharField(max_length=255) address = models.TextField() city = models.CharField(max_length=120) state = models.CharField(max_length=120) zip_code = models.CharField(max_length=10) location = models.PointField() # ... def __str__(self): return self.restaurant_name class Promotion(models.Model): """Promotion model""" promotion_name = models.CharField(max_length=100) # ... restaurant_name = models.ForeignKey(Restaurant, on_delete=models.CASCADE) def __str__(self): return self.promotion_name serializers.py class RestaurantSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = '__all__' class PromotionSerializer(serializers.ModelSerializer): restaurant_name = serializers.StringRelatedField() # location = PointField(source='restaurant_name.location') class Meta: model = Promotion fields = '__all__' And finally my … -
How to Get Server Error Message in Debug=False
I am new to Django and made a custom handler500 page for when debug=False: def handler500(request, *args, **argv): // Send me a Slack message of the error return render(request, '500.html', status=500) As shown in the comment, I want to send myself a Slack message of the 500 error (as would be shown in debug=True. How can I access that error message? Thanks! -
Django Form - Getting last record value from database as dynamic default or initial value for form field
I'm new in Python/Django with basic understanding and moving my steps slowly. This is my first question in stackoverflow. I've learned a lot from the previously discussed posts. Thanks to all who asked questions and special thanks to all those who contributed to such helpful answers. I searched and read a lot and tried to understand but could not figure out my way ahead on the following issue. I have a form for Transaction entry with the following fields. ==> Date ==> Farmer_num ==> purchase_qty ==> tr_rate I need to enter many records (500+ for a date) with the same date and same price (tr_rate). Instead of selecting date from datepicker and writing price (tr_rate) on entry form every time, i want to get them as default/initial value when form loads for new entry. This will save my time as well as prevent from entering the wrong date and price. When the form loads, in the date field, I want the last entry date as initial/default date from Trans table. For example if the last entry date was 2020-08-08, form should load with this date. When that date's entry is finished, I select another date manually e.g. 2020-08-12 for another … -
Django Email Backend Failing when DEBUG = False
Has anyone experienced this issue where when DEBUG = True your applications can't send emails? I'm trying to set up a password reset email and a contact form and both work fine in development and in production as long as DEBUG = False, but as soon as it equals True the email backend breaks (this is especially frustrating because I can't use DEBUG to find the issue). My email config looks as follows: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'admin@programaticlearning.com' EMAIL_HOST_PASSWORD = 'CorrectPassword' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
Bootstrap tabpanel isn't showed with django url view
I am working with Django 3.1 and Bootstrap 4. I am trying to implement a tablist with href pointing to django view. However, when I click the second tab, nothing happens. The expected behavior is that the response from the view function is rended in the content of the tabpanel. This is my code: template.html <ul class="nav tab-switch" role="tablist" id="profile-tabs"> <li class="nav-item"> <a class="nav-link active" id="user-profile-info-tab" data-toggle="pill" href="#user-profile-info" role="tab" aria-controls="user-profile-info" aria-selected="true">Profile</a> </li> <li class="nav-item {% if active_tab == 'research2' %} active {% endif %}"> <a class="nav-link" id="user-profile-research-tab2" href="{% url 'app:research_profile' %}" role="tab" aria-controls="user-profile-research2" aria-selected="false">Research</a> </li> </ul> <div class="tab-pane fade show pr-3" id="user-profile-research2" role="tabpanel" aria-labelledby="user-profile-research-tab2"> <div class="table-responsive"> <div class="main-panel col-12"> <div class="content-wrapper"> {% include 'templates/_research_list.html' %} </div> </div> </div> </div> The view.py include in the response the variable "active_tab", but for some reason, the tab content never is showed. Any help would be very appreciated. -
Where to add Tinymce api key?
i downloaded the zip file form tinymce.cloud. and added the file in static folder everything is working fine, except now i'm getting this notification every time i want to create a post. I already have an account but as they suggested to add key in tinymce.js file the content is totally different in mine because i'm not using just single js file but bunch of files now i don't know where i should put my api key. so it stop giving me notification. script file i'm using in head file post_create.html where i added script.