Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
long running task manager project
I have to implement a project in which the user can stop the long-running task at any given point in time, and can choose to resume or terminate it. This will ensure that the resources like compute/memory/storage/time are used efficiently at our end, and do not go into processing tasks that have already been stopped (and then to roll back the work done post the stop-action). I also have to create Rest API endpoints. Can anyone help with intuition? -
Adding your own language for translation in Django
We need to make a translation into the Bashkir language on the site. This does not seem to exist in the locale django file. I'm trying to do this. In the settings.py file added. import django.conf.locale EXTRA_LANG_INFO = { 'ba': { 'bidi': False, 'code': 'ba', 'name': 'Bashkir', 'name_local': 'башкирский' }, } d = django.conf.locale.LANG_INFO.copy() d.update(EXTRA_LANG_INFO) django.conf.locale.LANG_INFO = d LANGUAGE_CODE = 'ru' LANGUAGES = ( ('ru', 'Russian'), ('en','English'), ('ba', 'Bashkir'), ) Now, when following the link, it writes that it cannot find the / ba page. I display links on the page as follows.(When switching to ru and en, the translation goes without problems). {% for language in languages %} <a href="/{{ language.code }}/"}>{{ language.code }} </a> {% endfor %} in urls + = i18n_patterns added. Maybe there is some other way? Or how to finish the given one? -
Using App name with Django.contrib.auth views
I am new to Django and I am creating a user change password page. However, I keep encountering a NoReverseMatch error which I suspect is due to my app name but I am not able to resolve it even after spending hours googling for a solution. My urls.py file: from os import name from django.urls import path from account import views from django.contrib.auth import views as auth_views # Import Django built-in authentication views app_name = 'account' urlpatterns = [ path('test/', views.test_login, name='test'), path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), ] My settings.py: # Login Logic LOGIN_REDIRECT_URL = 'account:test' # Tells Django which URL to redirect user to after a successful login if no next parameter is present in the request LOGIN_URL = 'account:login' # The URL to redirect the user to log in - based on the name in the urls.py LOGOUT_URL = 'account:logout' # The URL to redirect the user to log out - based on the name in the urls.py Much help is appreciated. -
How to get only content from JSON using Regex
How to get JobTitle from following json which item have "Country":"CN" {"Data":[{"JobTitle":"Asset Management Analyst","Country":"CN","City":"Shenzhen","DisplayJobId":"349356BR","UrlJobTitle":"Asset-Management-Analyst","JobId":1041047,"Latitude":22.54286,"Longitude":114.059563},{"JobTitle":"Package Consultant: SAP C/4 HANA C4C","Country":"CN","City":"Bangalore","DisplayJobId":"349128BR","UrlJobTitle":"Package-Consultant-SAP-C-4-HANA-C4C","JobId":1041046,"Latitude":12.976746,"Longitude":77.57528},{"JobTitle":"Package Specialist: SAP HANA Security","Country":"IN","City":"Pune","DisplayJobId":"348219BR","UrlJobTitle":"Package-Specialist-SAP-HANA-Security","JobId":1041045,"Latitude":18.528904,"Longitude":73.87435},{"JobTitle":"Cloud Developer (Go Lang)","Country":"CN","City":"Bangalore","DisplayJobId":"349318BR","UrlJobTitle":"Cloud-Developer-(Go-Lang)","JobId":1041026,"Latitude":12.976746,"Longitude":77.57528},{"JobTitle":"Watson AI Site Reliability Engineering Team Manager","Country":"IN","City":"Bangalore","DisplayJobId":"348769BR","UrlJobTitle":"Watson-AI-Site-Reliability-Engineering-Team-Manager","JobId":1041025,"Latitude":12.976746,"Longitude":77.57528},{"JobTitle":"Site Reliability Engineering (SRE)","Country":"IN","City":"Bangalore","DisplayJobId":"348768BR","UrlJobTitle":"Site-Reliability-Engineering-(SRE)","JobId":1041024,"Latitude":12.976746,"Longitude":77.57528},{"JobTitle":"Site Reliability Engineering (SRE)","Country":"IN","City":"Bangalore","DisplayJobId":"348765BR","UrlJobTitle":"Site-Reliability-Engineering-(SRE)","JobId":1041023,"Latitude":12.976746,"Longitude":77.57528} -
Trying to use multiple listviews on one HTML file?
I'm trying to create a website where I can display my projects, and for each project I can include programming languages used that are also a model. I created a couple of different programming languages, then tried making a project and selected some programming languages I used, but when I run the server, the languages used don't show up like I intended (refer to HTML code in the {%for language in languages%}) My models page is like this: from django.contrib.auth.models import User from django.utils import timezone class Language(models.Model): name = models.CharField(max_length=12) icon = models.ImageField(upload_to="languages/", null=True) def __str__(self): return self.name class Project(models.Model): name = models.TextField(max_length = 75) description = models.TextField(max_length=300) gitlink = models.CharField(max_length=100) image = models.ImageField(null=True) languages = models.ManyToManyField(Language) author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.name My HTML file is like this: {% block content %} <div class="projects"> {% for project in projects %} <div class="project"> <h2>{{ project.name }}</h2> <p> {{ project.description }}</p> <img src="{{ project.image.url }}" style="width: 800px; height: 600px;"> <p>GitHub: {{ project.gitlink }}</p> {% for language in languages %} <p>{{ language.name }}</p> <img src="{{ language.icon.url }}" style="width: 60px; height: 60px;"> {% endfor %} </div> {% endfor %} </div> {% endblock %} And my views page … -
Cannot access form.first_name and form.email from django default authentication form
I am using the default Django AuthenticationForm() for the user login feature. Now when I see inside the user model in Django admin it has fields like username, email address, first name last name and active status. But in my sign-in.html page I can only access form.username and form.password, but cant access to form.email and form.first_name?? My views: def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() authlog(request, user) return redirect('home') else: messages.error(request, 'Invalid username or password') # back_page = request.META.get('HTTP_REFERER') return redirect('login') # messages.error(request, student_form.errors, 'Incorrect') # return HttpResponse(back_page) else: content = { 'form': AuthenticationForm() } return render(request, 'sign-in.html', content) <div class="input-group"> <span class="input-group-text" id="basic-addon1"><span class="fas fa-envelope"></span></span> {{form.emailaddress}} </div> <div class="input-group"> <span class="input-group-text" id="basic-addon2"><span class="fas fa-unlock-alt"></span></span> {{form.password}} </div> Here I can access form.password and form.username but cant login with email address. But we know we should be able to login with email address as well. I have the picture here of the html page. Sign-In Page -
Having Problem in adding redirect URL on Faliure of payment razorpay python?
I am using Django Web Framework for my E-commerce Website, and Using Razor-pay as my payment gateway. The Problem is that I cannot make a track of users with failed payments, So I need to make a redirect URL for every failure payments, So that I can Save the order and redirect it to any URL for the Customers. I am using razorpay python library. Python version = 3.6.8 Django version = 2.2.3 Thank You -
Get constant incoming post requests from multiple devices with Django Rest Framework or listen TCP Server Socket
I have IoT devices which are rfıd readers. This devices send stream data with HTTP Post message. I use Django to get data from these devices. While receiving this data, I can write a function to get data from post requests coming directly with Django and receive the data from the request in this function with Django REST Framework or I can listen with a TCP Server socket. Which of these two approaches is more suitable for retrieving data? Because when I use a TCP Server socket, Django REST Framework does not work for HTTP requests, only the TCP socket works. -
How to add a property to a model which will be calculated based on input?
class TransactionHistory(models.Model): from_account = models.ForeignKey( 'Account', on_delete=models.CASCADE, related_name='from_account' ) to_account = models.ForeignKey( 'Account', on_delete=models.CASCADE, related_name='to_account' ) amount = models.DecimalField( max_digits=12, decimal_places=2 ) created_at = models.DateTimeField(default=timezone.now) @property def way(self): # Here I need to access a list of user's accounts # (request.user.accounts) to mark the transaction # as going out or in. return def get_own_transaction_history(me_user): my_accounts = me_user.accounts.all() # TODO: mark transactions with way as in and out own_transactions = TransactionHistory.objects.filter( Q(from_account__in=my_accounts) | Q(to_account__in=my_accounts) ) return own_transactions I want to add a "way" property for the model so when I return the queryset via serializer, the user could understand if the transaction is for going out from his account or in. But if I just add property, it can not be calculated with me_user user in mind, AFAIK the property can only access the local model fields like "from_account" or "to_account". -
Using Bootstrap Modal as Register and Login Form. On error the full page is served
I am using jquery.bootstrap.modal.forms.js to load Login and Register form from their url as Modals using the code below: <script> $(function ($, undefined) { // log in & sign up buttons $(".register-btn").modalForm({ modalID: "#registerModal", formURL: "/register-modal/", }); }); $(function ($, undefined) { // log in & sign up buttons $(".login-btn").modalForm({ modalID: "#registerModal", formURL: "/login-modal/", }); }); $(function ($, undefined) { // log in & sign up buttons $(".forgot-password").modalForm({ modalID: "#registerModal", formURL: "/recover-modal/", }); }); </script> HTML code for the modal <div class="modal fade" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document" style="width:400px;"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="registerModalLabel">Register</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> Modal Code : {% extends 'base.html' %} {% load static %} {% block title %} Login {% endblock %} {% block style %} {% endblock %} {% block content %} <div class="container-fluid "> <div class="row "> <div class="col-sm-12 col-xs-12 col-md-12"> <form class="account-register form-narrow p-3 mb-4 bg-white" id="login_form" method="POST" action="" autocomplete="off"> {% if messages %} <div id="messages"> {% for message in messages %} <div class="alert alert-dismissible alert-info" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span … -
ON deployment to heroku: RelatedObjectDoesNotExist at /admin/login/ User has no profile
I have no problem with regards to the development stage. The problem is when I deploy my web thru heroku. i got an error everytime I log in or go to my admin.. RelatedObjectDoesNotExist at /admin/login/ User has no profile. Request Method: POST Request URL: https://azheafaith.herokuapp.com/admin/login/?next=/admin/ Django Version: 3.1.4 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no profile. Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py, line 424, in get Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.12 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Mon, 28 Dec 2020 06:18:42 +0000 --any help is highly appreciated.. Thank you -
save uploaded file to aws s3 and path to database in django using boto3
models.py def document_file_name(instance, filename): char_set = string.ascii_uppercase + string.digits dat = "".join(random.sample(char_set * 6, 12)) return 'documents/' + str(instance.created_by_id) + '/' + dat + '_' + re.sub(r'[^a-zA-Z0-9-_.]', r'_', filename); class UploadDocument(models.Model): document = models.FileField(upload_to=document_file_name, blank=True, null=True) other_doc = models.ForeignKey("doc.OtherDocuments") views.py def opportunity_document_add(request, opportunity_id): c = setup_context(request) other_documents = get_object_or_404(OtherDocuments, pk=opportunity_id) c["other_documents "] = other_documents c["other_documents_id"] = other_documents document = UploadDocument(other_doc=other_documents) errors = {} if request.method == "POST": document.type = request.POST.get("type") if "document" in request.FILES: document.document = request.FILES["document"] document.created_by = request.user document.save() cloudFilename = '<someDirectory>/' + document.document.name session = boto3.session.Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) s3 = session.resource('s3') s3.Bucket(AWS_STORAGE_BUCKET_NAME).upload_file(Key=cloudFilename, Body=document.document) else: errors['document'] = "There is no document specified" c['errors'] = errors c['document'] = document return render_to_response( 'documents/document_form.django.html', c, context_instance=RequestContext(request)) Here my file is getting saved to AWS S3 folder but the path is not getting saved to my database -
Django - how to create a new company and link it to the existing user
Good day all :) I am new in Django world, Basically I have a three apps: CustomUsers , Company and Team with the following: First a user creates an 'account' , then user create a new 'Company' and then a new'Team', my question is how to link the user to the new team and company when they are created? CustomUSer App: class CustomUser(AbstractUser): bio = models.CharField(max_length=300, null=True, blank=True) image = models.ImageField(upload_to="userimages/", null=True, blank=True) job_title = models.CharField(max_length=300, null=True, blank=True) member_of_company = models.ForeignKey("company.Company", null=True, blank=True, on_delete=models.SET_NULL) and Company App class Company(models.Model): title = models.CharField(max_length=200) logo = models.ImageField(null=True, blank=True,upload_to="logos/") website= models.CharField(null=True, blank=True, max_length=200) and finally team app: class Team(models.Model): title = models.CharField(max_length=150) members = models.ManyToManyField("accounts.CustomUser", blank=True, related_name='team_members') company = models.ForeignKey("company.Company", null=True, blank=True, on_delete=models.SET_NULL, related_name='teams') my questions are 1) how to link the new company with the current user and 2) how to link the new "team" with the existing company and user. Thanks in advance. -
How to pass python string to javascript as string in Django?
I have a python string which is javascript code and I want to pass this string to javascript as string too. My idea is to pass python string to javascript string and then use eval() function in javascript to turn that string to actual code and execute it. def login(request): success = ''' window.location = '{% url 'home' %}'; # some other codes ''' return render(request, "app/login.html", {'success': success}) var code = "{{success}}" console.log(code) // return Uncaught SyntaxError: Invalid or unexpected token I have also tried pass the string as json like this def login(request): success = ''' window.location = '{% url 'home' %}'; # some other codes ''' success = json.dumps(success) return render(request, "app/login.html", {'success': success}) var code = JSON.parse("{{success|safe}}"); console.log(code) //return Uncaught SyntaxError: missing ) after argument list Last thing that I have tried is def login(request): success = ''' window.location = '{% url 'home' %}'; # some other codes ''' return render(request, "app/login.html", {'success': success}) <h3 id="success_id" hidden>{{success}}</h3> <script> var code = $("#success_id").text(); console.log(code) //return window.location = "{% url 'home' %}" // if i do this var code = "window.location = '{% url 'home' %}'"; console.log(code) // return window.location = /app/home/ // I want it to return … -
Django sessions doesn't allow me to add items in my cart
I am creating an eCommerce store and I use Django sessions to store the cart information. However, for some reason, only 2 items get stored in the cart and no more. Once I add the first item, it stays there as it is. Then I add the 2nd item. However, when I add the 3rd item, the 2nd item is overwritten by the 3rd one, still keeping only 2 products in the cart. I feel it would be a simple logic error but I can't seem to figure it out. My views.py... def shop(request): if not request.session.get('order1'): request.session['order1'] = [] if request.method == "POST": quantity = int(request.POST.get('quantity')) name = request.POST.get('name') if quantity >= 1: request.session.get('order1').append({"quantity":quantity, "name":name}) context = { "check":request.session.get('order1'), } else: messages.warning(request, "You have entered an invalid quantity") context={} else: context={} return render(request, "store/shop.html", context) And the output of the context = {"check":request.session.get('order1')} is something like this [{'quantity': 1, 'name': 'Tissot Watch for men - black star striped'}, {'quantity': 2, 'name': 'Jewelry Bangles Stripes for Girls'}] and always stays with only 2 items. Is there any error in the code that I have done? Any help would be greatly appreciated. Thanks! -
Check if user is in the group before posting
I have a project called Star Social this project you can only post if you are in group in this case i can still post even if i am not in a group and i can't see that post. What i want is when user tried to post even out of the group they will receive an error and redirect them to group page so that they can join a group and they can now post.I tried to search on google but i get no result and btw i am new in this field and i am currently learning django. models.py ########################## ## POSTS MODELS.PY FILE ## ########################## from django.contrib.auth import get_user_model from django.db import models from groups.models import Group from misaka import html from django.urls import reverse User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message = models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.message def save(self, *args, **kwargs): self.message_html = html(self.message) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( 'posts:single', kwargs={ 'username': self.user.username, 'pk': self.pk } ) class Meta: ordering = ['-created_at'] views.py ######################### ## POSTS VIEWS.PY FILE ## ######################### from braces.views import SelectRelatedMixin from django.contrib.auth import get_user_model … -
Why heroku is keep saying to me "No web processes running?"
I'm trying to deploy my django project at heroku, but it keep saying the error like below. According to that error, I did heroku logs --tail, and the error was like this. 2020-12-28T03:44:38.472162+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=nbnb-clone.herokuapp.com request_id=1e862587-ebc8-4dbb-85be- 12487ff9ae16 fwd="1.250.241.55" dyno= connect= service= status=503 bytes= protocol=https I've tried heroku ps:scale web=1, and the return was like below. Scaling dynos... ! ! Couldn't find that process type (web). Currently I'm using github as my deployment method in heroku. I've tried heroku buildpacks:clear and heroku buildpacks:add heroku/python, but it didn't work for me. Also I've tried git git push heroku main, return was like below. error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/nbnb-clone.git' My Procfile is like this web: gunicorn config.wsgi --log-file - My requirements.txt certifi==2020.12.5 chardet==4.0.0 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' django-countries==7.0 django-dotenv==1.4.2 django-seed==0.2.2 django==2.2.5 faker==5.0.2 ; python_version >= '3.6' idna==2.10 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' pillow==8.0.1 python-dateutil==2.8.1 ; python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3' pytz==2020.5 requests==2.25.1 six==1.15.0 ; python_version >= '2.7' and python_version not in '3.0, … -
Searching and Sorting in Jquery DataTable for my Django app, PostgreSQL DB is not working
I am using Jquery DataTable and in my Django app where I am getting data from the PostgreSQL DB. I am able to get the data into the table but I cannot get the table to sort and search. datatables.js: // Call the dataTables jQuery plugin $(document).ready(function() { $('#dataTable').DataTable(); }); index.html: <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <th>Testing Type</th> <th>Question</th> <th>Difficulty Level</th> </tr> </thead> {% for qiq in qa_interview_questions %} <tbody> <tr> <td>{{ qiq.testingtype }}</td> <td>{{ qiq.question }}</td> <td>{{ qiq.difficultylevel }}</td> </tr> </tbody> {% endfor %} </table> </div> </div> Somehow the Search and Sorting in the DataTable does not work at all. It works if I hardcore the data. What am I doing wrong here? -
NoReverseMatch: Urlpatterns path name for route with int:pk
I am trying to create a dashboard with multiple customers rendered in the template, and a link to their individual profile. I was wondering if there is a way to pass in the url name and object pk id using django url in my template. This is my code so far and I am getting a NoReverseMatch error. urlpatterns = [ path('', views.index, name='home'), path('dashboard/', views.dashboard, name='dashboard'), path('about/', views.about, name='about'), path('product/', views.product, name='product'), path('customer/<int:pk>', views.customer, name='customer'), ] <th><a href="{% url 'customer' %}">{{ customer.first_name }} {{ customer.last_name }}</a></th> I understand that this is wrong but I cannot find the right way to do it. I am relatively new to django programming. -
Unable to figure out the cause of a Django KeyError
I am trying to make an eCommerce site and I am using Django sessions to store items in the cart, initially, it was all working perfectly fine until I decided to do something stupid and changed the session token in the inspection in chrome. And from then onwards I am thrown with a KeyError. Django Version: 3.0.8 Exception Type: KeyError Exception Value: 'order1' I then ran the following code in my terminal... from django.contrib.sessions.models import Session Session.objects.all().delete() That cleared out my table but still didn't seem to sort out this error. I even tried to host it in Heroku and access the website from a different device and a still thrown with this error. Is there anything I can do about this? And just in case here is my views.py... def shop(request): if not request.session['order1']: request.session['order1'] = [] if request.method == "POST": quantity = int(request.POST.get('quantity')) name = request.POST.get('name') if quantity >= 1: new_order = {"quantity":quantity, "name":name} request.session['order1'].append(new_order) # request.session['order'] = order context = { "check":request.session['order1'], } else: messages.warning(request, "You have entered an invalid quantity") context={} else: context={} return render(request, "store/shop.html", context) Any help would be greatly appreciated. Thanks! -
Automatically join the user who created the group
I have a project called social clone project in this project you can only post if you are in a group. What i want to happen is if the user created a group the user should automatically in the group, in this case if i created a group i still need to join the group to join my own group. I tried to search this on google but i get no result and i hope someone will help me and btw i'm just new here in programming and i'm currently learning django. models.py ########################## ## GROUPS VIEWS.PY FILE ## ########################## from django.contrib.auth import get_user_model from django import template from django.db import models from django.utils.text import slugify from misaka import html from django.urls import reverse User = get_user_model() register = template.Library() class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default="") description_html = models.TextField(editable=False, blank=True, default="") members = models.ManyToManyField(User, through='GroupMember') def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) self.description_html = html(self.description) super().save(*args, **kwargs) def get_absolute_url(self): return reverse('groups:single', kwargs={'slug': self.slug}) class Meta: ordering = ['name'] class GroupMember(models.Model): user = models.ForeignKey(User, related_name='user_groups', on_delete=models.CASCADE) group = models.ForeignKey(Group, related_name='memberships', on_delete=models.CASCADE) def __str__(self): return self.user.username class Meta: unique_together = … -
How to shrink flexbox when downsizing image
I am using flexbox to center items on a page and also to center items within a row. I have to handle potentially large images within the row, so I am using max-width=40% to downsize the image. However, when I do this the flexbox for the applicable row does not shrink to fit the new image size, but retains the size as if the image is still max-width=100%. How can I make the flexbox row smaller to account for the 40% max width property? Here current html code: <div style="display: flex; flex-direction: column; align-items: center;> <label>This is my header.</label> <div style="display: flex; flex-direction: row; align-items: center; border: 1px solid black;"> <img style="max-width: 40%; padding: 5%;" src="path_to_my_image" alt="(!)"/> <div style="border: 1px solid black"> <label>Here is my label</label><br> <label>Here is another label</label> </div> </div> </div> This is an image of what the current display looks like with a border around the flexbox row: Here is what it looks like without setting max-width (bottom cropped to fit): -
Ajax post requests seem to not work for some users?
I've been testing my site by having friends try it, and some friends have an issue where some of my javascript functions don't work, and some functions do. After figuring out it's not their browsers or devices, I noticed the functions that weren't working for them were the ones with Ajax post requests, so I think that's the issue here. Does anyone know why Ajax post requests work for only some users? Also, FYI, I'm using Django as a framework. Example of one of my functions using ajax: $('#button').click(function(){ $.ajax({ url: '/get_url/', type: "POST", data: { data_name: data_to_send }, beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", csrftoken); }, success: function (data) { //change some html text using data }, error: function (error) { console.log(error); } }); }); -
How to capture selected values, in Django, from two separate select fields and pass it to the view upon form submission?
I am trying to create a filtered list from model class "Animal" based off of two separate select field drop down values. If user selects "baby" and "dog" then a list of puppies would be generated from the Animal model. I cannot seem to figure out how to capture the value pks for both the "age_group" and "type" fields so that I can use them to filter the queryset. Any suggestions or guidance is appreciated. I am very new to Django. models.py class Animal(models.Model): name = models.CharField(max_length=500, blank=False, null=False) type = models.ForeignKey(Type, on_delete=models.SET_NULL, blank=False, null=True) ageGroup = models.ForeignKey(AgeGroup, max_length=300, on_delete=models.SET_NULL, blank=False, null=True) age = models.PositiveIntegerField(blank=False, null=False) sex = models.CharField(max_length=100, choices=SEX, blank=False, null=False, default='NA') breedGroup = models.ManyToManyField(BreedGroup, blank=False) breed = models.ManyToManyField(Breed, blank=False) tagLine = models.CharField(max_length=300, blank=False, null=False) goodWithCats = models.BooleanField(blank=False, null=False, default='Not Enough Information') goodWithDogs = models.BooleanField(null=False, blank=False, default='Not Enough Information') goodWKids = models.BooleanField(null=False, blank=False, default='Not Enough Information') forms.py class AnimalSearchForm(ModelForm): chooseType = ModelChoiceField(queryset=Animal.objects.values_list('type', flat=True).distinct(),empty_label=None) chooseAge = ModelChoiceField(queryset=Animal.objects.values_list('ageGroup', flat=True).distinct(), empty_label=None) class Meta: model = Animal exclude = '__all__' views.py class VisitorSearchView(View): def get(self, request): animalList = AnimalSearchForm(self.request.GET) context = {'animal_list': animalList} return render(request, "animals/landing.html", context) templates {% extends 'base.html' %} {% block content %} <h1>Animal Search</h1> <form class="form-inline" action="." method="POST"> {% … -
POST 500 error django react site, POST /api/create-room
I have created a component for a Django React Rest Framework site and I keep getting an error when I click on the Create Room button on my site. The error seems to be located at the fetch portion of the component for the CreateRoom.js file I created. Any help in identifying the issue is much appreciated. Here is the error and the code that seems to be triggering the error. Please take a look at what I've got and let me know if I can provide any more information to help figure out what the issue is. Usually I try and figure it out myself but I've spent hours doing so and haven't been able to figure it out. Error: CreateRoomPage.js:67 POST http://localhost:8000/api/create-room 500 (Internal Server Error) handleRoomButtonPressed @ CreateRoomPage.js:67 Rb @ react-dom.production.min.js:52 Xb @ react-dom.production.min.js:52 Yb @ react-dom.production.min.js:53 Ze @ react-dom.production.min.js:100 se @ react-dom.production.min.js:101 eval @ react-dom.production.min.js:113 Jb @ react-dom.production.min.js:292 Nb @ react-dom.production.min.js:50 jd @ react-dom.production.min.js:105 yc @ react-dom.production.min.js:75 hd @ react-dom.production.min.js:74 exports.unstable_runWithPriority @ scheduler.production.min.js:18 gg @ react-dom.production.min.js:122 Hb @ react-dom.production.min.js:292 gd @ react-dom.production.min.js:73 create:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.then (async) handleRoomButtonPressed @ CreateRoomPage.js:67 Rb @ react-dom.production.min.js:52 Xb @ react-dom.production.min.js:52 …