I've got following code and got two issues.
1. I couldn't get joins added up and not showing up on the page.
2. Admin interface is not loading.
I've re-created the DB checked the code thoroughly and really need help.
Views.py.
from django.conf import settings
from django.shortcuts import render, HttpResponseRedirect, Http404
from.models import Join
from .forms import EmailForm, JoinForm
def get_ip(request):
try:
x_forwarded = request.META.get("HTTP_X_FORWARDED_FOR")
if x_forwarded:
ip = x_forwarded.split(",")[0]
else:
ip = request.META.get("REMOTE_ADDR")
except:
ip = ""
return ip
import uuid
def get_ref_id():
ref_id = str(uuid.uuid4())[:11].replace('-', '').lower()
try:
id_exists = Join.objects.get(ref_id=ref_id)
get_ref_id()
except:
return ref_id
def home(request):
try:
join_id = request.session['join_id_ref']
obj = Join.objects.get(id=join_id)
except:
obj = None
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
email = form.cleaned_data['email']
new_join_old, created = Join.objects.get_or_create(email=email)
if created:
new_join_old.ref_id = get_ref_id()
if not obj == None:
new_join_old.friend = obj
new_join_old.ip_address = get_ip(request)
new_join_old.save()
return HttpResponseRedirect("/%s" %(new_join_old.ref_id))
context = {"form": form}
template = 'home.html'
return render(request, template, context)
def share(request, ref_id):
#try:
join_obj = Join.objects.get(ref_id=ref_id)
friends_referred = Join.objects.filter(friend=join_obj)
count = join_obj.referral.all().count()
ref_url = settings.SHARE_URL + str(join_obj.ref_id)
context = {"ref_id": join_obj.ref_id, "count": count, "ref_url": ref_url}
template = "share.html"
return render(request, template, context)
#except:
#raise Http404
Error message I am getting after commenting out exception is:
DoesNotExist at /admin
Join matching query does not exist. Lookup parameters were {'ref_id': u'admin'}
Urls.py includes following.
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'joins.views.home', name='home'),
url(r'^(?P<ref_id>.*)$', 'joins.views.share', name='share'),
)
Your regular expression in line
url(r'^(?P<ref_id>.*)$', 'joins.views.share', name='share'),
matches admin/ as well you should use something less "greedy".
Related
So I'm creating a web app in Django, and I encountered this error:
my urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:user_id>/', views.profile, name="profile"),
#path('signup/', views.signup, name="signup"),
path("signup/", views.signup, name="signup")
]
my views.py:
from django.shortcuts import render, get_object_or_404
from django.contrib.auth import forms
from django.urls import reverse_lazy
from django.http import HttpResponse, Http404
from django.template import loader
from .models import User
from .forms import SignUpForm
from datetime import datetime
def index(request):
cool_people_list = User.objects.order_by("-username")[:5]
_template = loader.get_template("front_page.html")
context = {
"cool_people_list" : cool_people_list,
}
return HttpResponse(_template.render(context, request))
def profile(request, user_id):
try:
user = get_object_or_404(User, pk=user_id)
_template = loader.get_template("profile.html")
context = {
"user" : user
}
return HttpResponse(_template.render(context, request))
except:
raise Http404("The user you are looking for doesn't exist.")
def signup(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
rn = str(datetime.today().strftime("%Y-%m-%D"))
rn2 = str(datetime.today)
"""usr_list = User.objects.order_by('-join_date')
latest_usr = usr_list.first()"""
new_user = User(3, str(form.cleaned_data.get("username")), str(form.cleaned_data.get("password")), rn, rn2)
new_user.save()
return render(request, "signup.html")
my models.py:
from django.db import models
from django.core.validators import MinLengthValidator
import datetime
class User(models.Model):
user_id = models.IntegerField(unique=True)
username = models.CharField(max_length=25, validators=[MinLengthValidator(3)])
password = models.CharField(max_length=25, validators=[MinLengthValidator(7)])
join_date = models.DateField()
last_online = models.DateTimeField()
def __str__(self):
return self.username
I kept trying different methods, like manually adding the user ID (temporary fix), but Django can't see where I type in the ID! It doesn't register it when I typed it in what I believe is the correct format for my 'User' model.
You need to save an object in User Model like this...
def signup(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
rn = datetime.today().strftime("%Y-%m-%D")
rn2 = datetime.today
new_user = User(username= form.cleaned_data["username"], password=form.cleaned_data["password"], rn=rn, rn2=rn2)
new_user.save()
else:
form.errors
return render(request, "signup.html")
Hi All i have a small test app that has a basic model with a form based on this model:
class PublicNotesPost(models.Model):
noteName = models.CharField(max_length=255)
termsAgreed = models.BooleanField(default=False)
noteData = models.TextField()
def __str__(self):
return self.pk
class Meta:
verbose_name_plural = "Test Note Post Data"
My aim is when i post a note it redirects to a viewer with a dynamic url, at the moment i have not setup the viewer just an empty html file with a H1 tag just to test redirection. However what happens is a Hash is appended to the end of the url and i cant for the life of me figure out why this is and wanted to post here in case anyone has experienced this and has an understanding of how to rectify it?
http://127.0.0.1:8000/note/ryXVe7tAhC/#
My Url patterns are as follows:
from django.urls import path
from .import views
urlpatterns = [
path('note/composer/', views.NoteComposer.as_view() ,name="note_composer"),
path('note/<str:shorturl>/', views.ViewNote ,name="noteviewer")
]
View functions:
from django.shortcuts import render, redirect
from .forms import PostComposerForm
from django.urls import reverse
from django.views import View
import string
import random
# Create your views here.
def short_random_string(N:int) -> str:
return ''.join(random.SystemRandom().choice(string.ascii_uppercase +string.ascii_lowercase+ string.digits) for i in range(N))
class NoteComposer(View):
def get(self, request):
try:
formdata = {
'form': PostComposerForm(),
'navbar_active': 'composer',
'agreedTerms': False
}
return render(request, 'main/composer.html', formdata)
except Exception as ex:
print(ex)
return redirect('/')
def post(self, request):
try:
form = PublicComposerForm(self.request.POST)
if form.is_valid():
shortUrl = short_random_string(10)
return redirect(reverse('noteviewer', kwargs={"shorturl": shortUrl}))
pass
except Exception as ex:
print(ex)
return redirect('/')
def ViewNote(request, shorturl):
try:
return render(request,'main/view_note.html')
except:
return redirect('/')
when i run the URL http://127.0.0.1:8000/crud/add/1 it gives me error add() got an unexpected keyword argument 'id', can anyone please help me why i am getting this error ? here i have added my whole code, can anyone please help me how to resolve this issue ?
urls.py
app_name = 'crud'
urlpatterns = [
path('',views.index, name='index'),
path('add/',views.add, name='add'),
path('add/<int:id>',views.add, name='update'),
]
views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Pages
from django.urls import reverse
from django.shortcuts import get_object_or_404, render
def index(request):
pagelist = Pages.objects.all()
context = {'pagelist': pagelist}
return render(request, 'polls/index.html', context)
def add(request):
if request.POST:
title = request.POST.get("title")
permialink = request.POST.get("permialink")
updated_date = request.POST.get("updated_date")
bodytext = request.POST.get("bodytext")
page_data = Pages(title=title,permialink=permialink,updated_date=updated_date,bodytext=bodytext)
page_data.save()
return HttpResponseRedirect(reverse('crud:index', args=('')))
else:
return render(request,'polls/add.html')
You are passing parameter in URL but not receiving it in in view function. You should define add function like this
def add(request, id=None):
pass
# rest of code
If you have a method, eg:
#app.route('/transcript/<int:id>', methods=['GET', 'POST'])
def transcript(employeeId):
if x == 'NoneType':
employee = Employee()
else:
employee = Employee(employeeId)
The argument doesn't match the route, eg employeeId doesn't equal <int:id>, so we change the argument to id
#app.route('/transcript/<int:id>', methods=['GET', 'POST'])
def transcript(id):
if x == 'NoneType':
employee = Employee()
else:
employee = Employee(employeeId)
Strangely we still get the same error. The trick is that you may not have changed all old occurrences of the old employeeId argument:
#app.route('/transcript/<int:id>', methods=['GET', 'POST'])
def transcript(id):
if x == 'NoneType':
employee = Employee()
else:
employee = Employee(id)
I have a contact page for my website. The contact form is working but I want to add a background image to this page (which is saved in the database).But how can I combine my email(request) and a query to get the image ?
views.py
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import ContactForm
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin#example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('./success')
return render(request, "contact/email.html", {'form': form})
def success(request):
return HttpResponse('Success! Thank you for your message.')
models.py
from django.db import models
class Background(models.Model):
name = models.CharField(max_length=200, null=False)
image = models.ImageField(upload_to='./background/', default=None)
def __str__(self):
return self.name
urls.py
from django.conf.urls import url
from . import views
app_name = 'contact'
urlpatterns = [
url(r'^$', views.email, name='email'),
url(r'^success/$', views.success, name='success'),
]
You could retrieve the image on your view:
def get_background():
try:
background = Background.objects.get(name="your image name") # add your filters where to get the image
if background.image and background.image.url:
return background.image.url
except Background.DoesNotExist:
return
def email(request):
if request.method == 'GET':
form = ContactForm()
else:
...
...
# add the background to context
return render(request, "contact/email.html", {'form': form, 'background_img': get_background()})
And in your HTML (it's just a exemple, always try to style your site with a separate css file):
...
<div {% if background_img %}style="background: url('{{background_img}}') center no-repeat;"{% endif %}>
...
Views.py
from django.shortcuts import render
from django.template.context_processors import csrf
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from .models import studentDetails
from .forms import loginForm
# Create your views here.
def login(request):
c = {}
c.update(csrf(request))
return render(request, "login.html", c)
def auth_view(request):
username = request.POST.get("username", "")
password = request.POST.get("password", "")
q = studentDetails.objects.get(name=username)
if q.password==password:
return HttpResponseRedirect("/student/accounts/loggedin")
return HttpResponseRedirect("/studemt/accounts/invalid")
def loggedin(request):
username = request.GET.get("username")
return render(request, "loggedin.html", {"full_name": username})
def invalid(request):
return render(request, "invalid_login.html")
def logout(request):
return render(request, "logout.html")
Urls.py
from django.conf.urls import url
from django.contrib import admin
from .views import (
login,
auth_view,
loggedin,
logout
)
urlpatterns = [
url(r"^accounts/login/$", login , name="login"),
url(r"^accounts/auth/$", auth_view ,name="auth_view"),
url(r"^accounts/loggedin/$", loggedin , name="loggedin"),
url(r"^accounts/logout/$", logout, name="logout"),
]
i want to send username from auth_view to loggedin view but i don'y know how to do that.
i have used username = request.GET.get("username") but it is not working.
i want to show username in url also such that it looks like /student/username/
where username will change as different user login.
You should pass parameter in url first:
url(r'^student/(?P<username>\w+)/$', views.userpage, name='userpage)
But better use pk field or something with name + pk, as url parametr, because username can be duplicate.
Now you can pass this parameter in view and don't hardcore url, use reverse with url name instead.
def auth_view(request):
username = request.POST.get("username", "")
password = request.POST.get("password", "")
q = studentDetails.objects.get(name=username)
if q.password==password:
return HttpResponseRedirect(reverse('userpage', args=[q.username]))
return HttpResponseRedirect(reverse('invalid'))