Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multi-app static files - developing locally and pushing to Elastic Beanstalk server
I have a django project with multiple apps inside it as so: /UserProject /Static /UserApp /UserApp/Static I have my global styling held within the /static/ folder, then individual UserApp styling held within the UserApp static folder. Then, within my settings.py I have: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) This is great for local development - I can run the development server and the site updates as I update the stylesheets within either the root /static or the UserApp /static. However, when I push to my elastic beanstalk instance (depending on my configuration) - I get either (a) only the root /static files loading, (b) no static files loading or (c) an error on deployment You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I have tried using the following in my .ebextensions folder container_commands: 03_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" But this gives me the staticfiles app error. What is the correct setup in my settings.py to allow local development, and then also allow pushing to the EB instance? -
Authenticate Generated API Key in accessing Django Rest API
I need to let third-party users access some of the REST APIs that I have. I made an APIkey model that will store the generated keys that can be used in accessing the API. I just don't know yet how will I add the API key to the authentication of my app since I already have a BearerTokenAuthentication in my auth.py -
add to favourite list in django
I have added the add to favorites list feature for each product on the product page of my website, and the user can add any product to their favorites list. But if the user already adds this product to the favorites list, I want the word remove to be displayed instead of the word add, so that if he wants, he can remove that product from his favorite list. But the following error occurs: AttributeError: 'QuerySet' object has no attribute 'favourite' # model class Product(models.Model): title = models.CharField(max_length=200) favourite = models.ManyToManyField(User, related_name='user_favourite') # view def product(request): products = Product.objects.all() is_favourite = False if products.favourite.filter(id=request.user.id).exists(): is_favourite = True context = {'products': products, 'is_favourite': is_favourite} #template {% if is_favourite %} <a href="{% url 'home:favourite' product.id %}"> remove </a> {% else %} <a href="{% url 'home:favourite' product.id %}"> add </a> {% endif %} -
how to create ForeignKey for username (not userid) in django models.py
I created the following fieldmodels.py added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and it contained the user Id , but how to make it contain the username instead. -
403 Forbidden request when making an axios call with React (Django backend)
I am trying to authenticate my session on a web application using ReactJS. My backend is setup on Django. When logging in to the application, I do receive the cookies in the header, however I am unable to set the cookies. However, when I try to post the request 'withCredentials: true', it returns me the 403 error. The login call (Where I receive the cookies in response header) let url = `${BASE_URL}/login/`; console.log('params for validateOtp:', params); axios .post(url, params) .then((res) => { console.log('validate otp code res: ', res); resolve(res); }) .catch((err) => { console.log('validate otp code err: ', err); reject(err); }); After seeing the console, it is visible under the 'Network' tab that I do receive cookies from this API. This is the API where I make the authenticated call. let url = `${BASE_URL}/updatemerchant/`; axios .post(url, params, { withCredentials: true } ) .then((res) => { console.log('updateDukaanUserToCloud res : ', res); // resolve(res) if (res.status === 200) { resolve(res); } else { reject('updateDukaanUserToCloud something went wrong'); } }) .catch((err) => { if (err.response && err.response.status === 400) { reject('updateDukaanUserToCloud updating user info failed'); } else { reject('updateDukaanUserToCloud something went wrong'); } }); settings.py CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_NAME = … -
Do not display the product category name on the details page in django
when I want to display the category name of the desired product in the details page, it returns a good value if the brand name of the desired product returns correctly. # model class Product(models.Model): category = models.ManyToManyField(Category, related_name='cat_product') brand = models.ForeignKey('Brand', on_delete=models.CASCADE) # view def product_detail(request,id) products = product.objects.get(id=id) context = {'products': products} return render(request, 'home/detail.html', context) #template <p>category : {{products.category}}</p> <br> <p>category : {{products.brand}}</p> -
Celery only responding Sending due tasks
I followed this instruction on how to implement Celery with Django. However, after everything done, on my terminal it just repeating Sending due tasks "NAME" users.tasks.send_notification Here is what I did: tasks.py from celery import task from celery import shared_task def send_notification(): print("TEST") project's init.py from __future__ import absolute_import, unicode_literals from .celery import celery_app as celery_app __all__ = ('celery_app',) apps' init.py default_app_config = 'users.apps.UsersConfig' settings.py from celery.schedules import crontab BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Tokyo' -
How can I get the current user in models.py?
Hi I am trying to add the User column to know which User added the tool in the tools/model.py page tools_name = models.CharField('Tool\'s Name', max_length=100, unique=True) tools_project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, null=True, blank=True, limit_choices_to=~Q(project_status=2), verbose_name='Project\'s Name') user = models.CharField(max_length=100, editable=False) But I want to know how to save the user that created or updated the tool ? -
Django foreign key: auto-lookup related object when the update record has the key value
I have legacy code which had no foreign keys defined in the schema. The raw data for the row includes the key value of the parent, naturally. My first porting attempt to postgresql just updated the field with the raw value: I did not add foreign keys to Django's models. Now I am trying to add foreign keys to make the schema more informative. When I add a foreign key, django's update requires me to provide an instance of the parent object: I can no longer update by simply providing the key value. But this is onerous because now I need to include in my code knowledge of all the relations to go and fetch related objects, and have specific update calls per model. This seems crazy to me, at least starting from where I am, so I feel like I am really missing something. Currently, the update code just pushes rows in blissful ignorance. The update code is generic for tables, which is easy when there are no relations. Django's model data means that I can find the related object dynamically for any given model, and doing this means I can still keep very abstracted table update logic. So … -
Javascript Error - Uncaught ReferenceError: load_mailbox is not defined at HTMLDocument
I'm working on an app to send email messages using Django and Javascript. I'm getting the error in the Javascript file: Uncaught ReferenceError: load_mailbox is not defined at HTMLDocument. The issue happens at the 13th line which is: load_mailbox('inbox'); I have tried re-writing it many different ways but for some reason cannot figure out how to 'define' this. I'm very new to JS, any help is appreciated. inbox.js: document.addEventListener('DOMContentLoaded', function(e) { // Send the email to server upon clicking on submit document.querySelector('#compose-form').addEventListener('submit', (e) => submit_email(e)); // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', () => compose_email()); // By default, load the inbox load_mailbox('inbox'); }); //Submit email after user composes an email and submits function submit_email(e){ e.preventDefault(); const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipients, subject: subject, body: body }) }) .then(response => response.json()) .then(result => { console.log("result"); }) .catch(error => { console.log('Error:', error); }); load_mailbox('sent'); }; -
Django file not uploaded using FileField(upload to=)
am very new to concepts of django and it's functionalities so i came across a project which will easily help one to upload a file to a directory using FileField Upload to , but for me it is not working , i tried different ways i modifed it but still i am not sure about the error am getting . So someone please guide me here is my code : Models.py class UploadedFiles(models.Model): files_to_upload = models.FileField(upload_to='uploaded_files/', default=None, validators=[validate_file]) path = models.CharField(max_length=100) server = MultiSelectField(choices=server_list) SalesforceTicket = models.ForeignKey(SalesforceTicket, related_name="files", on_delete=models.CASCADE) def __str__(self): return str(self.SalesforceTicket) forms.py class FilesForm(forms.ModelForm): class Meta: model = UploadedFiles fields = ['files_to_upload', 'path', 'server'] # called on validation of the form def clean(self): # run the standard clean method first cleaned_data = super(FilesForm, self).clean() files_to_upload = cleaned_data.get("files_to_upload") path = cleaned_data.get("path") server = cleaned_data.get("server") # print(files_to_upload) # print(path) # print(server) new_path = path.replace(':', '$', 1) # print(new_path) mode = 0o666 for s in server: s = r'\\' + s unc_path = os.path.join(s, new_path) print("hello"+unc_path) #unc_path = os.mkdir(unc_path, mode) isdir = os.path.isdir(unc_path) if isdir: print("ok") else: unc_path = os.mkdir(unc_path, mode) return cleaned_data Views.py def files(request): num_of_files = 1 filled_multi_file_form = MultipleForm(request.GET) if filled_multi_file_form.is_valid(): num_of_files = filled_multi_file_form.cleaned_data['num_of_files'] FilesFormSet = formset_factory(FilesForm, extra=num_of_files) … -
How to get html form field data in JSON and insert into database with Django?
I have created one project where User Registration functionality is there. Once user fill the form, I'll be getting data in Django using POST and insert into Database. Now I don't want to get data into my code directly from the form. My requirement is: 1. Once User fill the form and submit, then JSON data should be created so that I can give that API to the frontend. 2. I would take that JSON data using API and insert that record into my MySQL database dynamically for different users. Here is my code : models.py from django.db import models class Employee(models.Model): name = models.CharField(max_length=100, blank=False, null=True) username = models.CharField(max_length=100, blank=False, null=True) email = models.EmailField(max_length=200, blank=False, null=True) mobile = models.CharField(max_length=30, blank=False, null=True) def __str__(self): return self.name viewsets.py from rest_framework import viewsets from . import models from . import serializers class EmployeeViewset(viewsets.ModelViewSet): queryset = models.Employee.objects.all() serializer_class = serializers.EmployeeSerializer serializers.py from rest_framework import serializers from employeeapi.models import Employee class EmployeeSerializer(serializers.ModelSerializer): class Meta: model =Employee fields = '__all__' urls.py from django.contrib import admin from django.urls import path, include from .router import router urlpatterns = [ path('admin/', admin.site.urls), path('api/',include(router.urls)) ] router.py from employeeapi.viewsets import EmployeeViewset from rest_framework import routers router = routers.DefaultRouter() router.register('employee',EmployeeViewset) These … -
Check if the wishlist already exist before creating one of the logged in user in django rest framework
I have a create API that creates a wishlist of a user after the user logged in on the frontend. But before creating one I want to check whether the user already has a wishlist before. For that I wrote a validation function but its not working. Error:TypeError: int() argument must be a string, a bytes-like object or a number, not 'collections.OrderedDict My view: class WishListAPIView(ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = WishList.objects.all() serializer_class = WishListSerializer def perform_create(self, serializer): user = self.request.user serializer.save(owner=user) My serializers: class WishListSerializer(serializers.ModelSerializer): def validate(self, owner): abc = WishList.objects.filter(owner=owner).exists() if abc: raise serializers.ValidationError('Wishlist exists.Now add items') return owner class Meta: model = WishList fields = '__all__' depth = 1 My model: class WishList(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) # item = models.ManyToManyField(Product,blank=True, null=True) def __str__(self): return self.owner.email My urls: path('api/createwishlist/<int:pk>', views.WishListAPIView.as_view(), name='api-wishlist'), -
getting 'name' is an invalid keyword argument (using graphene-django)
i am using graphene and getting 'name' is an invalid keyword argument for GuestMutation error what is it related to? //models.py class Guest(models.Model): name = models.CharField(max_length=100) phone = models.IntegerField() def __str__(self): return self.name //schema.py class GuestType(DjangoObjectType): class Meta: model = Guest fields = ('id','name','phone') class GuestMutation (graphene.Mutation): class Arguments: name = graphene.String(required=True) phone = graphene.Int(required=True) guest = graphene.Field(GuestType) @classmethod def mutate(cls, root,info,name,phone): guest = Guest(name=name, phone=phone) guest.save() return GuestMutation(name=name, phone=phone) class Mutation(graphene.ObjectType): add_guest = GuestMutation.Field() error message Traceback (most recent call last): File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/promise/promise.py", line 489, in _resolve_from_executor executor(resolve, reject) File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/promise/promise.py", line 756, in executor return resolve(f(*args, **kwargs)) File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise return next(*args, **kwargs) File "/home/ahmed/Documents/Django/Shalleh/booking/schema.py", line 66, in mutate return GuestMutation(name=name, phone=phone) File "/home/ahmed/Documents/Django/Shalleh/my-project-env/lib/python3.8/site-packages/graphene/types/objecttype.py", line 169, in init raise TypeError( graphql.error.located_error.GraphQLLocatedError: 'name' is an invalid keyword argument for GuestMutation -
AJAX way of handling filters in a Django based ecommerce application is not working upon copy pasting the url in new tab
So I ran into this problem two days back and still haven't got a proper solution. I would highly Appreciate any help in here. Let me explain the scenario first, so the idea is I have one django based ecommerce site and I want to render the product showcase page through ajax call (without reloading) and same time also update the url as the selected filters for example (http://vps.vanijyam.com:8000/customerlist?category=category_1). I want to achieve similar to this site - shutterstock. My Scenario - http://vps.vanijyam.com:8000/customerlist this page to showcase all the available products and also have the filters option and pagination. Now when I change the page or apply some filter I am e.g. http://vps.vanijyam.com:8000/customerlist?category_slug=category_1 then it is working, but when I refresh the page it is not.. the reason behind this the way I am handling this ajax call in the backend. def customer_categories(request): # Get attributes from request url current_page = request.GET.get('page' ,'1') category_slug = request.GET.get('category_slug') sortby_filter = request.GET.get('sortby_filter') price_filter = request.GET.get('price_filter') search_query= request.GET.get('term') line_filter_min = request.GET.get('price_min') line_filter_max = request.GET.get('price_max') # Set limit and offset for queryset limit = REQUEST_PER_PAGE * int(current_page) offset = limit - REQUEST_PER_PAGE categories = Category.objects.all() # products = Product.objects.filter(available=True)[offset:limit] # limiting products based on current_page … -
Why psycopg2 keep spitting out this error?
I'm very newbie at deploying stuff to somewhere. I'm working on deploying django rest api and react app to my ec2 instance. The instance is Ubuntu 20.04.2 LTS focal. This is my project scheme backend \-backend(folder) \-core(folder) \-todos(folder) \-uploads(folder) \-users(folder) \-db.sqlite3 \-Dockerfile \-manage.py \-Pipfile \-Pipfie.lock frontend \-assets(folder) \-public(folder) \-src(folder) \-Dockerfile \-gulpfile.js \-package-lock.json \-package.json \-tailwind.config.json webserver \-nginx-proxy.conf docker-compose.yml I made an dockerfile for the django rest api, and this is what it looks like. backend/Dockerfile FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 ... ARGs and ENVs ... RUN mkdir /backend WORKDIR /backend RUN pip3 install pipenv COPY . /backend/ RUN pipenv install --python 3.7 RUN python manage.py makemigrations RUN python manage.py migrate But when I'm trying to do sudo docker-compose up at my ec2 instance, it spits out the error at RUN pipenv install. It spits out the error while locking Pipfile.lock. This is what error looks like. [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/cli/command.py", line 253, in install [InstallError]: site_packages=state.site_packages [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 2063, in do_install [InstallError]: keep_outdated=keep_outdated [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 1312, in do_init [InstallError]: pypi_mirror=pypi_mirror, [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 900, in do_install_dependencies [InstallError]: retry_list, procs, failed_deps_queue, requirements_dir, **install_kwargs [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line 796, in batch_install [InstallError]: _cleanup_procs(procs, failed_deps_queue, retry=retry) [InstallError]: File "/usr/local/lib/python3.7/site-packages/pipenv/core.py", line … -
How to receive notifications from PostgreSQL table in Python
I'm using psycopg2 for Postgres in python and want notifications and row data when the DateTime column data matched with the current time from the Postgres table. I can do this with a scheduler that is run on x seconds interval and get the rows that are matched with the current time, but it is the worst solution. So, I have to get Listen/Notify in Postgres which is notified when some new changes occurred in the table. Is it possible to get this scenario from Listen/Notify? An alternative solution will be appreciated. -
django: im trying to add checked value and line through to a completed task in to-do list app
Im trying to add checked value and line through to a completed task in to-do list app, i have a div element that have the class completed which is styled in css to strikethrough and a checked attribute in the checkbox element. So inside my html template, i created a for loop to loop through all the todos and check if a todo with attribute completed(an attribute of todo object in model.py) is true, then if it is, the todo(attribute of todo object in model.py) should be place within the element with the class completed and the checked checkbox. And if it is not true, it should be placed within the elements without the completed and checked class. but it rendered the html and it didnt apply the effect to it, despite the fact that there are some todo which their (completed) attribute is set to true in the admin panel This is my html template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'Todoapp/css/style.css' %}"> <link rel="stylesheet" href="{% static 'Todoapp/fontawesome/css/all.min.css' %}"> <title>Todo</title> </head> <body> <div class="container"> <div class="wrapper"> <div> <div class="header"> <h3><i class="fa fa-tasks fa-white … -
Passing a Django Statement or Accessing specific query set index
I am trying to return the number of threads and posts that belong to that specific forum. The structure is like this: Category -> Forum -> Thread. I want to query the database for all threads and posts that belong to that Forum. This is my current code: Models.py class Forum(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='forums') def __str__(self): return self.name class Thread(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) thread_forum = models.ForeignKey(Forum, on_delete=models.CASCADE) def __str__(self): return self.name class Post(models.Model): post_body = models.TextField(blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) post_date = models.DateTimeField(auto_now_add=True) post_thread = models.ForeignKey(Thread, on_delete=models.CASCADE) def __str__(self): return str(self.id) + ' | ' + str(self.author) Views.py class HomeView(ListView): context_object_name = 'name' template_name = 'index.html' queryset = Category.objects.all() def get_context_data(self, *args, **kwargs): context = super(HomeView, self).get_context_data(*args, **kwargs) context['thread_count'] = Thread.objects.all().count() context['post_count'] = Post.objects.all().count() context['user_count'] = User.objects.all().count() context['categorys'] = Category.objects.all() context['newest_user'] = User.objects.latest('username') return context index.html {% for forum in category.forums.all %} <div class="container-fluid category-forums clearfix"> <!-- 3 red --> <div class="container-fluid category-forums-wrap d-flex align-items-center"> <!-- 4 green --> <div class="container-fluid forum-details-wrapper clearfix"> <div class="container-fluid forum-details-container"> <p class="forum-name"><a href="{% url 'threadlist' forum.pk %}">{{ forum.name }}</a> </p> <p class="forum-desc">{{ forum.description }}</p> <div class="sub-forum-container container clearfix"> … -
how to create multiple/different types of signup forms in `django-allauth` for respective multiple/different types of users
I have searched high and low and none of the solutions I have found work. Using django-allauth how can I create and use multiple types of signup forms specific to respective multiple types of users? Here are some posts that I've looked at: Suggest using SignupForm which @pennersr advises against, and Same solution and same problem, and response related to customizing a form but not multiple from @pennersr, and suggested link from @pennersr that provides some helpful info but again not specific to multiple forms, and lastly this thread Does anyone have the solution to this? Is it possible? I have one form, view and template that works as intended. The following works for 1 django-allauth signup form settings.py #assign to custom form ACCOUNT_SIGNUP_FORM_CLASS = 'users.forms.GeneralSignupForm' forms.py #django-allauth extends SignupForm by default so the following forms are simply adding additional fields that SignupForm does not include class GeneralSignupForm(forms.Form): first_name = forms.CharField(max_length=255, help_text="Your first name") last_name = forms.CharField(max_length=150, help_text="Your last name") phone = forms.CharField(max_length=150) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.phone = self.cleaned_data['phone'] user.save() views.py class GeneralSignupView(SignupView): template_name = 'account/signup.html' form_class = GeneralSignupForm redirect_field_name = 'next' view_name = 'signup' success_url = None def get_context_data(self, **kwargs): data = … -
I want to make cards responsive. but in django
image 1 image 2 the cards goes horizontally i want it to go down vertically when the card goes off screen. This is a project of django so im looping over a div but the card is going off the screen horizontally i want it to go vertically when the card goes off the screen. PYTHON CODE [HTML] ` <div class="container"> {% for project in projects %} <div class="items"> <h2>{{project}}</h2> <div class="purl"> <p>{{project.description}}</p> </div> <div class="purl1"> <a href='{{project.url}}'>{{project.url}}</a> </div> <div class='buttons'> <a class='btn' href='{% url "update" project.id %}'>Edit</a> <a style='background-color:#f25042' class='btn' href='{% url "delete" project.id %}'>Delete</a> </div> </div> {% endfor %} </div> ` CSS ` .container{ display:flex; } .purl{ text-overflow: hidden; padding-right:.1em; } .purl1{ max-width:20em; margin-right:14px; } .items{ border-radius: 8px; padding:1em 1.5em .5em 1.4em; box-shadow: 0px 0px 17px 0px black; margin:5% 1em 2em .5em; width:100%; } .items h2{ color:#fffffe; } .items p{ color:#94a1b2; } a{ text-decoration: none; color:#7f5af0; } a:hover{ text-decoration: none; color:#fffffe; } .buttons{ display:flex; } .btn{ float:left; text-align: center; font-size:17px; font-weight:bold; padding:.5em; margin:2em 1em .5em 1em ; width:3.5em; border:none; border-radius: 8px; background-color: #2cb67d; color:#fffffe; font-family: 'Noto Sans', sans-serif; } .btn:hover{ background-color: #3dd696; cursor: pointer; } @media only screen and (max-width: 800px) { .container{ margin-left:10%; display:block; } .items{ width:60%; … -
Python Django OpenCV TensorFlow deploy current = current[int(bit)]
I want to deploy a project to azure that contains tensorflow and opencv however i'm getting this error below, i hope someone can help me, i already added the path of the video_feed at urls.py on project Exception while resolving variable 'name' in template 'unknown'. Traceback (most recent call last): File "/antenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/antenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 165, in _get_response callback, callback_args, callback_kwargs = self.resolve_request(request) File "/antenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 288, in resolve_request resolver_match = resolver.resolve(request.path_info) File "/antenv/lib/python3.8/site-packages/django/urls/resolvers.py", line 576, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLPattern list> (admin:admin) 'admin/'>], [<URLResolver <module 'streamapp.urls' from '/home/site/wwwroot/streamapp/urls.py'> (None:None) ''>, <URLPattern '' [name='index']>], [<URLResolver <module 'streamapp.urls' from '/home/site/wwwroot/streamapp/urls.py'> (None:None) ''>, <URLPattern 'video_feed' [name='video_feed']>], [<URLResolver <module 'streamapp.urls' from '/home/site/wwwroot/streamapp/urls.py'> (None:None) ''>, <URLPattern 'video' [name='video']>], [<URLPattern 'video_feed' [name='video_feed']>]], 'path': 'robots933456.txt'} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/antenv/lib/python3.8/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] TypeError: 'URLResolver' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/antenv/lib/python3.8/site-packages/django/template/base.py", line 837, in _resolve_lookup current = getattr(current, bit) AttributeError: 'URLResolver' object has no attribute 'name' During handling of the above exception, another exception … -
Getting 'undefined' when accessing item in an array returned from Django Rest Framework via AJAX
I am trying to access data in an array returned from an AJAX GET Request to Django Rest Framework. However, I keep getting undefined, I can console log the data and see what I am trying to target with my index numbers but I am having no luck. I also tried using JSON.parse() but this just threw an error. For visualisation here is what the console.log prints:https://ibb.co/9y8CBw9 Here's what I've got for my Javascript: document.querySelector('#userLists').addEventListener('click', function(event) { if (event.target.dataset.name) { var listname = event.target.dataset.name console.log(listname); getTableData() } }) const getTableData = function(){ $.ajax({ type: 'GET', url: '/api/uservenue/', data: {}, success: function (data) { data.forEach(item => { console.log(item.venue) }) fillTable(data) } }); }; function fillTable(data) { console.log(data) const table = document.getElementById("dashboardTableBody"); let row = table.insertRow(); let name = row.insertCell(0); name.innerHTML = data[0][1]; } Here is my serializers from DRF: class mapCafesSerializer(serializers.ModelSerializer): class Meta: model = mapCafes fields = ['id', 'cafe_name', 'cafe_address', 'description'] class UserVenueSerializer(serializers.ModelSerializer): venue = mapCafesSerializer() class Meta: model = UserVenue fields = ['id', 'list', 'venue'] And these are the pertinent models: class UserVenue(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) list = models.ForeignKey(UserList, on_delete=models.PROTECT) class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation … -
How do I make highly scalable chat app with django?
I am currently using ajax , on set interval page would refresh giving a real time feel but i fear on long run if if it scale will clients have the problem, as page refresh every second I think it may overload server, which is the best option for a real time chat app using django, except redis(not free and it has limit) The app should be scalable upto 1000 concurrent connections Server is vps with 4 core 4gb ram and 4tb bandwidth -
How do I fix the ssl module for my Digital Ocean droplet?
I have completed a project I have been working on for quite a while that is a Django-React app. My Django-React app only works with Python 3.6. I have been following a guide to deploy my Django-React app to a Digital Ocean droplet server. I have been following the guide found at this link. I am using a video to guide me, so this is why this guide is using some slightly older versions of Ubuntu, etc., but this shouldn't be an issue. When I follow this guide, I come into the issue that I am automatically using the newest version of Python. It took me many hours but I was eventually able to download Python version 3.6 onto this server... I have been able to get through most of the guide I linked. I have gotten to the point where I create my virtual environment, but in my case I use pipenv instead of virtualenv because this is what I'm used to. So I will explain my problem with the following details: I enter my virtual environment with pipenv shell. I run django-admin --version: The command-line responds: 3.1.6. I run python3.6 -V: The command-line responds: Python 3.6.0. I run …