Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RelatedObjectDoesNotExist - User has no profile
I'm very new here, hello. Building my first Django app was doing great so far. Now I have one little problem I'm not able to solve on my own. When I'm trying to create new user, associated profile doesn't create. RelatedObjectDoesNotExist at /login/ User has no profile. Request Method: POST Request URL: http://127.0.0.1:8000/login/ Django Version: 3.0.7 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no profile. Exception Location: /Users/dmszanowski/PycharmProjects/django_to_dos/venv/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py in __get__, line 420 Really appreciate your help. output [02/Aug/2020 02:20:14] "GET / HTTP/1.1" 200 5034 [02/Aug/2020 02:20:14] "GET /static/list/main.css HTTP/1.1" 304 0 [02/Aug/2020 02:20:16] "GET /register/ HTTP/1.1" 200 6400 [02/Aug/2020 02:20:33] "POST /register/ HTTP/1.1" 200 6571 [02/Aug/2020 02:20:43] "POST /register/ HTTP/1.1" 302 0 [02/Aug/2020 02:20:43] "GET /login/ HTTP/1.1" 200 5944 Internal Server Error: /login/ Traceback (most recent call last): File "/Users/dmszanowski/PycharmProjects/django_to_dos/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/dmszanowski/PycharmProjects/django_to_dos/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/dmszanowski/PycharmProjects/django_to_dos/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/dmszanowski/PycharmProjects/django_to_dos/django_project/users/views.py", line 30, in login_view login(request, user) File "/Users/dmszanowski/PycharmProjects/django_to_dos/venv/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 131, in login user_logged_in.send(sender=user.__class__, request=request, user=user) File "/Users/dmszanowski/PycharmProjects/django_to_dos/venv/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 173, in send return [ File "/Users/dmszanowski/PycharmProjects/django_to_dos/venv/lib/python3.8/site-packages/django/dispatch/dispatcher.py", line 174, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/Users/dmszanowski/PycharmProjects/django_to_dos/django_project/users/signals.py", line 21, in got_online user.profile.is_online … -
Form not showing up in page
Hey guys need a little help cant seem to figure it out. For some reason my form won't show up in my page please see code below. forms.py class NewEntryForm(forms.Form): title = forms.CharField(label = "Title") content = forms.CharField(label = "Body") views.py def new(request): if request.method == 'POST': form = NewEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] content = form.cleaned_data['body'] content = markdown2.markdown(title) filename = f"entries/{title}.md" if default_storage.exists(filename): return render(request, "encyclopedia/error.html", { "error":'A file with this title already exists.' }) else: util.save_entry(title, content) return redirect('entry_page', title=title) else: return render(request, 'encyclopedia/new.html', {'form':NewEntryForm()}) urls.py urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry, name="entry"), path("search/", views.search, name="search"), path("wiki/new", views.new, name="new") ] results.html {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <form class="" action="" method="post"> {% csrf_token %} {{form}} <input type="submit" name="" value="Submit"> </form> {% endblock %} Page output cli output -
Django CBVs: get_queryset() and get_context_data()?
What is the difference between get_queryset() and get_context_data() in a ListView (and what is their relationship). And what gets passed as **kwargs in get_context_data(self, **kwargs) for example in path(' ', SomeViewList.as_view())? My question applies to both the default methods and where applicable as overriden methods. -
How to reload url in Django to the same page to the same point
I am a beginner in Django and I have been trying to make a social media app where a Post gets a like or a from any other user . Each time when a user adds a comment or likes a post I used forms to change the data in the database. I want the page to reload the fresh data i.e a comment or a like on the post but due to the redirect function the whole page is reloading interrupting my user experience . In simpler terms there are 2 users x and y . y made a 1000 posts and all the posts are available on the profile page of y . x is critic and y asks x to comment the quality of the post for each and every one of the 1000 posts. According to what I wrote in views.py whenever x comments on a post I made a form that takes the content and stores it to the database but because of the redirect after each time he adds a comment on a post the web page is refreshed to the top of the page making x to scroll down all the posts to … -
Cannot deploy Django app on Heroku: "Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output."
I was trying to deploy my Django app to Heroku using "git push heroku master", when this problem occurred. The full error lines are below: Tungs-MBP:werewolf2 tungdo$ git push heroku master Enumerating objects: 84, done. Counting objects: 100% (84/84), done. Delta compression using up to 8 threads Compressing objects: 100% (81/81), done. Writing objects: 100% (84/84), 25.04 KiB | 2.78 MiB/s, done. Total 84 (delta 13), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.11 remote: -----> Installing pip 20.0.2, setuptools 39.0.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ! Your Django version is nearing the end of its community support. remote: ! Upgrade to continue to receive security updates and for the best experience with Django. remote: ! For more information, check out https://www.djangoproject.com/download/#supported-versions remote: Collecting altgraph==0.10.2 remote: Downloading altgraph-0.10.2.tar.gz (481 kB) remote: Collecting bdist-mpkg==0.5.0 remote: Downloading bdist_mpkg-0.5.0.tar.gz (19 kB) remote: Collecting configparser==4.0.2 remote: Downloading configparser-4.0.2-py2.py3-none-any.whl (22 kB) remote: Collecting contextlib2==0.6.0.post1 remote: Downloading contextlib2-0.6.0.post1-py2.py3-none-any.whl (9.8 kB) remote: Collecting distlib==0.3.1 remote: Downloading distlib-0.3.1-py2.py3-none-any.whl (335 kB) remote: Collecting Django==1.11.29 remote: Downloading Django-1.11.29-py2.py3-none-any.whl (6.9 MB) remote: Collecting gunicorn==19.10.0 remote: Downloading gunicorn-19.10.0-py2.py3-none-any.whl (113 … -
Allow only logged users to operate chrome extension (django login)
what is the best/simple way to allow only logged (django project) users to access my chrome extension? my django face, its simple: im using the login(request, user). How can i get in the extension face? Im trying: var ID; function getCookies(domain, name) { chrome.cookies.get({"url": domain, "name": name}, function(cookie) { ID = cookie.value; }); } getCookies("http://http://www.example.com", "id") alert(ID); -
Duplicate images on docker-compose build. How to properly push two services of docker-compose.yml to Docker hub registry?
I have a docker-compose.yml defined as follows with two services (the database and the app): version: '3' services: db: build: . image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=(adminname) - POSTGRES_PASSWORD=(adminpassword) - CLOUDINARY_URL=(cloudinarykey) app: build: . ports: - "8000:8000" depends_on: - db The reason I have build: . in both services is due to how you can't do docker-compose push unless you have a build in all services. However, this means that both services are referring to the same Dockerfile, which builds the entire app. So after I run docker-compose build and look at the images available I see this: $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE mellon_app latest XXXXXXXXXXXX 27 seconds ago 1.14GB postgres latest XXXXXXXXXXXX 27 seconds ago 1.14GB The IMAGE_ID is the exact same for both images, the size is exactly the same for both images. This makes me think I've definitely done some unnecessary duplication as they're both just running the same Dockerfile. I don't want to take up any unnecessary space, how do I do this properly? This is my Dockerfile: FROM (MY FRIENDS ACCOUNT)/django-npm:latest RUN mkdir usr/src/mprova WORKDIR /usr/src/mprova COPY frontend ./frontend COPY backend ./backend WORKDIR /usr/src/mprova/frontend RUN npm install RUN npm run … -
Apache2 shows default page when I visit the site without 'www' on an android device, but works fine with 'www'
I deployed Django website: www.alahaberry.com on Linode Ubuntu 20.04 LTS. Whenever I try to access it with my computer, it works just fine whether I add www or not. Today my friend tried to check it out from his android device and the apache2 default page appeared. This only happened on android device (or maybe all mobile). I tried with BlueStacks too the same. Without www it shows default apache2 page. Please what could be wrong. I really need your help. Thanks advance. I used letsencrypt to get SSL on it. My alahaberry-le-ssl.conf looks like this: <IfModule mod_ssl.c> <VirtualHost *:443> # The ServerName directive sets the request scheme, hostname and port th> # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. ServerName alahaberry.com ServerAlias www.alahaberry.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., … -
Get user geolocation while saving object in Django admin
The project have some models, as Employee, Customer, Visit, Plan and etc. The employee make visits to customers and make some notes. There is need to get user location on map, when the Visit done. During the day, there will be some visits and as a result on map it should be a road with points on made visits to customers. As you understand, here are two tasks: Get user location while saving the object Draw a road(direction) during day user save objects. -
Django: How do the methods get_queryset() and get_context_data() work? What are they used for? What is **kwargs in get_context_data(self, **kwargs)?
I am trying to understand class-based-views step by step. Please can you help me understand how get_queryset and get_context_data() work, and what are they used for? Why do we override them in the class-based-view definition? -
Using Django-filter with DRF
I am trying to use django-filter with DRF. I am trying to do the integration with DRF documented here: https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html Here is my view class: class PageView(APIView): filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('category', 'start_date', "end_date", "limit") def get(self, request): page_saves = Page.objects.all() serializer = PageSerializer(page_saves, many=True) return Response({"pages": serializer.data}) However I feel I must be missing something - nothing is filtering. Do I need a filter like this: class PageFilter(filters.FilterSet): with some logic in it? I'm just not entirely sure how to get filtering to work here -
What is the Terminal Command to update code on web server under Django framework
My configuration is Python 3.81 and window 10 I got a Django Project connected to online server . Once I changed the codes with my IDE, how to update the code on server ? I only got the result of root@localhost:/home/project # sudo supervisorctl restart Project && sudo service nginx restart in Linux Environment How to transform the above code to WINDOW OS environment ? -
Django redirect users based on group upon login
I am trying to redirect users in a particular group to a particular template and those not in it to the dashboard when they login. What I've done currently keeps bringing up the http response for users not in the group whenever I try to login with a user in the group. from django.shortcuts import render from django.contrib.auth import login, authenticate, logout from .forms import SignUpForm from django.shortcuts import render, redirect from .models import Profile from .decorators import allowed_users from django.contrib import messages from django.http import HttpResponse from django.contrib.auth.decorators import login_required # Create your views here. def homepage(request): return render(request, 'core/frontpage.html') def login_user(request): if request.method == 'POST': username = request.POST.get('Username') password = request.POST.get('Password') user = authenticate(username=username, password=password) print(username,password,user) if user is None: messages.success(request, 'Username or Password is incorrect') return redirect('login') else: group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'Hospitals': return redirect('core/hospital.html') else: return HttpResponse('You are not authorised to access this page') login(request, user) return redirect('dashboard') -
Fail to install pyrebase on windows Python 3.81
My Python version is 3.81 and PC is window 10 I tried to install pyrebase by pip install pyrebase But install fail . Got this error : How to solve ? -
Problem in collecting static files when deploying a Django Web App to Heroku
Images I've tried deploying my Django web app to Heroku but it's having some problems with collecting the static files, it looks it can't find the image that's being referred to by a css file. My settings.py file STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' django_heroku.settings(locals()) What am I doing wrong here? and what should I do? I used the AdminLTE bootstrap theme. -
Uncaught (in promise) TypeError: Cannot read property 'push' of undefined axios
I am trying to collect books in a shelf object. However when i try to add a book, the page does nothing and i get this error in my console "Uncaught (in promise) TypeError: Cannot read property 'push' of undefined". Need help with this. main.js function sendRequest(url,method,data) { var r = axios({ method: method, url: url, data: data, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) return r } var app = new Vue({ el : '#app', data: { book: '', books: [ {title: 'one'}, {title: 'two'} ] }, created(){ var vm = this; var r = sendRequest('','get') .then(function(response){ vm.books = response.data.books; }) }, methods: { createBook(){ var vm = this; var formData = new FormData(); formData.append('title', this.book); sendRequest('','post',formData) .then(function (response) { vm.books.push(response.data.book); //PROBLEM HERE vm.book = ''; }) } } }) views.py def add_book(request, shelf_id): context = {} if request.POST: shelf = get_object_or_404(Shelf, pk=shelf_id) book_form = BookCreation(request.POST) temp = book_form.save(commit=False) temp.shelf = shelf temp.save() if book_form.is_valid(): books = book_form.save() return JsonResponse({'book': model_to_dict(books)},status=200) return render(request, 'shelf/addBook.html') url.py path('<int:shelf_id>/create_book', add_book, name='addbook'), -
Meet the error of "Did you install mysqlclient?"
I got a Django project and I m trying to connect to my linode online server . I type cd \\\folder location.... in cmd console then python manage.py runserver 0.0.0.0:8070 got the result .....django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Then I referenced to Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?' And enter pip install pymysql Got Requirement already satisfied: pymysql in c:\users\appdata\local\programs\python\python38\lib\site-packages (0.10.0) How to solve it? -
Why Ubuntu is highly recommended for WSGI and Nginx installation?
I am new to Django integration with uWSGI and Nginx. Most of the tutorials in internet requires Ubuntu to test it. I am on Windows, Does they work in Windows ? If not should I install Ubuntu / Linux OS to work with it ? -
How do i resolve this Error while Deploying Django app to Heroku
error while git push Heroku master: I am new to Django and I follow the instructions as on some website except I create a virtual environment with Conda. -
Pip not found in Vagrant's VM with VSCode
I am running a VM with Vagrant to run a basic Django REST API project. I initially created a venv at the VM's home directory at ~/venv, then I installed Django and started the project. All the files and folders are inside /vagrant/ in the VM. It looks something like this when in /: (venv) vagrant@ubuntu-bionic:$ ls / bin dev home initrd.img.old lib64 media opt root sbin srv tmp vagrant vmlinuz boot etc initrd.img lib lost+found mnt proc run snap sys usr var vmlinuz.old Now I have added my a remote via SSH to my VSCode but it initializes in home/vagrant/' which is different than my /vagrant/ folder. Is there a way to change this? Then I also have to select Python interpreter and install pylint but when I try to install it I get: There is no Pip installer available in the selected environment., even though I have pip installed. I am a little confused about how to properly set up the remote on VSCode to run smoothly with a proper interpreter, pylint and everything just as my local machine. Also, I am running python 3.8.3 on my local machine but the remote on VSCode only allows me to … -
Problem with Samesite in Google Login Popup
In my project I use Google Login. This functionality stopped working few weeks ago. I run login with Google in iframe. It just closes the window and nothing happens. Inside dev tools there is the following warnings A cookie associated with a cross-site resource at http://google.com/ was set without the SameSite attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. A cookie associated with a cross-site resource at https://google.com/ was set without the SameSite attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. A cookie associated with a cross-site resource at https://accounts.google.com/ was set without the SameSite attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with SameSite=None and Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. -
With django update a user every second that they are logged in
I'm building a website that will have users that can login and do stuff. But every second that they are logged in I want to decrement a value that is associated to that user(called time_left). Right now I'm thinking of calling a method when logging in that then keeps running continuously till the user logs out. So I call a method in login view called time_update: def login(request): """ View function. In case it is a POST request, the user login form is created and is checked if valid. If it is valid, it is processed checked if user can log in. Otherwise a response with the form is sent. """ if request.user.is_authenticated: return redirect('home-page') if request.method == "POST": form = UserLoginForm(request, data=request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(email=email, password=password) if user is not None: if user.is_active: auth_login(request, user) time_update(user.email) else: print("user is not authenticated") return redirect('home-page') # user is redirected to dashboard else: form = UserLoginForm() return render(request, 'users/login.html', {'form': form}) But I'm kinda stuck on what to with this time_update method that should decrement the time_left value every second. Especially for multiple users that are logged in at the same time. Anyone any … -
Single page linking
i have made my personal website, with django. My website is a single website application, so my navigation-bar links to different sections on my website. My problem is that it is linking to the "id" of the section. Thats makes the url look like something like this. http://127.0.0.1:8000/#home Is there any way that i can remove the hashtag # from the url? I have tried to do something with my urls.py file, but i havent seem to find a solution to my problem. -
Object of type Publisher is not JSON serializable in Django Multiple Pagination
I have tried DjangoRestMultipleModels Pagination from here, Now I'm facing JSON serializable error! Views.py from drf_multiple_model.views import ObjectMultipleModelAPIView from drf_multiple_model.pagination import MultipleModelLimitOffsetPagination class LimitPagination(MultipleModelLimitOffsetPagination): default_limit = 2 class MultiplePagination(ObjectMultipleModelAPIView): pagination_class = LimitPagination def get(self, request, *args, **kwargs): querylist = ( {'queryset': Publisher.objects.all(), 'serializer_class': PublisherSerializer}, {'queryset': Book.objects.all(), 'serializer_class': BookSerializer}, ) return Response(querylist, status=200) This is the error I am facing... -
Can I create unrestricted schema with sql database like the one sed in django?
In mongodb or firebase I can create {title:"sothigs, content:"somthing"} then I can create other object with only title for example {title:"second title"} or I even can create object with new values that i never defined before. Is it possible to do with django sql databases?