ImportError: cannot import name 'forms' from 'basicapp' - python

form.py:
from django import forms
class FormName(forms.Form):
name=forms.CharField()
email=forms.EmailField()
text=forms.CharField(widget=forms.Textarea)
views.py:
from django.shortcuts import render
from .forms import forms
def index(request):
return render(request,'basicapp/index.html')
def form_page(request):
Form = forms.FormName()
return render(request,'basicapp/form_page.html',{'form':Form})
I dont know what is wrong here! when I run server, it makes an error, saying ImportError : cannot import name 'forms' from 'basicapp'.

First of all, it looks like you have named your forms file, form.py and you are trying to access a module called forms. Rename form.py file to forms.py.
Second, you are trying to import forms from your forms file. This is actually referencing forms you imported via from django import forms. You have a couple options here. In your view file you can either import .forms or from .forms import FormName I prefer the latter.
So, after you rename form.py to forms.py I would rewrite views.py to look like this:
from django.shortcuts import render
from .forms import FormName
def index(request):
return render(request,'basicapp/index.html')
def form_page(request):
this_form = FormName()
return render(request,'basicapp/form_page.html',{'form':this_form})

You made two mistakes in your code
1) Your form file should be named forms.py and not form.pY
2) your views.py import code should be
from django.shortcuts import render
from basicapp import forms

There is an issue in your view.py
replace
below line
from .forms import forms
with
from <your app name>.forms import forms
You are getting this error because django is trying to find it in root folder where your manage.py exist.

Related

What is the best, cleanest and shortest way to check if a given value is valid URL when working with models?

I rather want to use Django's built-in functionalities as much as possible and avoid implementing stuff myself as much as possible!
Why doesn't the following code issue exceptions when given a non-URL value?
models.py:
from django.core.validators import URLValidator
from django.db import models
class Snapshot(models.Model):
url = models.URLField(validators=[URLValidator])
views.py:
from django.http import HttpResponse
from .models import Snapshot
def index(request):
a = Snapshot(url='gott ist tot')
a.save()
Because this validator is run when you use a django form.
More information about validators on the doc : https://docs.djangoproject.com/en/4.1/ref/validators/
if you do a form :
from django import forms
from .models import Snapshot
class SnshotForm(forms.ModelForm):
class Meta:
model = Snapshot
fields = ('url', )
and your views.py :
from django.http import HttpResponse
from .forms import SnapshotForm
def index(request):
a = SnapshotForm(data={'url': 'gott ist tot'})
if a .is_valid()
a.save()
else:
print(a.errors)
Your validator will be run and you will see the errors form message
Without using form, you can call manually validator in your view or in the save method:
# in views
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
def index(request):
url_validator = URLValidator()
url = 'gott ist tot'
is_valid_url = False
try:
url_validator(url)
except ValidationError:
pass
if is_valid_url:
a = Snapshot(url=url)
a.save()
else:
print(a.errors)
Be careful ! I do not recommanded to bypass the validator with forms, i think it is the better way for maximizing usage of django builtins funtions

Exception happened during processing of request from ('127.0.0.1', 9464)

I don't know why this eror I wrote it from a tutorial but It's happend
this is view.py file
here
import view as view
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
# Create your views here.
from teams.models import Team
class HomePageView(View):
def get(self,requests):
all_teams = Team.objects.all()
context = {"teams": all_teams}
return render(requests,"teamlist.html",context)
this is my admin.py file
this is my admin.py file:here
from django.contrib import admin
# Register your models here.
from teams.models import Team, Player, GameScore
admin.site.register(Team)
admin.site.register(Player)
admin.site.register(GameScore)
that's my first question on stack over flow I don't know I ask True or not . I just need some help :)

How do I import and use the python files in a view in django?

