Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to iterate over a model in Django with class based views but getting the error Project object is not iterable
I used the following code for models.py class Project(models.Model): name = models.CharField(max_length=20,null=True) description = models.TextField(null=True) clientid = models.ForeignKey(Client, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): # new return reverse('projectdetail', args=[str(self.id)]) This is the code for views.py class ProjectDetailView(DetailView): model = Project template_name = 'projectdetail.html' fields='__all__' And this is the template i am using {% extends 'base.html' %} {% block content %} {% if project %} There are {{ project|length }} records: {% for i in project %} <div class="project-entry"> <h2>{{ i.id }}</h2> <p>{{ i.name }} </p> <p>{{ i.description }} </p> <p>{{ i.clientid }} </p> {% endfor %} {% else %} There are no records in the system {% endif %} </div> {% endblock content %} I get the error TypeError at /client/1/projectexisting 'Project' object is not iterable Request Method: GET Request URL: http://02ccd1dfc89b4b71b62f894adef16c07.vfs.cloud9.us-east-2.amazonaws.com/client/1/projectexisting Django Version: 2.1 Exception Type: TypeError Exception Value: 'Project' object is not iterable Exception Location: /home/ec2-user/.local/lib/python3.7/site-packages/django/template/defaulttags.py in render, line 165 Python Executable: /usr/bin/python3 Python Version: 3.7.10 Python Path: ['/home/ec2-user/environment/cons_mgmt/cons_mgmt', '/usr/lib64/python37.zip', '/usr/lib64/python3.7', '/usr/lib64/python3.7/lib-dynload', '/home/ec2-user/.local/lib/python3.7/site-packages', '/usr/local/lib64/python3.7/site-packages', '/usr/local/lib/python3.7/site-packages', '/usr/lib64/python3.7/site-packages', '/usr/lib/python3.7/site-packages'] Server time: Tue, 20 Jul 2021 19:55:29 -0600 Error during template rendering In template /home/ec2-user/environment/cons_mgmt/cons_mgmt/templates/base.html, error at line 6 'Project' object is not iterable I am able to see data … -
Django Invalid Filter
I'm getting the following error message from my API request: { "errors": [ { "detail": "invalid filter[branch]", "status": "400", "source": { "pointer": "/data" }, "code": "invalid" } ] } I'm struggling with this since is have other ViewSets which follow the same structure but won't break once I try to filter by an FK. Below is the endpoint I'm hitting: http://localhost:8000/templates/?page[number]=1&filter[branch]=7KzZ5vLWlydlNbG&filter[name]=Client%20Portal%20Invitation For context I have a backend using Django DRF JsonAPI. It is structured as follow: Model: class Template(BaseModel): id = HashidUnsignedAutoField(db_column="template_id", primary_key=True, salt="Template", min_length=11) branch = ForeignKey(to="Branch", on_delete=DO_NOTHING) name = CharField(max_length=128) class Meta(BaseModel.Meta): db_table = "Templates" managed = False Serializer: class TemplateSerializer(BaseSerializer): included_serializers = { "branch": "app.serializers.BranchSerializer", } class Meta(BaseSerializer.Meta): model = Template ViewSet: class TemplateViewSet(BaseViewSet): queryset = Template.objects.all() serializer_class = TemplateSerializer filterset = TemplateFilterSet Filterset: class TemplateFilterSet(BaseFilterSet): class Meta: model = Template fields = { "branch": ["exact", "in"], "name": ["exact"], } Any hints on why would I be getting this error message would be greatly appreciated. -
redirect errot - NoReverseMatch: Reverse for 'edit' with keyword arguments '{'title': 'Python'}' not found
I'm working on an app that allows the user to create, show and edit an entry. right now i'm working on the editing function. what i'm trying to do is have an edit button (that's actually a form that sends data via hidden inputs) that sends the title of the entry to a view called trans whose sole purpose is redirect to the edit view, the reason i did this is so that when i'm working on the edit view, i can simplify the process where if the request method is GET it shows the page with the form where the user can edit the entry and if it's post the edit view can receive the changes and save them without worrying about the redirecting from the entry's page. The problem lies in the fact that everytime i click the edit button i get the error: NoReverseMatch at /wiki/trans Reverse for 'edit' with keyword arguments '{'title': 'Python'}' not found. I have checked over and over for any misspellings or issues in urls.py or any problems with the naming but i just can't find the bug. and it's frustrating because i thought that this would be the easiest part of the … -
Django parsing values of fields in models - Extracting pk
I'm completely lost on part of my Django website. I finally figured out a way to have the same model create a template and then use that template and create another post. This works and is ideal. Now I need to put them in different locations on the screen so I basically need two for-loops and a way to decipher the two(templates and posts off of templates) apart from each other. The model has a title and a content field. When a template is created the title always starts with "Temp: ". I'm completely lost on this because I need to parse through the model and not just use an HTML parser because the content won't already be on the page and there is more than just the title that needs to be moved. I need a way I think in the views.py file to get the pk of ALL titles that start with "Temp: " and the content field tied with it and return it in a variable to the HTML file. I have been working on this for 3 days now and I just really need help. -
NOT NULL constraint failed: KNB_balance.user_id Django
I'm trying to update a value that's stored in the database from views.py, I can't get form.save() to work I keep getting this error, I don't understand what's the problem and if Im going about this all wrong can you explain to me how I can update the value in the database by using user's input in views. Views.py def deposit(request): form = DepositForm(request.POST or None) pk = request.session.get('pk') if pk: user = CustomUser.objects.get(pk=pk) balance = user.balance code_user = f"{user.username}: {user.balance}" if not request.POST: balance.save() print(balance.number) if request.method == "POST": if form.is_valid(): print(balance.number) balance.number = balance.number + 5 print(balance.number) form.save() return redirect('home-view') return render(request, 'deposit.html') Models.py class Balance(models.Model): number = models.IntegerField(blank=True, null=True) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) def __int__(self): return int(self.number) def save(self, *args, **kwargs): number_int = 500 self.number = number_int super().save(*args, **kwargs) forms.py class DepositForm(forms.ModelForm): number = forms.IntegerField(label='balance',help_text='Please enter your deposit amount') class Meta: model = Balance fields = ('number',) HTML FIle {% load crispy_forms_tags %} {% load static %} {% block content %} <form method="POST" action="#"> {% csrf_token %} {{ form }} <input id="number" type="number" name="number" placeholder="Deposit amount"> <button type="submit" class="hero-btn sbmt">Deposit</button> </form> </div> {% endblock %} -
ERROR: Could not install packages due to an EnvironmentError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443)
I have a Python 3.7 Django project, and I am trying to generate a PDF using ReportLab and WeasyPrint. I ran into an issue while installing WeasyPrint, and since attempting to install it I have received the same error message while trying to install any pip install in new virtual environments. This issue has persisted for two weeks now, please help! Versions and Pip List, all of these were installed during the same day without issue, reportlab was installed without error seconds before I attempted to install WeasyPrint. image-1 These are the versions and the current pip list.. everything else installed normally up to this point without issues. The Project also runs without error, with the exception of needing to build out this aspect. Here is the error that happened when running the pip install WeasyPrint. image-2 I also attempted to switch gears and use other solutions but now every pip install I run, even in new environments returns this error. I'm guessing it's an actual permissions issue on my computer? And I have no idea what that means and where to start trouble shooting that if that's my issue. -
Django - how to display related many-to-many field in choice field?
I’m building a web app using Django for my music collection. For each album, there are multiple songs, and each song has one or more composers. Here’s the song model: class Song(models.Model): title = models.CharField(max_length=50) composer = models.ManyToManyField(Artist) class Meta: ordering = ['title'] def __str__ (self): return self.title The Artist model contains firstname and lastname fields. There are a number of occurrences of songs with the same title, and the only way to distinguish between them is by the composer. Currently, when songs are loaded into a choice field, only the title appears, using def__str. I’ve tried to include the composers, but haven’t found a way to make it work. Any suggestiions? -
python dictionary value is getting printed on a line but not getting printed on another line in django
I am new to django and using python version 3.8 In my index.html, I am trying to display the products and their info using for loop as below: {% for prod in products %} <footer class="card-footer"> <span id="atc_prod_{{ prod.product_id }}" class="atc_prod">prod_{{ prod.product_id }} <button class="button is-info is-small card-footer-item cart" id="prod_{{ prod.product_id }}">Add to Cart</button> </span> <a href="/shop/products/{{ prod.product_id }}"><button class="button is-small is-info card-footer-item cart" id="qv{{ prod.product_id }}">Quick View</button></a> </footer> {% endfor %} Structure of products list is as below: products = [ {'id':'1', 'name':'A'}, {'id':'2', 'name':'B'}, {'id':'3', 'name':'C'} ] Same prod.product_id is getting used in 3 places (span - id, button - id and a - href) but for few products (2 out of 5), id is blank. Refer screenshot below of HTML: I do not know the reason, please suggest. Also, please let me know if I missed any of the important info. Thanks in advance. -
I have problem Page not found (404) Django
import jobs.views urlpatterns = [ path('admin/', admin.site.urls), path('nick', jobs.views.nick, name='nick'), ] enter code here def nick(request): return render(request, 'jobs/nick.html') I got: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/nick/ -
Bootstrap 5 card footer not staying at the end of the page
I am still new to creating websites with Bootstrap and have come across an issue with adding a footer to my base.html template in Django. What I want is that the footer stays at the end of page and shows when I scroll to the end of that page. Here is my base.html code: {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Vlereso Profesorin</title> <!-- Bootstrap --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <!-- Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <!-- Google Font --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap" rel="stylesheet"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'vleresoprofesorin/css/master2.css' %}"> <link rel="stylesheet" href="{% static 'css/master.css' %}"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light mynav"> <div class="container-fluid"> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav leftnav"> <li class="nav-item"> <a class="navbar-brand" href="{% url 'home' %}">Kreu</a> </li> <li class="nav-item dropdown"> <a class="navbar-brand dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Universitetet</a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Universiteti i Tiranës</a></li> <li><a class="dropdown-item" href="#">Universiteti Politeknik i Tiranës</a></li> <li><a class="dropdown-item" href="#">Universiteti i Mjekësisë, Tiranë</a></li> <li><a class="dropdown-item" href="#">Universiteti i Sporteve të Tiranës</a></li> <li><a class="dropdown-item" href="#">Universiteti i Arteve Universitet</a></li> <li><a class="dropdown-item" href="#">Universiteti Bujqësor i Tiranës</a></li> … -
TypeError in heruko django
i wanna develop a Django project in Heroku but I have error. I Have Did everything that it Needs but still this Error Template error: In template /app/templates/base/Main_Layout.html, error at line 0 serve() missing 1 required positional argument: 'path' 1 : <!DOCTYPE html> 2 : <html lang="en"> 3 : {% load render_partial %} 4 : <head> 5 : {% include 'base/header_reffrences.html' %} 6 : <title> 7 : {% block title %} 8 : {% endblock %} 9 : </title> 10 : </head> Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/app/.heroku/python/lib/python3.9/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 938, in render bit = node.render_annotated(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/base.py", line 905, in render_annotated return self.render(context) File "/app/.heroku/python/lib/python3.9/site-packages/django/template/loader_tags.py", line … -
I am using filtering in django and it doesn't work
I am using filtering in Django and it is appearing on my website but doesn't do anything, and some of my fields I can't access to filter. def Books(request): Books = Book.objects.all() myFilter = BookFilter(request.GET, queryset=Books) Books = myFilter.qs context = {'pro':Book.objects.all(), 'myFilter':myFilter} return render(request, 'pages/Books.html', context) books.models class Book(models.Model): name = models.CharField(max_length=50) ISBN = models.IntegerField(max_length=20) image = models.ImageField(upload_to = 'photos/%y/%m/%d') stat = models.BooleanField(default=True) pubYear = models.IntegerField(max_length=4) author = models.CharField(max_length=50) categ = models.CharField(max_length=50) the fields (stat,pubYear) shows in the filter on the website but they are unwritable. -
Django -- Converting function views to class based views for TMDB API request
I'm using function views to generate render an output using the tmdb api I'm familiar with the basics on class based views. How would I write the following api request code into a TemplateView? Example output Views.py from django.shortcuts import render import requests # Create your views here. def index(request): # Query API with user input if 'movie' in request.GET: api_key = 'api' id = request.GET['movie'] url = 'https://api.themoviedb.org/3/search/movie?api_key={}&language=en-US&query={}&include_adult=false' response = requests.get(url.format(api_key,id)) # successful request if response.status_code == 200: # Parse json output for key value pairs tmdb = response.json() # backdrop image -- tmdb for each movie backdrop_path = tmdb['results'][0]['backdrop_path'] url_backdrop = 'https://image.tmdb.org/t/p/original'+backdrop_path # poster image -- tmdb for each movie poster_path = tmdb['results'][0]['poster_path'] url_poster = 'https://image.tmdb.org/t/p/original'+poster_path context = { 'title': tmdb['results'][0]['original_title'], 'overview': tmdb['results'][0]['overview'], 'release_date': tmdb['results'][0]['release_date'], 'vote_average': tmdb['results'][0]['vote_average'], 'vote_count': tmdb['results'][0]['vote_count'], 'backdrop_path' : tmdb['results'][0]['backdrop_path'], 'backdrop' : url_backdrop, 'poster' : url_poster } return render(request, 'home.html', {'context': context}) else: # returns homepage if invalid name is given in form return render(request, 'home.html') else: # Homepage without GET request return render(request, 'home.html') -
I want to use Django with Asp.net only database
I want to create a Django project where I can apply my machine learning and later want to sync it with Asp.net project which is already created, the only thing that I am interested in is the Database, and to be more specific only with a single table. Basically, I want to enter some data in my machine learning algo which on basis of that will return a specific value, and on basis of that value, I want to fetch certain records from the database. Can anyone guide me that is it possible? If yes then how. -
how do I run a function in django-admin?
I'm programming a project, and i need a way to run a function every time i access django admin. this function change some things in the DB, and if you know an easy way for it, i'll be happy. a thing like a function that run every time the database changes. thanks -
Celery/Django/Redis task getting executed multiple times
In my current project, what I need to do is to get data from 700+ endpoints and then send that data to another 700+ endpoints. My approach is to use Django Celery Redis, Put 70+ endpoints on each worker so that there are approx 10 workers which will retrieve the data and then post the data. For this, I am using Chord to do the parallel task and then calculate the time it takes. The problem is that Celery is running the same task multiple times. task_get_data is the main method that first gets the list of websites then splits it into groups of 70 each and then calls task_post_data using Chord. In the output below you can see website_A, website_B etc. multiple times, I have manually checked my data and everything and there is no repetition of websites but when the celery task is submitted, multiple entries are created. Also, Is there any way to monitor the number of workers and what are they processing? Below is the code os.environ.setdefault('DJANGO_SETTINGS_MODULE','django_backend.settings') app = Celery('django_backend', backend='redis://localhost:6379', broker='redis://localhost:6379') app.config_from_object('django.conf:settings', namespace='CELERY') # app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) def post_data(json_obj, website): for items in json_obj: md = md + items['data'] n … -
How to write a real self-contained Django app?
They say Django apps should be self-contained. I find it hard to implement. My website has 3 apps. All have their own static and templates folders. But — like many other sites — they share same front-end design. The problem is, I have a very small form at the footer of each page to sign up for my newsletter. First, I have to define the database model in one of apps, which means the other two rely on that one. Second, the view to update the database should be defined in an app — naturally, the same app that defines the model — which again means the other two have to call that view. So, app1 provides the model and view, app2 and app3 use them; so they are not self-contained. Isn't this against the philosophy? -
How to change Django Builtin dev Server inside a Docker container?
The Django builtin Development Server has the "feature" of filtering out HTTP Headers containing underscores: https://github.com/django/django/blob/7785e03ba89aafbd949191f126361fb9103cb980/django/core/servers/basehttp.py def get_environ(self): # Strip all headers with underscores in the name before constructing # the WSGI environ. This prevents header-spoofing based on ambiguity # between underscores and dashes both normalized to underscores in WSGI # env vars. Nginx and Apache 2.4+ both do this as well. for k in self.headers: if '_' in k: del self.headers[k] return super().get_environ() For development purposes, i'd like to comment out this for loop. I run Django inside a Docker container. How can I comment out these lines when building the image? -
How can I migrate changes from views.py in an app in Django?
I just started with Python/Django this week. I've been following the freeCodeCamp 4 hour course in youtube(https://www.youtube.com/watch?v=F5mRW0jo-U4&t=3885s). I didn't have any problem creating the virtual enviroment, the project and other apps that hold database models. However, at around the hour and 4 minutes mark of the video, the very same code the teacher is displaying in the video throws me an error. He creates a new app called "pages" and in the views.py script codes this function from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home_view(): return HttpResponse('<h1>Hello World</h1>') Then the pages app is included in the INSTALLED_APPS array, in the settings scripts INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', ] The problems comes when I try to migrate the changes from pages. The 'python manage.py makemigrations' followed by the 'python manage.py migrate' commands don't detect any change in the views.py script of any of the apps, so when I try to import those views in the urls.py file, it throws an error. I don't know how to make the changes in views noticeable for the manage.py, so it can migrate them. Ive been looking in the documentation and in StackOverflow, … -
For loop on form not functing properly
I have a feature that allows users to upload multiple images to their blog but it is not working correctly. When a user uploads multiple images only one of them is uploaded to the postgres db. view def DetailPostView(request, pk): model = Post post = Post.objects.get(pk=pk) form = CommentForm if request.method == 'POST': test = PostImagesForm(request.POST, request.FILES) files = request.FILES.getlist('images') if test.is_valid(): for f in files: instance = test.save(commit=False) instance.post = Post.objects.get(pk=pk) instance.save() else: print(instance.errors) postgallery = PostImages.objects.filter(post_id=post) #########ignore############ comments = Comment.objects.filter(post=post)#.order_by('-create') buildlogs = BuildLog.objects.filter(post_id=post) if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.author = request.user new_comment.post = post new_comment.save() context = { 'post':post, 'form':form, 'comments':comments, 'buildlogs':buildlogs, 'PostImagesForm':PostImagesForm, 'postgallery':postgallery } return render(request, 'blog/post_detail.html', context) form class PostImagesForm(ModelForm): class Meta: model = PostImages fields = ('images',) widgets = { 'images': forms.ClearableFileInput(attrs={'multiple': True}), } you can see i am getting the list of files via the files = request.FILES.getlist('images') then running a for loop on the contents. If I break the code in the stack trace I can see that the two files are in the list so i am very confused on why it is not properly iterating though the list and … -
large json data in django model slows down any query
I have a django model that looks like this: class SomeModel(Model): some_field = CharField(max_length=10) large_data = JsonField(blank=True, null=True) the "large_data" field can get really large, like 150mb. I know this is really bad practice, most of the data could decoupled into other sql database tables, but this is legacy application and the impact of the rework would be huge. It turns out that any query to this table is really slow, sometimes I just want to modify the "some_field" value, but even when I save that field individually like in the code below, the update query takes ages obj.some_field = "ice cream" obj.save(update_fields=["some_field"]) I am sure the large_data is the guilty because if I set its value to "None" then the save operation is committed right away. Are there optimization tricks that can be applied to my example without reworking the json field? Thanks in advance -
Django-rest framework "This field is required." with no empty fields
I'm tying to setup a basic API following the quickstart on https://www.django-rest-framework.org/tutorial/quickstart/ GET request are working but when I try to POST from the django-rest framework UI i get the following error. Data I want to post: { "name": "3", "description": "3", "price": 3, "speed": "3" } Answer I get from django-rest framework: (price field has default=0, anyhow it won't get the value posted) { "name": [ "This field is required." ], "description": [ "This field is required." ], "speed": [ "This field is required." ] } My serializer: class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ['name','description','price','speed'] My viewset: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } Models.py class Product(models.Model): name = models.CharField(max_length=100,null=False,unique=True) description = models.CharField(max_length=250,null=False) price = models.IntegerField(default=0) # price in cents speed = models.CharField(max_length=50,null=False) def __str__(self): return self.name def get_display_price(self): return (self.price / 100) class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' Urls.py router = routers.DefaultRouter() router.register(r'products', ProductViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('orders/', include('orders.urls')), path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] Any help would be appreciated and please Let me know if I should add more code -
django and node js integrate
Hello I don't know if this is a silly question or not. I'm planning to build a chat and live streaming app, I'm a Django developer, but it would be nice to include Node in this. Django will assign and register clients, node js will take care of the data in real time, but I ended up thinking about creating a request from React to Django, then sending Django a request to Nod and then to React. This is very expensive and there is no data allocation here. All clients will have all directories, and React will filter each person's data individually Node js server let express = require('express'); let cors = require('cors'); let http = require('http'); let bodyParser = require('body-parser'); let path = require('path'); const port = 9000; app = express(); const server = http.createServer(app).listen(port, () => {}); const { Server } = require('socket.io'); const io = new Server(server, { cors: { origin: 'http://localhost:3000', methods: ['GET', 'POST'], allowedHeaders: ['my-custom-header'], credentials: true, }, }); app.use(cors()); app.use(express.static(path.join(__dirname, 'client'))); app.use(bodyParser.json()); app.post('/server', (req, res) => { io.emit('command', req.body); console.log(req.body); res.status(201).json({ status: 'reached' }); }); io.on('connection', (socket) => { socket.on('command', (data) => { io.emit('command', data); console.log(data); }); }); Django Request def handelRequest(serializer): notification = … -
django form 'str' object has no attribute 'id' when passing a list of choices
I am creating a form where the view passes a list to the form and this list is used to create choices. The choices seems to be created correctly, but I get an error 'str' object has no attribute 'id' I first learned how to pass the list using this: Django pass list to form to create Choices models.py class Grade(models.Model): """Each time a new score is added we create a grade object to track history of grades""" score = models.CharField( max_length=3, choices=PROFSCALE, blank=True, default=INCOMPLETE) assessment = models.ForeignKey( Assessment, on_delete=models.CASCADE, null=True, blank=True) objective = models.ForeignKey( Objective, on_delete=models.CASCADE, blank=True) student = models.ForeignKey(Student, on_delete=models.CASCADE) cblock = models.ForeignKey(Classroom, on_delete=models.CASCADE, default=1) time_created = models.DateField( auto_now=False, auto_now_add=False, default=timezone.now) class Objective(models.Model): """The gradebook is graded agains learning objectives""" course = models.ForeignKey(Course, on_delete=models.CASCADE) objective_name = models.CharField(max_length=10) objective_description = models.CharField(max_length=30) def __str__(self): return self.objective_name forms.py class SingleGradeForm(forms.Form): """ form for adding in one single grade for a student. """ SCORE_CHOICES = ( ("IN", "I"), ("BE", "BEG"), ("DV", "DEV"), ("AP", "APP"), ("EX", "EXT"), ) score = forms.ChoiceField(choices=SCORE_CHOICES) objective = forms.ChoiceField(label='Learning Objectives', choices=[]) time_created = forms.DateField(widget=forms.TextInput( attrs={'type': 'date'}), label='Assessment Date') # from https://stackoverflow.com/questions/53177528/ def __init__(self, objs=None, *args, **kwargs): super(SingleGradeForm, self).__init__(*args, **kwargs) if objs: self.fields['objective'].choices = [ (o.id, o.objective_name) for o … -
How to get Django Admin Log Entries from last hour?
In standard Django, the django_admin_log table shows the date and time of changes to the database entries in the action_time column: sqlite> select * from django_admin_log; 1|2021-07-18 21:34:01.312033|6|[6] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 2|2021-07-18 21:47:02.451262|6|[6] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 3|2021-07-18 22:09:42.689067|6|[6] (1960-03-20) Pat Three|[]|8|1|2 4|2021-07-18 22:09:52.292117|6|[6] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 5|2021-07-19 12:21:57.715529|9|[9] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 6|2021-07-19 12:35:22.504624|9|[9] (1960-03-20) Pat Three|[{"changed": {"fields": ["Phy"]}}]|8|1|2 ... more entries I'd like to query the entries based on some comparison, I assumed a naive ansatz could work with filter (as is possible in SQLite itself), so I'd like the Python equivalent of the below SQL statement: sqlite> select * from django_admin_log where action_time > '2021-07-20'; 12|2021-07-20 16:34:00.114548|13|[13] (1960-01-20) Pat Changed|[{"changed": {"fields": ["Family name"]}}]|8|1|2 I thought it would be something along the lines of from django.contrib.admin.models import LogEntry last_hour_changes = LogEntry.objects.filter(last_hour > action_time)