maxg203 / django-tutorials Goto Github PK
View Code? Open in Web Editor NEWSource code for my free YouTube series on the Django web framework for Python.
Home Page: https://www.youtube.com/playlist?list=PLw02n0FEB3E3VSHjyYMcFadtQORvl1Ssj
Source code for my free YouTube series on the Django web framework for Python.
Home Page: https://www.youtube.com/playlist?list=PLw02n0FEB3E3VSHjyYMcFadtQORvl1Ssj
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
messages.success(request, f'Account created for {username}!')
return redirect('blog-home')
else:
form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})
This is my urls.py-
`from django.contrib import admin
from django.urls import include, path
from graphene_django.views import GraphQLView
from blog.schema import schema
urlpatterns = [
path('graphql/', GraphQLView.as_view(graphicql=True, schema=schema)),
]
`
this is my urls.py_chatter
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
```
`
and lastly my error
`Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f28f4559ae8>
Traceback (most recent call last):
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 397, in check
for pattern in self.url_patterns:
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/kevinm/djangogirls/chatter/chatter/urls.py", line 6, in <module>
path('', include('blog.urls')),
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/kevinm/djangogirls/chatter/blog/urls.py", line 9, in <module>
path('graphql/', GraphQLView.as_view(graphicql=True, schema=schema)),
File "/home/kevinm/djangogirls/myvenv/lib/python3.5/site-packages/django/views/generic/base.py", line 60, in as_view
"attributes of the class." % (cls.__name__, key))
TypeError: GraphQLView() received an invalid keyword 'graphicql'. as_view only accepts arguments that are already attributes of the class.
`
Thanks for taking your time max.
Traceback (most recent call last):
File "manage.py", line 22, in
execute_from_command_line(sys.argv)
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line
utility.execute()
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/core/management/base.py", line 350, in execute
self.check()
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check
include_deployment_checks=include_deployment_checks,
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/core/management/base.py", line 366, in _run_checks
return checks.run_checks(**kwargs)
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/urls/resolvers.py", line 396, in check
for pattern in self.url_patterns:
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/utils/functional.py", line 37, in get
res = instance.dict[self.name] = self.func(instance)
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/urls/resolvers.py", line 533, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/utils/functional.py", line 37, in get
res = instance.dict[self.name] = self.func(instance)
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/urls/resolvers.py", line 526, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib/python3.6/importlib/init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 994, in _gcd_import
File "", line 971, in _find_and_load
File "", line 955, in _find_and_load_unlocked
File "", line 665, in _load_unlocked
File "", line 678, in exec_module
File "", line 219, in _call_with_frames_removed
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial/urls.py", line 12, in
url(r'^account/', include('accounts.urls', namespace='accounts')),
File "/home/computer/saleor_Learn/Django-Tutorials/tutorial-env/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib/python3.6/importlib/init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 994, in _gcd_import
File "", line 971, in _find_and_load
File "", line 955, in _find_and_load_unlocked
File "", line 665, in _load_unlocked
File "", line 678, in exec_module
File "", line 219, in _call_with_frames_removed
File "/home/computer/saleor_Learn/Django-Tutorials/accounts/urls.py", line 3, in
from django.contrib.auth.views import (
ImportError: cannot import name 'login'
My Registration of user in database is successful but i am unable to redirect my page to successful registration page after the registration
def create_profile(sender, **kwargs):
# print(sender)
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance']) # error occurs here with Userprofile has no attributes objects. please help me with same
this is my repository
Hi Max
Please assist me, i keep getting redirected to the login page every time i try to access the admin page.
Iv been struggling with this for a bit.
I hope you can help.
which files would you need to see?
PS C:\Users\Dell\Django> python manage.py runserver
Unhandled exception in thread started by <function check_errors..wrapper at 0x000001BD1EFD91E0>
Traceback (most recent call last):
File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception
raise exception[1]
File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management_init.py", line 327, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\site-packages\django_init_.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python36\lib\importlib_init_.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 978, in _gcd_import
File "", line 961, in _find_and_load
File "", line 950, in _find_and_load_unlocked
File "", line 655, in _load_unlocked
File "", line 678, in exec_module
File "", line 205, in _call_with_frames_removed
File "C:\Users\Dell\Django\accounts\models.py", line 11, in
class UserProfile(models.Model):
File "C:\Users\Dell\Django\accounts\models.py", line 13, in UserProfile
user = models.OneToOneField(User)
TypeError: init() missing 1 required positional argument: 'on_delete'
Hi Max,
Thank you for your youtube videos and making your materials available.
I keep running into a value error. In the Django Tutorial Part 15 I was getting the following issue: "The view accounts.views.register didn't return an HttpResponse object. It returned None instead."
I cloned this repository so I could see where I was making the mistake. The same issue occurs in the cloned repository as well.
These are the steps I take to get the error. I make migrations, then run the server. Then I go to the website and click on register, I add in the credentials (username, first name, etc.) then click submit. The website always raises: "ValueError at /account/register/"
"The view accounts.views.register didn't return an HttpResponse object. It returned None instead."
I am using windows 10.
Any help would be greatly appreciated!
Thanks,
Bradon
Hi Guys,
I see that this issue has been resolved. But in my case is still bugging me.
This is my code, could someone check it and see what i'am doing wrong please?
Here is my code:
@login_required
def add_comment_to_post(request,pk):
post = get_object_or_404(Post,pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
# post is the pk in the model comment
comment.post = post
comment.save()
return redirect('blog:post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request,'blog/comment_form.html',{'form':form})
`from django.contrib import auth
from django.contrib.auth.forms import AuthenticationForm, UserModel, UsernameField
from django.http import request
from django.http.response import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.views.generic import View
from .forms import *
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import logout , login
from django.contrib.auth import get_user_model
def home(request):
return render(request,'home.html')
User = get_user_model()
class SignupView(View):
def get(self, request,*args, **kwargs):
fm = SignUpForm()
return render(request, 'signup.html', {'form':fm})
def post(self, request):
fm = SignUpForm(request.POST)
if fm.is_valid():
fm.save()
return redirect('home')
else:
return render(request, 'signup.html', {'form':fm})
class loginUser(View):
def get(self,request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username , password=password)
if user is not None:
login(request, user)
messages.success(request , "successfully loggend in")
return HttpResponseRedirect('/home')
else:
return HttpResponseRedirect('login')
def handelLogout(request):
logout(request)
messages.success(request, "Successfully logged out")
return redirect('/login')
I AM getting this error
The view core.views.loginUser didn't return an HttpResponse object. It returned None instead.
`
Tengo el siguiente error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/blog/7/compartir/
Django Version: 3.2.9
Python Version: 3.10.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog.apps.BlogConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\wilde\OneDrive\Desktop\DD - WEB\PythonProjects\env01\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\wilde\OneDrive\Desktop\DD - WEB\PythonProjects\env01\lib\site-packages\django\core\handlers\base.py", line 188, in _get_response
self.check_response(response, callback)
File "C:\Users\wilde\OneDrive\Desktop\DD - WEB\PythonProjects\env01\lib\site-packages\django\core\handlers\base.py", line 309, in check_response
raise ValueError(
Exception Type: ValueError at /blog/7/compartir/
Exception Value: The view blog.views.compartir_comentario didn't return an HttpResponse object. It returned None instead.
Mis códigos:
forms.py:
from django import forms
class FormularioEmailAnuncios(forms.Form):
nombre = forms.CharField(max_length=25)
email = forms.EmailField()
para = forms.EmailField()
comentarios = forms.CharField(required=False,
widget= forms.Textarea)
Compartir.html:
{% extends "../base.html" %}
{% block titulo %} Compartir un comentario {% endblock %}
{% block content %}
{% if enviado %}
<h1>El e-mail se ha enviado correctamente</h1>
<p>
"{{ comentario.titulo }}" fue enviado correctamente a {{ formulario.cleaned_data.para }}
</p>
{% else %}
<h1>Compartir "{{ comentario.titulo }}" por email </h1>
<form method='post'>
{{ formulario.as_p }}
{% csrf_token %} <!--Para prevenir ataques cross-site-->
<input type='submit' value='Enviar e-mail'>
</form>
{% endif %}
{% endblock %}
View compartir_comentario:
def compartir_comentario(request, comentario_id):
comentario = get_object_or_404(Anuncio, id=comentario_id, estado='publicado')
enviado = False
if request.method == 'POST':
formulario = FormularioEmailAnuncios(request.POST)
if formulario.is_valid():
datos = formulario.cleaned_data
comentario_url = request.build_absolute_uri(comentario.get_absolute_url())
asunto = f"{datos['nombre']} te recomienda que leas {comentario.titulo}"
mensaje = f"Leer {comentario.titulo} en {comentario_url} \n\n los comentarios de {datos['nombre']} : {datos['comentarios']} "
send_mail(asunto, mensaje, '[email protected]', [datos ['para']])
enviado = True
else:
formulario = FormularioEmailAnuncios() #es un GET que muestra el formulario limpio
return render(request,
'blog/post/compartir.html',
{'comentario': comentario,
'formulario':formulario,
'enviado':enviado})
Al intentar compartir un comentario, así:
[![Ejemplo compartir comentario via Email][1]][1]
[1]: https://i.stack.imgur.com/mGem0.png
I'm currently learning django, and using your tutorials. I wanted to check out your code. When I try making migrations i get this error
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
File "tutorial\accounts\models.py", line 24, in create_profile
user_profile = UserProfile.objects.create(user=kwargs['instance'])
AttributeError: type object 'UserProfile' has no attribute 'objects'
when we register new user or createsuperuser form commandline then above error comes.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.