StaticLiveServerTestCase Server Error 500 - django

Main urls.py file:
urlpatterns = [
path(
'admin/',
admin.site.urls
),
path(
'',
include(
'employee.urls'
)
),
path(
'',
include(
'epos.urls'
)
),
path(
'',
include(
'supplier.urls'
)
),
]
epos.urls:
urlpatterns = [
path(
'',
home_view,
name='home'
),
home_view:
#login_required
def home_view(request):
# Get all categories
categories = Category.objects.all()
# Get the first category which will be selected by default
selected_category = categories.first()
# Get the order_items for the selected category (first category)
products = Product.objects.filter(
category=selected_category.id
)
user = request.user
tax = Tax.objects.latest('id')
context = {
'categories': categories,
'user': user,
'title': "EPOS",
'products': products,
'selected_category': selected_category,
'tax': tax
}
return render(request, 'epos/epos.html', context)
Test case:
class LoginTests(StaticLiveServerTestCase):
fixtures = ['fixtures/employee/employee_data.json']
def setUp(self):
self.browser = webdriver.Chrome()
self.browser.get(self.live_server_url)
self.browser.maximize_window()
def tearDown(self):
self.browser.quit()
def test_login_when_clocked_in(self):
import ipdb;ipdb.set_trace()
login_button = self.browser.find_element_by_xpath(
'//button[normalize-space()="Login"]'
)
clock_in_out_button = self.browser.find_element_by_xpath(
'//button[normalize-space()="Clock In/Out"]'
)
pin_input = self.browser.find_element_by_id(
'pin'
)
pin_code = 'some pin'
employee_name = 'some name'
pin_input.send_keys(pin_code)
clock_in_out_button.click()
time.sleep(10)
login_button.click()
settings.py
ROOT_URLCONF = 'allPOS.urls'
LOGIN_URL = '/login/'
When the test logs in I am redirected to the main webpage which is localhost:46497/ but instead of the page I am getting Server Error 500.
This error occurs only when testing. In addition, if I add another path e.g. localhost:46497/analytics it opens the webpage as expected.
Any help would be appreciated.

After 4 hours of debugging, I found out that the issue was related to the database being empty.
The webpage that I wanted to render is expecting some models to be passed, and since the DB was empty those models weren't passed and hence the crash. In normal circumstances ( ./manage.py runserver) if DEBUG=True it will tell you what is wrong, but for some reason StaticLiveServerTestCase doesn't have this option or at least I am not aware of it. If anyone knows how to enable some debugger for the StaticLiveServerTestCase please feel free to add to this thread.
So what I did:
./manage.py dumpdata order.tax > data.json - I dumped the data that I needed into a json file and at the beginning of the TestCase I added that data into the fixture
Hope this helps someone with the same issue!

Related

Testing a query parameter in django restframework

I am testing a query parameter in djnago restframework to retrieve the detail of an object. The query works in the browser but not the test. I think I am not calling the response correctly with:
response = self.client.get(reverse('quote-requests:get-calculator-detail', kwargs={'calculator_code': self.calc1.calculator_code}))
the apps urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('api/v1/quote-requests/', include('quote_requests.urls')),
]
which includes the quotes.urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from quote_requests import views
router = DefaultRouter()
router.register('get-calculator', views.CalculatorCodeDetailViewSet, basename='get-calculator')
app_name = 'quote-requests'
urlpatterns = [
path('', include(router.urls)),
]
The viewset is:
class CalculatorCodeDetailViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = CalculatorCodeSerializer
lookup_field = ('calculator_code')
def get_queryset(self):
return (
Calculator.objects.filter(
calculator_code = self.request.query_params.get('calculator_code',)
)
)
The CalculatorCodeSerializer is:
class CalculatorCodeSerializer(serializers.ModelSerializer):
class Meta:
model = Calculator
fields = (
'name',
'calculator_code',
)
The test is:
def test_retrieving_calculator_detail_with_calculator_code(self):
''' test retrieving detail of a calculator '''
self.calc1 = Calculator.objects.create(
name = "Calculator 1000",
calculator_code = "HH1000",
)
response = self.client.get(reverse('quote-requests:get-calculator-detail', kwargs={'calculator_code': self.calc1.calculator_code}))
serializer = CalculatorCodeSerializer(self.calc1)
self.assertEqual(response.data, serializer.data)
This yields the error:
Traceback (most recent call last):
File "/app/quote_requests/tests/test_calculators_api.py", line 149, in test_retrieving_calculator_detail_with_calculator_code
self.assertEqual(response.data, serializer.data)
AssertionError: {'detail': ErrorDetail(string='Not found.',[14 chars]nd')} != {'name': 'Calculator 1000', 'calculator_cod[368 chars].25'}
When checking the browser link:
http://localhost:8000/api/v1/quote-requests/get-calculator/?calculator_code=HH1000
This works but test fails. Any help setting up the properly would be appreciated.
I think you are using the wrong endpoint name replace this "get-calculator-detail" with this "get-calculator"
def test_retrieving_calculator_detail_with_calculator_code(self):
# test retrieving detail of a calculator
self.calc1 = Calculator.objects.create(
name = "Calculator 1000",
calculator_code = "HH1000",
)
response = self.client.get(reverse('quote-requests:get-
calculator', kwargs={'calculator_code':
self.calc1.calculator_code}))
serializer = CalculatorCodeSerializer(self.calc1)
self.assertEqual(response.data, serializer.data)
With the help of others on Fiverr I have gotten the test to pass. I hesitate to call it answered but I am putting the detail here in case those who know a better way can comment.
TLDR - the response variable was not written correctly either the reverse does not do what I want or it cannot be done with reverse. Either way the change that worked was:
response = self.client.get('/api/v1/quote-requests/get-calculator/', {'calculator_code': self.calc1.calculator_code})
This does not return an iterable object. It returns an OrderDict which looks like this:
[{"name":"Calculator 1000","calculator_code":"HH1000","id":7,}]
I used print(response.content) to check this.
so you need to use the json function to pull the data out and match it to serializer.data - the response from the serializer.
response.data = response.json()[0]
this pulls the "[]" off and formats it like this:
{'name': 'Calculator 1000', 'calculator_code': 'HH1000', 'id': 7, }
The [0] on the end gets the object (I think) and returns it in json format.
The two fiverr users that helped me with this were:
https://www.fiverr.com/tailongk
and
https://www.fiverr.com/asipita

Django REST framework RetrieveAPIView gets empty "id" parameter and returns 404 error

I use Django 1.11 + Django REST Framework. I'm trying to get detailed data about distinct record using generic RetrieveAPIView from Django REST Framework and server returns "HTTP 404 Not Found" result, i.e. no data.
models.py file:
class TestPage( models.Model):
title = models.CharField( size = 120)
counter = models.IntegerField( default = 0)
def __unicode__(self):
return u'' + self.title
serializers.py file:
class TestPageSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'title', 'counter',)
model = models.TestPage
urls.py file:
urlpatterns = [
url( r'^admin/', admin.site.urls),
url( r'^api/', include( 'rest_framework.urls')),
url( r'^api/', include( 'testpages.urls')),
]
testpages/urls.py file:
urlpatterns = [
url( r'^$', views.TestPageList.as_view()),
url( r'^(?P<id>)\d+/$', views.TestPageDetail.as_view()),
]
and at last views.py file:
class TestPageList(generics.ListAPIView):
lookup_field = 'id'
queryset = TestPage.objects.all()
serializer_class = TestPageSerializer
class TestPageDetail(generics.RetrieveAPIView):
lookup_field = 'id'
queryset = TestPage.objects.all()
serializer_class = TestPageSerializer
# def get_object( self):
# print self.kwargs
If I request "http://127.0.0.1:8000/api/" for all records in the list, server returns all records. But if I want to get record by id using "http://127.0.0.1:8000/api/1/" for example, I get the empty result like in the photo below.
[![enter image description here][1]][1]
If I uncomment get_object()-function in last 2 lines, I can see {'id': u''} in terminal i.e. server gets empty parameter 'id'.
What wrong with this code?
The issue is your regular expression matching for id, you're putting \d+ outside of the matching group when it's actually what you want to match:
url(r'^(?P<id>\d+)/$', views.TestPageDetail.as_view())
By the way, to be good REST citizen, you shouldn't add the / at the end of a URL for a specific object.
Note: As mentioned by JPG, adding a name for the resource you're fetching (plural) would be proper RESTful:
url(r'^pages/(?P<id>\d+)$', views.TestPageDetail.as_view())
This way, you fetch page nr. 1 at /api/pages/1
The original problem was the closing parathesis (the regex expression), you were misplaced that.
urlpatterns = [
url(r'^$', views.TestPageList.as_view()),
url(r'^(?P<id>\d+)/$', views.TestPageDetail.as_view()),
^^^ here
]
Apart from that, You should change the urls patterns to a sensible form, as
#testpages/urls.py
urlpatterns = [
url(r'^test/$', views.TestPageList.as_view()),
url(r'^test/(?P<id>\d+)/$', views.TestPageDetail.as_view()),
]
then the list-api will be available on /api/test/ endpoint and the detail-api will be available on /api/test/{id}/

