No module named django.urls - django-models

I'm trying to create a new model, i named it products, and i found this error message which you see below
Note that my django version is 1.8.7
##urls.py:
from django.contrib import admin
from mySecondGdgBlogs import views
from django.urls import include, path
from myGdgBlogs import views
urlpatterns = [
path('admin/', admin.site.urls),
path('writeafterme/',include('mySecondGdgBlogs.urlss')),
path('htm/', views.htamal),
path('dp/',views.dpmain)
]
##views.py:
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def dbmain(request):
data = ''
return HttpResponse(data)
##models.py
from django.db import models
# Create your models here.
class Products(models.Model):
name = models.CharField (max_length=20)
price = models.IntegerField()
type=models.CharField(max_length=20,choices=(
('S', 'Small'),
('M', 'Medium'),
('L', 'Large'),
))
class Meta:
db_table = 'Products'
I expected to show me a white page but the actual result in the browser is :
No module named 'django.urls'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.8.7
Exception Type: ModuleNotFoundError
Exception Value:
No module named 'django.urls'
Exception Location: /home/mohammed/PycharmProject/GdgProject/myGdgProject/myGdgProject/urls.py in <module>, line 7
Python Executable: /usr/bin/python3
Python Version: 3.6.8
Python Path:
[
'/home/mohammed/PycharmProject/GdgProject/myGdgProject',
'/usr/local/lib/python3.6/dist-packages/pip-19.1.1-py3.6.egg',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/mohammed/.local/lib/python3.6/site-packages',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3/dist-packages'
]

Related

I have problem in django's dynamic urls system

I have been following this other tutorial on youtube on build a project of some sort.its been days trying to find the solution to the problem
I tried using the 'str' and the 'int'
from django.urls import path
from . import views
urlpatterns = [
path('', views.home),
path('products/', views.products),
path('customer/<int:my_id>/', views.customer),
]
this is my code in the views.py
def customer(request, my_id):
customer = Customer.objects.get(id=my_id)
orders = customer.order_set.all()
context = {'customer': customer, 'orders': orders}
return render(request, 'accounts/customer.htm', context)
please HELP

Upload Multiple Files (POST) __init__() takes 1 positional argument but 2 were given

I'm trying to do a multiple file upload functionality but I've been getting the issue: init() takes 1 positional argument but 2 were given
I was able to do it for uploading a single file or in my case an image.
model.py
from django.db import models
from django.utils import timezone
class images(models.Model):
session = models.CharField(max_length=50, blank=True)
picture = models.ImageField(upload_to='photoadmin/pictures')
created_date = models.DateTimeField(default=timezone.now)
forms.py
from django import forms
from django.db import models
from .models import images
class uploadImages(forms.ModelForm):
class Meta:
model = images
fields = ('session', 'picture')
widgets = {'picture': forms.ClearableFileInput(
attrs={'multiple': True})}
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .forms import uploadImages
from django.views.generic.edit import FormView
def index(request):
return render(request, 'photoadmin/index.html')
class upload(FormView):
form_class = uploadImages
template_name = 'photoadmin/upload.html'
success_url = 'photoadmin/upload.html'
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = uploadImages(request.POST, request.FILES)
if form.is_valid():
for f in files:
form.save()
return self.form_valid(form)
else:
return self.form_invalid(form)
Traceback
Environment:
Request Method: GET Request URL:
http://127.0.0.1:8000/photoadmin/upload
Django Version: 2.2.5 Python Version: 3.7.3 Installed Applications:
['django.contrib.admin', 'django.contrib.auth',
'django.contrib.contenttypes', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.staticfiles',
'photoadmin.apps.PhotoadminConfig'] 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:
File
"C:.virtualenvs\BusinessPhotoManagementApp-wSA_cSYW\lib\site-packages\django\core\handlers\exception.py"
in inner
34. response = get_response(request)
File
"C:.virtualenvs\BusinessPhotoManagementApp-wSA_cSYW\lib\site-packages\django\core\handlers\base.py"
in _get_response
115. response = self.process_exception_by_middleware(e, request)
File
"C:\Users.virtualenvs\BusinessPhotoManagementApp-wSA_cSYW\lib\site-packages\django\core\handlers\base.py"
in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
Exception Type: TypeError at /photoadmin/upload Exception Value:
init() takes 1 positional argument but 2 were given
Hi looks like the issue was the name of my Model was not following
PEP8, I changed images for Images, made the migrations and the error
disappeared.

