Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: totals subtotals item view in Django template
I have Models like from django.db import models class Order(models.Model): Category = models.CharField(max_length=225) # Men, Women, Child etc. Item = models.CharField(max_length=225) # Shirt, Pant, T-Shirt Price = models.IntegerField() Desire view in Templets by for loop Men Items Name Price Shirt 20 Pant 30 T-Shirt 10 Subtotal 60 Women Items Name Price Shirt 20 Pant 30 T-Shirt 10 Subtotal 60 Child Items Name Price Shirt 20 Pant 30 T-Shirt 10 Subtotal 60 Grand Total 180 -
Django Channels WebSocket argument
I am trying out an example from the book Django By Example, Chapter 13. There is an example there showing how to establish a socket for a chat room later on. Below is the code where I am sure the error comes from: room.html {% extends "base.html" %} {% block title %}Chat room for "{{ course.title }}"{% endblock %} {% block content %} <div id="chat"> </div> <div id="chat-input"> <input id="chat-message-input" type="text"> <input id="chat-message-submit" type="submit" value="Send"> </div> {% endblock %} {% block domready %} var url = 'ws://' + window.location.host + '/ws/chat/room/' + '{{ course.id }}/'; var chatSocket = new WebSocket(url); {% endblock %} Below are the routing.py and consumer.py routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/room/(?P<course_id>\d+)/$', consumers.ChatConsumer), ] consumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass # receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({'message': message})) Below is the error message I got when running python manage.py runserver WebSocket HANDSHAKING /ws/chat/room/6/ [127.0.0.1:57288] Exception inside application: object.__init__() takes exactly one argument (the instance to initialize) Traceback (most recent call last): File "/home/xxx/.local/share/virtualenvs/chat-ayPz2iC9/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) … -
how can i add a new key value to my request.data in django
I would like to know how can I add a new value to my request.data this is my request.data, structure: [{'fname': 'john', 'lname': 'Doe'}] how can I add the age key for example -
Django - NameError when trying to test ContentType
I have the following 3 models in my program - Actor, User and Applicant. Actor is a superset of User and Applicant. I made this approach ContentType to make Actor as a superset. Therefore, although the relationship of them is working properly I am not being able to test ContentType to check if it is returning the entity as it is when I return the value in /manage.py shell. The error I am getting is: NameError: name 'ContentType' is not defined ---------------------------------------------------------------------- Ran 2 tests in 0.004s Here is my models.py: from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.db import models # for testing Actor and ContentType: class Actor(models.Model): """ Actor: the superset for User and Applicant """ choices = models.Q(app_label='coretest', model='user') | \ models.Q(app_label='coretest', model='applicant') entity_type = models.ForeignKey(ContentType, limit_choices_to=choices, related_name='entity_types', on_delete=models.CASCADE, null=True) entity_id = models.PositiveIntegerField(_('object ID'), null=True) content_object = GenericForeignKey('entity_type', 'entity_id') company_id = models.IntegerField() created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.content_type) class User(models.Model): actor_id = models.ForeignKey(Actor, on_delete=models.CASCADE) created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.actor_id) class Applicant(models.Model): actor_id = models.ForeignKey(Actor, on_delete=models.CASCADE) created_at = models.DateTimeField() created_by = models.CharField(max_length=255) def __str__(self): return '{0}'.format(self.actor_id) test_models.py from django.contrib.contenttypes.models import ContentType, ContentTypeManager from django.test import TestCase from … -
How to send data from JavaScript file to views.py django?
How can I send data ( the user_to_follow in this example ) to my views.py function ( follow ) to do some updates? I'm trying to send the username from my JavaScript and then add the logged-in username to that username following list ( all done in my views.py function ) Views.py. def follow(request, profile_to_follow): try: user_to_follow = User.objects.get(username=profile_to_follow) user_to_following = Profile.objects.get(user=request.user.id) except User.DoesNotExist: return JsonResponse({"error": "Profile not found."}, status=404) if request.method == "PUT": user_to_following.following.add(user_to_follow) return HttpResponse(status=204) index.js function follow_user(user_to_follow){ // How To send the user_to_follow to my views.py method. // to add the current logged in user to the user_to_follow following list console.log(user_to_follow) } urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), # API Routes path("posts", views.compose_post, name="compose_post"), path("posts/all_posts", views.show_posts, name="show_posts"), path("posts/<int:post_id>", views.post, name="post"), path("profile/<str:profile>", views.display_profile, name="profile"), path("<str:profile_posts>/posts", views.display_profile_posts, name="profile_posts"), path("follow/<str:user_to_follow>", views.follow, name="follow"), ] -
Django - Cannot Create Follower Functionality
I'm new to Django and I'm trying to create a project similar to a social media site, where users can go to a user profile, and 'follow' another user profile. When I click 'follow' on the profile, currently I don't get any errors at all. Nothing happens. I don't see anything in my console/terminal etc. There's no error. Help is appreciated! views.py def fol(request, username): if request.method == 'GET': currentuser = request.user profileuser = get_object_or_404(User, username=username) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() follower = Follow.objects.filter(target=profileuser) following = Follow.objects.filter(follower=profileuser) following_each_other = Follow.objects.filter(follower=currentuser, target=profileuser) totalfollower = len(follower) totalfollowing = len(following) paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'posts': posts.count(), 'profileuser': profileuser, 'follower': follower, 'totalfollower': totalfollower, 'following': following, 'totalfollowing': totalfollowing, 'followingEachOther': following_each_other } return render(request, "network/profile.html", context) else: currentuser = request.user profileuser = get_object_or_404(User, username=username) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() following_each_other = Follow.objects.filter(follower=currentuser, target=profileuser) paginator = Paginator(posts, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) if not following_each_other: f = Follow.objects.create(target=profileuser, follower=currentuser) f.save() follower = Follow.objects.filter(target=profileuser) following = Follow.objects.filter(follower=profileuser) following_each_other = Follow.objects.filter(follower=request.user, target=profileuser) totalfollower = len(follower) totalfollowing = len(following) context = { 'posts': posts.count(), 'profileuser': profileuser, 'page_obj': page_obj, 'follower': follower, 'following': following, 'totalfollowing': totalfollowing, 'totalfollower': totalfollower, 'followingEachOther': following_each_other } return render(request, "network/profile.html", context) … -
How to update Foreign Key from another Foreign Key reference Models Django
I made two models that both have same foreign key reference models (usersold) and (currentuserbid) to User model(settings.AUTH_USER_MODEL). I have filled out the data for AuctionBids models.currentuserbid. When I try to reference it and set it to same value in AuctionListing model in view.py it doesn't get saved. I also tried , listing.sold = User.objects.get(id=listing.bid.currentuserbid.id) Thank you very much! Models.py class AuctionListing(models.Model): title = models.CharField(max_length=64) description = models.TextField() image = models.TextField() bid = models.ForeignKey(AuctionBids, on_delete=models.CASCADE, related_name="auctionbidding", null=True) usersold = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="auctionsold",null=True) class AuctionBids(models.Model): currentBid = models.IntegerField() currentuserbid = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="currentuserbid",null=True) Views.py listing = AuctionListing.objects.get(pk=id) listing.sold = listing.bid.currentuserbid listing.save() -
video not working in safari with django static files
It's a video page to make a website with django. It comes out well on Chrome, but it doesn't come out on Safari... The same goes for mobile safari. Playsinline and video tag are all correct. Video source is the address of a video on the Internet, but it doesn't play when I import it from a static file. Is there a solution? If I have to encode, I also want to know the code that automatically encodes when I load a video. -
Django - Can't access data from object in many to many relationship
In my Django project, I am trying to create a website that streams TV shows. Each show belongs in many categories, hence the use of many to many relations in my model. What I want to do with a certain page on my website is dynamically load a page of shows belonging to a specific category. However, all of my attempts have ended in failure as I am unable to figure out a way on how to access the actual category data from each show. In views.py def shows_in_category(request, category_slug): category = get_object_or_404(Category, slug=category_slug) showsall = animeShow.objects.all() shows = [] for show in showsall: print(show.category.name, category.name) if show.category.name == category.name: shows.append(show) print(shows) return render(request, 'show/show_list_view.html', {'category':category, 'shows': shows}) In models.py class Category(models.Model): name = models.CharField(max_length=255, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse("theshowapp:shows_in_category", args=[self.slug]) class theShow(models.Model): english_name = models.CharField(max_length=400) show_type = models.CharField(max_length=200, blank=True) is_active = models.BooleanField(default=False) category = models.ManyToManyField(Category) slug = models.SlugField(max_length=400,unique=True) class Meta: verbose_name_plural = 'Shows Series' def __str__(self): return self.english_name In the template (show_list_view.html) {% for show in shows %} <script> console.log("I'm trying to get in")</script> <script> console.log("{{ show.name }} {{show.category.name}}")</script> <script> console.log("I'm in")</script> <div class="row"> <div class="col-lg-4 … -
object has no attribute '_committed' error
I want django automatically download and locally save image from image_url and "connect" it with image_file how Upload image from an URL with Django i have error object has no attribute '_committed' error from PIL import Image import requests url = 'https://i.stack.imgur.com/0jot2.png' respone = requests.get(url, stream= True).raw img = Image.open(respone) img.save() def home(request): Topic(title='hjb',content='vf',slug='fvrs',image=img, author=User.objects.first() ) .save() -
In Django, how do add indefinite amount of images with text?
I am new to Django. I am building a website like a blog but I could not understand the scenerio how to add multiple images with text. "Creating seperate class which hold the images and which are connected by foreign key ?" Or another method ? In my plan, users will add some articles which we dont know the amount of images and text. I saw a website and I lıked the concept of it but I could not understand the structure. In this website, each part with contain text and image is composed of a section If you give me an idea about these kind of single-detail-page, I would be glad. Thank you -
module 'django.template' has no attribute 'resolve_variable'
I am porting an old Django project to Django 3.2. I have come across this code segment, which causes an exception to be raised. I have looked through the django documentation, but it seems the method has been removed completely - with no comments regarding replacement etc. Here is the offending code segment: class AddGetNode(template.Node): def __init__(self, new_values): self.new_values = new_values def render(self, context): request = template.resolve_variable('request', context) # <- barfs here ... params = request.GET.copy() for key, value in self.new_values.items(): resolved = value.resolve(context) if resolved: params[key] = resolved elif key in params: del params[key] return '?%s' % params.urlencode() What is the new method to fetch the request object from a context? -
How to pass image file from one page to another in multi-page form
In my django web app, I need to pass a form from one page to another so it can be completed and saved. In this form is an ImageField, and when I try the following, all other fields come pre-populated, but the image field shows "no file selected". Written below is a simplified version of my code. If I uncomment the code where I create an instance of the form in the views.py, the image field in the HTML shows the message "Upload a valid image. The file you uploaded was either not an image or a corrupted image." I have no idea why every other field can get passed into the next page, except the image field. Does anyone know how to do this? Or is there another way to go about this? models.py class MyModel(models.Model): name = models.CharField(max_length=50) age = models.CharField(max_length=50) picture = models.ImageField(default=None, upload_to='media/') forms.py class MyForm(ModelForm): class Meta: model = MyModel fields = '__all__' views.py def index_view(request): if request.method == 'POST': form = MyForm(request.POST, request.FILES) if form.is_valid(): ''' instance = form.save(commit=False) form = ConnectorForm(data=request.POST, files=request.FILES, instance=instance) ''' return render(request, 'main/page2.html', { 'form': form }) else: form = MyForm() return render(request, 'main/index.html', { 'form':form, "base":base }) def … -
Getting AttributeError: sender while iterating to get specific values
Getting "AttributeError: sender" is thrown as the exchange query iterates. Same with other values (message_id, etc) too. My only option at this point is to put a try/catch around it and need to refactor a lot of content under the loop. However, I would think the query should not be crashing under normal circumstances due to any data issue. Please let me know what could be going wrong. There appears to be a 'bad' email object that causes it? kwargs = {"is_read": False} kwargs["datetime_received__gt"] = some_date_time filtered_items = my_exchange._service_account.inbox.filter(**kwargs) filtered_items.page_size = 20 print(filtered_items.count()) 3 <-- 3 objects for sender_obj, msg_id, msg_subj, msg_text, msg_size in filtered_items.values_list("sender", "message_id", "subject", "text_body", "size").iterator(): print(sender_obj) count = count + 1 print(count) Mailbox(name='Some User1', email_address='someuser1@myemail.acme', routing_type='SMTP', mailbox_type='Mailbox') 1 Mailbox(name='Some User2', email_address='someuser2@myemail.acme', routing_type='SMTP', mailbox_type='OneOff') 2 Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 273, in __iter__ yield from self._format_items(items=self._query(), return_format=self.return_format) File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 352, in _item_yielder yield item_func(i) File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 380, in <lambda> item_func=lambda i: tuple(f.get_value(i) for f in self.only_fields), File "/usr/local/lib/python3.6/site-packages/exchangelib/queryset.py", line 380, in <genexpr> item_func=lambda i: tuple(f.get_value(i) for f in self.only_fields), File "/usr/local/lib/python3.6/site-packages/exchangelib/fields.py", line 189, in get_value return getattr(item, self.field.name) AttributeError: sender -
How to retrieve all messages in a Twilio Programmable Chat Channel?
privatechannel.getMessages().then(function (messages) { const totalMessages = messages.items.length; for (let i = 0; i < totalMessages; i++) { const message = messages.items[i]; console.log('Author:' + messages.author); printMessage(message.author, message.body); } console.log('Total Messages:' + totalMessages); deleteNotifs() }); This is listed as the way in Twilio docs to retrieve the most recent messages. I tried it and the maximum number of messages it displays are not even like 100, it just shows me the last 30 messages in the conversation. Is there a way to retrieve and display all the messages in a Twilio Programmable Chat channel ( private or otherwise )? -
Displaying relationship data inside Django templates
I followed the process of creating multi user type from this tutorial class User(AbstractUser): is_owner = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) class Owner(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, primary_key=True) I have a driver and owner profile with field user which has a OneToOneField relationship with the user model class OwnerProfile(models.Model): ] user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name='owner_profile') phone = models.CharField(max_length=15, blank=True, null=True) bio = models.TextField(blank=True, null=True) class DriverProfile(models.Model): ] user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name='owner_profile') phone = models.CharField(max_length=15, blank=True, null=True) bio = models.TextField(blank=True, null=True) Owners can create Cars class Car(models.Model): car_owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='car_owner', on_delete=models.CASCADE) car_make = models.CharField(max_length=20, blank=True, null=True) … While drivers can create CarRents class CarRent(models.Model): car = models.ForeignKey(Car, related_name='rented_car', on_delete=models.CASCADE) driver = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='driver_renting', on_delete=models.CASCADE) start_date = models.DateTimeField(blank=True, null=True) … I have a detailView class ActiveRent(DetailView): model = CarRent template_name = 'app/ActiveRent_detail.html' in my template i tried to access data in the Owner profile using each of the following {{object.car_owner.owner_profile.phone}, {{object.car.ownerProfile.phone}}, {{object.ownerProfile.phone}} but nothing is working. Thanks for your help in advance -
django searches for url which does not exist in my current project. Why is this happening? The project used to exist but no longer
i used to have an app in a project called catalog but i have deleted the project upon completion. Currently i have started a new project, but i have realised that the django searches for catalog which was an app in the old project. Instead of django searching for urls in my new project. i uninstalled anaconda and reinstalled it with django to see whether that will solve the issue but it still remains. One thing i noted was that in the previous project which contained catalog as a app i imported the Redirect View and redirected the homepage which was empty to the url of the app so that it rather acts as the index. Now whenever i run the server it points to the page where the redirect was done in my current project which does not exist throwing the exception below. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/catalog/ Using the URLconf defined in main.urls, Django tried these URL patterns, in this order: admin/ ^media/(?P<path>.*)$ The current path, catalog/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django … -
Django ArrayField creating three Charfields within?
It's my first time trying to pass in a field type within Django models.py where I can create a list within an arrayfield. For example I want to create.. neighborhood = Arrayfield(models.Charfield(max_length=100)) But within neighborhood I want to have the drop down choices of... area = [Brooklyn, Manhattan, Queens] How do I do this within models.py, is area suppose to be it's on class within my models.py? I am using Postgres SQL. -
How to resolve specific fields.E304 error
I'm learning to create custom user form on django and the procedure is still not very clear to me. So, I'm following a tutorial. However, when I try to make migrations I encounter the follow error, but the instructor's code program worked. I don't understand why mine is throwing back an error message. Please I need some clarification. I checked the answer to similar question online but I couldn't identify my mistake model.py from django.db import models from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin) from django.utils.translation import gettext_lazy as _ from django_countries.fields import CountryField class CustomAccountManager(BaseUserManager): def create_superuser(self, username, email, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, password, **other_fields) def create_user(self, email, username, password, **other_fields): if not email: raise ValueError(_('You must provide an email adresss')) email = self.normalze_email(email) user = self.mode(email=email, username=username, **other_fields) user.set_password(password) user.save() return user class UserBase(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=254, unique=True) company = models.CharField(max_length=50) license_number = models.CharField(max_length=50) country = CountryField() state = models.CharField(max_length=50) city = models.CharField(max_length=50) address = … -
Multiple LEFT JOIN with GROUP CONCAT using Django ORM
These are my 2 Django models: class Brand(models.Model): brand_no = models.CharField(max_length=100, unique = True) class Meta: db_table = 'brand' class BrandWhereUsed(models.Model): # Brand is a component of parent brand brand = models.ForeignKey(Brand, related_name="where_used", on_delete=models.CASCADE) parent_brand = models.ForeignKey(Brand, on_delete=models.PROTECT) class Meta: constraints = [ models.UniqueConstraint(fields=['brand', 'parent_brand '], name='brand_parent') ] db_table = 'brand_where_used' And I would like to do convert this SQL query to Django ORM, not raw query: SELECT t1.id, t1.brand_no , GROUP_CONCAT(t2.parent_brand_id) AS where_used , GROUP_CONCAT(t3.item_no) AS where_used_brand_no FROM brand AS t1 LEFT OUTER JOIN brand_where_used AS t2 ON (t2.item_id = t1.id) LEFT OUTER JOIN brand AS t3 ON (t3.id = t2.parent_brand_id) GROUP BY t1.id I tried this thread :GROUP_CONCAT equivalent in Django . But seems like it generated incorrected result query. Could you please help me on this? -
Django / React - Production API URL routing issues
I have a backend Django REST API that also helps serve my React frontend. I currently have an issue with my API requests url paths to my Django API in production for every page except my home page... API URL's that work: I'm able to visit my home page, within my home page, I have a GET request to my API which works great and loads data as expected. This is the only working GET request of my website because the API URL path is correct to my urlpatterns syntax. API URL's that DON'T work: The issues arise when I visit a page OTHER than the home page of my React app. My API requests to Django on other pages are using the wrong URL path according to my network panel (they are also responding with index.html), which has me believe I set up my django URLs wrong. Please checkout my configuration below: main urls.py: def render_react(request): return render(request, "index.html") #<---- index.html from React urlpatterns = [ path('auth/', include('drf_social_oauth2.urls', namespace='drf')), path('admin/', admin.site.urls), path('api/', include('bucket_api.urls', namespace='bucket_api')), path('api/user/', include('users.urls', namespace='users')), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] urlpatterns += [ re_path('',render_react) #<---- Serving React index.html ] Here is an example of the issue: When I … -
Django: Why does my Django model get "on_deleate" error
I know that ForeignHey of Django 2.2 require "on_delete" parameter and defined it in my model. Nevertheless, I got the error "TypeError: init() missing 1 required positional argument: 'on_delete' " Please tell me the resolution of this error I use Python3.7 and Django 2.2 My model is from django.db import models from treebeard.mp_tree import MP_Node from django_model_to_dict.mixins import ToDictMixin class Project(ToDictMixin,models.Model): name=models.CharField(max_length=200) def __str__(self): return self.name class Task(MP_Node, ToDictMixin): name=models.CharField(max_length=100) start=models.DateTimeField() end=models.DateTimeField() progress=models.PositiveIntegerField(default=0) custom_class=models.CharField(max_length=20,null=True, blank=True) project = models.ForeignKey( Project, related_name="tasks", on_delete=models.CASCADE, ) def __str__(self): return self.name and error is File "/Users/gensan/python/basic3_7/lib/python3.7/site- packages/django_model_to_dict/models.py", line 127, in <module> class Order(models.Model, ToDictMixin): File "/Users/gensan/python/basic3_7/lib/python3.7/site-packages/django_model_to_dict/models.py", line 134, in Order customer = models.ForeignKey(to=Customer, verbose_name=_('customer'), related_name='orders') TypeError: __init__() missing 1 required positional argument: 'on_delete' Thank you -
Django APScheduler job hang up without Error
I use django-apscheduler to manage task. But after the server start for a while, the job stop working and when I check the django admin page. There is no error log, too. This is my runapscheduler.py ... def start(): scheduler = BackgroundScheduler(timezone=settings.TIME_ZONE) scheduler.add_jobstore(DjangoJobStore(), "default") scheduler.add_job( process_tt_file.start_tt_process, trigger=CronTrigger(minute='5,20,35,50', hour='*'), id='process_tt_file', max_instances=1, replace_existing=True ) logger.info("Added job 'process_tt_file'.") ... try: logger.info("Starting scheduler...") scheduler.start() except KeyboardInterrupt: logger.info("Stopping scheduler...") scheduler.shutdown() logger.info("Scheduler shut down successfully!") ... this is my urls.py where I start apscheduler when django start ... urlpatterns = ... runapscheduler.start() The task should run every 15min. But somehow apscheduler didn't fire the job until I check the status. How should I prevent this? -
Django HTML Dropdown
I am trying to make a html dropdown and pass the values into Postgrase SQL database. My dropdown values are being retrieved from another database table. It gives me a MultiValueKeyDictError every time I submit the form. I know I can use forms.py to do the same thing but I want to explore the HTML way of doing this. My HTML file <form action = "" method = "post"> {% csrf_token %} <label for = "LogType"></label> <input id ="LogType" type = "text" value = "{{ user.department }}"> <label for ="DelayCategory">Delay Category</label> <select id = "delaycategory" class = "form-control"> {%if user.department == 'TechAssembly'%} {%for techdelay in techdelay%} <option value = "{{ techdelay.DelayCode }}">{{ techdelay.DelayCategory}}</option> {%endfor%} {%endif%} {%if user.department == 'Testing'%} {%for testdelay in testdelay%} <option value = "{{ testdelay.DelayCode }}">{{ testdelay.DelayCategory}}</option> {%endfor%} {%endif%} </select> <label for = "iterations">Iterations</label> <input type = "number" id = "iterations"> <center><input type="submit" value=Submit id = "button"></center> </form> My Views.py file def rulesView(request, user_name): testdelay = TestingDelayCategory.objects.all() techdelay = TechDelayCategory.objects.all() if request.method == "POST": rulesnew = rules() rulesnew.DelayCategory = request.GET['DelayCategory'] rulesnew.LogType = request.POST('LogType') rulesnew.iterations = request.POST('iterations') rulesnew.save() context = { 'techdelay':techdelay, 'testdelay':testdelay, } return render(request, 'rules/rules.html', context) -
No "Access Control-Allow-Origin' header is present even when Django CORS_ORIGIN_ALLOW_ALL = True
I just deployed my React/Django web app to a VM. Everything worked fine on my local before deployment. Just to test, I attempted to use my site with the development server. When my React code (statically bundled in the Django app) makes the following api call to http://localhost:8000/token-auth/ (this endpoint is automatically constructed from django rest_framework.views.obtain_jwt_token): fetch('http://localhost:8000/token-auth/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) the following error message is received: Access to fetch at 'http://localhost:8000/token-auth/' from origin 'http://34.XXX.XXX:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Note that the curl from an external origin (my local machine pinging the vm) works fine: curl -X POST -H "Content-Type: application/json" -d '{"username": "wgu_test_user", "password": "fgDq7YUmcd3n"}' http://34.XXX.XXX:8000/token-auth/ so this error seems solely to do with CORS. Strangely, after I whitelisted the domains, and even used CORS_ORIGIN_ALLOW_ALL = True in my settings.py, I still get the same problem. I did restart the development server after changing this file and saving. As one possible solution, …