What I want to do is I'd like to call the module( RSAtest ) already created in view in Django. I am calling a function in RSAtest module from AboutPageView. But for some reason, it shows the following error: ModuleNotFoundError: No module named 'webapp.functional' Could you give me an idea how to use modules in Django?
# howdy/views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from webapp.functional import RSAtest
class HomePageView(TemplateView):
def get(self, request, **kwargs):
return render(request, 'index.html', context=None)
# Add this view
class AboutPageView(TemplateView):
RSAtest.main()
#os.system('python3 howdy/RSAtest.py')
template_name = "about.html"
Thanks for the any help.

django registration redirection

I have used custom field in django registration form , every thing is working fine but whenever it try to redirect , it shows following error.
I dont know what i missed here.
NoReverseMatch at /accounts/register/
Reverse for 'registration_complete' with arguments '()' and keyword arguments '{}' not found.
I tried following
URL
url(r'^accounts/register/$', register, {'backend': 'registration.backends.default.DefaultBackend','form_class': RegistrationFormEx}, name='registration_register'),
registrationForm.py
from django import forms
from registration.forms import RegistrationForm
from django.utils.translation import ugettext_lazy as _
from registration.models import RegistrationProfile
class RegistrationFormEx(RegistrationForm):
#ADD ALL CUSTOM FIELDS BELOW
name=forms.CharField()
models.py
import hashlib
import datetime
import hmac
from django.db import models
from django.contrib.auth.models import User
from ecpCommon.models import StateModel
from ecpCommon.enum import enumauto
from ecpPayments.models import PaymentCard
from registration.signals import user_registered
from apps.ecpUser.models import UserProfile
from apps.ecpMerchant.registrationForm import RegistrationFormEx
from apps.ecpCommon.thumbs import ImageWithThumbsField
class MerchantProfile(StateModel):
name = models.CharField('Merchant Name', max_length=64)
def user_created(sender, user, request, **kwargs):
form = RegistrationFormEx(data=request.POST)
new_user = User.objects.get(username=request.POST['username'])
digest=hmac.new(str(request.POST['username'])+str(request.POST['password1']), str(request.POST['password1']),hashlib.sha1).hexdigest()
new_profile = UserProfile(user=new_user,api_key=digest)
new_profile.save()
#now add other fields including password hash as well
uid = new_profile.id
merchant_profile = MerchantProfile(user_id=uid,
create_time=datetime.datetime.now(),
modified_time=datetime.datetime.now(),
payment_card_id=uid,
current_state=1,
name=request.POST['name'],
)
merchant_profile.save()
return new_user
user_registered.connect(user_created)
It's likely because of the registration success redirection in your views is redirecting to a URL: registration_complete, that does not exist.
To fix it, you should add a url record similar to the one you have for registration_register
url(r'^accounts/register/$', register, {'backend': 'registration.backends.default.DefaultBackend','form_class': RegistrationFormEx}, name='registration_register'),
that points to the correct url with name=registration_complete.

Django serves zero byte response

This just happened to one of my sites and I have no idea what caused it.
This happens for any URL that is served by mod_wsgi for a particular application, which used to work fine.
Syntax errors in settings.py cause HTTP 500.
Syntax errors in urls.py don't influence anything—seems like this file is never loaded.
What is there to check?
The culprit was this line:
from django.contrib.auth.forms import AuthenticationForm
in middleware.py.
Moving the import into the function that uses AuthenticationForm solved the problem:
from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login
#from django.contrib.auth.forms import AuthenticationForm <-- THE LINE WAS HERE
class LoginFormMiddleware(object):
def process_request(self, request):
if request.method == 'POST' and 'is_top_login_form' in request.POST:
from django.contrib.auth.forms import AuthenticationForm # <-- MOVED HERE
form = AuthenticationForm(data=request.POST)
is_valid = form.is_valid()
if is_valid:
login(request, form.get_user())
program = request.user.get_profile().first_intern.program
NavigationMiddleware.set_program(request, program)
return HttpResponseRedirect('%s?quick' % program.get_absolute_url())
else:
messages.error(request, request.POST['username'], extra_tags='login')
return HttpResponseRedirect(request.get_full_path())
I still have no idea why the code used to work, why it suddenly broke and why doing this solved the problem.
There has to be some magick in Python, after all.

Categories