Hi I am new to Python/django and am using VS Code. Now I got python IntelliSense and pylance extension installed and most things are showing up on IntelliSense but some aren't.
How can I get it to work for everything?
I would very much appreciate some insight since it's driving me nuts...
request.POST from an imported lib not showing up
selected_meetup.participants not showing up nor is selected_meetup.participants.add
from urllib import request
from django.forms import SlugField
from django.shortcuts import render
from .models import Meetup
from .forms import RegistrationForm
# from django.http import HttpResponse
# Create your views here.
def index(request):
meetups = Meetup.objects.all()
return render(request, 'meetups/index.html', {
'meetups': meetups
})
def meetup_details(request, meetup_slug):
try:
selected_meetup = Meetup.objects.get(slug=meetup_slug)
if request == 'GET':
registration_form = RegistrationForm()
else:
registration_form = RegistrationForm(request.POST)
registration_form = RegistrationForm(request.)
if registration_form.is_valid():
participant = registration_form.save()
selected_meetup.participants.add(participant)
return render(request, 'meetups/meetup-detail.html', {
'meetup_found': True,
'meetup': selected_meetup,
'form': registration_form
})
except Exception as exc:
return render(request, 'meetups/meetup-detail.html', {'meetup_found': False
})
Update:
That's great guys, I now understand the type problem it's obvious now (only had so many extensions issues especially django/html) I got confused...
Now I added types to Meetup and Participant but selected_meetup.participants. still refused to show me its method ADD.
I assume the problem is the lib is written without types. Is there a way to solve that? because quite valuable to me to be able to see what's possible write away...
have you got solutions to that?
I would re-install the extensions, then make sure it is referencing the right version of python. If that doesn't work I would recommend to just type it out in full and look past the error.
You didn't declare what type of object request is in the programming process. Maybe you can declare request = request () in the code.The second is the same. vscode can't recognize the type of the selected_meetup you wrote.
You can hover over these two objects and find that the vscode prompt the type can be any.
Related
I started using django for the first time today and I have been encountering one issue
I want to use the PDFNetPython3 library for my project in Django framework.
I ran the command pip install PDFNetPython3 and it is says its already installed, however Django isn't able to resolve the import
Error/Warning
Import "PDFNetPython3" could not be resolvedPylancereportMissingImports
This is the line below being shown as unresolved import.
from PDFNetPython3 import PDFDoc, Optimizer, SDFDoc, PDFNet
views.py
from http.client import HTTPResponse
from django.shortcuts import render, HttpResponse
# Create your views here.
def index(request):
return render(request, 'index.html')
def compress(request):
return render(request, 'compress.html')
def showName(request):
if request.method == 'POST':
user_initial_pdf = request.POST['user_initial_pdf']
from PDFNetPython3 import PDFDoc, Optimizer, SDFDoc, PDFNet
return HttpResponse("ok")
Python Version - 3.9.7
Django Version - 4.0.1
Please note : I havent created any virtual environment as of now cause I just started django and found out its a good practice to do so, can it be the cause django not able to resolve the library through pip ?
Help would be appreciated :)
I have just started with using Django with a Django Crash Course book and got stuck on a part.
Let me show you what I have done so far and where I got stuck.
I opened a templates folder on the hellodjango project folder and wrote some basic HTML code like this.
<h1>Greetings</h1>
<p>Hello, world!</p>
<p>{{my_statement}}</p>
Here, the book says that it is okay to write my_statement like this because it will be later understood in python.
Later on it tells you to change views.py file under the homepage folder like this.
from django.views.generic import TemplateView
class HomepageView(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['my_statement'] = "Nice to see you:"
return context
However, when I refresh the page my_statement variable doesn't show up on the webpage at all. What could I possibly be doing wrong? I think if I didn't didn't have the packages, an error would pop up? But errors don't show up as well.
I have also checked the django documentation on this topic but the code here has similarities to the one I am working with.
Thanks for your help.
I have two pages, one which is to display details for a specific item and another to search for items. Let's say that the urls.py is properly configured for both of them and within views.py for my app, I have:
def item(request, id):
return render(request, 'item.html', data)
def search(request):
#use GET to get query parameters
if len(query)==1:
#here, I want to redirect my request to item, passing in the id
return render(request, 'search.html', data)
What do I do to properly redirect the request? I've tried return item(request, id) and that renders the correct page, but it doesn't change the URL in the address bar. How can I make it actually redirect instead of just rendering my other page? The URL pattern for the item page is /item/{id}. I've looked at the answer to similar questions on SO and the documentation, but still couldn't figure it out.
Edit: I just started learning Python less than a week ago and the other answer isn't clear enough to help me out.
Edit 2: Nvm, not sure what I did wrong before, but it worked when I tried it again.
You can use HttpResponseRedirect:
from django.http import HttpResponseRedirect
# ...
return HttpResponseRedirect('/url/url1/')
Where "url" and "url1" equals the path to the redirect.
Just minute suggestion from the above answer for the change in import statement
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/url-name-here/')
you can try this :
from django.shortcuts import redirect
return redirect(f'/customer/{pk}')
My views.py code:
from django.template import Context, loader, RequestContext
from django.http import HttpResponse
from skey import find_root_tags, count, sorting_list
from search.models import Keywords
def front_page(request):
if request.method == 'get' :
str1 = request.getvalue['word']
fo = open("xml.txt","r")
for i in range(count.__len__()):
file = fo.readline()
file = file.rstrip('\n')
find_root_tags(file,str1,i)
list.append((file,count[i]))
sorting_list(list)
for name, count in list:
s = Keywords(file_name=name,frequency_count=count)
s.save()
fo.close()
return HttpResponseRedirect('/results/')
else :
str1 = ''
list = []
template = loader.get_template('search/front_page.html')
c = RequestContext(request)
response = template.render(c)
return HttpResponse(response)
def results(request):
list1 = Keywords.objects.all()
t = loader.get_template('search/results.html')
c = Context({'list1':list1,
})
return HttpResponse(t.render(c))
#this for everyone.
the flow is this:
1) I run my app on the server .
2)It shows me the search page due to the else part of the view "def front_page(request)", now I want to execute the if part of the view "def front_page(request)" because I want to execute my python code written there and the redirected to the view "def results(request)", how can I do that ?
3) what should I mention in "action" of the front_page.html and in urls.py so that I can get back to the same view again. because I could'nt get back to the same view that I want it is repetitively showing me the same search page.Please help.
To enlarge upon the answer posted by #Barnaby....by using action='#' your form will be posted to the same url as the url used in the get request for the form.
Then in your view code, you have logic that says - if the request for this url is a GET request then do the work to configure the form, otherwise, you assume it is a POST and then you can handle the response.
Additionally I would advise that the your view explicitly checks that the request is a POST and if not make the assumption that it is a GET, rather than the other way around (as you have it), this is safer, as GET and POST are not the only request types, and you definitely need to know that you are dealing with a POST request if you want to deal with variables submitted in the POST request.
Hope that helps
Short answer: action="#". This is a HTML trick to post back to the current URL.
The general answer to how to reference a view in a template is to use the url tag. You may also want to consider using Django's forms functionality.
I have been looking online for localization of error messages and labels of pyramid forms but so far without any luck. I have worked on both pyramid_simpleform and pyramid_deform. Has anyone worked on something similiar. The docs are not much of help.
The example given on this page does not work for me.
I also tried the docs of pyramid_deform and pyramid_simpleform.
I do not care which form library I use. I want something that has straightforward support for localization.
This is what has worked for me.
from pyramid.i18n import get_locale_name
from pyramid_simpleform import Form,State
from formencode import api as formencode_api
def includeme(config):
config.scan(__name__)
config.add_route('login', '/login')
#view_config(route_name='login',renderer='website/login.mak')
def login(request):
formencode_api.set_stdtranslation(languages=[get_locale_name(request)])
form = Form(request,
defaults=dict(request.params),
schema=MySchema,
state=State()
)
form.state._ = ''