flask-admin incorrect relative url

I am trying to create a simple admin for editing a mongo collection. I have posted the code below. It all works perfectly locally or as a docker container. However when I deploy this in our micro-service architecture the app lives at: SERVER_NAME/TEAM_NAME/APP_NAME/.
Flask routes set with #app.route work correctly. However the urls in the admin templates are not correct and always start directly at SERVER_NAME ignoring team-name and app-name. The actual pages and resources are located at the correct urls but the urls for the static resources are not found. How do I make sure the urls generated within flask-admin also take into account the relative url?
The code:
import os
import flask_admin
from wtforms import form, fields
from flask_admin.contrib.pymongo import ModelView, filters
# User admin
class WordPairsForm(form.Form):
text = fields.StringField("Text")
language = fields.SelectField("Language", choices=[("de", "german"), ("en", "english"), ("pl", "polish")])
label = fields.SelectField("Label", choices=[("badword", "bad word"), ("no_stay", "no overnight stay")])
active = fields.BooleanField("Active", default="checked")
class WordPairsView(ModelView):
column_list = ("text", "language", "label", "active")
column_sortable_list = ("text", "language", "label", "active")
column_searchable_list = ("text",)
column_filters = (
filters.FilterLike("text", "Text"),
filters.FilterNotLike("text", "Text"),
filters.FilterEqual("language", "Language", options=[("de", "german"), ("en", "english"), ("pl", "polish")]),
filters.FilterEqual("label", "Label", options=[("badword", "bad word"), ("no_stay", "no overnight stay")]),
filters.BooleanEqualFilter("active", "Active")
)
form = WordPairsForm
def create_form(self):
_form = super(WordPairsView, self).create_form()
return _form
def edit_form(self, obj):
_form = super(WordPairsView, self).edit_form(obj)
return _form
def get_list(self, *args, **kwargs):
count, data = super(WordPairsView, self).get_list(*args, **kwargs)
return count, data
def get_url
def add_admin(app):
admin = flask_admin.Admin(
app,
name="CQAS Admin",
url=os.getenv(
"F_ADMIN_URL",
"/admin"
),
static_url_path=os.getenv("F_ADMIN_STATIC_URL", None),
subdomain=os.getenv("F_ADMIN_SUBDOMAIN", None),
endpoint=os.getenv("F_ADMIN_ENDPOINT", None)
)
admin.add_view(WordPairsView(app.data.data, "WordPairs"))

