Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: blog image not uploading properly
I'm sure i'm obviouly did something very stupid but, when I try to upload my profile picture on my blog website, even when I add one through admin page, the picture doesn't come up.. so here's what's happening, blog pic the picture right next to Kimmc6008, I should see my image, but somehow failed.. here's the code, I will upload more if needed. models.py class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username class CategoryBlog(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) comment_count = models.IntegerField(default=0) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(CategoryBlog) featured = models.BooleanField(null=True) def __str__(self): return self.title views.py def blog(request): post_list = Post.objects.all() context = { 'post_list': post_list } return render(request, 'blog.html', context) and my html <!-- post --> {% for post in post_list %} <div class="post col-xl-6"> <div class="post-thumbnail"><a href="/post"><img src="{{post.thumbnail.url}}" alt="..." class="img-fluid"></a></div> <div class="post-details"> <div class="post-meta d-flex justify-content-between"> <div class="date meta-last">20 May | 2016</div> {% for cat in post.categories.all %} <div class="category"><a href="#"></a>{{ cat }}</div> {% endfor %} </div><a href="/post"> <h3 class="h4">{{ post.title }}</h3></a> <p class="text-muted">{{ post.overview }}</p> <footer class="post-footer d-flex align-items-center"> <a href="#" class="author d-flex align-items-center flex-wrap"> … -
Sending an email with django custom forms with an attachment and without the need of a database
I am trying to create a vacancy form where applicants can submit their CV. When I submit the form for some reason the file field gets cleared and tell me to attach one. I DO NOT want to include a database in this method of approach as I feel like it may consume space in the database. Is it possible to do that? views.py def contact_us(request): if request.method == "POST": form = ContactUsEmploymentForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') designation = form.cleaned_data.get('designation') expected_salary = form.cleaned_data.get('expected_salary') cv = form.cleaned_data.get('cv') email = form.cleaned_data.get('email') content = form.cleaned_data.get('content') content = f""" WARNING: THIS IS AN EMAIL SENT BY A USER \n First name: {first_name} Last name: {last_name} User's Email: {email}\n Applying for: {designation} Expected salary: {expected_salary} Body: {content} """ send_mail( "Candidate applying for a vacancy", content, 'my_email', ['my_email'], fail_silently=False, ) return render(request, "homepage/email_confirmation.html") else: form = ContactUsEmploymentForm() return render(request, "homepage/contact_us.html", {"form":form}) forms.py class ContactUsEmploymentForm(forms.Form): first_name = forms.CharField(max_length=80) last_name = forms.CharField(max_length=80) email = forms.EmailField() designation = forms.ModelChoiceField(queryset=Vacancy.objects.filter().all()) expected_salary = forms.CharField(max_length=80) cv = forms.FileField() content = forms.CharField(max_length=800, widget=forms.Textarea) and the HTML file <div class="contact_us_container p-2"> <div class="contact_us_wrapper mt-5 mb-2"> <h2 class="font_1 big_font mt-5">Talk to us today!</h2> <div class="container"> <form method="POST"> {% csrf_token %} … -
cant reach static files django-react
I am trying to deploy a Django-React to elastic beanstalk the deploy shows as successfull but only gives me a white empty page,(api calls work properly ). Inspecting /var/log/nginx/error.log shows: 2020/08/06 02:58:06 [error] 4461#0: *11 open() "/var/app/current/staticbundle.js" failed (2: No such file or directory) So I understand it tries to find the bundle.js but on a wrong path,which I dont know how to fix and should look like this: /var/app/current/static/bundle.js I thought it wasn't building properly the static folder , but it does and it ends up like this: current │ └───static │ │ bundle.js │ │ index.html │ └───... this is my project settings Django side: 1.1 settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' 1.2 urls.py from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView urlpatterns = [ path('api/', include('backend.urls')), re_path(r'^.*', TemplateView.as_view(template_name='index.html')), ] 1.3 django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: cerbero.wsgi aws:elasticbeanstalk:environment:proxy:staticfiles: /static/: static/ container_commands: 01_node_install: command: "curl -sL https://rpm.nodesource.com/setup_12.x | sudo bash - && sudo yum -y install nodejs" ignoreErrors: false 02_npm_install: command: "npm install" ignoreErrors: false 03_react_collect: command: "npm run build" ignoreErrors: false 2.WebPack side: - webpack.config.js // webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { … -
Poetry install cannot find the module
I just migrated a library from one git repository to another one, and now poetry install is throwing the following error: - Installing my-lib (0.1.0 7cdc4ec) [ModuleOrPackageNotFound] No file/folder found for package my-lib ERROR: Service 'app' failed to build: The command '/bin/sh -c poetry $poetry_command' returned a non-zero code: 1 This is how the library looks like in my toml file: my-library = { git = "https://git-repository/my-lib", branch = "python3" } I am sure the git credentials are set correctly and I can clone/read the repo and that particular commit shown in the log (alongside other libraries with similar setups). -
Django parallel testing: Test processes incorrectly accessing test databases
I have a Django 3.0.8 project running locally, connected to a local PostgreSQL database (postgres:///myapp). When I run python manage.py test, my unit tests run fine; a test database called test_myapp automatically gets created, and it's correctly accessed. However, when I run python manage.py test --parallel 8, the test fails. I see that 8 cloned databases are correctly generated (test_myapp_1, test_myapp_2,..., test_myapp_8), but I get errors like these: psycopg2.OperationalError: FATAL: database "myapp_3" does not exist It appears that for parallel tests, databases are accessed incorrectly (trying to access the database myapp_N rather than test_myapp_N). I'm trying to figure out if my local config has issues, but this is all I have in my base config: DATABASES = { 'default': env.db('DATABASE_URL', default='postgres:///myapp'), } DATABASES['default']['ATOMIC_REQUESTS'] = True Why are my parallel tests processes not accessing their respective cloned test databases correctly? -
Do we really need a robot.txt with Django?
I can understand that if we have pages accessible from the site but not relevant to index that I want to say forbid it from the robot.txt file or if the crowler can find it by itself. But I don't think a robot can find the pages added on urls.py. In my case I don't use any useless or private page except the administration page. Do I really need to do: Disallow: myAdminpageWhoIsNoLongerAsecret/ -
Django: How to add user(author of the POST request) before save in serializers?
I'm tried to add author of the request before saving it in serializers.py And got error: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x0000029169C48040>": "Category_product.posted_user" must be a "User" instance. models.py class Category_product(models.Model): category_name = models.CharField(max_length=200, unique=True) posted_user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) def __str__(self): return self.category_name views.py class Category_productDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Category_product.objects.all() serializer_class = Category_productSerializer serializers.py class Category_productSerializer(serializers.ModelSerializer): post_user = serializers.ReadOnlyField( source='posted_user.username') class Meta: model = Category_product fields = ['id', 'category_name','post_user'] def validate(self, data): data['posted_user'] = self.context['request'].user return data -
React/Django Application working on local but not on production
I'm developing an application in Django and React. When I locally host the server and frontend, the application works fine and cookies get sent on requests that they need to be sent on since I set the axios defaults for withCredentials to true. However, when I deploy my frontend to production and try to access views with login required on my server, I continuously get 404 errors meaning the authentication is failing. I have tried a bunch of different solutions but seem to be really stuck on what this issue may be. -
Can I use gunicorn when deploying a django app on Windows?
I am trying to deploy a django app with Heroku and am getting caught up on my Procfile. The tutorial I am going off of uses gunicorn but I've read that I cant use gunicorn because I am developing on Windows. My Procfile looks like: web: gunicorn my_site.wsgi --log-file - and I am recieving this error: ModuleNotFoundError: No module named 'my_site' -
django - Count objects and sum values in a field
I want to include some basic statistics about a model in a stats.html file. The variables don't show in the html. What am I doing wrong? from django.shortcuts import render, get_object_or_404, redirect from django.db.models import Avg, Sum, Count from .models import Production def statistics(request): nr_of_plays = Production.objects.count() nr_of_actors = Production.objects.all().aggregate(Sum('nr_actors')) nr_of_audience = Production.objects.all().aggregate(Sum('est_audience')) context = { 'nr_of_plays': nr_of_plays, 'nr_of_actors': nr_of_actors, 'nr_of_audience': nr_of_audience, } return render(request, 'stats.html', context) The model: class Production(models.Model): title = models.CharField(max_length=200) nr_actors = models.IntegerField(default=0) est_audience = models.IntegerField(default=0) ... And the template: - Stats: {{ nr_of_plays }} plays produced, involving {{ nr_of_actors }} actors, seen by {{ nr_of_audience }} people. -
Using Django channels 2 as video stream server
I'm working on a project where I need to use live video streaming. Currently I'm using RTCMultiConnection for streaming and its server in the development but it cannot be used in the production environment. As I'm working in Django, I was thinking if using Django channels 2 as the streaming server will be possible? If so, how can I implement it. Thanks in advance. -
django rest-framework i am authenticated with token authentication but data is not showing? how can i check authentication and load data?
django rest framework i have a list of item set permission class permissions_isauthenticated i also authenticated with token in react redux. token is stored in localStorage how can i check isAuthenticated or not when i get some data from api.i have token but data is not showing? how can i check is authenticated or not from reducer? django views.py class ArticleList(ListAPIView): '''This is list of Data''' permission_classes = (permissions.IsAuthenticated, ) queryset = Article.status_objects.all() serializer_class = NewsSerializer here is the react-redux authentication authAction.js import axios from 'axios'; import * as actionTypes from './actionTypes'; export const authStart = () => { return { type: actionTypes.AUTH_START } } export const authSuccess = token => { return { type: actionTypes.AUTH_SUCCESS, token: token } } export const authFail = error => { return { type: actionTypes.AUTH_FAIL, error: error } } export const logout = () => { localStorage.removeItem('token'); return { type: actionTypes.AUTH_LOGOUT }; } export const authLogin = (userData) => { return dispatch => { dispatch(authStart()); axios.post('http://localhost:8000/rest-auth/login/', userData) .then(res => { const token = res.data.key; localStorage.setItem('token', token); dispatch(authSuccess(token)); }) .catch(err => { dispatch(authFail(err)) }) } } authReducer.js import * as actionTypes from '../actions/actionTypes'; import { updateObject } from '../utility'; const initialState = { isAuthenticated: null, … -
Django 3.0.8 URL/Template/Routing Troubles "No reverse match"
first post so please forgive my ignorance as this is my first django app. I am trying to create a template that displays all of the information regarding a specific "Ticket" from a list of all open tickets. Unfortunately I am receiving following message whenever I attempt to add an anchor with a template url tag: NoReverseMatch at /tickets/tasks/ Reverse for 'order' not found. 'order' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/tickets/tasks/ Django Version: 3.0.8 Exception Type: NoReverseMatch Exception Value: Reverse for 'order' not found. 'order' is not a valid view function or pattern name. Exception Location: /home/thecoder/.local/lib/python3.8/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 And it is ONLY on this one HTML Template. Below is all of the code I believe will be able to shed some light into the issue: models.py: from django.db import models # Create your models here. class Ticket(models.Model): """A basic support ticket""" # User ticket title. ticket_Name = models.CharField(max_length=50) # When the request was submitted. ticket_Submitted = models.DateTimeField(auto_now_add=True) #Ticket Type ticketTypeChoices=[ ('Update', 'Article Edit/Update'), ('Addition', 'New Content/Article Request'), ('Typo', 'Article Typo/Formatting Issue'), ('Issue', 'Website Error/Issue'), ('Other', 'Other'), ] # Type of ticket (Update, Addition, Typo, Site Issue) ticket_Type = … -
Django drop-down list
I'm new to Django and working on a crud application. I have already created an order form where the user can create an order. Now I want to implement a drop-down list for handled_by field in a template that will allow another user who will not have access to create order form to manually select a user in that drop-down list for a particular order and save it. I have a drop-down list in my template but it displays no user. class Order(models.Model): handled_by = models.ForeignKey(User, null=True, related_name='handled_by_user',on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) views.py def order_list(request): order = Order.objects.all() context = { 'order': order, } return render(request, "order_list.html", context) order_list.html {% for Order in order %} {{Order.name}} {{Order.address}} <select> <option value="">----------</option> <option value="{{Order.handled_by}}">{{Order.handled_by}}</option></td> </select> {% endfor %} -
Can I visualize database data on website?
I'm trying to make map visualization website based on web-crawling data. My plans are below: web-crawling from webpage store web-crawling data into database visualize map based on data from database Can I do number 3 part? I'm going to use Flask and visualize map using mapbox. (I use python.) -
How do I pass anchor tag id to urls in Django?
I'm trying to build an "add to cart" functionality for a pizza order website. To do this, I set up anchor tags and I need to send the specific item id to the views function from the anchor tag so that item can be added to the cart. I'm getting a TypeError with this code saying "add_to_cart() missing 1 required positional argument: 'item_id'". I believe this is because the item.id variable is not being passed to urls.py. Does anyone know the correct way to solve this? I am using Django 3.0.8 so I don't know if RegEx will work. Thanks in advance! urls.py: from django.urls import path, include from django.contrib import admin from django.contrib.auth.forms import UserCreationForm from . import views from users import views as users_views urlpatterns = [ path('', views.index, name="index"), path('admin/', admin.site.urls), path('login/', views.login_view, name="login"), path('logout/', views.logout_view, name = "logout"), path('register/', users_views.register_view, name = "register"), path('menu/', views.menu, name = "menu"), path('cart/', views.add_to_cart, name = "add_to_cart"), path('cart/<int:item_id>', views.add_to_cart, name = "add_to_cart") ] views.py: def add_to_cart(request, item_id): #query database for the correct item order_id = Pizza.objects.get(id = item_id) #add the new order to the cart new_item = Cart.objects.create(order_id) #test connection return render(request, "orders/homepage.html") html template: {% extends "orders/base.html" %} {% … -
Change course overview default template in edx
I would like to customize the default Course Overview when creating a course. The reason is to remove the FAQ part and remove any traces of the word 'Edx'. Tried searching the code for any appearance of that said template and commented it out but it still used the default template upon creation of course. My theory is that it is a data, not a static code but I have no clue where to customize. -
Django: implement chart.js to Django code
I have a trouble implementing my data into chart.js... currently, I have views.py def courseOne(request): marks = MarksInputOne.objects.filter(user=request.user) total_assign = TodoList.objects.filter(user=request.user) total = total_assign.count() this = total_assign.filter(category__name="MAT292H1").count() return render(request, 'courses/firstcourse.html', {'marks': marks, 'total_assign': total_assign, 'total': total, 'this': this}) models.py class MarksInputOne(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) date = models.DateTimeField(auto_now_add=True) mark = models.CharField(max_length=200) def __str__(self): return self.mark and views.py again, def lineChart(request): labels =[] data = [] queryset = MarksInputOne.objects.values('mark').filter(category__name='MAT292H1').order_by('date') for entry in queryset: labels.append(entry['date']) data.append(entry['mark']) return JsonResponse(data={ 'labels': labels, 'data': data, }) Finally, this is what I have on the HTML, <div class="card card-body"> <canvas id="chart" width="800" height="400"></canvas> <script> var ctx = document.getElementById('chart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{{data|safe}}], datasets: [{ label: 'Academic Performance', data: [{{ labels|safe }}], fill: false, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgb(255,99,132)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> </div> I tried … -
How do you mock queries that has comparison logic for testing in DJANGO
Let's say I have two class: class Classroom(models.Model): num_of_students= models.IntegerField class School(models.Model): classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE) I am trying to write a Mock that would return records for this query: School.objects.filter(classroom__num_of_students__lt=40) In test so far I have school = School() classroom = Classroom(num_of_students=10) mock.patch.object(school, 'classrooms', MockSet(classroom)) mock.patch.object(School, 'objects', MockSet(school)) I don't want to mock 'filter'. I would like filter to keep its behavior. -
mySQL database listening to tcp port
Very new to using databases, wanted to know how I can set up a mySQL database to store information (sensor readings) which is constantly streaming into a tcp port on my machine. Plan to connect this database to a Django Project Any help would be appreciated -
Oh my god leave me alone, Martijn Pieters [closed]
Not a real question but please, Martijn Pieters, All I am trying to do is ask some question. They are legit questions and some of them got answered and upvoted. It's not the answerer's fault you know. If you have a problem with me then go after my account, but leave my god forsaken questions alone as long as they are legit. Stop Locking me. Please just tell me what I did wrong and how can I make up so you will leave me alone to ask questions in peace. As long as I'm not being a nuisance (I wasn't being a nuisance until now, because you keep one taunting me for no reason), and my questions are legit, why not let me exist in peace? -
Getting post likes, and checking if user has liked post [Django]
I am trying to set up an instagram like page, where users can like posts, and each post has it's own comments(with likes too). Is there a more effective way of getting post likes count, and returning the liker user(for checking if the currently logged in user has liked the post) usage {%if post.like_user == user%} {# display filled heart#} models.py from django.db import models class User(AbstractUser): pass class Post(models.Model): post = models.CharField(max_length=140) writer = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["-created"] def __str__(self) -> str: return self.post def time(self): return self.created.strftime("%B %m, %Y, %I:%M %p") def total_likes(self): return self.likes.count() def like_user(self): return self.likes.all()[0].user class Like(models.Model): post = models.ForeignKey(Post, related_name="likes", on_delete=models.CASCADE) user = models.ForeignKey(User, related_name="liked_posts", on_delete=models.CASCADE) class Meta: unique_together = ("user", "post") def __str__(self) -> str: return self.post.post Any suggestions would be highly appreciated -
What is name used for in url path?
I am new to django and have this in my urlpatterns: path('bio/<username>/', views.bio, name='bio'), I don't understand the significance of putting name='bio'. What does this do? Thanks! -
can not render ' / ' in url in Django templates
in my urls.py path('', store_view, name='store'), path('category/<str:category_name>/', category_view, name='category'), in views.py def store_view(request): categories = list(Category.objects.all()) context = { 'categories': categories, } return render(request, 'store/store.html', context) def category_view(request, category_name): category = Category.objects.get(name=category_name) context = { 'category': category, } return render(request, 'store/single-category-view.html', context) in my template : store.html , that is rendered by store_view >> {% for item in categories %} <a href="{% url 'category' item.name %}"> {{item.name}} </a> {% endfor %} Now,the problem is, in the category column in my DB, i have got one category called 'Laptop/MacBook'.when ever this name is passed to the url, it says >> "Reverse for 'category' with arguments '('Laptop/MacBook',)' not found. 1 pattern(s) tried: ['category/(?P<category_name>[^/]+)/$'] But when i changed the category name from Laptop/MacBook to Laptop and MacBook , it worked fine and showed no error. But i want to keep it as it was,'Laptop/MacBook'.How can i do that??and how do you guys deal with that? -
Django Connection not working properly with Azure Active Directory
I'm trying to put my application out in production. It was fully working when I was working locally, and it also worked when I did it in a test database in azure. The problem is that now, when I want to use the actual production database, it is sending me errors. I'm pretty sure that I have all the settings correct, but I think this is something I have to change inside my Azure settings, but I can't find out why. This is the error I'm getting: [HY000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot open server "myserver" requested by the login. The login failed. (40532); [HY000] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)') Should I be changing some settings inside Azure for it to work?