Trouble with importing ListView - python

I'm using python 3.7 and django 2.1. Trying to create a class based view, and first have to import it in my views.py. So I put:
from django.views.generic import ListView
which is what the tutorial said to do. When I run the server, I get:
ImportError: cannot import name 'Listview' from 'django.views.generic
I tried it with
from django.views.generic.list import ListView
but that didn't work either.
Anyone have any ideas? Pretty new to coding, let me know if there's a better way to ask the question as well. I was as specific as I could be.

Example from Docs
from django.utils import timezone
from django.views.generic.list import ListView # <-- Working
from articles.models import Article
class ArticleListView(ListView):
model = Article
paginate_by = 100 # if pagination is desired
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['now'] = timezone.now()
return context

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

How to link between django views components

Actually, I am pretty new in Django. I have created three views in my views.py.
This is my following code in views.py :
from django.shortcuts import render
import pymongo
from .models import *
from .serializers import *
from .forms import *
from .codes.scraping import scrap
def home_view(request):
context = {}
context ['form'] = Scraping()
return render(request,'home.html',context)
def loading_view(request):
return render(request,'loading.html')
def datatable_view(request):
client = pymongo.MongoClient("mongodb://localhost:27017/")
db= client["aliexpress_db"]
col = db["segment"]
products = col.find()
context = {'products' : products}
return render(request,'datatable.html', context)
My question is that I want to get a method in order to get the home_view first then my loading_view while the scraping is processing then my datatable_view.
I don't know how to link between these views. I am completely beginner. Any help would be great.
this is not a job for Django. I think what you want to do is possible through these steps:
place your loading gif/vector animation in your home_view
when the user submits the form show this animation using some javascript code until you get a response from datatable_view and change the page
pass the results to the template of datatable_view to render them.
alternatively, you can use an AJAX Call to receive the results in the home view.
checking out this answer would also help.

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

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.

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 seems to be caching?

I'm running Django 1.2.1 for my personal website with a blog. It's all fine and dandy, but I've found that all the browsers I've tried (Firefox, Chromium, Opera) are caching webpages, which of course is a problem for other users viewing my blog (being that it won't load new posts up unless they empty their cache or force refresh the page). I didn't have this problem when my site ran on PHP, so how would I go about fixing this seemingly Django-related problem?
I've only been working with Django for about a week or so, so I don't really know where abouts I should be looking to fix something like this. Thanks in advance!
The way I do each page (and each blog post) is as a Page/Post object respectively so I can use the admin interface without having to write my own. Although the issue is happening for both situations, I'll just give the Post class for now:
class Post(models.Model):
author = models.ForeignKey(User, default=User.objects.get(username='nathan'))
status = models.ForeignKey(Status, default=Status.objects.get(text='Draft'))
date = models.DateTimeField(default=datetime.datetime.now())
title = models.CharField(max_length=100)
post = models.TextField()
categories = models.ManyToManyField(Category)
def __unicode__(self):
return u'%s' % self.title
def link(self):
return u'/blog/post/%s' % self.title
class Meta:
ordering = ['-date']
And here's my urls.py:
from django.conf.urls.defaults import *
from django.views.generic import list_detail
from feeds import PostFeed
from models import Post
blog_posts = {
'queryset': Post.objects.filter(status__text__exact='Published'),
}
urlpatterns = patterns('getoffmalawn.blog.views',
(r'^$', list_detail.object_list, blog_posts),
(r'^archive/(\d{4})$', 'archive'),
(r'^rss/$', PostFeed()),
(r'^search/$', 'search'),
(r'^tag/(.+)/$', 'tag'),
(r'^post/(.+)/$', 'post'),
)
If you guys would like to see the code from views.py, just ask and I'll throw that up too.
Edit:
Here's the views.
view.py for the blog App:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect
from django.core.context_processors import csrf
from django.db.models import Q
from models import Post, Category
def post(request, title):
post = Post.objects.get(title=title)
c = locals()
c.update(csrf(request))
return render_to_response('blog/post_detail.html', c)
def blog_detail(request, blog_id):
post = get_object_or_404(Post, pk=blog_id)
return list_detail.object_detail(request, queryset=Post.objects.all(), object_id=blog_id)
def archive(request, month, year):
pass
def search(request):
if request.method == 'GET':
query = request.GET['q']
object_list = Post.objects.filter(Q(post__icontains=query) | Q(title__icontains=query), status__text__exact='Published')
return render_to_response('blog/post_list_sparse.html', locals())
def tag(request, tag):
object_list = Post.objects.filter(categories__text__exact=tag, status__text__exact='Published')
return render_to_response('blog/post_list.html', locals())
The problem was that it really was browser-based caching, as I was told by a member on the Django-users mailing list. The reason I didn't see this problem in PHP is that it was sending cache suppression headers.
The solution was to add the #never_cache decorator to the relevant views.
Here is the documentation for caching in django.
https://docs.djangoproject.com/en/1.2/topics/cache/
Not ideal, but you can make all of the pages tell the browsers not to cache anything, to see if that helps.
https://docs.djangoproject.com/en/1.2/topics/cache/#controlling-cache-using-other-headers

Categories