django paypal notify_url not configured correctly or working

I did a pip install for django paypal. The button renders and the payment goes through. The return url works too but the notify_url part is not working. So I cannot update my database that a sale has gone through.
I don't get any errors either so I am stumped. If someone can help Id really appreciate it. Thanks
Edit: I added from paypal.standard.ipn.signals import payment_was_successful to the top of my views page. and changed the name of my notify_url to show_me_the_money (Not sure if that matters) I got it from a blog called http://djangodersleri.blogspot.ie/2013/11/paypal-ipn-with-django.html. But the good thing is now at least I seem to be getting my transactions recorded in the table paypal_ipn. But that's all! So still dont know if the show_me_the_money view is being executed.
Here is what I have..
Settings...
INSTALLED_APPS = (
...
'paypal.standard.ipn',
)
PAYPAL_RECEIVER_EMAIL = "my_sandbox_test_email_is_here#gmail.com"
PAYPAL_TEST = True
URLS...
(r'^show_me_the_money /', include('paypal.standard.ipn.urls')),
Views...
from paypal.standard.models import ST_PP_COMPLETED
from paypal.standard.ipn.signals import valid_ipn_received
from paypal.standard.ipn.signals import payment_was_successful
def show_me_the_money (sender, **kwargs):
ipn_obj = sender
if ipn_obj.payment_status == ST_PP_COMPLETED:
doc_id=ipn_obj.item_number1 # :document_id,
us_id=ipn_obj.item_number2 #user.id,
obj_doc=Document.objects.get(id=doc_id)
my_user = User.objects.get(id=us_id)
obj_doc.users.add(my_user)
obj_doc.save()
try:
ipn_obj.verify(item_check_callable)
except:
import sys, traceback
traceback.print_exc(file=sys.stdout)
valid_ipn_received.connect(paid)
#csrf_exempt
def myvideos(request):
try:
my_vids=Document.objects.filter(users=request.user.id)#request.user.id
except:
return render_to_response(
'myvideos.html',
context_instance=RequestContext(request)
)
#my_vids= Document.objects.filter(users=request.user.id)
return render_to_response(
'myvideos.html',
{'my_vids': my_vids},
context_instance=RequestContext(request)
)
def video(request, document_id):
document = Document.objects.get(id=document_id)
if request.user.id:
d1 =datetime.datetime.now()
t=d1.strftime('%y%m%d%h%m%s')
pp_price = str(document.price)
# What you want the button to do.
paypal_dict = {
"business": settings.PAYPAL_RECEIVER_EMAIL,
"amount": pp_price + ".00",
"item_number1":document_id,
"item_number2":request.user.id,
"item_name": document.name,
"invoice": document.name+t,
"notify_url": "http://wackosmackosite.com/"+ reverse('paypal-ipn'),
"return_url": "http://wackosmackosite.com/myvideos/",
"cancel_return": "http://wackosmackosite.com/video/"+document_id+"/",
}
form = PayPalPaymentsForm(initial=paypal_dict)
context = {"form": form, "document":document }
return render(request, "video.html", context)
else:
return render_to_response('video.html',{'document': document},
context_instance=RequestContext(request))
Here is the The urls from paypal.standard.ipn
from django.conf.urls import url
from paypal.standard.ipn import views
urlpatterns = [
url(r'^$', views.ipn, name="paypal-ipn"),
]
First off #mcastle Thank you so much for your help. But I just couldn't figure out the Django signals.
Ok so what I had to do in the end is go to the paypal.standard.ipn.views file and import my app and call the show_me_the_money view from there at the very bottom of the view just before it returns the http response.
So the notify url in the paypal dict like this...
"notify_url": "http://wackosmackosite.com/show_me_the_money/",
And the url in my urls file is like this..
url(r'^show_me_the_money/', include('paypal.standard.ipn.urls')),
I was able to extract the info I needed to update my database from the arguments passed to show_me_the_money. like this...
def show_me_the_money(sender, **kwargs):
ipn_obj = sender
payStatus=ipn_obj.POST.get('payment_status','')
if payStatus=='Completed':
....
Then in the paypal ipn view
at the top...
from myApp.views import show_me_the_money
At the bottom...
s_m_t_m=show_me_the_money(request, item_check_callable=None)
return HttpResponse("OKAY")
I found this whole set-up very confusing and think the documentaion for me just leaves lots of important stuff out. Anyway This is working perfect now and I just got off the phone with pay pal and they are happy it is configured correctly.
Review Django's documentation on signals. show_me_the_money looks like it needs to be connected to a signal.

Django : url main page

I want to add a main page with a login but I have the error
A server error occurred. Please contact the administrator.
what does it means ??
url:
urlpatterns = patterns('',
url(r'^ยง', main_page),
url(r'^mainView/$', mainView.as_view()),
url(r'^material/(?P<slug>[-\w]+)/$', MaterialDetailView.as_view(), name='material_material_detail'),
)
view:
def main_page(request):
template = get_template('registration/main_page.html')
variables = Context({ 'user': request.user })
output = template.render(variables)
return HttpResponse(ouput)
Pretty sure you meant
url(r'^$', main_page),