Django adding letters and numbers to imageField url

I have an ImageField in a django model
image = models.ImageField(upload_to='images')
My media root is set like so in settings.py
MEDIA_ROOT = '/art/'
But when I upload select a gif url for the Imagefield, the url does not save as /art/images
I get this error message in Django Admin when I upload the url for the gif "Barnie.gif", which is stored at art/images/Barnie.gif
Art with ID "1/change/images/Barnie_L2fAl.gif" doesn't exist. Perhaps it was deleted?
I had the same problem. I solved it by adding the following imports:
from django.conf import settings
from django.conf.urls.static import static
I also added the following urlpatterns:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I wanted to try to get away with not doing all the config stuff, but you do have to do that.
In my base app urls.py I added:
from django.conf import settings
from django.conf.urls.static import static
and at the end of the urls list I added:
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then in my settings.py I added:
MEDIA_ROOT = os.path.join(BASE_DIR, '/art/images')
MEDIA_URL = '/images/'

Creating new wagtail home_page

I changed a bit wagtail 0001_initial.py and 0002_chreate_homepage.py and if i do migrate/makemigrations i get Server Error
Here is how i changed these files
0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-02-11 16:32
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('wagtailcore', '0040_page_draft_title'),
]
operations = [
migrations.CreateModel(
name='HomePage',
fields=[
('page_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='wagtailcore.Page')),
('tournament_section_title', models.CharField(blank=True, help_text='Title to display above the next matches', max_length=255, null=True)),
('matches_section_title', models.CharField(blank=True, help_text='Title to display above the next matches', max_length=255, null=True)),
('news_section_title', models.CharField(blank=True, help_text='Title to display above the News section on Home page', max_length=255, null=True)),
('presentation_screen_section_title', models.CharField(blank=True, help_text='Title to display above the News section on Home page', max_length=255, null=True)),
('matches_section', models.ForeignKey(blank=True, help_text='Choose a page to link to for the Matches Page', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailcore.Page', verbose_name='Choose ')),
('news_section', models.ForeignKey(blank=True, help_text='Choose a page to link to for the News Page.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailcore.Page', verbose_name='News')),
('presentation_screen_section', models.ForeignKey(blank=True, help_text='Choose a page to link to for the Presentation Screen Page.', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailcore.Page', verbose_name='Presentation Screen')),
('tournament_section', models.ForeignKey(blank=True, help_text='Choose a page to link to for the Matches Page', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailcore.Page', verbose_name='Choose ')),
],
options={
'abstract': False,
},
bases=('wagtailcore.page',),
),
]
and 0002_chreate_homepage.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def create_homepage(apps, schema_editor):
# Get models
ContentType = apps.get_model('contenttypes.ContentType')
Page = apps.get_model('wagtailcore.Page')
Site = apps.get_model('wagtailcore.Site')
HomePage = apps.get_model('base.HomePage')
# Delete the default homepage
# If migration is run multiple times, it may have already been deleted
Page.objects.filter(id=2).delete()
# Create content type for homepage model
homepage_content_type, __ = ContentType.objects.get_or_create(
model='homepage', app_label='home')
# Create a new homepage
homepage = HomePage.objects.create(
title="Home",
draft_title="Home",
slug='home',
content_type=homepage_content_type,
path='00010001',
depth=2,
numchild=0,
url_path='/home/',
)
# Create a site with the new homepage set as the root
Site.objects.create(
hostname='localhost', root_page=homepage, is_default_site=True)
def remove_homepage(apps, schema_editor):
# Get models
ContentType = apps.get_model('contenttypes.ContentType')
HomePage = apps.get_model('base.HomePage')
# Delete the default homepage
# Page and Site objects CASCADE
HomePage.objects.filter(slug='home', depth=2).delete()
# Delete content type for homepage model
ContentType.objects.filter(model='homepage', app_label='home').delete()
class Migration(migrations.Migration):
dependencies = [
('base', '0001_initial'),
]
operations = [
migrations.RunPython(create_homepage, remove_homepage),
]
Which way I have to do this, so if I deploy my project to heroku and run migrate it will automatically create HomePage that i changed.
my Project tree
-Project/
|-requirements
|-treichle-cup
|-base
|-search
|-settings
|-static
|-templates
In site settings my HomePage is exist and set as Root Page

Integrating Chat with (webapp2 + python 2.7 + Jinja2)

I'm trying to add chat to my site and am integrating some code with my existing code. The chat app works fine on its own when it's all set up in the original main.app file. But when I try to move that same code to a handlers.py file and then setup up routes in routes.py I get errors saying template variables are undefined. Are the two different codes conflicting in the way they render templates? They seem to be using webapp2 differently, i.e. my code renders templates like this:
self.render_template('secure_zone.html', **params)
And the chat app like this:
self.response.out.write(render("main.html",
username=username,
usernameerror=usernameerror,
channel=channelname,
channelerror=channelerror))
Are both acceptable?
Here's my handlers.py file:
Routes are setup in routes.py and added in main.py
"""
import httpagentparser
from boilerplate import models
from boilerplate.lib.basehandler import BaseHandler
from boilerplate.lib.basehandler import user_required
class SecureRequestHandler(BaseHandler):
"""
Only accessible to users that are logged in
"""
#user_required
def get(self, **kwargs):
user_session = self.user
user_session_object = self.auth.store.get_session(self.request)
user_info = models.User.get_by_id(long( self.user_id ))
user_info_object = self.auth.store.user_model.get_by_auth_token(
user_session['user_id'], user_session['token'])
try:
params = {
"user_session" : user_session,
"user_session_object" : user_session_object,
"user_info" : user_info,
"user_info_object" : user_info_object,
"userinfo_logout-url" : self.auth_config['logout_url'],
}
return self.render_template('secure_zone.html', **params)
except (AttributeError, KeyError), e:
return "Secure zone error:" + " %s." % e
Here's the main.py file for the chat app:
import os
import hashlib
import urllib
import logging
import re
import json
import webapp2
import jinja2
from google.appengine.api import channel as channel_api # 'channel' is kind of ambiguous in context
from google.appengine.ext import db
from google.appengine.api import memcache
# This section will eventually get moved to a Handler class
template_dir = os.path.join(
os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(
loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
def render_str(template, **params):
'''Returns a string of the rendered template'''
t = jinja_env.get_template(template)
return t.render(params)
def render(template, **kw):
'''Render using the template and parameters'''
return(render_str(template, **kw))
# End Handler
class Main(webapp2.RequestHandler):
def get(self):
'''Show connection page'''
return self.render_template("main.html", channel="#udacity")
def post(self):
'''Displays chat UI'''
username = self.request.get('username')
channelname = self.request.get('channel')
usernameerror = ""
if not username:
usernameerror="Please enter a username"
elif not re.compile(r'^[a-zA-Z0-9_-]{3,20}$').match(username):
usernameerror = "Username must consist of 3-20 alphanumeric characters."
elif get_user(username):
usernameerror="Username already in use"
channelerror = ""
if channelname and not re.compile(r'^#[\w]{3,20}$').match(channelname):
channelerror="Channel must consist of 3-20 alpha_numeric characters and start with a #"
if len(usernameerror+channelerror) > 0:
self.response.out.write(render("main.html",
username=username,
usernameerror=usernameerror,
channel=channelname,
channelerror=channelerror))
app = webapp2.WSGIApplication([
('/', Main),
('/communication', Communication),
('/_ah/channel/connected/?', Connect),
('/_ah/channel/disconnected/?', Disconnect)
], debug=True)
The specific error you posted in the comments "Error: 'Main' object has no attribute 'render_template'" is because in your Main handler, you try to return self.render_template. You should be just calling the function like this:
render_template("main.html", channel="#udacity")
Please note that I did not check the rest of your code, so if you run into any other issues, please post the specific errors you get.
It is because your webapp2.RequestHandler do not have the corresponding function "render_template"
you can use a BaseHandler with render_template function added to achieve the template rendering
from google.appengine.ext.webapp import template
class BaseHandler(webapp2.RequestHandler):
def render_template(self, filename, **template_args):
path = os.path.join(os.path.dirname(__file__), 'templates', filename)
self.response.write(template.render(path, template_args))
class Main(BaseHandler):
def get(self):
'''Show connection page'''
return self.render_template("main.html", channel="#udacity")
ref: http://blog.notdot.net/2011/11/Migrating-to-Python-2-7-part-2-Webapp-and-templates
I just started using webapp2 + python 2.7 + Jinja2 few days, and that is the same problem I encountered.
Hope this solution can help you ;)

Resources