Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i filter field django jsonfield that is datetime?
I want to filter base on time field in jsonfield,but this field store as string and i can not use this query: Notification.objects.filter(Q(data__payload__request_visit_time__gte=timezone.now())) -
Send mail from any from email and through other verified email from other domain
I am working on a Django application that can allow users to send emails from their emails or from their domain emails after verification, I intended to use Zoho SMTP for sending emails, I wrote a function like so: def send_email(subject, to_list, from_email, text_content, content): email_message = mail.EmailMultiAlternatives( subject=subject, body=text_content, to=tuple(to_list), from_email=from_email, ) email_message.attach_alternative(content, "text/html") email_message.send() The problem is that it always throws smtplib.SMTPDataError: (553, b'Relaying disallowed as abc@gmail.com'). Although, the first time I tried, it sent an email with an included via mydomain.com in the from section. How can I achieve the following without having to set up my own SMTP server: Send mail from any from_email including a via in the from section of the received email. Send mail from other domains after making them verify their domain using MX Records or something Any links, suggestions would be highly appreciated. Thanks -
datatable serverSide processing not working with Django
I am an absolute beginner in Datatables (just started reading yesterday) and I have been reading DataTables documentation and this is what I have done so far, I'm having an issue using Datatables with Django. This is my JS code <script> $(document).ready( function (){ var table = $('#table_id').DataTable({ serverSide: true, "searching": false, "paging": true, "aLengthMenu": [[5, 10, 25, -1], [5, 10, 25, "All"]], "iDisplayLength": 5, "ajax":{ url:"/datatabletest/", type:"POST", data:{ name:"someVal", // More data will be added here for filtering }, }, dataSrc:"", columns: [ { data: 'id' }, { data: 'country_id' }, { data: 'state_name' }, ], }); }) </script> I've tried this in my views.py @csrf_exempt def datatabletest(request): if request.method == "POST": name = request.POST.get("name") start = int(request.POST.get('start')) length = int(request.POST.get("length")) states = Table_States_List.objects.all().values()[start:start+length] lt = [] for item in country: lt.append(item) return JsonResponse({"draw": 1, "recordsTotal": states.count(), "recordsFiltered": length, 'data':lt}) The issue is, when I load the template, data is properly visible in Datatable, but after clicking on pagination buttons, a POST request is made on the server with proper parameters, and data is fetched from the database, but it doesn't appear in the table. The expected output is the no. of rows in the table of the selected … -
Django Model Reference to Multiple Foreign Key with Child Property
I have the following Models of customer details with each customers having different payment modes (eg. cash, online transfer, etc...) : class Customer(models.Model): #some customer details class Payment(models.Model): customer = models.ForeignKey(Customer, on_delete=models.RESTRICT, related_name='payments') payment_mode = models.CharField(max_length=255, blank=True, null=True) And I would like to add a new Invoice Model to include the customer as well as the customer's payment modes. class Invoice (models.Model): customer = models.ForeignKey(Customer, on_delete=models.RESTRICT, related_name='payments') payment_mode = models.ForeignKey(Customer.payments.payment_mode, on_delete=models.RESTRICT) I am going to create an Invoice for a customer and will input the customer's available payment mode. But the the invoice's payment mode is giving me an AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'payment_mode'. May I know how do I set up the reference to the customer's child data? Thank you. -
There is no current event loop in thread 'Thread-12'
I am using Django with requests-html to scrape amazon and Udemy so I have a form that takes in details like the url, price and website but when I fill the form it returns There is no current event loop in thread 'Thread-12'. with any random thread (sometimes it is Thread-2, Thread-9, etc.) I don't know what is causing this error but is there any way that I can dispose of threads that don't have event loops by detecting them. views.py from django.http.response import HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from requests_html import HTMLSession from Products.webscraper import get_udemy_course_price, get_amazon_product_price @login_required def index(request): if 'url' in request.POST and 'desired price' in request.POST and 'website' in request.POST: product_url = request.POST.get("url") desired_price = request.POST.get("desired price") website = request.POST.get("website") session = HTMLSession() if website == "autodetect": if "amazon" in product_url: website = "amazon" if "udemy.com" in product_url: website = "udemy" if "udemy.com" in product_url: title, current_price, thumbnail_url = get_udemy_course_price( session, product_url) elif "amazon" in product_url: title, current_price, thumbnail_url = get_amazon_product_price( session, product_url) else: return HttpResponse("Please enter an Amazon or Udemy URL") print(f"Product URL: {product_url}, Desired price: {desired_price}, Website: {website}, Title: {title}, Current Price: {current_price}, Thumbanil URL: {thumbnail_url}") return render(request, "Pages/index.html") The … -
Django admin site is not showing default permissions of models
My Django admin site does not show any default permissions of any models. Actually, I checked the database and I can't find any model permission in the auth_permissions table. I've already run python manage.py makemigrations and python manage.py migrate I also tried deleting the database and migration files and run two above command again but doesn't work. I've already registered my models in admin.py Any other solutions I can try ? Thank you guys for your time. Merry Christmas !!! -
DoesNotExist at /cart/ Product matching query does not exist
def cartItems(cart): items=[] for item in cart: items.append(Product.objects.get(id=item)) return items -
ReactJS and Django Problems
mery techsmas btw So I was following this tutorial and was typing exactly what he types. When I load the page , and I click "Leave Room"; I get "this.props.leaveRoomCallback is not a function". I even checked the code hosted on github and it looked the same as my code. I dont know what I am doing wrong. Thank You. Feel free to contact me on discord : TooFastForYou#9742 -
How to make a search engine in django with suggestions?
I want to make a search bar that works with JavaScript. That way, I can add suggestions like Google does when you are looking for something. I already have the search bar and the view to filter the Patients (my model). Here is the code def search_patient(request): """ Will return all the patients that start with the name that the user searches """ q = request.POST['q'] results = Patient.objects.filter(names__startswith=q) for result in results: result.serialize() return JsonResponse({'results': results}, status=200) It is a pretty simple function. The problem is that I really think that requesting the new string every time the user types a letter or deletes one would blow up the server, and I don't want that. I really need help here, and I am open to every suggestion. Thanks! -
How to pass foreign key in django
I have created a form for feedback having model feedbackid = models.AutoField(primary_key=True) courseid = models.ForeignKey('Course', on_delete=models.CASCADE) description = models.CharField(max_length=500) submitdate = models.DateTimeField(auto_now_add=True) teacherid = models.ForeignKey('schoolTeacher', on_delete=models.CASCADE) studentid = models.ForeignKey('Student', on_delete=models.CASCADE) option = [('Good','Good'),('Average','Average'),('Bad','Bad')] rating = models.CharField(max_length=100, choices=option, default='none') And the input is taken through form <form action="/studentFeedBack/" method="POST"> {% csrf_token %} <label for="studentid">Student Id</label> <input type="number" name="studentid"><br><br> <label for="courseid">Course Id</label> <input type="number" name="courseid"><br><br> <label for="teacherid">Teacher Id</label> <input type="number" name="teacherid"><br><br> <label for="description" >Feedback</label> <textarea class="form-control" rows="3" name="description"></textarea><br><br> <label for="rating">Rating</label><br> <input type="radio" id="Good" name="rating" value="Good"> <label for="Good">Good</label><br> <input type="radio" id="Average" name="rating" value="Average"> <label for="Average">Average</label><br> <input type="radio" id="Bad" name="rating" value="Bad"> <label for="Bad">Bad</label><br><br> <button type="submit" class="btn btn-primary" >Submit</button> </form> This form has three foreign keys from the following tables class Course(models.Model): courseid = models.IntegerField(primary_key=True) coursedescription = models.CharField(max_length=500) coursename = models.CharField(max_length=50) userid = models.IntegerField() code = models.CharField(max_length=50) videolink = models.FileField(default='default_link') # roleid = models.ForeignKey(RoleName, on_delete=models.CASCADE) createddate = models.DateTimeField() imagelink = models.URLField(default='default_link') duration = models.DateTimeField() longdes = models.TextField() coursetype = models.CharField(max_length=50) # classid = models.ForeignKey(TblClass, on_delete=models.CASCADE) assignto = models.CharField(max_length=200) status = models.BinaryField() def _str_(self): return self.coursename class schoolTeacher(models.Model): teacherid = models.IntegerField(primary_key=True) name = models.CharField(max_length=50) address = models.CharField(max_length=200) email = models.EmailField() contact = models.IntegerField() passowrd = models.CharField(max_length=13) image = models.ImageField(default='default.jpg') regno = models.CharField(max_length=20) joiningdate = models.DateTimeField() def … -
can not import views to urls in django 3.1.4
this is my directory this is my views.py from django.contrib import admin from django.urls import path from mysite.mysite.views import hello urlpatterns = [ path('admin/', admin.site.urls), ] this is my urls.py from django.http import HttpResponse def hello(request): return HttpResponse('hello world') but i got this error: No module named 'mysite.mysite' -
Celery runs locally but not in production
My app involves Django, Celery, Redis, and Scrapy. Locally, I fire up Django (python manage.py runserver) and celery (celery -A web_app worker). Then, I trigger a command which runs a scrapy webcrawler (via CrawlerRunner), retrieves some information, and makes additional async calls which are pushed to my task queue. This all works fine. However, when I run celery via Kubernetes (called the same way celery -A web_app worker), my tasks stop running after the scrapy task finished. The worker won't execute any additional tasks unless I restart it. Ideas? What's going on under the hood when I run celery with the same command in Kubernetes versus when I run it locally? -
Django pass all sub-posts into template
I'm trying to show all the sub-posts that are related to the Post in my PostDetailView view but I can't figure out how to get these values from the sub-post class... Models.py class Post(models.Model): title = models.CharField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Subpost(models.Model): title = models.CharField(max_length=100) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.title Views.py def home(request): context = { 'posts': Post.objects.all() } return render(request, 'home/home.html', context) class PostListView(ListView): model = Post template_name = 'home/home.html' context_object_name = 'posts' ordering = ['title'] class PostDetailView(DetailView): model = Post How can I pass in all the sub-posts that are related to the Post to my PostDetailView? -
Django choice.py file or form choices or model choice. Which to use?
I see you can list the choices you want to appear in a dropdown in different places. The forms.py file, in your models.py, or in a separate choices.py file. Which one is ideal and what is the consequence of each choice? forms.py from django import forms # iterable CHOICES =( ("1", "One"), ("2", "Two"), ("3", "Three") ) # creating a form class Form(forms.Form): the_field = forms.ChoiceField(choices = CHOICES) models.py from django.db import models # specifying choices SEMESTER_CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) # declaring a Student Model class Student(models.Model): semester = models.CharField( max_length = 20, choices = SEMESTER_CHOICES, default = '1' ) choices.py (in choices.py file) bedroom_choices = { '1' : 1, '2' : 2, '3' : 3, } choices.py (in views.py file) from .choices import bedroom_choices ... context = { 'bedroom_choices' : bedroom_choices} choices.py (in the template file) <label class="sr-only">Bedrooms</label> <select name="bedrooms" class="form-control"> <option selected="true" disabled="disabled">Bedrooms (Any)</option> {% for key,value in bedroom_choices.items %} <option value="{{key}}" {% if key == values.bedrooms %} selected {% endif %} >{{value}}</option> {% endfor %} </select> -
Changing the content of the page by the user and creating new pages
I am learning Django and would like to know how I can implement editing the content of a page by an authorized user, as well as creating new pages with a fixed template and new URLs by a user with administrator rights. Can you give examples of how to accomplish this task? -
no such column: mains_profile_friends.user_id
I am going through a Django tutorial and getting this error when trying to open friends page in browser( In local Host ) in my blog app. I use Django==3.1.2. views.py @login_required def friend_list(request): p = request.user.profile friends = p.friends.all() context = {'p':p,'friends':friends} return render(request, 'mains/friends.html' , context ) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) full_name = models.CharField(max_length=100,default='') friends = models.ManyToManyField(User, related_name='friends',blank=True,default='',null=True) friends.py {% block content %} <div class="container"> <div class="row"> <div class="col-md-8"> {% if friends %} <div class="card card-signin my-5"> <div class="card-body"> {% for user_p in friends %} <a href="{{ user_p.get_absolute_url }}">{{ user }}</a> <a class="text-dark" href="{{ user_p.get_absolute_url }}" ><b>{{ user_p }}</b></a> <small><a class="btn btn-danger float-right" href="{% url 'mains:delete_friend' user_p.id %}" >UnFriend</a></small> <br /><br /> {% endfor %} {% endif %} {% endblock content %} urls.py path('friends/', views.friend_list, name='friend_list'), The Problem When i open friends.html in browser it is giving me an error :- no such column: mains_profile_friends.user_id. What i have tried. 1). I have replaced all the names related to friend_list view. 2). I have also migrated in Terminal. Help me in this !! I will really appreciate your Help. Thank you in Advance. -
Comment() got an unexpected keyword argument 'initial'
I am creating a Django blog and when trying to implement a comment system I got the above error. I am not really sure what caused the problems, but I'll describe some of the things I did before I got the error. I decided to use Django's class-based views to display all of my data. In the PostDetailView shown I tried making it inherit from both DetailView and FormView so I get both the detail and form view displayed. The commented-out code is code that I was going to use for the form view but I didn't know how to make it share the same template and URL route. Views.py from django.views.generic import DetailView, FormView from .forms import Comment from .models import Post class PostDetailView(DetailView, FormView): model = Post template_name= 'optionhouseapp/post-detail.html' form_class = Comment def form_valid(self, form): return super().form_valid(form) # class CommentFormView(FormView): # template_name= 'optionhouseapp/post-detail.html' # form_class = Comment # success_url ='/' # def form_valid(self, form): # return super().form_valid(form) Here is the form page forms.py from django import forms from .models import Comment class CommentForms(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') Here is the associated model models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = … -
save() method does not save form data to the database (Django ModelForm)
I'm making a simple todo list using Django, it works fine except that whatever data is entered into the form does not save to the database (and does not get displayed). My models.py: from django.db import models class TodoListItem(models.Model): content = models.TextField() def __str__(self): return self.content forms.py: from .models import TodoListItem from django.forms import ModelForm class TodoListForm(forms.ModelForm): class Meta: model = TodoListItem fields = ['content'] views.py: from django import forms from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from .models import TodoListItem from .forms import TodoListForm def home(request): context = { 'items': TodoListItem.objects.all() } return render(request, 'home.html', context) def enter_task(request): if request.method == 'POST': form = TodoListForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/') else: return HttpResponse('Form not valid') else: form = TodoListForm() return render(request, 'form.html', {'form': form}) I did it according to the documentation, what I fail to understand is why the line form.save() won't execute when return HttpResponseRedirect('/') right underneath it does. The form.html file, just in case: <!DOCTYPE html> <html> <head> <title>Add task</title> <h1>Add Task</h1> </head> <body> <form action="{% url 'home' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> </body> </html> I know that the error has to be in views.py because I used … -
Django not running on MacOS 11.1 (command not found: django-admin)
I am trying to run Django in my Mac's terminal, but it seems like Python cannot find it. I get the error in the title when I try to use the command python -m django startproject scriptsite I get the error command not found: django-admin when I try to use the command django-admin startproject scriptsite When I try installing Django, all four packages are already there, but commands involving Django don't seem to work. Importing Django in a python file is okay, though. How do I fix these problems? And are the previous commands necessary to use Django? I'm just planning to run a simple script on an HTML website, so I'm not sure if I'll even need the web server stuff in the Django tutorial. -
Following tutorial TDD with Python, change default url from localhost to IP
I'm working through "Test Driven Development with Python" The book uses Django 1.11 I'm following along with Chapter 6 and I'm stuck with the server configuration. I can't use --liveserver=IP_ADDRESS as it was deprecated in 1.10 and I can't quite figure out how to set the live_server_url to use the specific IP_ADDRESS I want. The error says: ====================================================================== ERROR: test_can_start_a_list_and_retrieve_it_later (functional_tests.tests.NewVisitorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/me/TUTORIALS/tdd/superlists/functional_tests/tests.py", line 29, in test_can_start_a_list_and_retrieve_it_later self.browser.get('self.live_server_url') File "/home/me/.virtualenvs/superlists/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 333, in get self.execute(Command.GET, {'url': url}) File "/home/me/.virtualenvs/superlists/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/home/me/.virtualenvs/superlists/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidArgumentException: Message: Malformed URL: URL constructor: self.live_server_url is not a valid URL. I would appreciate any tips on how to move forward. -
Why is it recommended to ad sqlite database to gitignore?
I understand other files being ignored. But why would I ignore the sqlite database file if that holds data needed to run the website. How can the website function without a database? -
Trying to Build url path through DetailView , but am getting duplicate values in html page
I am starting to learn django. I want to create a directory site. I want it to be: home page -> list of States -> List of Restaurant Types -> List of Restaurant names I have 'list of States' as a generic.ListView and it works perfect. I tried making 'List of Restaurant Types' as a ListView as well but it wouldn't pull any data in the html. Changing it to a DetailView it pulls the data but has duplicate entries. Is there a way to restrict it as unique outputs in either views.py or the restaurant_detail.html? The current html code is: <p><b>Restaurant SECTION</b></p> {% for name in states.restaurant_name_set.all %} <p>{{name.restaurant_types}}</p> {% endfor %} I get something like: Fine Dining Buffet Buffet Buffet Food Truck I want just one of each I can then link to go to a list of Restaurant Names -
Add strikethrough to a radio input
In my html I have a button and a radio form where the inputs are created using a for loop. <form id="form" class="mb-1"> {% for option in option_list %} <input class="form-check-input text-primary" type="radio" name="option" value="{{option}}"> {{option}} <br> {% endfor %} </form> <button type="button" class="btn btn-primary" id="btn">Button</button> When the button is clicked, the radio inputs are either disabled or enabled based on some condition, which I have working fine, but when disabling an option, I also want to add a strike to the input to better show it's disabled. My js file has something like this. $(document).ready(function() { $('#btn').click(function() { $('#form *').filter(':input').each(function(){ if (condition) { $(this).prop('disabled', false) } else { $(this).prop('disabled', true) } }); }) }) I've tried putting label tags around the inputs and using .wrap() and .css(("text-decoration", "line-through"), but it didn't work. They work on regular text fine, so I think I'm just not formatting the radio input labels correctly? -
'wordItem' object has no attribute 'len',django,python
I'm making word counter by using django. ↓this is views def wordcountView(request): all_word_contents = wordItem.objects.all() return render(request, 'count.html', {'all_contents':all_word_contents}) ↓this is models class wordItem(models.Model): content = models.TextField() I also add path in urls. However, I was given AttributeError: 'wordItem' object has no attribute 'len' this error. -
How to instantiate different classes based on Django model field
I have a table Webhook with a CharField called type that has a list of choices from enum WEBHOOK_TYPE. For each of these types, I want to treat POST requests to the same endpoint differently. So I'm trying to use that same enum to map to a class. For example the view is something like: def get_integration(message_type): webhook_to_message_map = { WEBHOOK_TYPE['FACEBOOK']: Facebook, WEBHOOK_TYPE['TWITTER']: Twitter } def post(req, **kwargs): webhook_type = Webhook.objects.get(kwargs['webhook_id']).type message_type_class = get_integration(webhook_type) message_type_instance = message_type_class() return JsonResponse(message_type_instance.some_function()) I'm having a ton of difficulty situating this such that I don't have circular dependencies, so what's the "correct" way to do this in Django?